Skip to content

Agent Tracing

View as Markdown

Agent tracing records what an agent does while it runs: each LLM call, each tool call, token usage, latency, and errors. The recorded data is sent to an agent tracing platform of your choice, where you can inspect individual runs, follow the steps an agent took, and find where it failed or slowed down.

The agent runs inside a Daytona sandbox and sends traces directly to the platform over HTTPS. Daytona supplies the credentials, the network path, and the sandbox identity, so the agent can reach the platform without holding the credentials in plaintext and every trace can be matched to the sandbox that produced it.

Agent tracing is separate from the two telemetry paths described in OpenTelemetry collection, which report on the sandbox and on Daytona operations. You can use agent tracing together with them to see the agent, the sandbox, and your application in one picture.

TypeRecordsRuns in
Sandbox telemetryCPU, memory, and filesystem metrics, application logs, and HTTP spansSandbox runtime
SDK tracingDaytona SDK operations and API callsYour application
Agent tracingLLM calls, tool calls, token usage, and errorsAgent code in the sandbox

Agent tracing supports the following platforms:

An agent sends traces to the platform from inside the sandbox, using credentials it never holds in plaintext:

  1. You store the tracing platform’s key and the LLM provider’s key as secrets. Each secret is limited to the hosts that need it.
  2. You create a sandbox that maps those secrets to environment variables. The sandbox holds placeholders, not keys.
  3. The agent runs in the sandbox with a tracing library that records each LLM call and tool call.
  4. The library sends traces to the platform over HTTPS. Daytona replaces the placeholder with the real key on the way out.
  5. The agent flushes pending traces before it exits. The trace appears in the platform with the sandbox ID on it.

The examples call the model through the OpenAI SDK pointed at an OpenAI-compatible endpoint. You use your own key from the provider you already have, with no router or gateway in between. Three settings select the provider: the base URL, the key, and the model. A fourth setting names the provider on the trace.

The model must accept tool calls on the Chat Completions API with no extra request setting. Some OpenAI models accept tool calls there only with reasoning turned off, as OpenAI’s model pages note, or only through the Responses API, as described in OpenAI’s function calling guide.

ProviderBase URLTested
OpenAIhttps://api.openai.com/v1Yes
Anthropichttps://api.anthropic.com/v1/Yes
Google Geminihttps://generativelanguage.googleapis.com/v1beta/openai/Yes

Anthropic describes its OpenAI-compatible endpoint as meant mainly for testing and comparing models, and Google describes its OpenAI compatibility as beta. If you build on a provider’s native SDK, use your tracing platform’s integration for that SDK.

The platform key and the provider key belong in secrets with a host allowlist. Daytona substitutes secrets in HTTPS request headers only, so the examples send traces over HTTPS and not gRPC. Platforms that use HTTP Basic authentication are supported. Settings that are not secret, such as the project name or the region, go in sandbox environment variables.

Secrets are substituted by the sandbox’s outbound proxy. The sandbox points clients to the proxy with the HTTP_PROXY and HTTPS_PROXY environment variables. A client that ignores these variables connects to the platform directly, so its requests carry the placeholder and the platform rejects them. Python libraries read the variables by default. Node.js reads them only when NODE_USE_ENV_PROXY is set to 1, so the TypeScript launchers set it. The setting covers the built-in fetch of Node.js and its shared pool of HTTPS connections, https.globalAgent. OpenTelemetry exporters open their connections through a pool of their own that ignores the setting, so the TypeScript examples give them https.globalAgent to use.

Creating secrets requires the manage:secrets permission. Creating the sandbox and mounting secrets into it requires write:sandboxes, and deleting the sandbox requires delete:sandboxes. See secret permissions and API key permissions.

The examples use the Python and TypeScript SDKs because the agent file is written in one of those languages. The secrets file and the launcher work with any Daytona SDK. For the other languages, see use a secret in a sandbox.

The launcher passes the sandbox ID to the agent as an environment variable for that run, and the agent attaches the ID to the trace. You can then match the trace to the sandbox that produced it. If you also collect sandbox telemetry, the sandbox’s metrics and logs carry the same ID in the service.instance.id resource label, so you can go from a trace to the sandbox’s own telemetry.

PlatformField
Grafana CloudResource attribute service.instance.id
ArizeMetadata key sandbox_id on the agent span
LangfuseMetadata key sandbox_id on every observation
LangSmithMetadata key sandbox_id on the root run
DatadogTag sandbox_id on the agent span

For environment variables on a single run, see process and code execution.

Tracing libraries send traces in the background. An agent process that exits right after its last call can lose the traces that are still pending. Every example ends with the platform’s flush call.

Traces can include prompts, model outputs, and tool arguments and results. This data leaves the sandbox and is stored by the platform. Each platform has a setting that keeps this content out of the trace. All five settings were tested with the Python and TypeScript examples.

PlatformSettingSource
Grafana CloudLeave out the gen_ai.input.messages and gen_ai.output.messages attributesGrafana Cloud documentation
ArizeOPENINFERENCE_HIDE_INPUTS and OPENINFERENCE_HIDE_OUTPUTS set to trueArize documentation
LangfuseA mask_otel_spans function on the Langfuse client (Python) or a mask function on LangfuseSpanProcessor (TypeScript) that replaces inputs and outputsLangfuse documentation
LangSmithLANGSMITH_HIDE_INPUTS and LANGSMITH_HIDE_OUTPUTS set to trueLangSmith documentation
DatadogA span processor passed to LLMObs.enable (Python) or registered with llmobs.registerProcessor (TypeScript) that replaces inputs and outputsDatadog documentation

