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

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.

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 (for TEXT response types)
  • object (for JSON response 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

PropertyTypeDefault BehaviorDescription
bypassbooleanfalseWhen set to true, the task will execute, ignoring any existing cached results and forcing a fresh execution.
ttlSecondsnumber21600 (6 hours)Specifies the time in seconds to cache the new result. Set to 0 to disable caching for the new result.

Behavior Matrix

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.

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 TEXT response type. It is not compatible with JSON response 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

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)

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 whether streamOptions is provided.