@cognitivecloud/actions
v1.0.10
Published
Convenient package for running Actions by Cognitive Cloud
Readme
Cognitive Cloud Actions SDK
A Node.js SDK for interacting with Cognitive Cloud's Actions API. This is a wrapper library around the main GraphQL API designed to make it quick and easy to integrate Cognitive Cloud Actions into your project.
Helpful links:
Installation
Install from NPM:
npm install @cognitivecloud/actionsyarn add @cognitivecloud/actionsSetup
Initialize the SDK with your API key.
You can create your API key on the Cognitive Cloud Dashboard. The API key must have either Admin or Developer permissions to run actions. For read-only access, Read-only permissions are sufficient.
Note: this example uses COGNITIVE_CLOUD_API_KEY as the name of the environment variable with the API key value, but you can configure your own environment variables as needed.
import { ActionsAPI } from '@cognitivecloud/actions';
const API_KEY = process.env.COGNITIVE_CLOUD_API_KEY;
// Initialize the SDK with your API key
const client = new ActionsAPI(API_KEY);API Reference
Authentication
init(apiKey: string): Promise<void>
Initializes the SDK with your API key and validates it against the API.
- Parameters:
apiKey(string): Your Cognitive Cloud API key
- Returns: Promise<void>
- Throws: Error if the API key is missing or invalid
Action Operations
getAction(actionId: string): Promise<Action>
Fetches an Action by its ID.
- Parameters:
actionId(string): The ID of the Action to fetch
- Returns: Promise<Action>
searchActions(filters?: ActionFilter | string | null): Promise<Action[]>
Searches for Actions based on provided filters.
- Parameters:
filters(ActionFilter | string | null): Search filters. If string, it's treated as a search keyword
- Returns: Promise<Action[]>
suggestActionsForPrompt(prompt: string): Promise<Action[]>
Fetches a list of possible Actions that could be helpful/relevant based on a prompt that the user provides. This can be useful for finding results in chat-based interfaces.
- Parameters:
prompt(string): The text prompt to get suggestions for
- Returns: Promise<Action[]>
Job Operations
runActionJob(actionId: string, payload?: object | null, options?: object | null): Promise<Job>
Runs an Action job with the provided payload. Waits for the job to complete before returning the result. An optional options object can be provided for additional features.
- Parameters:
actionId(string): The ID of the Action to runpayload(object | null): The payload for the Actionoptions(ActionJobOptions | null): Optional webhook URL for receiving job status updates
- Returns: Promise<Job>
getJob(jobId: string): Promise<Job>
Fetches job status and results by job ID.
- Parameters:
jobId(string): The ID of the job to fetch
- Returns: Promise<Job>
Payload Utility Methods
validatePayload(payload: object | null, schema: object | null): boolean
Validates a payload against an Action's JSON schema. This will return true if the payload is valid, but throw an error if it's invalid. To always get a true/false response, use isPayloadValid.
- Parameters:
payload(object | null): The payload to validateschema(object | null): The JSON schema to validate against
- Returns: true if valid
- Throws: Error with validation errors if invalid
isPayloadValid(payload: object | null, schema: object | null): boolean
Checks if a payload is valid against an Action's JSON schema.
- Parameters:
payload(object | null): The payload to validateschema(object | null): The JSON schema to validate against
- Returns: boolean
trueif the payload is valid andfalseif invalid
Types
Action
Represents a Cognitive Cloud Action.
- Properties:
id(string): The unique identifier of the Action.name(string): The name of the Action.description(string): A description of what the Action does.cost_unit(string): The unit of cost (e.g., "query", "second").cost_amount(number): The amount of cost per execution (e.g., 0.0001). The cost format depends on the action type, e.g.:- $0.0001/query made
- $0.0001/second of runtime
created_at(string): When the Action was created.updated_at(string): When the Action was last updated.trigger_word(string): Some actions have a trigger word. Including this trigger word in the prompt field for that action significantly improves results.json_schema(object): The JSON schema defining the Action's input parameters. May benullcategory_details(object): Details about the category this Action belongs toid(string): The unique identifier of the category.
is_featured(boolean): Whether the Action is featured.is_popular(boolean): Whether the Action is popular.is_trending(boolean): Whether the Action is trending.is_new(boolean): Whether the Action is new.is_highly_rated(boolean): Whether the Action is highly rated.popular_score(number): The popularity score of the Action.trending_score(number): The trending score of the Action.rating_count(number): The number of ratings the Action has received.rating_total(number): The sum of all ratings for the Action.
ActionFilter
A class to represent filters for searching actions.
- Properties:
searchKeyword(string): The search keyword.collection(string): The collection ID to filter by.categories(string[]): The category IDs to filter by.offset(number): The offset for pagination.limit(number): The limit for pagination.
ActionJobOptions
Represents the options for running an Action
- Properties:
webhookUrl(string): Optional webhook URL for receiving job status updateswaitForResult(boolean): Optional setting to wait for the job to complete before responding. By default, a response is returned once the job is in the system. SetwaitForResult: trueto only respond when the job has either completed successfully or failed. Some actions run quickly enough to return straight away, but others can take minutes (e.g., Generate Video actions).
Job
Represents a Job executed for an Action.
- Properties:
id(string): The unique identifier of the Job.action_id(string): The ID of the Action this Job is associated with.status(string): The current status of the Job (e.g., "QUEUED", "IN_PROGRESS", "COMPLETED", "FAILED").started_at(string): Timestamp indicating when the Job started execution.finished_at(string): Timestamp indicating when the Job completed execution.request(object): Thepayloaddata sent to the Action.response(object): The result/response data returned by the Action.error_message(string | null): Error message if the Job failed, null otherwise.created_at(string): Timestamp indicating when the Job was created.action(object): Information about the associated Action.id(string): The unique identifier of the Action.name(string): The name of the Action.
Examples
// Initialization
import { ActionsAPI, ActionFilter } from '@cognitivecloud/actions';
const API_KEY = process.env.COGNITIVE_CLOUD_API_KEY;
const client = new ActionsAPI(API_KEY);
// Initialize ActionFilter for a search
const filters = new ActionFilter({
searchKeyword: 'podcasts',
limit: 10,
offset: 0,
});
// Running the search query
const actions = await client.searchActions(filters);
console.log('\nSEARCH RESULTS:', actions);
// Action ID for the Search Podcasts action
const actionId = '709e6f87-48a7-49ed-b1cb-ca4ad7d68aec';
// Fetch Search Podcasts details and print the payload schema.
const action = await client.getAction(actionId);
console.log('\nSEARCH PODCASTS ACTION:', action);
const schema = action?.json_schema ?? null;
console.log('\nACTION SCHEMA:', schema);
// Construct a payload
const payload = { type: 'podcast', q: 'reuters world news' };
// Get a true/false result if the payload is valid
const isValid = client.isPayloadValid(payload, schema);
console.log('\nIS PAYLOAD VALID:', isValid);
// Alternatively use validatePayload to get error messages for an invalid payload
const errorPayload = {type: 'podcast', qqqq: 'error payload field'};
try {
// This will throw an error message
client.validatePayload(errorPayload, schema);
} catch (e) {
console.error('\nPAYLOAD ERRORS:', e);
}
// Run an Action job for the Search Podcasts action
const job = await client.runActionJob(actionId, payload);
console.log('\nRUN ACTION JOB DETAILS:', job);
// Get the details for the job you just ran
const jobDetails = await client.getJob(
job.id,
);
console.log('\nACTION JOB DETAILS:', jobDetails);
// Wait for the job to be complete (or failed) before getting the response
const completedJob = await client.runActionJob(actionId, payload, { waitForResult: true });
console.log('\nCOMPLETED ACTION JOB DETAILS:', completedJob);
// Get some suggested actions for a chat-style prompt query
const suggestions = await client.suggestActionsForPrompt(
'I want to remove the background from my profile picture',
);
console.log('\nPROMPT SUGGESTIONS:', suggestions);