Anything the agent prints is also collected as sandbox logs by sandbox telemetry.

Agent Observability in Grafana Cloud lets you inspect model calls, token usage, and conversation content. This example uses OpenTelemetry to record the agent’s model calls and weather tool call in one trace and sends it to your Grafana Cloud stack over HTTPS.

You need a Grafana Cloud stack with Agent Observability enabled and an access policy token with the traces:write scope. In the Grafana Cloud Portal, select your stack and click Configure on the OpenTelemetry tile. Follow the instructions to generate the token and copy the OTLP endpoint URL and Instance ID. Use the instance ID from the OpenTelemetry tile, not the Agent Observability instance ID.

SettingValueType
llm-api-keyYour model provider’s API key, read from LLM_API_KEYSecret
grafana-otlp-authThe Base64-encoded pair made from GRAFANA_INSTANCE_ID and GRAFANA_ACCESS_TOKENSecret
LLM_BASE_URLThe base URL of your model provider’s OpenAI-compatible endpointEnvironment variable
LLM_MODELA model that accepts tool calls on the Chat Completions APIEnvironment variable
LLM_PROVIDERThe model provider name recorded in the traceEnvironment variable
GRAFANA_OTLP_ENDPOINTYour stack’s OTLP endpoint from the OpenTelemetry tile, ending in /otlp without /v1/tracesEnvironment variable
<provider host>Host of LLM_BASE_URL, on the allowlist of llm-api-keyAllowed host
otlp-gateway-prod-<region>.grafana.netHost of GRAFANA_OTLP_ENDPOINT, on the allowlist of grafana-otlp-auth. Use the actual host shown on your stack’s OpenTelemetry tile.Allowed host
  1. Install the Daytona SDK on your machine: pip install "daytona[v0-sdk]>=2,<3" for Python, or npm install @daytona/sdk@2 tsx for TypeScript. The TypeScript SDK requires Node.js 22.15 or later.
  2. Set these environment variables on your machine: DAYTONA_API_KEY, LLM_API_KEY, LLM_BASE_URL, GRAFANA_INSTANCE_ID, GRAFANA_ACCESS_TOKEN, GRAFANA_OTLP_ENDPOINT, LLM_MODEL, and LLM_PROVIDER.
  3. Save the secrets file as store_secrets.py or store_secrets.ts and run it once to store the keys: python store_secrets.py or npx tsx store_secrets.ts.
  4. Save the agent file as agent.py or agent.ts in the same directory.
  5. Save the launcher as run.py or run.ts in the same directory and run it: python run.py or npx tsx run.ts. It prints the sandbox ID and the agent’s answer, then deletes the sandbox. You can run it again without storing the keys again.
  6. View the trace in Grafana Cloud as described below.

The secrets file stores your model provider key and your Grafana Cloud credentials as Daytona secrets, each limited to the host that uses it. Run it once on your machine.

store_secrets.py
import os
from base64 import b64encode
from urllib.parse import urlparse
from daytona import Daytona
from daytona.v0 import CreateSecretParams
daytona = Daytona()
daytona.v0.secret.create(CreateSecretParams(
name="llm-api-key",
value=os.environ["LLM_API_KEY"],
hosts=[urlparse(os.environ["LLM_BASE_URL"]).hostname],
))
credentials = f"{os.environ['GRAFANA_INSTANCE_ID']}:{os.environ['GRAFANA_ACCESS_TOKEN']}"
daytona.v0.secret.create(CreateSecretParams(
name="grafana-otlp-auth",
value=b64encode(credentials.encode()).decode(),
hosts=[urlparse(os.environ["GRAFANA_OTLP_ENDPOINT"]).hostname],
))

The agent file runs inside the sandbox. It calls the model, runs the weather tool, and sends a trace of the run to your Grafana Cloud stack before it exits.

