Skip to contentSkip to page list

Docs

npx langwatch

Trace any coding agent · Setup guide →

Python Connected Agent Reference

API reference for langwatch.connect_agent, the decorator that makes a Python function a LangWatch simulation target, with its options, turn fields, parameter reflection and reply types.

On this page

@langwatch.connect_agent()

Registers the decorated function as a simulation target. The SDK opens one outbound connection per process, registers the agent with its name, its environment and the parameters read from the signature, and calls the function once per conversation turn.

example.pyPython
import langwatch​@langwatch.connect_agent(name="support-agent")async def support_agent(messages: list[dict], thread_id: str) -> str:    return await run_my_agent(messages)

The function keeps working as a plain function. A direct call runs the body and touches no connection.

The process connects only with an API key. The SDK reads LANGWATCH_API_KEY from the environment, logs one line when it is absent, and lets the process run.

Options

OptionTypeDefaultEffect
namestrrequiredThe agent's name, and the first half of a connected:<name>@<environment> target.
environmentstr | Noneresolved, see belowThe environment row this process registers under.
descriptionstr | NoneNoneOne line about the agent, shown on the agents page.
parametersdict | Noneread from the signatureAn explicit declaration that replaces signature reflection.
enabledbool | NoneTrue, False when CI is setWhether this process connects.
instance_labelstr | NoneNoneA name for this instance in the instances table.
timeoutfloat120Seconds one call may take. The ceiling is 300.
concurrencyint | None10Calls this instance takes at the same time.
stickyboolFalseKeep every turn of one conversation on one instance.
api_keystr | NoneLANGWATCH_API_KEYThe key the connection authenticates with.
endpointstr | NoneLANGWATCH_ENDPOINTThe LangWatch instance to connect to.
project_idstr | NoneNoneThe project, for a key that covers more than one.
transportstr | Nonewebsocketwebsocket or http. See Transport.

Environment resolution

environment, then LANGWATCH_AGENT_ENVIRONMENT, then APP_ENV, ENVIRONMENT and NODE_ENV, then development.

development makes the agent personal: it belongs to the API key's owner when the key is personal, and to the machine, identified by its hostname, when the key is a project key. Every other name is shared by the project. See Environments and personal agents.

Turn fields

The platform sends the same fields on every call. The SDK reads the signature once, at decoration, and passes exactly the names the function declares. A function that declares **kwargs receives all of them.

NameTypeValue
messageslist[dict]The whole conversation so far, as OpenAI-style messages
new_messageslist[dict]The messages added since the previous turn
thread_idstrThe platform's conversation id, the same on every turn of one run
sessionAny | NoneWhat the function returned as session on the previous turn
statedict | NoneThe scenario's state: what the setup hook returned, as the latest turn updated it
trace_idstrThe id of the turn's trace

These names are never run parameters.

langwatch.AgentCall

A function whose first parameter is annotated langwatch.AgentCall receives one object carrying every turn field plus parameters, instead of separate arguments.

example.pyPython
@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"])
AttributeValue
messages, new_messages, thread_id, session, state, trace_idThe turn fields above
parametersA dict of the run's values for the declared parameters

Run parameters

Every parameter that is not a turn field is a run parameter. A parameter with a default is optional, and the run dialog prefills that default. A parameter with no default is required, and the run must supply a value for it.

Read fromGives
str, int, float, boolThe parameter's type
Literal[...], an Enum classA closed list of options
Optional[T]The type, and a value that may be empty
The default valueThe default the run dialog prefills
Annotated[T, langwatch.Param(...)]A description, an options list, or a type

An annotation the SDK does not map falls back to that type's JSON schema and is offered as text.

Values arrive validated against the declaration. A value the declaration refuses fails the call with agent_parameter_invalid before the function runs. A parameter the run did not supply arrives as its default; one with no default that the run did not supply fails the call with the name in the message.

langwatch.Param()

Annotates one run parameter.

