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

# Connect a text agent

> Connect an existing Python chat agent or HTTP chat backend to Coval's simulated users with the Agent SDK text client.

Use `CovalTextClient` from `coval-agent-sdk` to run Coval text simulations against a chat agent that your application runs. Your handler receives each simulated-user message and sends the agent's reply. Coval records and evaluates the conversation. The SDK opens an outbound WebSocket, so your agent does not need a public endpoint.

The text client also fits chat backends that the [standard chat connection](https://docs.coval.ai/concepts/agents/connections/chat.md) cannot call directly, for example an API that needs a session setup request, a fresh credential for each request, or a cleanup call after the conversation. Your handler makes those calls itself.

Text agents require `coval-agent-sdk` 0.2.0 or later and Python 3.10 or newer. See [Install](https://docs.coval.ai/sdks/agent-sdk.md#install).

## Before you run

Select these resources from the same Coval workspace:

* An organization API key with the [Agent SDK permissions](https://docs.coval.ai/sdks/agent-sdk.md#api-key-permissions).
* The workspace ID.
* An agent whose type is `MODEL_TYPE_SDK_CHAT`.
* A persona and a test set containing your scenarios.

For a first run, one case and one iteration are enough.

### Create an SDK chat agent

The Coval web app and CLI don't create SDK chat agents yet. Create one with the [Agents API](https://docs.coval.ai/api-reference/v1/agents/agents/connect-an-agent.md). The agent needs no endpoint or metadata, because your application connects to Coval:

```sh theme={null}
curl -X POST https://api.coval.dev/v1/agents \
  -H "x-api-key: $COVAL_API_KEY" \
  -H "X-Coval-Workspace-Id: $COVAL_WORKSPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"display_name": "Support chat (Agent SDK)", "model_type": "MODEL_TYPE_SDK_CHAT"}'
```

The response's `agent.id` is the `agent_id` for `RunConfig`. Creating an agent requires the `agents:write` permission, which the SDK itself doesn't need.

## Check the connection

Pass your API key and workspace ID to `CovalTextClient`, and the agent, persona, and test-set IDs to `RunConfig`. This example reads those values from environment variables. The handler echoes each simulated-user message to check the connection:

```python theme={null}
import asyncio
import os

import coval_agent_sdk


async def on_connection(connection: coval_agent_sdk.TextConnection) -> None:
    async for message in connection.receive_messages():
        await connection.send_message(f"You said: {message}")


async def main() -> coval_agent_sdk.RunResult:
    client = coval_agent_sdk.CovalTextClient(
        api_key=os.environ["COVAL_API_KEY"],
        workspace_id=os.environ["COVAL_WORKSPACE_ID"],
    )
    config = coval_agent_sdk.RunConfig(
        agent_id=os.environ["COVAL_AGENT_ID"],
        persona_id=os.environ["COVAL_PERSONA_ID"],
        test_set_id=os.environ["COVAL_TEST_SET_ID"],
        run_timeout_seconds=600,
    )
    return await client.run(config, on_connection=on_connection)


if __name__ == "__main__":
    result = asyncio.run(main())
    print(result.run_id, result.status)
```

`run()` creates a run, calls your handler for each conversation, and waits for the run to complete, including evaluation. `RunConfig` works as it does for [voice agents](https://docs.coval.ai/sdks/agent-sdk.md#launch-a-run-or-connect-to-one-conversation).

## How a text conversation works

The SDK calls your handler with a ready `TextConnection` for each conversation. In the handler:

* Read simulated-user messages from `receive_messages()`. Each message is one user turn. Use one receive loop per connection.
* Reply to each message with one `send_message()` call. Each call is one complete agent turn, so combine a multi-part backend response into one reply. A reply must be nonempty and at most 64 KiB when UTF-8 encoded.
* If the persona's **Conversation Initiator** setting is **Persona waits to speak**, send the agent's greeting with `send_message()` before reading. Otherwise, wait for the first simulated-user message.
* The simulated user ends the conversation. `receive_messages()` then stops, and `send_message()` returns `False` instead of sending. The SDK never resends a message.
* Return from the handler after `receive_messages()` ends. Finish your own cleanup first. Returning earlier raises an SDK error.

Reply promptly. At most 64 unread messages can wait in the connection, and the session fails if no simulated-user message arrives for 600 seconds, which bounds how long your agent can take to answer one turn. Handlers for different conversations may run concurrently, so keep conversation state inside the handler.

### Text connection reference

| Member | Behavior |
| - | - |
| `simulation_id` | Identifies this conversation for application state and traces. |
| `receive_messages()` | Async iterator of simulated-user messages. Ends when the conversation ends; failures raise. |
| `send_message(text)` | Sends one complete reply. Returns `True` when sent, or `False` if the conversation already ended. Concurrent calls are sent in call order. |
| `wait_closed()` | Waits for the conversation to end without reading messages; failures raise. |
| `closed` | Reports whether the conversation ended, including failure. |
| `result` | Finalized `ConversationResult` after a successful connection context exits; otherwise `None`. |

## Wrap an existing HTTP chat backend

The handler can call any API your agent already exposes. This example uses [HTTPX](https://www.python-httpx.org/) with a chat API that:

1. Starts a session with a `GET` request.
2. Needs a new access token on every request.
3. Ends the session with a `DELETE` request.

Replace the URLs, payload fields, and `get_access_token()` with your API's own:

```python theme={null}
import os

import httpx

import coval_agent_sdk

CHAT_API_URL = os.environ["CHAT_API_URL"]
AGENT_SPEAKS_FIRST = True  # Match the persona's Conversation Initiator setting.


async def get_access_token(http: httpx.AsyncClient) -> str:
    """Return a short-lived token. Replace with your authentication flow."""
    response = await http.post(
        "/oauth/token",
        data={
            "grant_type": "client_credentials",
            "client_id": os.environ["CHAT_CLIENT_ID"],
            "client_secret": os.environ["CHAT_CLIENT_SECRET"],
        },
    )
    response.raise_for_status()
    return response.json()["access_token"]


async def auth_headers(http: httpx.AsyncClient) -> dict[str, str]:
    return {"Authorization": f"Bearer {await get_access_token(http)}"}


async def on_connection(connection: coval_agent_sdk.TextConnection) -> None:
    async with httpx.AsyncClient(base_url=CHAT_API_URL, timeout=60) as http:
        # Start one backend session per Coval conversation.
        started = await http.get(
            "/chat/sessions/new",
            headers=await auth_headers(http),
            params={"client_ref": connection.simulation_id},
        )
        started.raise_for_status()
        session = started.json()
        session_id = session["session_id"]

        try:
            if AGENT_SPEAKS_FIRST:
                await connection.send_message(session["greeting"])

            async for message in connection.receive_messages():
                response = await http.post(
                    f"/chat/sessions/{session_id}/messages",
                    headers=await auth_headers(http),
                    json={"text": message},
                )
                response.raise_for_status()
                replies = response.json()["messages"]
                await connection.send_message(
                    "\n\n".join(reply["text"] for reply in replies)
                )
        finally:
            # The conversation has ended or failed; release the backend session.
            ended = await http.delete(
                f"/chat/sessions/{session_id}",
                headers=await auth_headers(http),
            )
            ended.raise_for_status()
```

Pass this handler to `client.run(config, on_connection=on_connection)` as in [Check the connection](#check-the-connection).

The `finally` block runs after the simulated user ends the conversation and also when a request or the connection fails, so the backend session is released either way. An exception in the handler propagates from `run()` after the SDK cleans up the connection.

## Connect to one conversation or serve your own run

`client.connect(simulation_id)` attaches the text client to one existing simulation without launching a run:

```python theme={null}
async def attach_one(
    client: coval_agent_sdk.CovalTextClient, simulation_id: str
) -> coval_agent_sdk.ConversationResult | None:
    async with client.connect(simulation_id) as connection:
        await on_connection(connection)
    return connection.result
```

To choose metrics, test cases, or run metadata that `RunConfig` doesn't cover, [launch the run through the API](https://docs.coval.ai/api-reference/v1/runs/runs/launch-run.md) yourself and pass its ID to `attach()`. `attach()` serves every conversation in that run and returns the same results as `run()`:

```python theme={null}
result = await client.attach(run_id, on_connection, run_timeout_seconds=900)
```

Connecting the text client to a simulation whose agent isn't an SDK chat agent fails before your handler runs.

## Results and errors

Text results use the same `RunResult` and `ConversationResult` types as voice. For text conversations, `ConversationResult.received_messages` and `sent_messages` count the messages exchanged, and the audio byte counts are zero.

Errors, partial results, and local timeouts work as they do for voice. See [Results and errors](https://docs.coval.ai/sdks/agent-sdk.md#results-and-errors).

To send OpenTelemetry traces, pass a `CovalTraceExporter` to `CovalTextClient(trace_exporter=...)` and follow [Optional OpenTelemetry traces](https://docs.coval.ai/sdks/agent-sdk.md#optional-opentelemetry-traces).

## Source and support

See the [SDK repository](https://github.com/coval-ai/coval-agent-sdk) for the implementation and API contracts. For integration help, contact [Coval support](mailto:support@coval.dev).


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