agent.py
import json
import os
from uuid import uuid4
from openai import OpenAI
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace import SpanKind
client = OpenAI(api_key=os.environ["LLM_API_KEY"], base_url=os.environ["LLM_BASE_URL"])
model = os.environ["LLM_MODEL"]
agent_name = "weather-agent"
conversation_id = str(uuid4())
endpoint = os.environ["GRAFANA_OTLP_ENDPOINT"].rstrip("/")
exporter = OTLPSpanExporter(
endpoint=f"{endpoint}/v1/traces",
headers={"Authorization": f"Basic {os.environ['GRAFANA_OTLP_AUTH']}"},
)
provider = TracerProvider(resource=Resource.create({
"service.name": agent_name,
"service.instance.id": os.environ["SANDBOX_ID"],
}))
provider.add_span_processor(BatchSpanProcessor(exporter))
tracer = provider.get_tracer(agent_name)
def get_weather(city):
return "sunny, 64 degrees Fahrenheit"
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
prompt = "What is the weather in San Francisco?"
messages = [{"role": "user", "content": prompt}]
trace_messages = [{"role": "user", "parts": [{"type": "text", "content": prompt}]}]
def chat():
with tracer.start_as_current_span(f"chat {model}", kind=SpanKind.CLIENT, attributes={
"agento11y.record": True,
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": os.environ["LLM_PROVIDER"],
"gen_ai.request.model": model,
"gen_ai.agent.name": agent_name,
"gen_ai.conversation.id": conversation_id,
}) as span:
span.set_attribute("gen_ai.input.messages", json.dumps(trace_messages))
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
if response.usage is not None:
span.set_attribute("gen_ai.usage.input_tokens", response.usage.prompt_tokens)
span.set_attribute("gen_ai.usage.output_tokens", response.usage.completion_tokens)
message = response.choices[0].message
parts = []
if message.content is not None:
parts.append({"type": "text", "content": message.content})
for call in message.tool_calls or []:
parts.append({"type": "tool_call", "id": call.id, "name": call.function.name,
"arguments": json.loads(call.function.arguments)})
output = {"role": "assistant", "parts": parts}
span.set_attribute("gen_ai.output.messages", json.dumps([output]))
trace_messages.append(output)
return message
try:
with tracer.start_as_current_span(agent_name):
message = chat()
if message.tool_calls:
messages.append({
"role": "assistant",
"content": message.content,
"tool_calls": [
{
"id": call.id,
"type": "function",
"function": {"name": call.function.name, "arguments": call.function.arguments},
}
for call in message.tool_calls
],
})
for call in message.tool_calls:
with tracer.start_as_current_span("execute_tool get_weather", attributes={
"gen_ai.operation.name": "execute_tool",
"gen_ai.tool.name": "get_weather",
}):
result = get_weather(**json.loads(call.function.arguments))
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
trace_messages.append({"role": "tool", "parts": [
{"type": "tool_call_response", "id": call.id, "response": result},
]})
message = chat()
print(message.content)
finally:
provider.shutdown()

The launcher runs on your machine. It creates a sandbox with the secrets mounted, uploads and runs the agent file, and deletes the sandbox when the agent finishes.

run.py
import os
import sys
from daytona import Daytona
from daytona.v0 import CreateSandboxFromSnapshotParams
daytona = Daytona()
sandbox = daytona.v0.create(CreateSandboxFromSnapshotParams(
language="python",
secrets={"LLM_API_KEY": "llm-api-key", "GRAFANA_OTLP_AUTH": "grafana-otlp-auth"},
env_vars={
"LLM_BASE_URL": os.environ["LLM_BASE_URL"],
"LLM_MODEL": os.environ["LLM_MODEL"],
"LLM_PROVIDER": os.environ["LLM_PROVIDER"],
"GRAFANA_OTLP_ENDPOINT": os.environ["GRAFANA_OTLP_ENDPOINT"],
},
))
print(f"Sandbox ID: {sandbox.id}")
try:
sandbox.fs.upload_file("agent.py", "agent.py")
sandbox.process.exec("pip install -q openai opentelemetry-sdk opentelemetry-exporter-otlp-proto-http", timeout=300)
response = sandbox.process.exec("python agent.py", env={"SANDBOX_ID": sandbox.id}, timeout=120)
print(response.result)
if response.exit_code != 0:
sys.exit(response.exit_code)
finally:
sandbox.delete()
  1. Follow Grafana’s OpenTelemetry verification steps and open Observability > Agent Observability > Conversations.
  2. Select a time range that includes the run, filter by agent name weather-agent, and open the conversation. The underlying trace carries the sandbox ID in the service.instance.id resource attribute.

Arize AX is a platform for tracing AI applications. This example sends traces from a Daytona Sandbox to Arize AX over HTTPS. OpenInference records the model calls, while the example records the agent run and tool execution in the same trace.

You need an Arize AX account. From Space Settings, copy your Space ID and API Key.

SettingValueType
llm-api-keyYour model provider’s API key, read from LLM_API_KEYSecret
arize-api-keyYour Arize API key, read from ARIZE_API_KEYSecret
LLM_BASE_URLThe base URL of your model provider’s OpenAI-compatible endpointEnvironment variable
LLM_MODELA model that accepts tool calls on the Chat Completions APIEnvironment variable
LLM_PROVIDERThe model provider name recorded in the traceEnvironment variable
ARIZE_SPACE_IDYour Arize Space IDEnvironment variable
ARIZE_PROJECT_NAMEweather-agent, set by the launcherEnvironment variable
<provider host>Host of LLM_BASE_URL, on the allowlist of llm-api-keyAllowed host
otlp.arize.comArize collector host, on the allowlist of arize-api-keyAllowed host
  1. Install the Daytona SDK on your machine: pip install "daytona[v0-sdk]>=2,<3" for Python, or npm install @daytona/sdk@2 tsx for TypeScript. The TypeScript SDK requires Node.js 22.15 or later.
  2. Set these environment variables on your machine: DAYTONA_API_KEY, LLM_API_KEY, LLM_BASE_URL, ARIZE_API_KEY, LLM_MODEL, LLM_PROVIDER, and ARIZE_SPACE_ID.
  3. Save the secrets file as store_secrets.py or store_secrets.ts and run it once to store the keys: python store_secrets.py or npx tsx store_secrets.ts.
  4. Save the agent file as agent.py or agent.ts in the same directory.
  5. Save the launcher as run.py or run.ts in the same directory and run it: python run.py or npx tsx run.ts. It prints the sandbox ID and the agent’s answer, then deletes the sandbox. You can run it again without storing the keys again.
  6. View the trace in Arize AX as described below.

