Getting Started
The fastest path is the connect-agent skill. Install it in your coding agent (Claude Code, Cursor, or any agent with shell access), or copy the full prompt, and the agent performs the whole setup, from finding the function to running the first suite:
Connect my agent to LangWatch agent testing
Install once, then run /connect-agent in your coding agent.
View prompt
Connect my agent to LangWatch simulations
You are using LangWatch for your AI agent project. Follow these instructions.
The steps below are the same setup by hand, and what to check when the skill's run needs a correction.
1. Install the SDK
pip install langwatchnpm install langwatch zodThe agent entry point is Node only. It is a separate export, langwatch/agent. zod declares the run parameters. Install it if the project does not have it yet.
The process needs LANGWATCH_API_KEY in its environment. It is the project API key from Settings > API Keys, the same one the CLI and the SDK use for tracing. Without a key the SDK logs one line and opens no connection, so a build that has no key runs unchanged.
2. Connect it where your service starts
Write a small function beside the code that starts your service. This is the adapter between the messages that come from a scenario test and your agent.
# main.py, beside your server startupimport langwatchfrom my_app.agent import SupportAgent@langwatch.connect_agent(name="support-agent")async def support_agent( messages: list[dict], thread_id: str, *, model: str = "gpt-6-luna",) -> str: result = await SupportAgent(model=model).run(messages, conversation_id=thread_id) return result.output_textmodel is a run parameter, so a run can select it. messages and thread_id are turn fields that LangWatch sends. See What the agent receives and Run parameters below.
A synchronous function works the same way. It runs in a worker thread, so the connection stays responsive.
// server.ts, beside your server startupimport { z } from "zod";import { connectAgent } from "langwatch/agent";import { runSupportAgent } from "./agent";connectAgent( { name: "support-agent", parameters: z.object({ model: z.enum(["gpt-6-sol", "gpt-6-luna"]).default("gpt-6-luna"), }), }, async ({ messages, threadId, params }) => { const result = await runSupportAgent({ messages, conversationId: threadId, model: params.model, }); return result.text; },);The zod schema declares the run parameters, and it types params in the handler. See Run parameters below for what each part of the schema does. An agent whose tests vary no value takes parameters away and keeps the rest.
connectAgent returns the function, so a code-first scenario run and a unit test can call it directly.
Put this on the startup path: the file that starts your service, or a module that file imports at startup. The connection opens with the process, so the code has to run when the process runs.
Then start your service the way you always start it. The start command does not change, and there is no new process to run. A web server holds the connection open by itself, and one process serves every agent it declares over a single connection.
No long-running service? When the agent is a library with no process of its own, put the connect function in a small script and keep the script alive.
In Python, call langwatch.agent.serve() at the end of the script. It blocks until Ctrl-C.
In TypeScript, keep the script alive yourself. An open WebSocket holds the event loop while it is connected, but the HTTP fallback and the reconnect wait use unreferenced timers, so a script with no server of its own can exit between polls.
setInterval(() => {}, 1 << 30);Run the script with whatever runner the project uses, for example tsx agent.ts.
3. Confirm it is online
The agent appears on the Agents page with a green Online mark, its environment, and the number of connected instances. From the terminal:
langwatch agent listRun a test suite against it by name:
langwatch test-suite run 'Smoke' --target connected:support-agent --waitconnected:<name> runs the agent in development. When no process is connected there but one other environment is online, the run uses that one. When several are online, or none, the run is refused with agent_environment_unresolved and names them: pick one as connected:<name>@<environment>. connected:<agent-id> is the same target, and langwatch agent list --format json prints the id.
What the agent receives
The platform sends the same fields on every call. They describe the turn, and they are never run parameters.
| Python | TypeScript | Value |
|---|---|---|
messages | messages | The whole conversation so far, as OpenAI-style messages |
new_messages | newMessages | The messages added since the previous turn |
thread_id | threadId | The platform's conversation id, the same on every turn of one run |
session | session | What the function returned as session on the previous turn, empty on the first |
state | state | The scenario's state: what the setup hook returned, as the latest turn updated it, empty without one |
trace_id | traceId | The id of the turn's trace |
In Python the SDK reads the signature once, at decoration, and passes exactly the names the function declares. A function that declares messages and thread_id receives those two. A function that declares **kwargs receives all of them. A first parameter annotated langwatch.AgentCall receives one object with every field and the parameter values:
@langwatch.connect_agent(name="support-agent")async def support_agent(call: langwatch.AgentCall) -> str: return await run_my_agent(call.messages, tenant=call.parameters["tenant"])In TypeScript the handler receives one object, { messages, newMessages, threadId, session, state, params, traceId }.
The function returns a string, one message, a list of messages, or a reply with a session value: langwatch.AgentReply(output, session=...) in Python, { output, session } in TypeScript.
Attachments
A connected agent column in the experiments workbench has an optional attachment input beside input. Map a dataset image or file column to it. See Images and files in datasets.
The last user message then carries content parts instead of plain text. It holds the text of the turn, plus an image_url part for a picture, an input_audio part for a recording, or a file part with the file name and the file data in base64.
Run parameters
A run parameter is a value a run supplies, so one scenario covers several conditions: a model, a plan, a tenant, a fixture. The agent declares the parameters it accepts, and the platform offers them in the run dialog, in --param and in the API.
Every parameter with a default that is not a turn field is a run parameter:
from typing import Annotated, Literalimport langwatch@langwatch.connect_agent(name="support-agent")async def support_agent( messages: list[dict], *, model: Literal["gpt-6-sol", "gpt-6-luna"] = "gpt-6-luna", plan: str = "free", max_tools: int = 5, tenant: Annotated[str, langwatch.Param(description="Which tenant to answer for")] = "acme",) -> str: ...| Read from | Gives |
|---|---|
The annotation str, int, float, bool | The parameter's type |
Literal[...] and an Enum class | A closed list of options |
Optional[T] | The type, and a value that may be empty |
| The default value | The default the run dialog prefills |
Annotated[T, langwatch.Param(...)] | A description, an options list, or a type that overrides the annotation |
An annotation the SDK does not map falls back to the type's JSON schema and is offered as text. parameters={...} on the decorator replaces what the signature declares.
Declare the parameters with a zod schema. The schema types params in the handler, and the SDK validates the values a run supplies against it:
import { z } from "zod";import { connectAgent } from "langwatch/agent";export const supportAgent = connectAgent( { name: "support-agent", parameters: z.object({ model: z.enum(["gpt-6-sol", "gpt-6-luna"]).default("gpt-6-luna"), plan: z.string().default("free").describe("Customer plan"), maxTools: z.number().int().default(5), }), }, async ({ messages, params }) => { // params is typed: { model: "gpt-6-sol" | "gpt-6-luna"; plan: string; maxTools: number } return await runMyAgent(messages, { model: params.model }); },);| In the schema | On the platform |
|---|---|
z.enum([...]) | A closed option list in the run dialog. A value outside it is refused. |
.default(value) | The default the run dialog prefills |
.describe(text) | The description shown beside the field |
z.number(), z.boolean() | The parameter's type. z.string() is text. |
Give every property a default, or the run must supply a value for it. Keep the schema flat and scalar: nested objects and arrays are not run parameters.
Pass the schema object itself, not schema["~standard"].jsonSchema and not a validator instance. valibot and arktype work the same way: the SDK accepts any Standard Schema object that has a JSON Schema converter, and reads the converter without importing the library.
Two more forms exist for a project with no schema library. A definition map:
parameters: { model: { options: ["gpt-6-sol", "gpt-6-luna"], default: "gpt-6-luna" }, plan: { default: "free", description: "Customer plan" }, maxTools: { type: "number", default: 5 },}Or a plain JSON Schema object, { type: "object", properties: { ... } }. All three forms reach the platform as the same declaration.
The platform normalizes the declaration into the same shape a scenario declares, up to 20 parameters per agent. A closed list becomes a set of choices in the run dialog, and the platform refuses a value outside it before the run starts. A type the platform cannot map is offered as text, and the SDK logs which parameter that happened to.
A parameter the run does not supply takes its default. When a parameter has no default and the run does not supply it, the SDK refuses the call before it reaches the function, and the message includes the parameter name.
Scenario-declared parameters and agent-declared parameters share one list. See Run parameters for how a run supplies values, for secret parameters, and for what happens when two targets accept different names.
Session, when your agent keeps its own conversation id
thread_id is the platform's id for the conversation. Many agents create their own conversation on their side and cannot accept an id from outside. session covers that: it is an opaque JSON value the agent owns, empty on the first turn, and whatever the function returns comes back on the next turn of the same conversation.
import langwatch@langwatch.connect_agent(name="support-agent")async def support_agent(messages: list[dict], session: str | None = None): conversation_id = session or await my_agent.create_conversation() reply = await my_agent.send(conversation_id, messages[-1]["content"]) return langwatch.AgentReply(reply, session=conversation_id)export const supportAgent = connectAgent( { name: "support-agent" }, async ({ newMessages, session }) => { const conversationId = (session as string) ?? (await myAgent.createConversation()); const output = await myAgent.send(conversationId, newMessages); return { output, session: conversationId }; },);The platform holds the value for the run, so the next turn reaches any instance with the value. The process stores no state, and a deployment with many pods needs no routing rule.
To keep the state in your own process instead, use an in-memory map. Key it by thread_id and set sticky=True (sticky: true), which keeps every turn of one conversation on the instance that took the first one:
import langwatchSESSIONS: dict[str, str] = {}@langwatch.connect_agent(name="support-agent", sticky=True)async def support_agent(messages: list[dict], thread_id: str) -> str: conversation_id = SESSIONS.setdefault(thread_id, my_agent.create_conversation()) return await my_agent.send(conversation_id, messages[-1]["content"])const sessions = new Map<string, string>();export const supportAgent = connectAgent( { name: "support-agent", sticky: true }, async ({ newMessages, threadId }) => { let conversationId = sessions.get(threadId); if (!conversationId) { conversationId = await myAgent.createConversation(); sessions.set(threadId, conversationId); } return await myAgent.send(conversationId, newMessages); },);With sticky, a conversation whose instance goes away fails with agent_instance_lost instead of restarting somewhere else. A session value is limited to 64 kilobytes.
An agent that reads the whole messages list on every turn needs neither of these.
Test data for each run
If a scenario needs data that exists before the conversation starts, such as a customer with an order to refund, declare a setup hook that creates it and a teardown hook that deletes it. Both run in this same process, and the agent receives what setup returned as state on every turn. See Setup and teardown hooks.
Environments and personal agents
The agent registers under an environment. Each environment is its own row and its own target. support-agent in production and support-agent in development are two targets, so one comparison run puts your machine next to production.
The SDK resolves the environment in this order:
- The
environmentargument on the decorator. LANGWATCH_AGENT_ENVIRONMENT.APP_ENV, thenENVIRONMENT, thenNODE_ENV.development.
development makes the agent personal. With a personal API key it belongs to the key's owner, and only that person can run it. With a project API key it belongs to the machine, and the team can see and run it. Every other environment name is shared by the whole project. On a project key the machine is identified by its hostname, which in a container changes every time the container is recreated, see Containers and the machine identity.
For a development box the team runs against, give it a name of its own:
LANGWATCH_AGENT_ENVIRONMENT=dev-sharedSee Environments and personal agents for the full rules, the local loop, and what a teammate sees.
Production with many instances
One deployment with several pods is one row and several instances. The platform dispatches each call to one live instance and reports the instance that served each run.
| Setting | What it does |
|---|---|
concurrency | How many calls one instance takes at the same time. Default 10. When every instance is full, the platform waits and retries within the call's deadline. |
instance_label (instanceLabel) | A name for this instance in the instances table, for example the pod name. Also read from LANGWATCH_AGENT_INSTANCE_LABEL. |
enabled | Whether this process connects. It takes any boolean, so one expression decides which deployments connect: enabled=os.environ.get("APP_ENV") != "production" and not os.environ.get("CI") connects everywhere but production and CI. Without the argument the default is true, and false when CI is set. An enabled argument replaces that rule, so keep the CI half unless a CI job is deliberately the target. |
LANGWATCH_AGENT_CONNECT=0 | Turns the connection off for a deployment without a code change. |
The platform delivers each call at most once. The SDK confirms a call when the function starts, and the platform never sends a confirmed call to a second instance, so a turn with side effects runs one time.
During a rolling deploy the platform closes the connections after the request drain and the SDK reconnects at once, so a new pod picks the agent up.
Tracing
The platform passes the turn's trace context in the call, and the SDK adopts it before it calls the function. The spans your agent produces land in the turn's trace, and the judge reads them before its verdict: tool calls, database writes, retrievals. A criterion such as "the agent looked up the order before answering" then passes on evidence instead of on the reply's wording.
There is no middleware to add, and the SDK does this for a synchronous function and an asynchronous one alike.
Report the traces to the same project that runs the scenarios. Traces sent to another project, or to another observability backend only, are invisible to the judge. See Linking your traces for what the judge reads and how long it waits.
Security
The connection is outbound only. The process opens one TLS connection to LangWatch and keeps it. It opens no listening port, needs no public URL and no tunnel, and needs no inbound firewall rule. A network that already allows outbound HTTPS to your LangWatch endpoint needs no change.
No credentials are shared. The only credential the SDK reads is the LangWatch API key. Model provider keys, database connections and internal API tokens stay inside your process and are never sent to LangWatch.
What LangWatch sends in a call: the conversation, the values of the parameters you declared, the session value your function returned on the previous turn, and the turn's trace context. What it cannot do: it can only call the function you decorated, with the parameters you declared. An instance receives calls for the agents that instance registered, and for no other agent.
What the key needs. Connecting needs scenarios:manage, and starting a run needs scenarios:create. An ingestion key cannot connect. A personal API key never exceeds the permissions its owner has, so a person who cannot run suites cannot connect an agent that runs them. A personal development agent can be run by its owner only.
The SDK sends the API key in a request header, never in the URL, so proxy logs and browser history do not record it. On a self-hosted deployment behind a private certificate authority, point the runtime at the certificate bundle: SSL_CERT_FILE for Python, NODE_EXTRA_CA_CERTS for Node.
Behind a proxy that blocks WebSockets
The connection is a WebSocket by default. Some corporate proxies refuse the upgrade and answer it with an HTTP status such as 403 or 426. The SDK then switches to HTTP long polling on its own, prints one warning line with the status, and the agent connects the same way: one POST registers, one request waits for the next turn, one POST sends each answer. No WebSocket egress is needed for this path, only outbound HTTPS.
To use HTTP from the start, pass transport="http" in Python or transport: "http" in TypeScript, or set LANGWATCH_AGENT_TRANSPORT=http in the process environment. A poll waits up to 25 seconds on the platform side; a proxy with a shorter read timeout closes it early, and the SDK polls again.
Declare parameters with their types and their options, and do not pass a raw parameter string into a privileged operation. LangWatch only calls the function. What the function does is your code, and its safety is yours.
Troubleshooting
The decorator never stops the application from starting. Every problem is one warning line on stdout with the fix, and the process runs on.
| Warning | Fix |
|---|---|
LANGWATCH_API_KEY is missing | Set the project API key in the process environment. Without it the SDK opens no connection. |
| The key reaches several projects and no project is named | Set LANGWATCH_PROJECT_ID, or pass project_id. The warning lists the projects the key reaches. |
| The key is not valid | Read the key from Settings > API Keys of the project that runs the suites. |
| The key is of the wrong type | An ingestion key cannot connect. Use a project or personal API key. |
The key has no scenarios:manage permission | Give the key that permission, or use a key that has it. |
| The endpoint is unreachable | Check LANGWATCH_ENDPOINT and the outbound path to it. The SDK keeps reconnecting with a growing wait, so the agent appears as soon as the path opens. |
| A parameter was refused | The name breaks the parameter name grammar, or the agent declares more than 20. The warning includes the parameter name. |
| The environment name was refused | Use lower-case letters, digits, dashes and underscores, up to 32 characters. |
Options reference
@langwatch.connect_agent(...)
| Option | Default | Effect |
|---|---|---|
name | required | The agent's name, and the connected:<name> target. |
environment | resolved, see above | Which environment row this process registers under. |
parameters | read from the signature | An explicit parameter declaration that replaces what the signature declares. |
enabled | True, False under CI | Whether this process connects at all. Takes any boolean, and replaces the CI default rather than adding to it. |
instance_label | none | A name for this instance in the instances table. |
timeout | 120 seconds | How long one call may take. The ceiling is 300 seconds. |
concurrency | 10 | Calls this instance takes at the same time. |
sticky | False | Keep every turn of one conversation on one instance. |
api_key | LANGWATCH_API_KEY | The project key the connection authenticates with. |
endpoint | LANGWATCH_ENDPOINT | Which LangWatch instance to connect to. |
project_id | none | The project, for a key that covers more than one. |
langwatch.agent.serve() blocks the current thread while the connection runs. langwatch.Param(description=..., options=[...], type=...) annotates one parameter. langwatch.AgentReply(output, session=...) returns a reply with a session value.
connectAgent(options, handler) from langwatch/agent
| Option | Default | Effect |
|---|---|---|
name | required | The agent's name, and the connected:<name> target. |
environment | resolved, see above | Which environment row this process registers under. |
parameters | none | A zod schema, a definition map, or a JSON Schema object. |
enabled | true, false under CI | Whether this process connects at all. Takes any boolean, and replaces the CI default rather than adding to it. |
instanceLabel | none | A name for this instance in the instances table. |
timeoutMs | 120000 | How long one call may take. The ceiling is 300000. |
concurrency | 10 | Calls this instance takes at the same time. |
sticky | false | Keep every turn of one conversation on one instance. |
apiKey | LANGWATCH_API_KEY | The project key the connection authenticates with. |
endpoint | LANGWATCH_ENDPOINT | Which LangWatch instance to connect to. |
projectId | none | The project, for a key that covers more than one. |
The returned function calls the handler directly and exposes .disconnect(), which closes the connection and drops the agent from the presence list.
Environment variables, read by both SDKs:
| Variable | Effect |
|---|---|
LANGWATCH_API_KEY | The project key. Without it, the process does not connect. |
LANGWATCH_ENDPOINT | The LangWatch instance, for a self-hosted deployment. |
LANGWATCH_AGENT_ENVIRONMENT | The environment to register under. |
LANGWATCH_AGENT_CONNECT | 0 or false stops this process from connecting. |
LANGWATCH_AGENT_INSTANCE_LABEL | The instance name shown in the instances table. |
Read the first run
Open the run in Agent Testing > Results. A connected setup shows the conversation transcript, a trace link on each turn, and judge reasoning that cites what the agent did.


The trace link on a turn opens the full trace: the simulation's own steps first, then your agent's spans for that turn. This is the evidence the judge reads:

The run settings also record which instance served each run, so a result from a deployment with several pods shows which instance served it.
Common failures
| Symptom | Cause | Fix |
|---|---|---|
| The row reads Offline | The process stopped, or its outbound connection is blocked by a proxy or a firewall. | Restart the process. On a network that blocks WebSockets, set LANGWATCH_AGENT_TRANSPORT=http, see Behind a proxy that blocks WebSockets. |
The run is refused with agent_offline | No instance was connected when the run started. | Start the agent process, then run again. |
The run is refused with agent_owner_only | The agent registered under development with a personal key, so it belongs to one person. | Run it as its owner, or register it under a shared environment name. |
| A new agent row appears on every start, each with a different host label | The agent registered under development with a project key from a container, and the container's hostname changes on every recreate. | Set LANGWATCH_AGENT_ENVIRONMENT to a name other than development, or pin the container's hostname, see Containers and the machine identity. |
A turn fails with agent_call_timeout | The function took longer than the agent's timeout. | Raise timeout, up to 300 seconds, or make the agent answer faster. |
A turn fails with agent_busy | Every instance was already running as many calls as it accepts. | Raise concurrency above its default of 10, or start more instances. |
| Trace-dependent criteria come back inconclusive | The agent reports its traces to a different project, or it reports none at all. | Point the agent's tracing at the project that runs the scenarios. |