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

# Connect a Streaming Agent

> Connect an agent that streams its reply (SSE, NDJSON or WebSocket) to Galtea with an Endpoint Connection, map the answer, the retrieved context and the conversation id, and test it.

> [!WARNING]
>
> You are reading the docs of Galtea 5.23. [Read this page in the latest version](https://docs.galtea.ai/sdk/tutorials/connect-a-streaming-agent.md).

Many agents send their answer piece by piece as they write it, instead of one JSON body at the end. This guide takes such an agent from "it streams" to a tested [Endpoint Connection](https://docs.galtea.ai/v5.23/concepts/product/endpoint-connection.md). It starts from your stack, not from Galtea terms, and ends with a working Output Mapping for the answer, the retrieved context and the conversation id.

> [!NOTE]
>
> This guide uses the Dashboard. To create the same connection in code, see the [SDK streaming example](https://docs.galtea.ai/v5.23/sdk/api/endpoint-connection/create.md#streaming-example) or the request body in the [REST API reference](https://docs.galtea.ai/v5.23/api-reference/endpoint-connections/create-endpoint-connection.md), which the CLI sends too. Every field is listed in [Streamed Replies](https://docs.galtea.ai/v5.23/concepts/product/endpoint-connection-configuration.md#streamed-replies).

## Prerequisites

* A [Product](https://docs.galtea.ai/v5.23/concepts/product.md) in the [Galtea Dashboard](https://platform.galtea.ai/).
* The URL of your agent, and a way to call it with `curl`.
* The basics of an Endpoint Connection. If you have never made one, read [Direct Inferences and Evaluations from the Platform](https://docs.galtea.ai/v5.23/sdk/tutorials/direct-inferences-and-evaluations-from-platform.md) first.

## Does Your Agent Stream?

Call your agent once with `curl`. The `-N` flag prints each piece as it arrives, and `-i` shows the response headers:

```bash theme={"system"}
curl -N -i https://agent.example.com/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello"}'
```

Look at the `Content-Type` header of the response:

| `Content-Type` | What it is | Reply in Galtea |
| - | - | - |
| `text/event-stream` | Server-Sent Events (SSE): lines that start with `event:` and `data:` | **Streamed reply**, format SSE |
| `application/x-ndjson` | One JSON value per line | **Streamed reply**, format NDJSON |
| `application/json` | One JSON body | **JSON reply**. You do not need this guide |

The header only helps you choose. Galtea reads the stream with the **Format** you set, whatever the header says. Some servers send NDJSON as `text/plain`: pick NDJSON when each line is one JSON value.

If your agent's URL starts with `wss://`, it answers over a WebSocket. Pick format **WebSocket** and see [Example 3](#example-3-a-websocket-agent).

Most agent stacks stream when you ask them to: the OpenAI and Anthropic APIs with `"stream": true`, a Google ADK server at `/run_sse`, and a Vercel AI SDK route that returns a UI message stream. If your agent can answer both ways, a JSON reply is the simpler choice. Pick streaming when the stream is the only way your agent answers, or when you want to test the exact endpoint your users call.

## How Galtea Reads a Stream

Galtea reads the whole stream and turns it into **one object**. Your Output Mapping then reads that object with JSONPath, the same way it reads a JSON reply.

Take this invented stream. An in-house agent opens a conversation, sends its answer in two pieces, lists the passages it used, and ends:

```text Stream theme={"system"}
event: conversation.started
data: {"conversation_id":"conv_9b21"}

event: delta
data: {"text":"You can return "}

event: delta
data: {"text":"an item within 30 days."}

event: sources
data: {"items":[{"content":"Returns are accepted within 30 days of delivery."}]}

event: done
data: {"finish_reason":"stop"}
```

With the settings of [Example 2](#example-2-custom-settings), Galtea builds this object:

```json Assembled object theme={"system"}
{
  "text": "You can return an item within 30 days.",
  "byEvent": {
    "conversation.started": [{ "conversation_id": "conv_9b21" }],
    "delta": [{ "text": "You can return " }, { "text": "an item within 30 days." }],
    "sources": [{ "items": [{ "content": "Returns are accepted within 30 days of delivery." }] }],
    "done": [{ "finish_reason": "stop" }]
  },
  "final": { "finish_reason": "stop" },
  "json": null
}
```

* **`text`** is the answer: the text of the chunks that give text, joined. In **Last** mode it is the text of the last such chunk. When the text path of a chunk finds a list of strings, such as `$.content.parts[*].text`, Galtea joins them in order.
* **`byEvent`** keeps every chunk, grouped by its event name, in the order they came. It is a list for each event, so `[0]` is the first chunk of that event.
* **`final`** is the last chunk whose data is a JSON object or list. Agents often put the conversation id or a summary there.
* **`json`** is `text` parsed, when the answer is one JSON object or list. It is `null` here, because this answer is plain text. See [Structured Replies](#structured-replies).

## Example 1: A Preset

A preset fills every stream setting for a known agent stack. This example uses an agent built on the OpenAI Responses API, for example with the OpenAI Agents SDK, that forwards its stream events. The agent also adds one event of its own, `retrieval.results`, with the passages it found.

```text Stream theme={"system"}
event: response.created
data: {"type":"response.created","response":{"id":"resp_7f3a","status":"in_progress"}}

event: retrieval.results
data: {"type":"retrieval.results","results":[{"content":"Orders ship within 2 business days."},{"content":"Express orders ship the same day."}]}

event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":"Your order ships "}

event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":"within 2 business days."}

event: response.completed
data: {"type":"response.completed","response":{"id":"resp_7f3a","status":"completed"}}
```

**1. Choose the reply type and the preset**

In the connection form, set **Reply type** to **Streamed reply**. In **Preset**, choose **OpenAI Responses API**. Open **What this preset sets** to see its settings: it names each event from the `type` field and takes text only from `response.output_text.delta` events.

On a Conversation connection, the form also sets the Output Mapping to `output: $.text` when it still holds the default.

**2. Map the answer, the retrieved context and the conversation id**

Galtea builds this object from the stream:

```json Assembled object theme={"system"}
{
  "text": "Your order ships within 2 business days.",
  "byEvent": {
    "response.created": [{ "type": "response.created", "response": { "id": "resp_7f3a", "status": "in_progress" } }],
    "retrieval.results": [{ "type": "retrieval.results", "results": [{ "content": "Orders ship within 2 business days." }, { "content": "Express orders ship the same day." }] }],
    "response.output_text.delta": [{ "type": "response.output_text.delta", "delta": "Your order ships " }, { "type": "response.output_text.delta", "delta": "within 2 business days." }],
    "response.completed": [{ "type": "response.completed", "response": { "id": "resp_7f3a", "status": "completed" } }]
  },
  "final": { "type": "response.completed", "response": { "id": "resp_7f3a", "status": "completed" } },
  "json": null
}
```

Add two keys next to `output`:

```json Output Mapping theme={"system"}
{
  "output": "$.text",
  "retrieval_context": "$.byEvent['retrieval.results'][0].results[*].content",
  "session_id": "$.final.response.id"
}
```

The event name `retrieval.results` has a dot, so the path uses the bracket form. See [The Conversation Id](#the-conversation-id).

**3. Send the id back on the next turn**

On the first turn there is no id yet, so send it only when it exists:

```jinja2 Input Template theme={"system"}
{"message": "{{ input.user_message }}"{% if session_id %}, "previous_response_id": "{{ session_id }}"{% endif %}}
```

![Endpoint connection form with Streamed reply selected and the OpenAI Responses API preset](https://mintcdn.com/galtea/ge9MNq6xCisiT3m3/images/guides/stream-reply-preset.png?fit=max\&auto=format\&n=ge9MNq6xCisiT3m3\&q=85\&s=f3aae208099d069827ad4712566294eb)

> [!TIP]
>
> The `retrieval_context` key is an explicit input: Galtea stores it as a retriever span on the trace, so RAG metrics can read it. No preset maps it for you, because each agent sends its sources in its own way. See [Stream Presets](https://docs.galtea.ai/v5.23/concepts/product/endpoint-connection-configuration.md#stream-presets) for the Output Mapping to start from for each preset.

## Example 2: Custom Settings

Use **Custom** when no preset matches your agent. This example reads the in-house stream from [How Galtea Reads a Stream](#how-galtea-reads-a-stream).

**1. Set the stream settings**

Set **Reply type** to **Streamed reply** and **Preset** to **Custom**. Then fill in:

| Field | Value | Why |
| - | - | - |
| **Format** | SSE | The agent sends `event:` and `data:` lines. |
| **Text path** | `$.text` | Each answer chunk holds its text in `text`. |
| **Mode** | Append | Each chunk holds a new piece of the answer. Use **Last** when each chunk resends the whole answer so far. |

Open **More options**:

| Field | Value | Why |
| - | - | - |
| **Event field** | *(empty)* | The agent names each event on its SSE `event:` line. Set a JSONPath such as `$.type` when the name is inside the data, which is always the case for NDJSON. |
| **End marker** | `done` | Galtea stops reading at this event, even if the connection stays open. Leave it empty to read until the stream closes. |
| **Text event** | `delta` | Only `delta` chunks add text. Set it when other events could hold a field at the same path. |
| **Error event** | *(empty)* | This agent sends no error event. Set the event name when your agent reports a failure in its stream, such as `error`: that event fails the turn with its data. |

When you switch to **Custom** from a preset, the form keeps that preset's settings as a start. Clear the ones your agent does not need. This includes **Error event**: clear it if your agent never sends that event.

**2. Map the fields**

```json Output Mapping theme={"system"}
{
  "output": "$.text",
  "retrieval_context": "$.byEvent.sources[0].items[*].content",
  "session_id": "$.byEvent['conversation.started'][0].conversation_id"
}
```

**3. Send the id back on the next turn**

```jinja2 Input Template theme={"system"}
{"message": "{{ input.user_message }}"{% if session_id %}, "conversation_id": "{{ session_id }}"{% endif %}}
```

![Endpoint connection form with the Custom preset: format SSE, text path \$.text, mode Append, and under More options the end marker done, the text event delta and an empty error event](https://mintcdn.com/galtea/RoPOOY6-3PSnsStr/images/guides/stream-reply-custom.png?fit=max\&auto=format\&n=RoPOOY6-3PSnsStr\&q=85\&s=576db447688ef55ad1f9c4408b4f8524)

## Example 3: A WebSocket Agent

A WebSocket agent gets the question as one message and answers in several messages on the same socket. It keeps the socket open for the next question, so Galtea needs a rule that tells it when the answer is complete.

**1. Set the URL and the format**

Enter the `wss://` URL of your agent. Set **Reply type** to **Streamed reply**, **Format** to **WebSocket** and **Preset** to **Custom**. Galtea sends the rendered Input Template as one text message, and the headers on the opening request.

**2. Read the messages**

Each message is one chunk. A JSON message is read as JSON, and any other message as plain text. For an agent that sends `{"delta": "..."}` pieces:

| Field | Value | Why |
| - | - | - |
| **Text path** | `$.delta` | Each message holds a new piece of the answer in `delta`. Use `$` for plain text messages. |
| **Mode** | Append | Each message adds to the answer. |

**3. Tell Galtea when the answer ends**

Set one or both of these fields. They sit next to each other, outside **More options**:

| Field | Value | Why |
| - | - | - |
| **End marker** | `done` | Set it when your agent sends a last message, such as `{"type": "done"}`, with **Event field** `$.type`. |
| **Quiet period (seconds)** | `2` | The answer ends after this many seconds with no message, from 1 to 30. Set it when your agent sends no last message. |

The quiet period starts at the first message that gives text, so a slow first token is never cut, even after an acknowledgement message. Before the first text, only the idle timeout and the connection timeout apply. Pick a quiet period longer than the longest pause inside one answer, such as a tool call. A pause inside the reply that is longer than the quiet period ends the reply there with no warning, so set an end marker when your agent sends one. If your agent sends heartbeat messages during a reply, or can answer with no text, set an End marker: each message restarts the quiet period.

Galtea opens a new socket for each turn and closes it when the answer ends. An agent that keeps the conversation state only on the socket starts a new conversation on every turn. Sending the conversation id helps only when your agent can resume its state from that id on a new socket. Return the id in a message and send it back on the next turn, as in the [next section](#the-conversation-id). The close codes and limits are in [WebSocket Agents](https://docs.galtea.ai/v5.23/concepts/product/endpoint-connection-configuration.md#websocket-agents).

## The Conversation Id

Most agents keep a conversation by an id: a thread id, a session id, a response id. Galtea stores the id your agent returns and sends it back on the next turn as `{{ session_id }}`. The form fills only `output: $.text`, and only on a Conversation connection, so add the `session_id` key yourself.

Find the chunk that carries the id in your stream, then pick where to read it:

* **`$.byEvent['<event>'][0].<path>`** when one event names the id, often the first one. Example 2 reads `$.byEvent['conversation.started'][0].conversation_id`.
* **`$.final.<path>`** when the last event carries it. Example 1 reads `$.final.response.id`.

Some agents send the id only on the first turn. On a later turn the path finds nothing, and Galtea keeps the id it stored. The `{% if session_id %}` branch in the Input Template covers the first turn, when Galtea has no id yet.

> [!WARNING]
>
> An event name with a dot needs the bracket form. Most vendor events have one, such as `response.completed` or `thread.created`.
>
> * Right: `$.byEvent['conversation.started'][0].conversation_id`
> * Wrong: `$.byEvent.conversation.started[0].conversation_id` reads an event `conversation` with a field `started`. It matches nothing, and no error tells you.
>
> The bracket form works for every event name, so use it when you are not sure.

## Structured Replies

Some agents answer with one JSON object, sent as text in small pieces. Agents built on structured output do this, and so do agents that answer through a tool call. Galtea joins the pieces into `text`, then parses that text once, at the end of the stream, into `json`. The output mapping then reads each field of the answer.

Take an agent whose joined text is this invented answer:

```json Joined text theme={"system"}
{"answer": "You can return an item within 30 days.", "sources": [{"content": "Returns are accepted within 30 days of delivery."}]}
```

Map the answer and its sources from `json`:

```json Output Mapping theme={"system"}
{
  "output": "$.json.answer",
  "retrieval_context": "$.json.sources[*].content"
}
```

The text path is the same as for a plain answer: the path of each text piece, such as `$.delta` or the argument pieces of a tool call. `json` is `null` when the text is not one JSON object or list, when the stream is cut before its End marker, when the value is nested deeper than 32 levels, and when its parse does not fit the stream size limit. A path into a `null` `json` matches nothing, like any path that finds no value.

## Files in a Stream

`output_files` reads the assembled object too. Map it to a file in one event, as a URL or as base64, for example `$.byEvent.file[0]` or `$.final.files`. A file that comes in several text pieces is read from the joined text or from `json`, for example `$.json.files`. In `text`, send the file as a `data:` URI: a bare base64 string there is refused. Raw Response then shows the bytes once, as a short `<base64, size>` mark. If your agent's JSON encoder escapes `/` or `+` in the base64, the bytes also stay visible in `text`.

## Test the Connection

Click **Test Connection** at the bottom of the form. Galtea calls your agent with sample values, reads the stream as a real turn would, and shows two tabs:

* **Raw Response** shows the assembled object. `byEvent` starts closed: open it to see each event and to copy the paths you need.
* **Extracted Fields** shows the value of each Output Mapping key. A required key that matched nothing says "Required — no value extracted. Check your JSONPath expression."

When the stream closes before its End marker, the test shows the text that came, with the mark "The streamed reply closed before its terminal event, so this output is partial". In a run, the turn keeps that text and shows a warning mark with the same message. See [the troubleshooting row](#troubleshooting) for a cut stream.

Test Connection reads at most 1 MB of the reply. A very long sample answer can fail the test and still work in a run.

> [!NOTE]
>
> Test Connection sends a random `session_id`, so the `{% if session_id %}` branch of your Input Template is taken, and your agent receives an id it does not know. In a run, the first turn has no id, and the health check before a run sends no id either, until a step returns one. If your agent rejects an unknown id, test with a template that leaves the id out, then put it back.

## Troubleshooting

| Symptom | Error text | Fix |
| - | - | - |
| The turn fails after a pause | `The streamed reply sent nothing for 60 seconds (idle timeout)` | Your agent went silent after it started, for example during a long tool call. Send an SSE comment line such as `: keep-alive` while it works. A WebSocket agent sends a ping frame or a message instead; a ping or a pong restarts the idle timeout, until the first text starts the quiet period. 60 seconds is the default; a self-hosted deployment can change it with `ENDPOINT_STREAM_IDLE_TIMEOUT_SECONDS`. With retry on, the turn is retried. |
| The turn fails with your agent's error | `The streamed reply sent an error event "<name>": <data>` | Your agent reported a failure in its stream. Read the data and fix the agent. Galtea fails a turn on this event only when the connection names it in `streamAssembly.errorEvent` (SDK: `error_event`). The OpenAI ChatKit, OpenAI Responses API, Anthropic Messages API and Vercel AI SDK presets name `error` for you. With Custom settings, set it in **Error event** under **More options**. With retry on, the turn is retried. |
| The answer is cut short and marked partial | `The streamed reply closed before its terminal event, so this output is partial` | The stream closed before the End marker. Check that the End marker is the real last event of your agent, and that no proxy in front of it closes long responses. The turn keeps its text and is not retried. |
| The turn fails with no answer | `The streamed reply closed before its terminal event "<end marker>" and carried no output` | The same cut, before any text came. Check the same two things. |
| The turn fails on a long reply | `The streamed reply exceeded the stream limit of <N> bytes (ENDPOINT_STREAM_MAX_BYTES). The limit is an approximate memory limit of the assembled reply, not its raw size.` | The stream is over the [size limit](https://docs.galtea.ai/v5.23/concepts/product/endpoint-connection-configuration.md#streamed-replies). Stop forwarding events you do not map, such as reasoning tokens. A self-hosted deployment can raise the limit. |
| The turn fails on a bad NDJSON line | `Line <N> of the NDJSON reply is not JSON` | Line `<N>` of the reply (blank lines count) is not one JSON value. Send one JSON value per line. If your agent sends SSE, set **Format** to **SSE** instead. Galtea ignores a bad line that comes after the End marker. The turn is not retried. |
| Test Connection fails on a long reply | `Response body exceeded 1048576 bytes limit` | Test Connection reads at most 1 MB. Test with a shorter sample answer. |
| A JSON reply connection gets no output | `Failed to extract "output" from response using outputMapping: the reply looks like a stream (SSE). Set "streamFormat" and "streamAssembly" on this connection to read it.` | Your agent streams. Set **Reply type** to **Streamed reply** and follow this guide. The message says NDJSON for a line stream. |
| `output` is empty, but the stream looks right | Required — no value extracted | Open **Raw Response**. If `text` is empty, the **Text path** or the **Text event** does not match your chunks. |
| `session_id` stays empty | No value extracted | Check the path in **Raw Response**. An event name with a dot needs the [bracket form](#the-conversation-id). |
| A WebSocket turn fails on close | `The WebSocket closed with code <N>: <reason>` | Your agent closed the socket with an error code. Only `1000`, `1001` or a close with no code is a normal close. |
| A WebSocket turn fails on a message | `The agent sent a binary WebSocket message. Only text messages are read.` or `The agent sent a WebSocket text message that is not valid UTF-8.` | Send each piece as a text message of valid UTF-8. The turn is not retried. |

## Not Supported

Galtea reads streams as SSE, NDJSON or WebSocket messages. **gRPC** agents are not supported today. If your agent speaks gRPC:

* **Put a small adapter in front of it.** It takes Galtea's HTTP request, calls your agent, and answers with one JSON body or an SSE stream. Galtea then connects to the adapter like to any agent.
* **Check for a gateway you already run.** gRPC services are often exposed through gRPC-Web, Connect or a JSON transcoding gateway (for example Envoy), which already speak HTTP and JSON.
* **Run the conversation yourself.** Call your agent from your own code and send each turn to Galtea with the SDK. See [Run Dataset-Based Evaluations](https://docs.galtea.ai/v5.23/sdk/tutorials/run-dataset-based-evaluations.md).

**A file split across events** is only partly supported, for example audio sent as base64 pieces. Galtea reads the joined text and `json`, so put the pieces in a structured reply and map the file from `json`, or join them into one `data:` URI in the text. A bare base64 string in the text is refused. Otherwise send the whole file in one event, or a URL to it.

## Learn More

> [card] [Streamed Replies reference](https://docs.galtea.ai/v5.23/concepts/product/endpoint-connection-configuration.md#streamed-replies)
>
> Every stream field, the presets and their sources, and the limits.

> [card] [Direct Inferences Tutorial](https://docs.galtea.ai/v5.23/sdk/tutorials/direct-inferences-and-evaluations-from-platform.md)
>
> Attach the connection to a version and run an evaluation.

> [card] [SDK: create a streaming connection](https://docs.galtea.ai/v5.23/sdk/api/endpoint-connection/create.md#streaming-example)
>
> The same connection in Python.

> [card] [REST API: create a streaming connection](https://docs.galtea.ai/v5.23/api-reference/endpoint-connections/create-endpoint-connection.md)
>
> The request body for a preset, `CUSTOM` settings, a structured reply and a WebSocket agent. The CLI sends the same body.


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