The secrets file stores your model provider key and your Arize API key as Daytona secrets, each limited to the host that uses it. Run it once on your machine.

store_secrets.py
import os
from urllib.parse import urlparse
from daytona import Daytona
from daytona.v0 import CreateSecretParams
daytona = Daytona()
daytona.v0.secret.create(CreateSecretParams(
name="llm-api-key",
value=os.environ["LLM_API_KEY"],
hosts=[urlparse(os.environ["LLM_BASE_URL"]).hostname],
))
daytona.v0.secret.create(CreateSecretParams(
name="arize-api-key",
value=os.environ["ARIZE_API_KEY"],
hosts=["otlp.arize.com"],
))

The agent file runs inside the sandbox. It calls the model, runs the weather tool, and sends a trace of the run to Arize AX before it exits.

agent.py
import json
import os
from openai import OpenAI
from openinference.instrumentation import TracerProvider, using_metadata
from openinference.instrumentation.openai import OpenAIInstrumentor
from openinference.semconv.resource import ResourceAttributes
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace.export import BatchSpanProcessor
tracer_provider = TracerProvider(resource=Resource.create({
ResourceAttributes.PROJECT_NAME: os.environ["ARIZE_PROJECT_NAME"],
}))
exporter = OTLPSpanExporter(
endpoint="https://otlp.arize.com/v1/traces",
headers={
"space_id": os.environ["ARIZE_SPACE_ID"],
"api_key": os.environ["ARIZE_API_KEY"],
},
)
tracer_provider.add_span_processor(BatchSpanProcessor(exporter))
OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)
tracer = tracer_provider.get_tracer(__name__)
client = OpenAI(api_key=os.environ["LLM_API_KEY"], base_url=os.environ["LLM_BASE_URL"])
model = os.environ["LLM_MODEL"]
def get_weather(city):
return "sunny, 64 degrees Fahrenheit"
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What is the weather in San Francisco?"}]
with using_metadata({
"sandbox_id": os.environ["SANDBOX_ID"],
"llm_provider": os.environ["LLM_PROVIDER"],
}), tracer.start_as_current_span("weather-agent", attributes={"openinference.span.kind": "AGENT"}):
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
if message.tool_calls:
messages.append({
"role": "assistant",
"content": message.content,
"tool_calls": [
{
"id": call.id,
"type": "function",
"function": {"name": call.function.name, "arguments": call.function.arguments},
}
for call in message.tool_calls
],
})
for call in message.tool_calls:
with tracer.start_as_current_span("get_weather", attributes={
"openinference.span.kind": "TOOL",
"tool.name": "get_weather",
}):
result = get_weather(**json.loads(call.function.arguments))
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
print(message.content)
tracer_provider.force_flush()

The launcher runs on your machine. It creates a sandbox with the secrets mounted, uploads and runs the agent file, and deletes the sandbox when the agent finishes.

run.py
import os
import sys
from daytona import Daytona
from daytona.v0 import CreateSandboxFromSnapshotParams
daytona = Daytona()
sandbox = daytona.v0.create(CreateSandboxFromSnapshotParams(
language="python",
secrets={"LLM_API_KEY": "llm-api-key", "ARIZE_API_KEY": "arize-api-key"},
env_vars={
"LLM_BASE_URL": os.environ["LLM_BASE_URL"],
"LLM_MODEL": os.environ["LLM_MODEL"],
"LLM_PROVIDER": os.environ["LLM_PROVIDER"],
"ARIZE_SPACE_ID": os.environ["ARIZE_SPACE_ID"],
"ARIZE_PROJECT_NAME": "weather-agent",
},
))
print(f"Sandbox ID: {sandbox.id}")
try:
sandbox.fs.upload_file("agent.py", "agent.py")
sandbox.process.exec(
"pip install -q openai openinference-instrumentation-openai opentelemetry-exporter-otlp-proto-http",
timeout=300,
)
response = sandbox.process.exec("python agent.py", env={"SANDBOX_ID": sandbox.id}, timeout=120)
print(response.result)
if response.exit_code != 0:
sys.exit(response.exit_code)
finally:
sandbox.delete()
  1. Open your Arize AX space and select project weather-agent.
  2. Open the trace and select the weather-agent span. Match the sandbox_id in its metadata to the sandbox ID printed by the launcher.
  3. Expand the span to see the two model calls and the get_weather tool execution.

Langfuse Cloud is the hosted version of Langfuse, an open source platform for tracing LLM applications. This example uses the Langfuse SDK and its OpenAI integration to record each model call as a generation and the weather tool call as a tool observation in one trace. The SDK sends the trace to your Langfuse Cloud project over HTTPS before the agent exits. Every observation in the trace carries the sandbox ID and the model provider name as metadata.

You need a Langfuse Cloud project and its public and secret key pair. To create the keys, open Project Settings > API Keys > Create new API keys in Langfuse. Langfuse shows the secret key only once.

