Skip to content

Task Agent

Open in ChatGPT Open in Claude

Run a configured task through the SDK and get back text or JSON you can trust, adding AI to a product feature without writing prompts: call a curated, versioned, observable skill from code.

Reach for it when you need:

  • Synchronous AI APIs: quick, reliable responses inside a product feature.
  • Deterministic contracts: predictable outputs shaped by a schema.
  • Non-chat tasks: summaries, classification, extraction, or generation.

Both complete and streaming modes use the same call: foldspace.agent('AGENT-API-NAME').runTask(). Passing streamOptions switches it to streaming.

ParameterTypeRequiredDescription
taskKeystringYesThe unique identifier for the task you want to run.
datastring | objectYesThe input payload for the task.
streamOptionsobjectNoEnables streaming mode if provided.
cacheOptionsobjectNoConfigures caching behavior, such as defining a Time-To-Live (TTL) or forcing a fresh execution.

Call runTask() without streamOptions to wait for the server and resolve a Promise with the full result once the task finishes.

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);
});

The resolved value depends on the task’s configured response type:

  • string for TEXT response types.
  • object for JSON response types.

The optional cacheOptions object controls when cached results are used, when to force a fresh execution, and how long new results are cached. Caching behaves identically in both complete and streaming modes.

PropertyTypeDefaultDescription
bypassbooleanfalseWhen true, the task executes fresh, ignoring any existing cached result.
ttlSecondsnumber21600 (6 hours)How long to cache the new result, in seconds. Set to 0 to disable caching for the new result.
bypassttlSecondsResult
Omitted / falseOmittedCheck cache. If executed, cache new result for 6 hours.
Omitted / false300 (custom)Check cache. If executed, cache new result for 5 minutes.
Omitted / false0Check cache. If executed, do not cache new result.
trueOmittedSkip cache. Execute fresh & cache new result for 6 hours.
true0Skip cache. Execute fresh & cache new result for 6 hours.

Ignore any cached value and run the task. The new result is cached for the default 6 hours.

foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'SUMMARIZE_TASK',
data: 'some long text...',
cacheOptions: {
bypass: true
}
});

Still check for an existing cached result, but if a new result is generated (for example, because no cache was found), don’t store it for future use.

foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'SUMMARIZE_TASK',
data: 'some long text...',
cacheOptions: {
ttlSeconds: 0
}
});

Skip reading from the cache and prevent the new result from being stored.

foldspace.agent('AGENT-API-NAME').runTask({
taskKey: 'SUMMARIZE_TASK',
data: 'some long text...',
cacheOptions: {
bypass: true,
ttlSeconds: 0
}
});

cacheOptions works the same in streaming mode. This caches the streamed result for 10 minutes (600 seconds).

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.');
}
}
});

Provide a streamOptions object to receive incremental chunks as they become available, ideal for AI text generation, incremental updates, or long-running processes. Each chunk triggers onMessage, letting you render output progressively.

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);
}
}
});
CallbackDescriptionParameters
onStartCalled when the stream begins.{ id: string, abortStreamTask: () => void }
onMessageCalled for every data chunk received from the stream.{ textDelta: string, fullText: string, chunk: object, id: string }
onCompleteCalled once the stream ends (naturally or via abort).{ textDelta?: string, fullText: string, chunk?: object, id?: string }
onErrorCalled if an error occurs during the stream.(error: Error)

The onStart callback provides an abortStreamTask function. Store it and call it at any time to stop the stream from the client side, useful for “Stop Generation” buttons, handling user navigation, or enforcing a client-side timeout. Calling abortStreamTask() gracefully terminates the stream, and onComplete still fires.

// 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();
}
}
  • Run any registered agent API using its unique taskKey. Create and manage your task agents on the agent functions page.
  • For long tasks, prefer streaming mode to get progressive feedback.
  • Both modes use foldspace.agent('AGENT-API-NAME').runTask(): behavior changes based on whether streamOptions is provided.