Task Agent API
The Task Agent API enables you to execute dynamic tasks directly through the Foldspace SDK. It supports both complete (Promise-based) and streaming modes, allowing you to run flexible AI or automated task workflows and handle real-time responses.
Overview
Make your product AI-powered without prompts. Task Agent let you call curated LLM skills from code and receive text or JSON outputs you can trust, with versioning, tests, and observability built in.
When to Use Functions
- Synchronous AI APIs: quick, reliable responses for product features.
- Deterministic contracts: predictable outputs via schemas.
- Non-chat use cases: summaries, classification, extraction, or generation tasks.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
taskKey | string | Yes | The unique identifier for the task you want to run. |
data | string | object | Yes | The input payload for the task. |
streamOptions | object | No | Enables streaming mode if provided. |
cacheOptions | object | No | Configures caching behavior, such as defining a Time-To-Live (TTL) or forcing a fresh execution. |
Basic Usage (Complete Task)
Use foldspace.agent('AGENT-API-NAME').runTask() to execute a task and receive the complete result as a Promise.
Example
foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'TASK-KEY',
data: 'ANY-STRING-OR-OBJECT'
})
.then((result) => {
console.log('Task result:', result);
})
.catch((error) => {
console.error('Task failed:', error);
});
Description
The complete (non-streaming) mode waits for the server response and returns the full result once the task finishes.
Returns
The returned Promise resolves with the complete output from the task. The data type depends on the task's configured response type.
string(forTEXTresponse types)object(forJSONresponse types)
Cache Options
The optional cacheOptions object gives you explicit control over when to use cached results, when to force a fresh execution, and how long new results should be cached.
Caching functionality works identically for both Complete (Promise-based) and Streaming modes of runTask().
cacheOptions Properties
cacheOptions Properties| Property | Type | Default Behavior | Description |
|---|---|---|---|
bypass | boolean | false | When set to true, the task will execute, ignoring any existing cached results and forcing a fresh execution. |
ttlSeconds | number | 21600 (6 hours) | Specifies the time in seconds to cache the new result. Set to 0 to disable caching for the new result. |
Behavior Matrix
bypass | ttlSeconds | Result |
|---|---|---|
Omitted / false | Omitted | Check cache. If executed, cache new result for 6 hours. |
Omitted / false | 300 (custom) | Check cache. If executed, cache new result for 5 minutes. |
Omitted / false | 0 | Check cache. If executed, do not cache new result. |
true | Omitted | Skip cache. Execute fresh & cache new result for 6 hours. |
true | 0 | Skip cache. Execute fresh & cache new result for 6 hours. |
Examples
Example 1: Forcing a Refresh (Bypass Cache)
This ignores any cached value and forces the task to run. The newly generated result will be cached for the default 6 hours.
foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'SUMMARIZE_TASK',
data: 'some long text...',
cacheOptions: {
bypass: true
}
});Example 2: Disabling Caching for a New Result
This will still check for an existing cached result, but if a new result is generated (e.g., because no cache was found), it will not be cached for future use.
foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'SUMMARIZE_TASK',
data: 'some long text...',
cacheOptions: {
ttlSeconds: 0
}
});Example 3: Full-Fresh, No-Cache Operation
The "full-fresh, no-cache" operation, which both skips reading from the cache and prevents the new result from being stored.
foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'SUMMARIZE_TASK',
data: 'some long text...',
cacheOptions: {
bypass: true,
ttlSeconds: 0
}
});Example 4: Setting a Custom TTL (with Streaming)
cacheOptions works identically with streaming mode. This example sets a 10-minute (600 seconds) cache for the streamed result.
foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'LONG_STREAM_TASK',
data: { prompt: 'Generate a story...' },
// Cache this specific stream's result for 10 minutes
cacheOptions: {
ttlSeconds: 600
},
streamOptions: {
onMessage: ({ textDelta }) => {
// Append text to UI
},
onComplete: () => {
console.log('Stream done and result is cached.');
}
}
});Streaming Mode
Note: Streaming mode is only supported for tasks configured with a
TEXTresponse type. It is not compatible withJSONresponse types.
For real-time responses, such as AI text generation, incremental updates, or long-running processes, you can enable streaming by providing the streamOptions object.
Example
foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'TASK-KEY',
data: { input: "Hello, world" },
streamOptions: {
onStart: ({ id, abortStreamTask }) => {
console.log('Stream started with ID:', id);
// You can call abortStreamTask() to stop the stream at any time
},
onMessage: ({ textDelta, fullText, chunk }) => {
console.log('New message chunk:', textDelta);
console.log('Full accumulated text:', fullText);
},
onComplete: ({ fullText }) => {
console.log('Stream completed:', fullText);
},
onError: (error) => {
console.error('Stream error:', error);
}
}
});Description
In streaming mode, the server sends incremental chunks of data as they become available.
Each chunk triggers the onMessage callback, allowing you to process output progressively.
streamOptions Callbacks
streamOptions Callbacks| Callback | Description | Parameters |
|---|---|---|
| onStart | Called when the stream begins. | { id: string, abortStreamTask: () => void } |
| onMessage | Called for every data chunk received from the stream. | { textDelta: string, fullText: string, chunk: object, id: string } |
| onComplete | Called once the stream ends (naturally or via abort). | { textDelta?: string, fullText: string, chunk?: object, id?: string } |
| onError | Called if an error occurs during the stream. | (error: Error) |
Aborting a Stream Manually
The onStart callback provides an abortStreamTask function. You can store this function and call it at any time to manually stop the stream from the client side.
This is useful for implementing "Stop Generation" buttons, handling user navigation, or enforcing a client-side timeout. Calling abortStreamTask() will gracefully terminate the stream, and the onComplete callback will still be triggered.
Example Implementation:
// Store the abort function in a higher scope
let abortTask = null;
function startStream() {
foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'LONG_STREAM_TASK',
data: { prompt: 'Generate a very long story...' },
streamOptions: {
onStart: ({ id, abortStreamTask }) => {
console.log('Stream started:', id);
// Store the function so it can be called by other elements
abortTask = abortStreamTask;
},
onMessage: ({ textDelta }) => {
console.log(textDelta); // Append text to UI
},
onComplete: ({ fullText }) => {
console.log('Stream completed.');
abortTask = null; // Clean up
},
onError: (err) => {
console.error('Stream error:', err);
abortTask = null; // Clean up
},
}
});
}
// Imagine this is called by a "Stop" button click
function stopStream() {
if (abortTask) {
console.log('Manually aborting stream...');
abortTask();
}
}Notes
- You can run any registered agent API using its unique
taskKey. To create and manage your task agents, visit the agent functions page: https://app.foldspace.ai/agent/functions - For long tasks, prefer streaming mode to get progressive feedback.
- Both modes use the same function:
foldspace.agent('AGENT-API-NAME').runTask()— behavior changes depending on whetherstreamOptionsis provided.
Updated 4 months ago