SettingValueType
llm-api-keyYour model provider’s API key, read from LLM_API_KEYSecret
langfuse-secret-keyYour Langfuse secret key, read from LANGFUSE_SECRET_KEYSecret
LLM_BASE_URLThe base URL of your model provider’s OpenAI-compatible endpointEnvironment variable
LLM_MODELA model that accepts tool calls on the Chat Completions APIEnvironment variable
LLM_PROVIDERThe model provider name recorded in the traceEnvironment variable
LANGFUSE_PUBLIC_KEYYour Langfuse public keyEnvironment variable
LANGFUSE_BASE_URLhttps://cloud.langfuse.com for the EU region, or https://us.cloud.langfuse.com for the US regionEnvironment variable
<provider host>Host of LLM_BASE_URL, on the allowlist of llm-api-keyAllowed host
cloud.langfuse.comHost of LANGFUSE_BASE_URL in the EU region, on the allowlist of langfuse-secret-keyAllowed host
us.cloud.langfuse.comHost of LANGFUSE_BASE_URL in the US region, on the allowlist of langfuse-secret-keyAllowed host
  1. Install the Daytona SDK on your machine: pip install "daytona[v0-sdk]>=2,<3" for Python, or npm install @daytona/sdk@2 tsx for TypeScript. The TypeScript SDK requires Node.js 22.15 or later.
  2. Set these environment variables on your machine: DAYTONA_API_KEY, LLM_API_KEY, LLM_BASE_URL, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL, LLM_MODEL, LLM_PROVIDER, and LANGFUSE_PUBLIC_KEY.
  3. Save the secrets file as store_secrets.py or store_secrets.ts and run it once to store the keys: python store_secrets.py or npx tsx store_secrets.ts.
  4. Save the agent file as agent.py or agent.ts in the same directory.
  5. Save the launcher as run.py or run.ts in the same directory and run it: python run.py or npx tsx run.ts. It prints the sandbox ID and the agent’s answer, then deletes the sandbox. You can run it again without storing the keys again.
  6. View the trace in Langfuse Cloud as described below.

The secrets file stores your model provider key and your Langfuse secret key as Daytona secrets, each limited to the host that uses it. Run it once on your machine.

store_secrets.py
import os
from urllib.parse import urlparse
from daytona import Daytona
from daytona.v0 import CreateSecretParams
daytona = Daytona()
daytona.v0.secret.create(CreateSecretParams(
name="llm-api-key",
value=os.environ["LLM_API_KEY"],
hosts=[urlparse(os.environ["LLM_BASE_URL"]).hostname],
))
daytona.v0.secret.create(CreateSecretParams(
name="langfuse-secret-key",
value=os.environ["LANGFUSE_SECRET_KEY"],
hosts=[urlparse(os.environ["LANGFUSE_BASE_URL"]).hostname],
))

The agent file runs inside the sandbox. It calls the model, runs the weather tool, and sends a trace of the run to Langfuse Cloud before it exits.

agent.py
import json
import os
from langfuse import get_client, observe, propagate_attributes
from langfuse.openai import OpenAI
client = OpenAI(api_key=os.environ["LLM_API_KEY"], base_url=os.environ["LLM_BASE_URL"])
model = os.environ["LLM_MODEL"]
@observe(as_type="tool")
def get_weather(city):
return "sunny, 64 degrees Fahrenheit"
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
@observe(name="weather-agent")
def weather_agent():
metadata = {"sandbox_id": os.environ["SANDBOX_ID"], "llm_provider": os.environ["LLM_PROVIDER"]}
with propagate_attributes(metadata=metadata):
messages = [{"role": "user", "content": "What is the weather in San Francisco?"}]
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
if message.tool_calls:
messages.append({
"role": "assistant",
"content": message.content,
"tool_calls": [
{
"id": call.id,
"type": "function",
"function": {"name": call.function.name, "arguments": call.function.arguments},
}
for call in message.tool_calls
],
})
for call in message.tool_calls:
result = get_weather(**json.loads(call.function.arguments))
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
print(message.content)
weather_agent()
get_client().flush()

The launcher runs on your machine. It creates a sandbox with the secrets mounted, uploads and runs the agent file, and deletes the sandbox when the agent finishes.

run.py
import os
import sys
from daytona import Daytona
from daytona.v0 import CreateSandboxFromSnapshotParams
daytona = Daytona()
sandbox = daytona.v0.create(CreateSandboxFromSnapshotParams(
language="python",
secrets={"LLM_API_KEY": "llm-api-key", "LANGFUSE_SECRET_KEY": "langfuse-secret-key"},
env_vars={
"LLM_BASE_URL": os.environ["LLM_BASE_URL"],
"LLM_MODEL": os.environ["LLM_MODEL"],
"LLM_PROVIDER": os.environ["LLM_PROVIDER"],
"LANGFUSE_PUBLIC_KEY": os.environ["LANGFUSE_PUBLIC_KEY"],
"LANGFUSE_BASE_URL": os.environ["LANGFUSE_BASE_URL"],
},
))
print(f"Sandbox ID: {sandbox.id}")
try:
sandbox.fs.upload_file("agent.py", "agent.py")
sandbox.process.exec("pip install -q langfuse openai", timeout=300)
response = sandbox.process.exec("python agent.py", env={"SANDBOX_ID": sandbox.id}, timeout=120)
print(response.result)
if response.exit_code != 0:
sys.exit(response.exit_code)
finally:
sandbox.delete()
  1. Open your project in Langfuse Cloud and go to the Tracing table.
  2. Filter by the metadata key sandbox_id with the sandbox ID that the launcher printed. Every observation of the run carries this key and the llm_provider key.
  3. Open the trace. It holds two generations, one for each model call, and the get_weather tool observation.

