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

# Streaming Responses

> Real-time streaming responses for immediate agent feedback

> [!NOTE]
>
> Streaming is enabled by setting `"streaming_on": true` in your agent configuration.

## Quick Start

Enable streaming by adding the `streaming_on` parameter to your agent configuration:

> [tab] Python
>
> ```python theme={null}
> import requests
> import json
> import os
> from dotenv import load_dotenv
>
> load_dotenv()
>
> API_KEY = os.getenv("SWARMS_API_KEY")
> BASE_URL = "https://api.swarms.world"
>
> headers = {
>     "x-api-key": API_KEY,
>     "Content-Type": "application/json",
>     "Connection": "keep-alive",
>     "X-Accel-Buffering": "no"
> }
>
> payload = {
>     "agent_config": {
>         "agent_name": "Creative Writer",
>         "description": "A creative writing specialist",
>         "system_prompt": "You are a creative writer who specializes in storytelling.",
>         "model_name": "gpt-4.1-mini",
>         "max_tokens": 2048,
>         "temperature": 0.8,
>         "streaming_on": True
>     },
>     "task": "Write a short story about a robot learning to paint"
> }
>
> response = requests.post(
>     f"{BASE_URL}/v1/agent/completions",
>     headers=headers,
>     json=payload,
>     stream=True
> )
>
> # Process the streaming response
> for line in response.iter_lines():
>     if line:
>         line = line.decode('utf-8')
>         if line.startswith('data: '):
>             try:
>                 data = json.loads(line[6:])
>                 if 'content' in data:
>                     print(data['content'], end='', flush=True)
>             except json.JSONDecodeError:
>                 continue
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> const API_KEY = process.env.SWARMS_API_KEY;
> const BASE_URL = "https://api.swarms.world";
>
> const headers = {
>     "x-api-key": API_KEY,
>     "Content-Type": "application/json",
>     "Connection": "keep-alive",
>     "X-Accel-Buffering": "no"
> };
>
> const payload = {
>     agent_config: {
>         agent_name: "Creative Writer",
>         description: "A creative writing specialist",
>         system_prompt: "You are a creative writer who specializes in storytelling.",
>         model_name: "gpt-4.1-mini",
>         max_tokens: 2048,
>         temperature: 0.8,
>         streaming_on: true
>     },
>     task: "Write a short story about a robot learning to paint"
> };
>
> fetch(`${BASE_URL}/v1/agent/completions`, {
>     method: 'POST',
>     headers: headers,
>     body: JSON.stringify(payload)
> })
> .then(response => {
>     const reader = response.body.getReader();
>     const decoder = new TextDecoder();
>
>     function readStream() {
>         reader.read().then(({ done, value }) => {
>             if (done) return;
>
>             const chunk = decoder.decode(value);
>             const lines = chunk.split('\n');
>
>             for (const line of lines) {
>                 if (line.startsWith('data: ')) {
>                     try {
>                         const data = JSON.parse(line.substring(6));
>                         if (data.content) {
>                             process.stdout.write(data.content);
>                         }
>                     } catch (e) {
>                         // Skip malformed JSON
>                     }
>                 }
>             }
>
>             readStream();
>         });
>     }
>
>     readStream();
> });
> ```

> [tab] cURL
>
> ```bash theme={null}
> curl -X POST "https://api.swarms.world/v1/agent/completions" \
>   -H "x-api-key: your-api-key" \
>   -H "Content-Type: application/json" \
>   -H "Connection: keep-alive" \
>   -H "X-Accel-Buffering: no" \
>   -d '{
>     "agent_config": {
>       "agent_name": "Creative Writer",
>       "model_name": "gpt-4.1-mini",
>       "max_tokens": 2048,
>       "temperature": 0.8,
>       "streaming_on": true
>     },
>     "task": "Write a short story about a robot learning to paint"
>   }' \
>   --no-buffer -N
> ```

## Advanced Configuration

For more complex streaming scenarios, you can customize the agent configuration:

## Stream Format

The API returns data in Server-Sent Events (SSE) format:

```
data: {"job_id": "abc123", "success": true, "name": "Creative Writer", "description": "A creative writing specialist", "temperature": 0.8, "timestamp": "2026-02-05T00:58:15.121915+00:00", "stream": true, "type": "metadata"}

event: start
data: {"message": "Starting agent processing..."}

event: chunk
data: {"content": "Once upon a time", "timestamp": "2026-02-05T00:58:15.200000+00:00"}

event: chunk
data: {"content": ", in a workshop filled with", "timestamp": "2026-02-05T00:58:15.250000+00:00"}

event: usage
data: {"input_tokens": 45, "output_tokens": 120, "total_tokens": 165, "image_count": 0, "img_cost": 0.0, "flash_sale_applied": false, "total_cost": 0.000241}

event: end
data: {"job_id": "abc123", "usage": {"input_tokens": 45, "output_tokens": 120, "total_tokens": 165, "image_count": 0, "img_cost": 0.0, "flash_sale_applied": false, "total_cost": 0.000241}, "timestamp": "2026-02-05T00:58:16.000000+00:00", "complete": true}

event: done
data: {"message": "Agent processing complete"}
```

> [!NOTE]
>
> The first frame (initial metadata) is sent without an `event:` line, so it arrives as a default `message` event. Only `content` chunks include the `content` key, which is what the example consumer code above checks for.

### Errors

The HTTP status (`200`) is sent when the stream opens, so a failed run is reported inside the stream: a single `event: error` frame, with no `usage`, `end` or `done` events after it. This includes request validation that runs after the stream has opened, such as an unknown model, a premium model on a free-tier key, or a missing `task`.

```
event: start
data: {"message": "Starting agent processing..."}

event: error
data: {"error": "The provider rejected the request for model 'gpt-5.4': <provider reason>. Nothing was charged.", "status_code": 400, "timestamp": "2026-02-05T00:58:15.300000+00:00"}
```

When the model provider fails the call, the frame carries the `status_code` the non-streaming request would have returned (400, 404, 429 or 502) and nothing is charged. Any other failure sends `{"error": "AgentCompletionError: <status>: <detail>", "timestamp": "..."}`. Watch for the `error` event in your consumer instead of relying on the HTTP status. See [Error Handling](https://docs.swarms.ai/docs/documentation/capabilities/agent.md#error-handling) for the status codes.

## Key Benefits

* **Real-time Feedback**: See results as they're generated
* **Better User Experience**: Reduced perceived latency
* **Progress Tracking**: Monitor long-running operations
* **Immediate Error Detection**: Catch issues early in the process

## Use Cases

* **Creative Writing**: Generate stories, articles, or content with live updates
* **Data Analysis**: Process large datasets with streaming insights
* **Research Tasks**: Get research findings as they're discovered
* **Code Generation**: See code being written in real-time
* **Educational Content**: Create interactive learning experiences


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.