Skip to main content
POST
/
v1
/
agents
/
{agent_id}
/
invoke
/
stream
Invoke Agent (Stream)
curl --request POST \
  --url https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '
{
  "input": {
    "text": "",
    "files": [],
    "user": {
      "email": "<string>",
      "id": "<string>",
      "first_name": "<string>",
      "last_name": "<string>",
      "additional_attributes": {}
    }
  },
  "id": "<string>",
  "payload_extension": {},
  "parent_execution_id": "<string>",
  "worker_id": "<string>",
  "source": "<string>",
  "output_format": "text",
  "output_schema": {},
  "run_locally": false,
  "additional_context": "<string>",
  "expected_output": "<string>",
  "events_streaming": false,
  "mcp_servers": [],
  "triggering_agent_id": "<string>",
  "title": "<string>",
  "think_mode": "default",
  "disable_attachment_injection": false
}
'
{
  "detail": [
    {
      "loc": [
        "<string>"
      ],
      "msg": "<string>",
      "type": "<string>"
    }
  ]
}
Execute an agent task with real-time streaming responses. This endpoint returns Server-Sent Events (SSE) that provide live updates as the agent processes the task. Perfect for interactive applications and real-time user interfaces.

Path Parameters

agent_id
string
required
Unique identifier of the agent to invoke (UUID format)

Request Body

input
object
required
Agent execution input containing the task details
output_format
string
Desired output format. Valid values: text | json | markdownDefault: text
  • text: Plain text response
  • json: Structured JSON output (use with output_schema for validation)
  • markdown: Formatted markdown response
output_schema
object
JSON Schema to validate and structure the agent’s output. When provided with output_format: "json", the agent will return data conforming to this schema.Example:
{
  "type": "object",
  "required": ["summary", "insights"],
  "properties": {
    "summary": {"type": "string"},
    "insights": {"type": "array", "items": {"type": "string"}}
  }
}
events_streaming
boolean
Enable detailed event streaming for granular progress tracking. When true, emits events for tool calls, intermediate steps, and execution progress.Default: falseRecommended: Set to true for this endpoint to get maximum visibility into agent execution.
additional_context
string
Additional context to guide the agent’s behavior. Use this to specify tone, audience, constraints, or background information.Example: "This is for executive leadership. Use professional tone and focus on business impact."
expected_output
string
Description of the expected output format, length, or structure. Helps guide the agent to produce the desired result.Example: "A 500-word summary with 3 key recommendations and supporting data."
title
string
Human-readable title for the task. Useful for identification and organization in task lists.Example: "Real-time Data Analysis"
parent_execution_id
string
UUID of the parent task if this is a sub-task. Used for multi-agent workflows and task hierarchies.Example: "550e8400-e29b-41d4-a716-446655440000"
triggering_agent_id
string
UUID of the agent that triggered this task. Used for tracking agent-to-agent delegation.Example: "7c9e6679-7425-40de-944b-e07fc1f90ae7"
payload_extension
object
Custom metadata to attach to the task. Any valid JSON object. Useful for tracking, routing, or application-specific data.Example:
{
  "request_id": "REQ-2025-001",
  "priority": "high",
  "stream_session_id": "stream-789"
}
mcp_servers
array
Array of Model Context Protocol (MCP) server configurations to use during execution. Enables integration with external tools and services.Example:
[
  {
    "name": "real-time-data",
    "config": {"refresh_interval": 5}
  }
]
source
string
Identifier for the source system or application that created this task. Useful for analytics and debugging.Example: "chat-widget" | "mobile-app" | "websocket-client"
user_tokens
object
User-specific authentication tokens for MCP servers with OAuth authentication. Allows passing pre-authenticated tokens to bypass the interactive OAuth flow during agent execution.The object maps MCP graph item IDs to their corresponding access tokens. To get the graph item IDs for your agent’s MCP servers, use the Get Agent endpoint and inspect the graph.items array for items with type: "mcp".Example:
{
  "mcp-graph-item-uuid-1": "user-access-token-abc123",
  "mcp-graph-item-uuid-2": "user-access-token-xyz789"
}
When to use: If your agent uses MCP servers with OAuth authentication, you can pre-authenticate users through your own OAuth flow and pass their tokens here to avoid the interactive login prompt during execution.
id
string
Thread ID for conversation context. This ID is critical for multi-turn conversations:
  • If not provided: A UUID will be automatically generated (recommended for single-turn requests)
  • First message in conversation: Provide a unique UUID and save it for subsequent messages
  • Follow-up messages: Use the same id from the first request to maintain conversation history
  • The agent will remember all previous messages in the thread when you reuse the same ID
Example: "a37db9a1-e483-4544-9136-b32120ae8c81"
Multi-Turn Conversations: To enable the agent to remember previous messages, always use the same id for all requests in a conversation thread. Each unique id represents a separate conversation session. The response will include the same id (whether you provided it or it was auto-generated).