LangSmith records each request to an agent as a trace: a tree of runs for the agent’s steps, model calls, and tool calls. This example uses the LangSmith SDK to wrap the OpenAI client and to trace the agent function and its weather tool, so one trace holds both model calls and the tool call. The SDK sends the trace to LangSmith Cloud over HTTPS. The sandbox ID and the model provider name travel with the trace as metadata on its root run.

You need a LangSmith account with a project-based workspace and a LangSmith API key, either a personal access token or a service key. To create the key, navigate to the Settings page and select the API Keys section.

SettingValueType
llm-api-keyYour model provider’s API key, read from LLM_API_KEYSecret
langsmith-api-keyYour LangSmith API key, read from LANGSMITH_API_KEYSecret
LLM_BASE_URLThe base URL of your model provider’s OpenAI-compatible endpointEnvironment variable
LLM_MODELA model that accepts tool calls on the Chat Completions APIEnvironment variable
LLM_PROVIDERThe model provider name recorded in the traceEnvironment variable
LANGSMITH_TRACINGtrue, set by the launcher to turn on tracingEnvironment variable
LANGSMITH_ENDPOINTThe API URL of your LangSmith region: https://api.smith.langchain.com for US or https://eu.api.smith.langchain.com for EUEnvironment variable
LANGSMITH_PROJECTweather-agent, set by the launcher as the project that receives the tracesEnvironment variable
LANGSMITH_WORKSPACE_IDOptional. Your Workspace ID from the Settings page under General, needed only when your API key is scoped to more than one workspaceEnvironment variable
<provider host>Host of LLM_BASE_URL, on the allowlist of llm-api-keyAllowed host
api.smith.langchain.comHost of LANGSMITH_ENDPOINT in the US region, on the allowlist of langsmith-api-keyAllowed host
eu.api.smith.langchain.comHost of LANGSMITH_ENDPOINT in the EU region, on the allowlist of langsmith-api-keyAllowed host
  1. Install the Daytona SDK on your machine: pip install "daytona[v0-sdk]>=2,<3" for Python, or npm install @daytona/sdk@2 tsx for TypeScript. The TypeScript SDK requires Node.js 22.15 or later.
  2. Set these environment variables on your machine: DAYTONA_API_KEY, LLM_API_KEY, LLM_BASE_URL, LANGSMITH_API_KEY, LANGSMITH_ENDPOINT, LLM_MODEL, LLM_PROVIDER, and LANGSMITH_WORKSPACE_ID if your API key is scoped to more than one workspace.
  3. Save the secrets file as store_secrets.py or store_secrets.ts and run it once to store the keys: python store_secrets.py or npx tsx store_secrets.ts.
  4. Save the agent file as agent.py or agent.ts in the same directory.
  5. Save the launcher as run.py or run.ts in the same directory and run it: python run.py or npx tsx run.ts. It prints the sandbox ID and the agent’s answer, then deletes the sandbox. You can run it again without storing the keys again.
  6. View the trace in LangSmith as described below.

The secrets file stores your model provider key and your LangSmith API key as Daytona secrets, each limited to the host that uses it. Run it once on your machine.

store_secrets.py
import os
from urllib.parse import urlparse
from daytona import Daytona
from daytona.v0 import CreateSecretParams
daytona = Daytona()
daytona.v0.secret.create(CreateSecretParams(
name="llm-api-key",
value=os.environ["LLM_API_KEY"],
hosts=[urlparse(os.environ["LLM_BASE_URL"]).hostname],
))
daytona.v0.secret.create(CreateSecretParams(
name="langsmith-api-key",
value=os.environ["LANGSMITH_API_KEY"],
hosts=[urlparse(os.environ["LANGSMITH_ENDPOINT"]).hostname],
))

The agent file runs inside the sandbox. It calls the model, runs the weather tool, and sends a trace of the run to LangSmith before it exits.

agent.py
import json
import os
from langsmith import Client, traceable
from langsmith.wrappers import wrap_openai
from openai import OpenAI
langsmith_client = Client()
client = wrap_openai(
OpenAI(api_key=os.environ["LLM_API_KEY"], base_url=os.environ["LLM_BASE_URL"]),
tracing_extra={"client": langsmith_client},
)
model = os.environ["LLM_MODEL"]
@traceable(run_type="tool", client=langsmith_client)
def get_weather(city):
return "sunny, 64 degrees Fahrenheit"
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
@traceable(
name="weather-agent",
client=langsmith_client,
metadata={"sandbox_id": os.environ["SANDBOX_ID"], "llm_provider": os.environ["LLM_PROVIDER"]},
)
def weather_agent():
messages = [{"role": "user", "content": "What is the weather in San Francisco?"}]
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
if message.tool_calls:
messages.append({
"role": "assistant",
"content": message.content,
"tool_calls": [
{
"id": call.id,
"type": "function",
"function": {"name": call.function.name, "arguments": call.function.arguments},
}
for call in message.tool_calls
],
})
for call in message.tool_calls:
result = get_weather(**json.loads(call.function.arguments))
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
return message.content
print(weather_agent())
langsmith_client.flush()

The launcher runs on your machine. It creates a sandbox with the secrets mounted, uploads and runs the agent file, and deletes the sandbox when the agent finishes.