ArgumentTypeEffect
descriptionstrShown beside the field in the run dialog
optionslistA closed list of allowed values, up to 50
typestrOverrides the type read from the annotation
example.pyPython
from typing import Annotated​tenant: Annotated[str, langwatch.Param(description="Which tenant to answer for")] = "acme"

Return values

ReturnMeaning
strThe reply text
dictOne message
list[dict]Several messages
langwatch.AgentReply(output, session=..., state=...)A reply, plus the session value for the next turn and an update to the scenario's state

A generator is refused with a message saying that streaming is not supported.

langwatch.AgentReply

FieldTypeValue
outputstr | dict | list[dict]The reply
sessionAny | NoneAn opaque JSON value the platform echoes on the next turn of the same conversation, up to 64 kilobytes
statedict | NoneAn update to the scenario's state, up to 64 kilobytes

@agent.scenario.setup and @agent.scenario.teardown

The decorated agent has a scenario attribute whose two decorators declare the hooks LangWatch calls around a scenario run. See Setup and teardown hooks for when they run and how they fail.

example.pyPython
@my_agent.scenario.setupasync def setup(run, plan: str = "free") -> dict:    return {"customer_id": "cus_123"}  # the state the run starts with​​@my_agent.scenario.teardownasync def teardown(run, state, plan: str = "free") -> dict | None:    return {"deleted": (state or {}).get("customer_id")}  # shown on the run
ArgumentTypeValue
runlangwatch.agent.ScenarioRunscenario_run_id, scenario_name and batch_run_id of the run, each None when absent
statedict | NoneTeardown only, the second positional argument: the latest state
keyword argumentsRun parameters, read from the signature as on the agent function

A hook's keyword arguments join the agent's run parameters. A name declared with a different type or default by the agent and a hook logs a parameters_invalid warning, and the agent is not registered. A setup that returns None sends an empty state. A sync hook runs in a worker thread, like a sync agent function.

langwatch.agent.serve()

Blocks the calling thread while the connection runs, for a script whose only job is the agent. A web server does not need it: the connection runs on its own daemon thread.

Lifecycle

The connection starts on first use, once per process, on a daemon thread with its own event loop. A fork restarts it in the child, so a preloading worker server keeps working. SIGINT, SIGTERM and normal exit send a deregistration, so the agent reads Offline at once. A dropped connection is retried with a growing wait, from 1 second to 30 seconds.

Transport

The connection is an outbound WebSocket by default. On a network that blocks WebSockets, the same frames travel over HTTP long polling: the SDK posts the registration, waits on a request for the next turn, and posts each answer. Pass transport="http" or set LANGWATCH_AGENT_TRANSPORT=http to use it from the start.

With the default transport, a proxy that answers the WebSocket upgrade with an HTTP status makes the SDK switch to HTTP on its own, with one warning line that names the status. The transport in use is printed on the connected line.

Environment variables

VariableEffect
LANGWATCH_API_KEYThe project key. Without it, the process does not connect.
LANGWATCH_ENDPOINTThe LangWatch instance, for a self-hosted deployment.
LANGWATCH_PROJECT_IDThe project, for a key that covers more than one.
LANGWATCH_AGENT_ENVIRONMENTThe environment to register under.
LANGWATCH_AGENT_CONNECT0 or false stops this process from connecting.
LANGWATCH_AGENT_INSTANCE_LABELThe instance name shown in the instances table.
LANGWATCH_AGENT_TRANSPORThttp uses HTTP long polling instead of the WebSocket.

Errors

A failing call answers with a typed code rather than a stack trace. agent_offline, agent_owner_only, agent_call_timeout, agent_call_failed, agent_disconnected, agent_instance_lost, agent_busy, agent_parameter_invalid, agent_register_refused, agent_payload_too_large, hook_not_declared.

Next steps

Connect your agent

The three-step guide, with the session and parameter recipes

Python SDK reference

Setup, tracing, spans and prompt management

Documentation