> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xpander.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Invoke Agent (Stream)

> Execute an agent with real-time Server-Sent Events (SSE). Reusing `id` continues the same task/thread.

Invoke an agent with real-time streaming via Server-Sent Events (SSE). Events fire as the agent works, so you can render progress, chunks, tool activity, and the final result in an interactive UI.

## Path Parameters

<ParamField path="agent_id" type="string" required>
  Agent ID (UUID)
</ParamField>

## Request Body

The request body is identical to [Invoke Agent (Sync)](/api-reference/v1/agents/invoke-sync). Only `input.text` is required.

<ParamField body="input" type="object" required>
  <Expandable title="Input Object">
    <ParamField body="text" type="string" required>
      The message or prompt to send to the agent.
    </ParamField>

    <ParamField body="files" type="string[]">
      URLs of files for the agent to process. For large files, set `disable_attachment_injection: true`.
    </ParamField>

    <ParamField body="user" type="object">
      End user identity. See [Invoke Sync docs](/api-reference/v1/agents/invoke-sync#with-user-identity) for the full `user` object schema.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="id" type="string">
  Task/thread ID for multi-turn conversations. Pass the `id` from a previous task response to continue the same conversation. Continued turns keep using that same ID.
</ParamField>

<ParamField body="disable_attachment_injection" type="boolean" default="false">
  When `true`, files in `input.files` are not injected into the LLM context window. See [Invoke Sync: Processing Files](/api-reference/v1/agents/invoke-sync#processing-files).
</ParamField>

<ParamField body="think_mode" type="string" default="default">
  `default` or `harder`. Controls reasoning depth.
</ParamField>

<ParamField body="instructions_override" type="string">
  Additional instructions appended to the system prompt for this invocation only.
</ParamField>

<ParamField body="additional_context" type="string">
  Extra context appended to the agent's system prompt **for this invocation only**. Unlike `instructions_override` (which adds behavioral instructions), this supplies supplementary facts or context the agent should consider for this run — e.g. relevant background data, the current state of an external system, or a user's recent activity.
</ParamField>

<ParamField body="expected_output" type="string">
  Natural-language description of desired output
</ParamField>

<ParamField body="llm_model_provider" type="string">
  Per-execution LLM provider override. See [Invoke Sync: Per-Execution LLM Override](/api-reference/v1/agents/invoke-sync#per-execution-llm-override).
</ParamField>

<ParamField body="llm_model_name" type="string">
  Per-execution model override. See [Invoke Sync: Per-Execution LLM Override](/api-reference/v1/agents/invoke-sync#per-execution-llm-override).
</ParamField>

<ParamField body="llm_reasoning_effort" type="string" default="medium">
  Per-execution reasoning-effort override (`low` | `medium` | `high` | `xhigh`). See [Invoke Sync: Per-Execution LLM Override](/api-reference/v1/agents/invoke-sync#per-execution-llm-override).
</ParamField>

## Query Parameters

<ParamField query="version" type="string">
  Agent version to invoke. Defaults to latest deployed. Use `"draft"` to test undeployed changes.
</ParamField>

## Response Format

Returns `Content-Type: text/event-stream`. Each SSE line is prefixed with `data: ` and contains a JSON object with this top-level shape:

```json theme={"dark"}
{
  "type": "task_created | task_updated | chunk | task_finished | ...",
  "task_id": "<task-id>",
  "organization_id": "<org-id>",
  "time": "2026-03-23T00:46:03.782693Z",
  "data": {}
}
```

For `chunk` events, `data` is a string fragment. For task lifecycle events, `data` is the task object snapshot at that moment.

<Info>
  If you continue a conversation by sending `id: "<previous-task-id>"`, the stream keeps emitting that same `task_id`. Use [Get Task](/api-reference/v1/tasks/get-task) for the latest turn state and [Get Task Thread](/api-reference/v1/tasks/get-thread) or [Get Task Thread (Full)](/api-reference/v1/tasks/get-thread-full) for the full message history.
</Info>

## Event Types

Events are emitted in this order during a typical invocation:

<ResponseField name="task_created" type="event">
  Fired immediately. Contains the task object with `status: "pending"`. This is emitted for both brand-new threads and follow-up turns on an existing task/thread ID.
</ResponseField>

<ResponseField name="task_updated" type="event">
  Fired when the task status changes, usually to `executing`. Contains the updated task object.
</ResponseField>

<ResponseField name="think" type="event">
  Agent's internal reasoning step. Contains the thought process as a string.
</ResponseField>

<ResponseField name="analyze" type="event">
  Agent's analysis step before tool selection.
</ResponseField>

<ResponseField name="tool_call_request" type="event">
  Agent is calling a tool. Contains tool name, parameters, and reasoning.
</ResponseField>

<ResponseField name="tool_call_result" type="event">
  Tool returned a result. Contains the output from the tool.
</ResponseField>

<ResponseField name="chunk" type="event">
  A piece of the agent's final response. Accumulate these to build the full result.

  ```json theme={"dark"}
  {"type": "chunk", "task_id": "...", "data": "partial response text..."}
  ```
</ResponseField>

<ResponseField name="task_finished" type="event">
  Task is done. Contains the final task object with `status`, `result`, and `finished_at`.
</ResponseField>

<ResponseField name="sub_agent_trigger" type="event">
  A sub-agent was triggered (multi-agent workflows).
</ResponseField>

<ResponseField name="plan_updated" type="event">
  Deep planning step was updated (when `deep_planning` is enabled on the agent).
</ResponseField>

<ResponseField name="auth_event" type="event">
  MCP connector requires authentication. Contains an auth URL the user must visit.
</ResponseField>

## Basic Example

```bash theme={"dark"}
curl -s --no-buffer -X POST "https://api.xpander.ai/v1/agents/<agent-id>/invoke/stream" \
  -H "Content-Type: application/json" \
  -H "x-api-key: <your-api-key>" \
  -d '{"input": {"text": "Say hello in 5 words"}}'
```

Use `--no-buffer` (or `-N`) for real-time output.

## Real Event Stream

Here's what the actual SSE output looks like from a live invocation:

```
data: {"type":"task_created","task_id":"81c63a62-96f9-47bf-818c-8a0a3e4b6ec8","organization_id":"<org-id>","time":"2026-03-23T00:46:03.782693Z","data":{"id":"81c63a62-96f9-47bf-818c-8a0a3e4b6ec8","agent_id":"<agent-id>","input":{"text":"Reply with exactly RAW","files":[]},"status":"pending","source":"api","output_format":"markdown","events_streaming":true}}

data: {"type":"task_updated","task_id":"81c63a62-96f9-47bf-818c-8a0a3e4b6ec8","organization_id":"<org-id>","time":"2026-03-23T00:46:04.419449Z","data":{"id":"81c63a62-96f9-47bf-818c-8a0a3e4b6ec8","status":"executing",...}}

data: {"type":"chunk","task_id":"81c63a62-96f9-47bf-818c-8a0a3e4b6ec8","organization_id":"<org-id>","time":"2026-03-23T00:46:06.316302Z","data":"RAW"}

data: {"type":"task_finished","task_id":"81c63a62-96f9-47bf-818c-8a0a3e4b6ec8","organization_id":"<org-id>","time":"2026-03-23T00:46:06.797966Z","data":{"id":"81c63a62-96f9-47bf-818c-8a0a3e4b6ec8","status":"completed","result":"RAW","finished_at":"2026-03-23T00:46:06.752706Z",...}}
```

## Consuming the Stream (Node.js)

```javascript theme={"dark"}
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: 'Your task here' }
    })
  }
);

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

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const lines = decoder.decode(value).split('\n');

  for (const line of lines) {
    if (!line.startsWith('data: ')) continue;

    const event = JSON.parse(line.slice(6));

    switch (event.type) {
      case 'chunk':
        // Stream text to UI as it arrives
        process.stdout.write(event.data);
        break;
      case 'tool_call_request':
        console.log(`\n[Tool: ${event.data?.tool_name}]`);
        break;
      case 'task_finished':
        console.log('\n\nDone:', event.data.result);
        break;
    }
  }
}
```

## Consuming the Stream (Python)

```python theme={"dark"}
import requests
import json

response = requests.post(
    'https://api.xpander.ai/v1/agents/<agent-id>/invoke/stream',
    json={'input': {'text': 'Your task here'}},
    headers={
        'x-api-key': '<your-api-key>',
        'Content-Type': 'application/json'
    },
    stream=True
)

for line in response.iter_lines():
    if not line:
        continue
    line = line.decode('utf-8')
    if not line.startswith('data: '):
        continue

    event = json.loads(line[6:])

    if event['type'] == 'chunk':
        print(event['data'], end='', flush=True)
    elif event['type'] == 'tool_call_request':
        print(f"\n[Calling tool: {event['data'].get('tool_name', 'unknown')}]")
    elif event['type'] == 'task_finished':
        print(f"\n\nDone. Status: {event['data']['status']}")
```

## Notes

* Use `curl --no-buffer` or `curl -N` for real-time terminal output
* The stream ends after the `task_finished` event — close the connection at that point
* `chunk` events contain raw text fragments; concatenate them for the full response
* `tool_call_request` and `tool_call_result` events let you show tool usage in your UI
* `think` and `analyze` events show the agent's reasoning (useful for debugging and transparency)
* For multi-turn conversations, wait for `task_finished` before sending the next message with the same `id`
* Reusing `id` continues the same task/thread; it does not mint a new top-level task ID for the follow-up turn
* [Get Task](/api-reference/v1/tasks/get-task) shows the latest turn state for that ID, while [Get Task Thread](/api-reference/v1/tasks/get-thread) and [Get Task Thread (Full)](/api-reference/v1/tasks/get-thread-full) show the accumulated conversation

## See Also

* [Invoke Agent (Sync)](/api-reference/v1/agents/invoke-sync) — blocks until completion
* [Invoke Agent (Async)](/api-reference/v1/agents/invoke-async) — returns task ID for polling
* [Get Thread](/api-reference/v1/tasks/get-thread) — retrieve conversation history after streaming


## OpenAPI

````yaml POST /v1/agents/{agent_id}/invoke/stream
openapi: 3.1.0
info:
  title: xpander.ai API Service
  description: |2-

        The xpander.ai API Service provides a unified REST API for managing AI agents,
        executing tasks, managing knowledge bases, and integrating with external systems.
        
        Features:
        - Agent Management: Create, update, deploy, and delete AI agents
        - Task Execution: Invoke agents with support for sync, async, and streaming modes
        - Knowledge Bases: Manage knowledge bases and documents for RAG workflows
        - Tools: Discover, connect, and attach tools (connectors, custom functions, MCP servers, sub-agents, workflows) to agents and workflows
        - MCP Integration: Model Context Protocol support for standardized AI interactions
        
        Authentication: All endpoints require authentication via either an API key (`x-api-key`) or an OAuth2 JWT (`Authorization: Bearer <jwt>`).
        
  version: '0.001'
servers:
  - url: https://api.xpander.ai
security: []
paths:
  /v1/agents/{agent_id}/invoke/stream:
    post:
      tags:
        - API v1
        - Agents
        - Agents Invocation
      summary: Invoke Agent (Stream)
      description: >-
        Invoke an AI agent with real-time streaming. Returns Server-Sent Events
        (SSE) for live task updates.
      operationId: Invoke_Agent__Stream__v1_agents__agent_id__invoke_stream_post
      parameters:
        - name: agent_id
          in: path
          required: true
          schema:
            type: string
            title: Agent Id
        - name: version
          in: query
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            description: The agent/workflow version to invoke. default = latest
            title: Version
          description: The agent/workflow version to invoke. default = latest
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentExecutionRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - APIKeyHeader: []
components:
  schemas:
    AgentExecutionRequest:
      properties:
        input:
          $ref: '#/components/schemas/AgentExecutionInput-Input'
        id:
          anyOf:
            - type: string
            - type: 'null'
          title: Id
        payload_extension:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Payload Extension
        parent_execution_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Parent Execution Id
        worker_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Worker Id
        source:
          anyOf:
            - type: string
            - type: 'null'
          title: Source
        output_format:
          anyOf:
            - $ref: '#/components/schemas/OutputFormat'
            - type: 'null'
        output_schema:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Output Schema
        run_locally:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Run Locally
          default: false
        additional_context:
          anyOf:
            - type: string
            - type: 'null'
          title: Additional Context
        instructions_override:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions Override
        test_run_node_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Test Run Node Id
        expected_output:
          anyOf:
            - type: string
            - type: 'null'
          title: Expected Output
        events_streaming:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Events Streaming
          default: false
        mcp_servers:
          anyOf:
            - items:
                additionalProperties: true
                type: object
              type: array
            - type: 'null'
          title: Mcp Servers
          default: []
        triggering_agent_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Triggering Agent Id
        title:
          anyOf:
            - type: string
            - type: 'null'
          title: Title
        think_mode:
          anyOf:
            - $ref: '#/components/schemas/ThinkMode'
            - type: 'null'
          default: default
        disable_attachment_injection:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Disable Attachment Injection
          default: false
        user_tokens:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: User Tokens
        user_oidc_token:
          anyOf:
            - type: string
            - type: 'null'
          title: User Oidc Token
        return_metrics:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Return Metrics
          default: false
        llm_model_provider:
          anyOf:
            - type: string
            - type: 'null'
          title: Llm Model Provider
          description: >-
            Per-execution override for the LLM provider (e.g. 'openai',
            'anthropic'). Falls back to the agent's configured provider when
            unset.
        llm_model_name:
          anyOf:
            - type: string
            - type: 'null'
          title: Llm Model Name
          description: >-
            Per-execution override for the LLM model name. Falls back to the
            agent's configured model when unset.
        llm_reasoning_effort:
          anyOf:
            - $ref: '#/components/schemas/LLMReasoningEffort'
            - type: 'null'
          description: >-
            Per-execution override for reasoning effort on reasoning-capable
            models.
        source_node_type:
          anyOf:
            - $ref: '#/components/schemas/SourceNodeType'
            - type: 'null'
          description: >-
            Surface that created this execution (mirrored to
            AgentExecutionHistory.source_node_type). Falls back to
            SourceNodeType.SDK at persist time when unset.
      type: object
      required:
        - input
      title: AgentExecutionRequest
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    AgentExecutionInput-Input:
      properties:
        text:
          anyOf:
            - type: string
            - type: 'null'
          title: Text
          default: ''
        files:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Files
          default: []
        user:
          anyOf:
            - $ref: '#/components/schemas/User-Input'
            - type: 'null'
      type: object
      title: AgentExecutionInput
    OutputFormat:
      type: string
      enum:
        - text
        - markdown
        - json
        - voice
      title: OutputFormat
    ThinkMode:
      type: string
      enum:
        - default
        - harder
      title: ThinkMode
    LLMReasoningEffort:
      type: string
      enum:
        - low
        - medium
        - high
        - xhigh
      title: LLMReasoningEffort
    SourceNodeType:
      type: string
      enum:
        - workbench
        - sdk
        - task
        - assistant
        - webhook
        - mcp
        - a2a
        - telegram
        - slack
      title: SourceNodeType
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    User-Input:
      properties:
        id:
          anyOf:
            - type: string
            - type: 'null'
          title: Id
        first_name:
          anyOf:
            - type: string
            - type: 'null'
          title: First Name
        last_name:
          anyOf:
            - type: string
            - type: 'null'
          title: Last Name
        email:
          type: string
          title: Email
        additional_attributes:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Additional Attributes
        role:
          anyOf:
            - type: string
            - type: 'null'
          title: Role
          default: member
        is_super_admin:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Is Super Admin
          default: false
        timezone:
          anyOf:
            - type: string
            - type: 'null'
          title: Timezone
      type: object
      required:
        - email
      title: User
      description: |-
        Represents the details of a user.

        Attributes:
            id (Optional[str]): The unique identifier of the user. Defaults to None.
            first_name (Optional[str]): The first name of the user. Defaults to None.
            last_name (Optional[str]): The last name of the user. Defaults to None.
            email (str): The email address of the user. This field is required.
            additional_attributes (Optional[dict]): Possible additional parameters for the assistant's service.
            role (Optional[str]): The user's role in the organization. Defaults to "member".
            is_super_admin (Optional[bool]): Whether the user is a super admin. Defaults to False.
            timezone (Optional[str]): The user's timezone in IANA format (e.g. "America/New_York"). Defaults to None.
  securitySchemes:
    APIKeyHeader:
      type: apiKey
      description: API Key for authentication
      in: header
      name: x-api-key

````