run.py
import os
import sys
from daytona import Daytona
from daytona.v0 import CreateSandboxFromSnapshotParams
daytona = Daytona()
env_vars = {
"LLM_BASE_URL": os.environ["LLM_BASE_URL"],
"LLM_MODEL": os.environ["LLM_MODEL"],
"LLM_PROVIDER": os.environ["LLM_PROVIDER"],
"LANGSMITH_TRACING": "true",
"LANGSMITH_ENDPOINT": os.environ["LANGSMITH_ENDPOINT"],
"LANGSMITH_PROJECT": "weather-agent",
}
if "LANGSMITH_WORKSPACE_ID" in os.environ:
env_vars["LANGSMITH_WORKSPACE_ID"] = os.environ["LANGSMITH_WORKSPACE_ID"]
sandbox = daytona.v0.create(CreateSandboxFromSnapshotParams(
language="python",
secrets={"LLM_API_KEY": "llm-api-key", "LANGSMITH_API_KEY": "langsmith-api-key"},
env_vars=env_vars,
))
print(f"Sandbox ID: {sandbox.id}")
try:
sandbox.fs.upload_file("agent.py", "agent.py")
sandbox.process.exec("pip install -q langsmith openai", timeout=300)
response = sandbox.process.exec("python agent.py", env={"SANDBOX_ID": sandbox.id}, timeout=120)
print(response.result)
if response.exit_code != 0:
sys.exit(response.exit_code)
finally:
sandbox.delete()
  1. In LangSmith, open the project named by LANGSMITH_PROJECT, weather-agent.
  2. Click the weather-agent row to open the trace.
  3. Select the Details tab to see the full run tree: the weather-agent run with the two model calls and the get_weather tool call nested inside it.
  4. Find the sandbox ID in the metadata of the weather-agent run under the key sandbox_id, next to the model provider name under llm_provider.

Datadog Agent Observability records each run of an agent as a trace of spans for the agent’s steps, model calls, and tool calls. This example uses the Datadog SDK to instrument the OpenAI client and to trace the agent and its weather tool, so one trace holds both model calls and the tool call. The SDK sends the trace to Datadog over HTTPS without a Datadog Agent. The sandbox ID and the model provider name travel with the trace as tags on its agent span. The launcher turns off the SDK’s APM tracing, telemetry, and Remote Configuration, so the SDK sends the key only to the intake hosts in the table below.

You need a Datadog account and a Datadog API key. To create the key, navigate to Organization Settings and select API Keys.

SettingValueType
llm-api-keyYour model provider’s API key, read from LLM_API_KEYSecret
datadog-api-keyYour Datadog API key, read from DD_API_KEYSecret
LLM_BASE_URLThe base URL of your model provider’s OpenAI-compatible endpointEnvironment variable
LLM_MODELA model that accepts tool calls on the Chat Completions APIEnvironment variable
LLM_PROVIDERThe model provider name recorded in the traceEnvironment variable
DD_SITEYour Datadog site, such as datadoghq.com for US1 or datadoghq.eu for EU1Environment variable
DD_APM_TRACING_ENABLEDfalse, set by the launcher to turn off APM tracingEnvironment variable
DD_INSTRUMENTATION_TELEMETRY_ENABLEDfalse, set by the launcher to turn off the SDK’s telemetryEnvironment variable
DD_REMOTE_CONFIGURATION_ENABLEDfalse, set by the launcher to turn off Remote ConfigurationEnvironment variable
DD_LLMOBS_ENABLED1, set by the TypeScript launcher to turn on Agent ObservabilityEnvironment variable
DD_LLMOBS_ML_APPweather-agent, set by the TypeScript launcher as the application that receives the tracesEnvironment variable
DD_LLMOBS_AGENTLESS_ENABLED1, set by the TypeScript launcher to send traces without a Datadog AgentEnvironment variable
NODE_OPTIONS--import dd-trace/initialize.mjs, set by the TypeScript launcher to load the Datadog SDK before the agentEnvironment variable
<provider host>Host of LLM_BASE_URL, on the allowlist of llm-api-keyAllowed host
llmobs-intake.<DD_SITE>Agent Observability intake for your site, on the allowlist of datadog-api-keyAllowed host
public-trace-http-intake.logs.<DD_SITE>Trace intake that the TypeScript SDK also sends to, on the allowlist of datadog-api-keyAllowed host
  1. Install the Daytona SDK on your machine: pip install "daytona[v0-sdk]>=2,<3" for Python, or npm install @daytona/sdk@2 tsx for TypeScript. The TypeScript SDK requires Node.js 22.15 or later.
  2. Set these environment variables on your machine: DAYTONA_API_KEY, LLM_API_KEY, LLM_BASE_URL, DD_API_KEY, DD_SITE, LLM_MODEL, and LLM_PROVIDER.
  3. Save the secrets file as store_secrets.py or store_secrets.ts and run it once to store the keys: python store_secrets.py or npx tsx store_secrets.ts.
  4. Save the agent file as agent.py or agent.ts in the same directory.
  5. Save the launcher as run.py or run.ts in the same directory and run it: python run.py or npx tsx run.ts. It prints the sandbox ID and the agent’s answer, then deletes the sandbox. You can run it again without storing the keys again.
  6. View the trace in Datadog as described below.