Example Requests

Basic Streaming Request

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Write a story about AI"
       }
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

With Detailed Event Streaming

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Research AI trends and create a report"
       },
       "events_streaming": true,
       "title": "AI Trends Research"
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

File Processing with Progress Tracking

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Analyze these documents",
         "files": [
           "https://example.com/report1.pdf",
           "https://example.com/report2.pdf"
         ]
       },
       "events_streaming": true,
       "output_format": "markdown",
       "additional_context": "Focus on key metrics and trends"
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

Structured Output with Streaming

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Extract insights from customer feedback"
       },
       "output_format": "json",
       "output_schema": {
         "type": "object",
         "properties": {
           "sentiment": {"type": "string"},
           "themes": {"type": "array", "items": {"type": "string"}},
           "recommendations": {"type": "array", "items": {"type": "string"}}
         }
       },
       "events_streaming": true
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

With MCP OAuth Authentication (user_tokens)

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Get my latest Gmail messages and summarize",
         "user": {
           "id": "user-789",
           "email": "user@example.com"
         }
       },
       "user_tokens": {
         "mcp-graph-item-uuid-gmail": "ya29.a0AfH6SMBx...",
         "mcp-graph-item-uuid-calendar": "ya29.a0AfH6SMBy..."
       },
       "events_streaming": true
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream
How to get MCP graph item IDs: Call GET /v1/agents/ and inspect graph.items for entries with type: "mcp".

Multi-Turn Conversation (Streaming)

# First message - creates a new conversation thread
curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "My favorite color is blue"
       },
       "id": "stream-thread-789",
       "events_streaming": true
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

# Follow-up message in the same thread
curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "What is my favorite color?"
       },
       "id": "stream-thread-789",
       "events_streaming": true
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream
# Agent will stream response: "Your favorite color is blue"

# Another follow-up with conversation history
curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "How many messages have I sent in this thread?"
       },
       "id": "stream-thread-789",
       "events_streaming": true
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream
# Agent will respond based on complete conversation history

Response Format

This endpoint returns Server-Sent Events (SSE) with Content-Type: text/event-stream

Event Stream Format

Events are sent in SSE format:
data: {"type": "task_started", "task_id": "...", "timestamp": "..."}

data: {"type": "content_chunk", "content": "...", "is_final": false}

data: {"type": "task_completed", "task_id": "...", "result": "..."}

Event Types

task_started
event
Sent when the task begins execution
content_chunk
event
Sent for each piece of generated content
task_completed
event
Sent when the task finishes successfully
error
event
Sent if an error occurs during execution

Example: JavaScript Client

const response = await fetch('https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream', {
  method: 'POST',
  headers: {
    'x-api-key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    input: {
      text: 'Analyze this data',
      files: []
    },
    events_streaming: true
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value);
  const lines = chunk.split('\n');
  
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const event = JSON.parse(line.slice(6));
      console.log('Event:', event);
      
      if (event.type === 'task_completed') {
        console.log('Result:', event.result);
      }
    }
  }
}

Notes

  • The agent must have deployment_type: serverless or be a running container
  • Connection stays open until task completes or errors
  • Set appropriate timeout values for long-running tasks
  • Handle connection errors and implement retry logic
  • Multi-Turn Conversations: Use the same id parameter across requests to maintain conversation context. The agent will remember all previous messages in the thread and stream responses with full context awareness.

See Also

  • [Invoke Agent (Sync)](/API reference/v1/agents/invoke-sync) - For quick tasks with immediate results
  • [Invoke Agent (Async)](/API reference/v1/agents/invoke-async) - For long-running tasks with polling
  • [Get Task](/API reference/v1/tasks/get-task) - Retrieve task details after streaming completes
  • [Get Task Thread](/API reference/v1/tasks/get-thread) - View complete conversation history for a thread
  • Agent Memory - Configure how agents store and recall conversation history

Authorizations

x-api-key
string
header
required

API Key for authentication

Path Parameters

agent_id
string
required

Body

application/json
input
AgentExecutionInput · object
required
id
string | null
payload_extension
Payload Extension · object
parent_execution_id
string | null
worker_id
string | null
source
string | null
output_format
enum<string> | null
default:text
Available options:
text,
markdown,
json
output_schema
Output Schema · object
run_locally
boolean | null
default:false
additional_context
string | null
expected_output
string | null
events_streaming
boolean | null
default:false
mcp_servers
Mcp Servers · object[] | null
triggering_agent_id
string | null
title
string | null
think_mode
enum<string> | null
default:default
Available options:
default,
harder
disable_attachment_injection
boolean | null
default:false

Response

Successful Response