The secrets file stores your model provider key and your Datadog API key as Daytona secrets, each limited to the hosts that use it. Run it once on your machine.

store_secrets.py
import os
from urllib.parse import urlparse
from daytona import Daytona
from daytona.v0 import CreateSecretParams
daytona = Daytona()
daytona.v0.secret.create(CreateSecretParams(
name="llm-api-key",
value=os.environ["LLM_API_KEY"],
hosts=[urlparse(os.environ["LLM_BASE_URL"]).hostname],
))
daytona.v0.secret.create(CreateSecretParams(
name="datadog-api-key",
value=os.environ["DD_API_KEY"],
hosts=[f"llmobs-intake.{os.environ['DD_SITE']}", f"public-trace-http-intake.logs.{os.environ['DD_SITE']}"],
))

The agent file runs inside the sandbox. It calls the model, runs the weather tool, and sends a trace of the run to Datadog before it exits.

agent.py
import json
import os
from ddtrace.llmobs import LLMObs
from openai import OpenAI
LLMObs.enable(
ml_app="weather-agent",
agentless_enabled=True,
site=os.environ["DD_SITE"],
api_key=os.environ["DD_API_KEY"],
)
client = OpenAI(api_key=os.environ["LLM_API_KEY"], base_url=os.environ["LLM_BASE_URL"])
model = os.environ["LLM_MODEL"]
def get_weather(city):
return "sunny, 64 degrees Fahrenheit"
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What is the weather in San Francisco?"}]
with LLMObs.agent(name="weather-agent"):
LLMObs.annotate(tags={
"sandbox_id": os.environ["SANDBOX_ID"],
"llm_provider": os.environ["LLM_PROVIDER"],
})
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
if message.tool_calls:
messages.append({
"role": "assistant",
"content": message.content,
"tool_calls": [
{
"id": call.id,
"type": "function",
"function": {"name": call.function.name, "arguments": call.function.arguments},
}
for call in message.tool_calls
],
})
for call in message.tool_calls:
with LLMObs.tool(name="get_weather"):
result = get_weather(**json.loads(call.function.arguments))
LLMObs.annotate(input_data=call.function.arguments, output_data=result)
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = response.choices[0].message
print(message.content)
LLMObs.flush()

The launcher runs on your machine. It creates a sandbox with the secrets mounted, uploads and runs the agent file, and deletes the sandbox when the agent finishes.

run.py
import os
import sys
from daytona import Daytona
from daytona.v0 import CreateSandboxFromSnapshotParams
daytona = Daytona()
env_vars = {
"LLM_BASE_URL": os.environ["LLM_BASE_URL"],
"LLM_MODEL": os.environ["LLM_MODEL"],
"LLM_PROVIDER": os.environ["LLM_PROVIDER"],
"DD_SITE": os.environ["DD_SITE"],
"DD_APM_TRACING_ENABLED": "false",
"DD_INSTRUMENTATION_TELEMETRY_ENABLED": "false",
"DD_REMOTE_CONFIGURATION_ENABLED": "false",
}
sandbox = daytona.v0.create(CreateSandboxFromSnapshotParams(
language="python",
secrets={"LLM_API_KEY": "llm-api-key", "DD_API_KEY": "datadog-api-key"},
env_vars=env_vars,
))
print(f"Sandbox ID: {sandbox.id}")
try:
sandbox.fs.upload_file("agent.py", "agent.py")
sandbox.process.exec("pip install -q ddtrace openai", timeout=300)
response = sandbox.process.exec("python agent.py", env={"SANDBOX_ID": sandbox.id}, timeout=120)
print(response.result)
if response.exit_code != 0:
sys.exit(response.exit_code)
finally:
sandbox.delete()
  1. In Datadog, open Agent Observability and select Traces.
  2. Search for sandbox_id:<id> with the sandbox ID the launcher printed. A trace can take up to a minute to appear.
  3. Open the weather-agent trace to see the two model calls and the get_weather tool call nested inside it.
  4. Find the sandbox ID among the tags of the weather-agent span under sandbox_id, next to the model provider name under llm_provider.

Check the agent’s output first. A tracing library reports a failed export in the agent’s output and does not stop the agent from printing its answer. The Datadog TypeScript example reports it only with debug logging turned on. The Python examples and the LangSmith and Datadog TypeScript examples then exit with code 0, and the Grafana Cloud, Arize, and Langfuse TypeScript examples exit with code 1. A run can print its answer without sending a trace.

Symptom: The agent runs and prints its answer, but no trace appears in the platform.

Cause: The agent exited before the library sent its pending traces, a setting the platform needs is missing, or the export failed.

Solution:

  1. End the agent with the platform’s flush call, as the examples do
  2. For Grafana Cloud, set agento11y.record to true on the spans
  3. For LangSmith, set LANGSMITH_TRACING to true
  4. For a direct OpenTelemetry export to Langfuse, send the x-langfuse-ingestion-version header with the value 4, as the TypeScript example does. The header turns on Langfuse’s real-time ingestion. Without it, a trace can appear up to 10 minutes late
  5. For Datadog in TypeScript, set DD_TRACE_DEBUG to true and DD_TRACE_LOG_LEVEL to error in the agent’s environment. The SDK does not report a failed export otherwise
  6. Look for an export error in the agent’s output. The exit code does not always show a failed export

See Flushing.