Agent Tracing
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.
| Type | Records | Runs in |
|---|---|---|
| Sandbox telemetry | CPU, memory, and filesystem metrics, application logs, and HTTP spans | Sandbox runtime |
| SDK tracing | Daytona SDK operations and API calls | Your application |
| Agent tracing | LLM calls, tool calls, token usage, and errors | Agent code in the sandbox |
Agent tracing supports the following platforms:
How agent tracing works
Section titled “How agent tracing works”An agent sends traces to the platform from inside the sandbox, using credentials it never holds in plaintext:
- 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.
- You create a sandbox that maps those secrets to environment variables. The sandbox holds placeholders, not keys.
- The agent runs in the sandbox with a tracing library that records each LLM call and tool call.
- The library sends traces to the platform over HTTPS. Daytona replaces the placeholder with the real key on the way out.
- The agent flushes pending traces before it exits. The trace appears in the platform with the sandbox ID on it.
Model provider
Section titled “Model provider”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.
| Provider | Base URL | Tested |
|---|---|---|
| OpenAI | https://api.openai.com/v1 | Yes |
| Anthropic | https://api.anthropic.com/v1/ | Yes |
| Google Gemini | https://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.
Credentials
Section titled “Credentials”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.
Sandbox ID
Section titled “Sandbox ID”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.
| Platform | Field |
|---|---|
| Grafana Cloud | Resource attribute service.instance.id |
| Arize | Metadata key sandbox_id on the agent span |
| Langfuse | Metadata key sandbox_id on every observation |
| LangSmith | Metadata key sandbox_id on the root run |
| Datadog | Tag sandbox_id on the agent span |
For environment variables on a single run, see process and code execution.
Flushing
Section titled “Flushing”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.
Captured content
Section titled “Captured content”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.
| Platform | Setting | Source |
|---|---|---|
| Grafana Cloud | Leave out the gen_ai.input.messages and gen_ai.output.messages attributes | Grafana Cloud documentation |
| Arize | OPENINFERENCE_HIDE_INPUTS and OPENINFERENCE_HIDE_OUTPUTS set to true | Arize documentation |
| Langfuse | A mask_otel_spans function on the Langfuse client (Python) or a mask function on LangfuseSpanProcessor (TypeScript) that replaces inputs and outputs | Langfuse documentation |
| LangSmith | LANGSMITH_HIDE_INPUTS and LANGSMITH_HIDE_OUTPUTS set to true | LangSmith documentation |
| Datadog | A span processor passed to LLMObs.enable (Python) or registered with llmobs.registerProcessor (TypeScript) that replaces inputs and outputs | Datadog documentation |
Anything the agent prints is also collected as sandbox logs by sandbox telemetry.
Grafana Cloud
Section titled “Grafana Cloud”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.
| Setting | Value | Type |
|---|---|---|
llm-api-key | Your model provider’s API key, read from LLM_API_KEY | Secret |
grafana-otlp-auth | The Base64-encoded pair made from GRAFANA_INSTANCE_ID and GRAFANA_ACCESS_TOKEN | Secret |
LLM_BASE_URL | The base URL of your model provider’s OpenAI-compatible endpoint | Environment variable |
LLM_MODEL | A model that accepts tool calls on the Chat Completions API | Environment variable |
LLM_PROVIDER | The model provider name recorded in the trace | Environment variable |
GRAFANA_OTLP_ENDPOINT | Your stack’s OTLP endpoint from the OpenTelemetry tile, ending in /otlp without /v1/traces | Environment variable |
<provider host> | Host of LLM_BASE_URL, on the allowlist of llm-api-key | Allowed host |
otlp-gateway-prod-<region>.grafana.net | Host of GRAFANA_OTLP_ENDPOINT, on the allowlist of grafana-otlp-auth. Use the actual host shown on your stack’s OpenTelemetry tile. | Allowed host |
- Install the Daytona SDK on your machine:
pip install "daytona[v0-sdk]>=2,<3"for Python, ornpm install @daytona/sdk@2 tsxfor TypeScript. The TypeScript SDK requires Node.js 22.15 or later. - 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, andLLM_PROVIDER. - Save the secrets file as
store_secrets.pyorstore_secrets.tsand run it once to store the keys:python store_secrets.pyornpx tsx store_secrets.ts. - Save the agent file as
agent.pyoragent.tsin the same directory. - Save the launcher as
run.pyorrun.tsin the same directory and run it:python run.pyornpx 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. - View the trace in Grafana Cloud as described below.
Secrets file
Section titled “Secrets file”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.
import osfrom base64 import b64encodefrom urllib.parse import urlparse
from daytona import Daytonafrom 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],))import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { await daytona.v0.secret.create({ name: 'llm-api-key', value: process.env.LLM_API_KEY!, hosts: [new URL(process.env.LLM_BASE_URL!).hostname], }) await daytona.v0.secret.create({ name: 'grafana-otlp-auth', value: Buffer.from(`${process.env.GRAFANA_INSTANCE_ID}:${process.env.GRAFANA_ACCESS_TOKEN}`).toString('base64'), hosts: [new URL(process.env.GRAFANA_OTLP_ENDPOINT!).hostname], })}
main()Agent file
Section titled “Agent file”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.
import jsonimport osfrom uuid import uuid4
from openai import OpenAIfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporterfrom opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom 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()import { randomUUID } from 'node:crypto'import { globalAgent } from 'node:https'import OpenAI from 'openai'import { ROOT_CONTEXT, SpanKind, trace } from '@opentelemetry/api'import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'import { resourceFromAttributes } from '@opentelemetry/resources'import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'
const client = new OpenAI({ apiKey: process.env.LLM_API_KEY, baseURL: process.env.LLM_BASE_URL })const model = process.env.LLM_MODEL!
function getWeather(city: string) { return 'sunny, 64 degrees Fahrenheit'}
const tools: OpenAI.ChatCompletionTool[] = [{ type: 'function', function: { name: 'get_weather', description: 'Get the current weather in a city.', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, },}]
async function main() { const agentName = 'weather-agent' const conversationId = randomUUID() const exporter = new OTLPTraceExporter({ url: `${process.env.GRAFANA_OTLP_ENDPOINT!.replace(/\/+$/, '')}/v1/traces`, headers: { Authorization: `Basic ${process.env.GRAFANA_OTLP_AUTH}` }, // Reuse Node's proxy-aware HTTPS agent so Daytona can inject the secret. httpAgentOptions: () => globalAgent, }) const provider = new TracerProvider({ resource: resourceFromAttributes({ 'service.name': agentName, 'service.instance.id': process.env.SANDBOX_ID! }), spanProcessors: [new BatchSpanProcessor({ exporter })], }) const tracer = provider.getTracer(agentName) const parent = tracer.startSpan(agentName) const parentContext = trace.setSpan(ROOT_CONTEXT, parent)
const prompt = 'What is the weather in San Francisco?' const messages: OpenAI.ChatCompletionMessageParam[] = [{ role: 'user', content: prompt }] const traceMessages: { role: string; parts: unknown[] }[] = [ { role: 'user', parts: [{ type: 'text', content: prompt }] }, ]
async function chat() { const span = tracer.startSpan(`chat ${model}`, { kind: SpanKind.CLIENT, attributes: { 'agento11y.record': true, 'gen_ai.operation.name': 'chat', 'gen_ai.provider.name': process.env.LLM_PROVIDER!, 'gen_ai.request.model': model, 'gen_ai.agent.name': agentName, 'gen_ai.conversation.id': conversationId, 'gen_ai.input.messages': JSON.stringify(traceMessages), }, }, parentContext) try { const response = await client.chat.completions.create({ model, messages, tools }) if (response.usage) { span.setAttribute('gen_ai.usage.input_tokens', response.usage.prompt_tokens) span.setAttribute('gen_ai.usage.output_tokens', response.usage.completion_tokens) }
const message = response.choices[0].message const calls = (message.tool_calls ?? []).filter((call) => call.type === 'function') const output = { role: 'assistant', parts: [ ...(message.content === null ? [] : [{ type: 'text', content: message.content }]), ...calls.map((call) => ({ type: 'tool_call', id: call.id, name: call.function.name, arguments: JSON.parse(call.function.arguments), })), ], } span.setAttribute('gen_ai.output.messages', JSON.stringify([output])) traceMessages.push(output) return { message, calls } } finally { span.end() } }
try { let { message, calls } = await chat() if (calls.length > 0) { messages.push({ role: 'assistant', content: message.content, tool_calls: calls.map((call) => ({ id: call.id, type: 'function', function: { name: call.function.name, arguments: call.function.arguments }, })), }) for (const call of calls) { const result = tracer.startActiveSpan('execute_tool get_weather', { attributes: { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': 'get_weather' }, }, parentContext, (span) => { try { return getWeather(JSON.parse(call.function.arguments).city) } finally { span.end() } }) messages.push({ role: 'tool', tool_call_id: call.id, content: result }) traceMessages.push({ role: 'tool', parts: [ { type: 'tool_call_response', id: call.id, response: result }, ] }) } message = (await chat()).message } console.log(message.content) } finally { parent.end() await provider.shutdown() }}
main()Launcher
Section titled “Launcher”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.
import osimport sys
from daytona import Daytonafrom 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()import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { const sandbox = await daytona.v0.create({ language: 'typescript', secrets: { LLM_API_KEY: 'llm-api-key', GRAFANA_OTLP_AUTH: 'grafana-otlp-auth' }, envVars: { LLM_BASE_URL: process.env.LLM_BASE_URL!, LLM_MODEL: process.env.LLM_MODEL!, LLM_PROVIDER: process.env.LLM_PROVIDER!, GRAFANA_OTLP_ENDPOINT: process.env.GRAFANA_OTLP_ENDPOINT!, NODE_USE_ENV_PROXY: '1', }, }) console.log(`Sandbox ID: ${sandbox.id}`)
try { await sandbox.fs.uploadFile('agent.ts', 'agent.ts') await sandbox.process.executeCommand( 'npm install openai tsx @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/resources @opentelemetry/exporter-trace-otlp-proto', undefined, undefined, 300, ) const response = await sandbox.process.executeCommand('npx tsx agent.ts', undefined, { SANDBOX_ID: sandbox.id }, 120) console.log(response.result) process.exitCode = response.exitCode } finally { await sandbox.delete() }}
main()View the trace
Section titled “View the trace”- Follow Grafana’s OpenTelemetry verification steps and open Observability > Agent Observability > Conversations.
- 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 theservice.instance.idresource 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.
| Setting | Value | Type |
|---|---|---|
llm-api-key | Your model provider’s API key, read from LLM_API_KEY | Secret |
arize-api-key | Your Arize API key, read from ARIZE_API_KEY | Secret |
LLM_BASE_URL | The base URL of your model provider’s OpenAI-compatible endpoint | Environment variable |
LLM_MODEL | A model that accepts tool calls on the Chat Completions API | Environment variable |
LLM_PROVIDER | The model provider name recorded in the trace | Environment variable |
ARIZE_SPACE_ID | Your Arize Space ID | Environment variable |
ARIZE_PROJECT_NAME | weather-agent, set by the launcher | Environment variable |
<provider host> | Host of LLM_BASE_URL, on the allowlist of llm-api-key | Allowed host |
otlp.arize.com | Arize collector host, on the allowlist of arize-api-key | Allowed host |
- Install the Daytona SDK on your machine:
pip install "daytona[v0-sdk]>=2,<3"for Python, ornpm install @daytona/sdk@2 tsxfor TypeScript. The TypeScript SDK requires Node.js 22.15 or later. - Set these environment variables on your machine:
DAYTONA_API_KEY,LLM_API_KEY,LLM_BASE_URL,ARIZE_API_KEY,LLM_MODEL,LLM_PROVIDER, andARIZE_SPACE_ID. - Save the secrets file as
store_secrets.pyorstore_secrets.tsand run it once to store the keys:python store_secrets.pyornpx tsx store_secrets.ts. - Save the agent file as
agent.pyoragent.tsin the same directory. - Save the launcher as
run.pyorrun.tsin the same directory and run it:python run.pyornpx 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. - View the trace in Arize AX as described below.
Secrets file
Section titled “Secrets file”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.
import osfrom urllib.parse import urlparse
from daytona import Daytonafrom 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"],))import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { await daytona.v0.secret.create({ name: 'llm-api-key', value: process.env.LLM_API_KEY!, hosts: [new URL(process.env.LLM_BASE_URL!).hostname], }) await daytona.v0.secret.create({ name: 'arize-api-key', value: process.env.ARIZE_API_KEY!, hosts: ['otlp.arize.com'], })}
main()Agent file
Section titled “Agent file”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.
import jsonimport os
from openai import OpenAIfrom openinference.instrumentation import TracerProvider, using_metadatafrom openinference.instrumentation.openai import OpenAIInstrumentorfrom openinference.semconv.resource import ResourceAttributesfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporterfrom opentelemetry.sdk.resources import Resourcefrom 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].messageprint(message.content)tracer_provider.force_flush()import { globalAgent } from 'node:https'import { setMetadata, wrapTracer } from '@arizeai/openinference-core'import { OpenAIInstrumentation } from '@arizeai/openinference-instrumentation-openai'import { SEMRESATTRS_PROJECT_NAME } from '@arizeai/openinference-semantic-conventions'import { context, trace } from '@opentelemetry/api'import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'import { registerInstrumentations } from '@opentelemetry/instrumentation'import { resourceFromAttributes } from '@opentelemetry/resources'import { SimpleSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'import OpenAI from 'openai'
const projectName = process.env.ARIZE_PROJECT_NAME!const provider = new TracerProvider({ resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: projectName, [SEMRESATTRS_PROJECT_NAME]: projectName, }), spanProcessors: [ new SimpleSpanProcessor({ exporter: new OTLPTraceExporter({ url: 'https://otlp.arize.com/v1/traces', headers: { space_id: process.env.ARIZE_SPACE_ID!, api_key: process.env.ARIZE_API_KEY!, }, // Reuse Node's proxy-aware HTTPS agent so Daytona can inject the secret. httpAgentOptions: () => globalAgent, }), }), ],})trace.setGlobalTracerProvider(provider)context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable())const instrumentation = new OpenAIInstrumentation()instrumentation.manuallyInstrument(OpenAI)registerInstrumentations({ instrumentations: [instrumentation] })
const tracer = wrapTracer(provider.getTracer('weather-agent'))const client = new OpenAI({ apiKey: process.env.LLM_API_KEY, baseURL: process.env.LLM_BASE_URL })const model = process.env.LLM_MODEL!
function getWeather(city: string) { return 'sunny, 64 degrees Fahrenheit'}
const tools: OpenAI.ChatCompletionTool[] = [{ type: 'function', function: { name: 'get_weather', description: 'Get the current weather in a city.', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, },}]
async function main() { const runContext = setMetadata(context.active(), { sandbox_id: process.env.SANDBOX_ID, llm_provider: process.env.LLM_PROVIDER, }) await tracer.startActiveSpan('weather-agent', { attributes: { 'openinference.span.kind': 'AGENT' }, }, runContext, async (span) => { try { const messages: OpenAI.ChatCompletionMessageParam[] = [{ role: 'user', content: 'What is the weather in San Francisco?' }] let response = await client.chat.completions.create({ model, messages, tools }) let message = response.choices[0].message const calls = (message.tool_calls ?? []).filter((call) => call.type === 'function') if (calls.length > 0) { messages.push({ role: 'assistant', content: message.content, tool_calls: calls.map((call) => ({ id: call.id, type: 'function', function: { name: call.function.name, arguments: call.function.arguments }, })), }) for (const call of calls) { const toolSpan = tracer.startSpan('get_weather', { attributes: { 'openinference.span.kind': 'TOOL', 'tool.name': 'get_weather' }, }) try { const result = getWeather(JSON.parse(call.function.arguments).city) messages.push({ role: 'tool', tool_call_id: call.id, content: result }) } finally { toolSpan.end() } } response = await client.chat.completions.create({ model, messages, tools }) message = response.choices[0].message } console.log(message.content) } finally { span.end() } }) await provider.forceFlush()}
main()Launcher
Section titled “Launcher”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.
import osimport sys
from daytona import Daytonafrom 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()import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { const sandbox = await daytona.v0.create({ language: 'typescript', secrets: { LLM_API_KEY: 'llm-api-key', ARIZE_API_KEY: 'arize-api-key' }, envVars: { LLM_BASE_URL: process.env.LLM_BASE_URL!, LLM_MODEL: process.env.LLM_MODEL!, LLM_PROVIDER: process.env.LLM_PROVIDER!, ARIZE_SPACE_ID: process.env.ARIZE_SPACE_ID!, ARIZE_PROJECT_NAME: 'weather-agent', NODE_USE_ENV_PROXY: '1', }, }) console.log(`Sandbox ID: ${sandbox.id}`)
try { await sandbox.fs.uploadFile('agent.ts', 'agent.ts') await sandbox.process.executeCommand( 'npm install openai tsx @arizeai/openinference-core @arizeai/openinference-instrumentation-openai ' + '@arizeai/openinference-semantic-conventions @opentelemetry/api @opentelemetry/context-async-hooks ' + '@opentelemetry/exporter-trace-otlp-proto @opentelemetry/instrumentation @opentelemetry/resources ' + '@opentelemetry/sdk-trace @opentelemetry/semantic-conventions', undefined, undefined, 300, ) const response = await sandbox.process.executeCommand('npx tsx agent.ts', undefined, { SANDBOX_ID: sandbox.id }, 120) console.log(response.result) process.exitCode = response.exitCode } finally { await sandbox.delete() }}
main()View the trace
Section titled “View the trace”- Open your Arize AX space and select project
weather-agent. - Open the trace and select the
weather-agentspan. Match thesandbox_idin its metadata to the sandbox ID printed by the launcher. - Expand the span to see the two model calls and the
get_weathertool execution.
Langfuse
Section titled “Langfuse”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.
| Setting | Value | Type |
|---|---|---|
llm-api-key | Your model provider’s API key, read from LLM_API_KEY | Secret |
langfuse-secret-key | Your Langfuse secret key, read from LANGFUSE_SECRET_KEY | Secret |
LLM_BASE_URL | The base URL of your model provider’s OpenAI-compatible endpoint | Environment variable |
LLM_MODEL | A model that accepts tool calls on the Chat Completions API | Environment variable |
LLM_PROVIDER | The model provider name recorded in the trace | Environment variable |
LANGFUSE_PUBLIC_KEY | Your Langfuse public key | Environment variable |
LANGFUSE_BASE_URL | https://cloud.langfuse.com for the EU region, or https://us.cloud.langfuse.com for the US region | Environment variable |
<provider host> | Host of LLM_BASE_URL, on the allowlist of llm-api-key | Allowed host |
cloud.langfuse.com | Host of LANGFUSE_BASE_URL in the EU region, on the allowlist of langfuse-secret-key | Allowed host |
us.cloud.langfuse.com | Host of LANGFUSE_BASE_URL in the US region, on the allowlist of langfuse-secret-key | Allowed host |
- Install the Daytona SDK on your machine:
pip install "daytona[v0-sdk]>=2,<3"for Python, ornpm install @daytona/sdk@2 tsxfor TypeScript. The TypeScript SDK requires Node.js 22.15 or later. - 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, andLANGFUSE_PUBLIC_KEY. - Save the secrets file as
store_secrets.pyorstore_secrets.tsand run it once to store the keys:python store_secrets.pyornpx tsx store_secrets.ts. - Save the agent file as
agent.pyoragent.tsin the same directory. - Save the launcher as
run.pyorrun.tsin the same directory and run it:python run.pyornpx 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. - View the trace in Langfuse Cloud as described below.
Secrets file
Section titled “Secrets file”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.
import osfrom urllib.parse import urlparse
from daytona import Daytonafrom 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],))import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { await daytona.v0.secret.create({ name: 'llm-api-key', value: process.env.LLM_API_KEY!, hosts: [new URL(process.env.LLM_BASE_URL!).hostname], }) await daytona.v0.secret.create({ name: 'langfuse-secret-key', value: process.env.LANGFUSE_SECRET_KEY!, hosts: [new URL(process.env.LANGFUSE_BASE_URL!).hostname], })}
main()Agent file
Section titled “Agent file”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.
import jsonimport os
from langfuse import get_client, observe, propagate_attributesfrom 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()import { globalAgent } from 'node:https'import { LangfuseSpanProcessor } from '@langfuse/otel'import { observeOpenAI } from '@langfuse/openai'import { propagateAttributes, startActiveObservation } from '@langfuse/tracing'import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'import { NodeSDK } from '@opentelemetry/sdk-node'import OpenAI from 'openai'
const credentials = `${process.env.LANGFUSE_PUBLIC_KEY}:${process.env.LANGFUSE_SECRET_KEY}`const exporter = new OTLPTraceExporter({ url: `${process.env.LANGFUSE_BASE_URL}/api/public/otel/v1/traces`, headers: { Authorization: `Basic ${Buffer.from(credentials).toString('base64')}`, 'x-langfuse-ingestion-version': '4', }, // Reuse Node's proxy-aware HTTPS agent so Daytona can inject the secret. httpAgentOptions: () => globalAgent,})const sdk = new NodeSDK({ spanProcessors: [new LangfuseSpanProcessor({ exporter })] })sdk.start()
const client = observeOpenAI(new OpenAI({ apiKey: process.env.LLM_API_KEY, baseURL: process.env.LLM_BASE_URL }))const model = process.env.LLM_MODEL!
function getWeather(city: string) { return 'sunny, 64 degrees Fahrenheit'}
const tools: OpenAI.ChatCompletionTool[] = [{ type: 'function', function: { name: 'get_weather', description: 'Get the current weather in a city.', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, },}]
async function weatherAgent() { const messages: OpenAI.ChatCompletionMessageParam[] = [{ role: 'user', content: 'What is the weather in San Francisco?' }]
let response = await client.chat.completions.create({ model, messages, tools }) let message = response.choices[0].message const calls = (message.tool_calls ?? []).filter((call) => call.type === 'function') if (calls.length > 0) { messages.push({ role: 'assistant', content: message.content, tool_calls: calls.map((call) => ({ id: call.id, type: 'function', function: { name: call.function.name, arguments: call.function.arguments }, })), }) for (const call of calls) { const input = JSON.parse(call.function.arguments) const result = startActiveObservation('get_weather', (tool) => { const output = getWeather(input.city) tool.update({ input, output }) return output }, { asType: 'tool' }) messages.push({ role: 'tool', tool_call_id: call.id, content: result }) } response = await client.chat.completions.create({ model, messages, tools }) message = response.choices[0].message } console.log(message.content)}
async function main() { const metadata = { sandbox_id: process.env.SANDBOX_ID!, llm_provider: process.env.LLM_PROVIDER! } await propagateAttributes({ metadata }, () => startActiveObservation('weather-agent', weatherAgent)) await sdk.shutdown()}
main()Launcher
Section titled “Launcher”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.
import osimport sys
from daytona import Daytonafrom 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()import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { const sandbox = await daytona.v0.create({ language: 'typescript', secrets: { LLM_API_KEY: 'llm-api-key', LANGFUSE_SECRET_KEY: 'langfuse-secret-key' }, envVars: { LLM_BASE_URL: process.env.LLM_BASE_URL!, LLM_MODEL: process.env.LLM_MODEL!, LLM_PROVIDER: process.env.LLM_PROVIDER!, LANGFUSE_PUBLIC_KEY: process.env.LANGFUSE_PUBLIC_KEY!, LANGFUSE_BASE_URL: process.env.LANGFUSE_BASE_URL!, NODE_USE_ENV_PROXY: '1', }, }) console.log(`Sandbox ID: ${sandbox.id}`)
try { await sandbox.fs.uploadFile('agent.ts', 'agent.ts') await sandbox.process.executeCommand( 'npm install openai @langfuse/tracing @langfuse/otel @langfuse/openai "@opentelemetry/sdk-node@>=0.202.0 <0.300.0" ' + '"@opentelemetry/exporter-trace-otlp-http@>=0.202.0 <0.300.0" tsx', undefined, undefined, 300, ) const response = await sandbox.process.executeCommand('npx tsx agent.ts', undefined, { SANDBOX_ID: sandbox.id }, 120) console.log(response.result) process.exitCode = response.exitCode } finally { await sandbox.delete() }}
main()View the trace
Section titled “View the trace”- Open your project in Langfuse Cloud and go to the Tracing table.
- Filter by the metadata key
sandbox_idwith the sandbox ID that the launcher printed. Every observation of the run carries this key and thellm_providerkey. - Open the trace. It holds two generations, one for each model call, and the
get_weathertool observation.
LangSmith
Section titled “LangSmith”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.
| Setting | Value | Type |
|---|---|---|
llm-api-key | Your model provider’s API key, read from LLM_API_KEY | Secret |
langsmith-api-key | Your LangSmith API key, read from LANGSMITH_API_KEY | Secret |
LLM_BASE_URL | The base URL of your model provider’s OpenAI-compatible endpoint | Environment variable |
LLM_MODEL | A model that accepts tool calls on the Chat Completions API | Environment variable |
LLM_PROVIDER | The model provider name recorded in the trace | Environment variable |
LANGSMITH_TRACING | true, set by the launcher to turn on tracing | Environment variable |
LANGSMITH_ENDPOINT | The API URL of your LangSmith region: https://api.smith.langchain.com for US or https://eu.api.smith.langchain.com for EU | Environment variable |
LANGSMITH_PROJECT | weather-agent, set by the launcher as the project that receives the traces | Environment variable |
LANGSMITH_WORKSPACE_ID | Optional. Your Workspace ID from the Settings page under General, needed only when your API key is scoped to more than one workspace | Environment variable |
<provider host> | Host of LLM_BASE_URL, on the allowlist of llm-api-key | Allowed host |
api.smith.langchain.com | Host of LANGSMITH_ENDPOINT in the US region, on the allowlist of langsmith-api-key | Allowed host |
eu.api.smith.langchain.com | Host of LANGSMITH_ENDPOINT in the EU region, on the allowlist of langsmith-api-key | Allowed host |
- Install the Daytona SDK on your machine:
pip install "daytona[v0-sdk]>=2,<3"for Python, ornpm install @daytona/sdk@2 tsxfor TypeScript. The TypeScript SDK requires Node.js 22.15 or later. - 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, andLANGSMITH_WORKSPACE_IDif your API key is scoped to more than one workspace. - Save the secrets file as
store_secrets.pyorstore_secrets.tsand run it once to store the keys:python store_secrets.pyornpx tsx store_secrets.ts. - Save the agent file as
agent.pyoragent.tsin the same directory. - Save the launcher as
run.pyorrun.tsin the same directory and run it:python run.pyornpx 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. - View the trace in LangSmith as described below.
Secrets file
Section titled “Secrets file”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.
import osfrom urllib.parse import urlparse
from daytona import Daytonafrom 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],))import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { await daytona.v0.secret.create({ name: 'llm-api-key', value: process.env.LLM_API_KEY!, hosts: [new URL(process.env.LLM_BASE_URL!).hostname], }) await daytona.v0.secret.create({ name: 'langsmith-api-key', value: process.env.LANGSMITH_API_KEY!, hosts: [new URL(process.env.LANGSMITH_ENDPOINT!).hostname], })}
main()Agent file
Section titled “Agent file”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.
import jsonimport os
from langsmith import Client, traceablefrom langsmith.wrappers import wrap_openaifrom 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()import { Client } from 'langsmith'import { traceable } from 'langsmith/traceable'import { wrapOpenAI } from 'langsmith/wrappers'import OpenAI from 'openai'
const langsmithClient = new Client()const client = wrapOpenAI( new OpenAI({ apiKey: process.env.LLM_API_KEY, baseURL: process.env.LLM_BASE_URL }), { client: langsmithClient },)const model = process.env.LLM_MODEL!
const getWeather = traceable( (city: string) => 'sunny, 64 degrees Fahrenheit', { name: 'get_weather', run_type: 'tool', client: langsmithClient },)
const tools: OpenAI.ChatCompletionTool[] = [{ type: 'function', function: { name: 'get_weather', description: 'Get the current weather in a city.', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, },}]
const weatherAgent = traceable(async () => { const messages: OpenAI.ChatCompletionMessageParam[] = [{ role: 'user', content: 'What is the weather in San Francisco?' }]
let response = await client.chat.completions.create({ model, messages, tools }) let message = response.choices[0].message const calls = (message.tool_calls ?? []).filter((call) => call.type === 'function') if (calls.length > 0) { messages.push({ role: 'assistant', content: message.content, tool_calls: calls.map((call) => ({ id: call.id, type: 'function', function: { name: call.function.name, arguments: call.function.arguments }, })), }) for (const call of calls) { const result = await getWeather(JSON.parse(call.function.arguments).city) messages.push({ role: 'tool', tool_call_id: call.id, content: result }) } response = await client.chat.completions.create({ model, messages, tools }) message = response.choices[0].message } return message.content}, { name: 'weather-agent', client: langsmithClient, metadata: { sandbox_id: process.env.SANDBOX_ID, llm_provider: process.env.LLM_PROVIDER },})
async function main() { console.log(await weatherAgent()) await langsmithClient.awaitPendingTraceBatches()}
main()Launcher
Section titled “Launcher”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.
import osimport sys
from daytona import Daytonafrom 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()import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { const envVars: Record<string, string> = { LLM_BASE_URL: process.env.LLM_BASE_URL!, LLM_MODEL: process.env.LLM_MODEL!, LLM_PROVIDER: process.env.LLM_PROVIDER!, LANGSMITH_TRACING: 'true', LANGSMITH_ENDPOINT: process.env.LANGSMITH_ENDPOINT!, LANGSMITH_PROJECT: 'weather-agent', NODE_USE_ENV_PROXY: '1', } if (process.env.LANGSMITH_WORKSPACE_ID) { envVars.LANGSMITH_WORKSPACE_ID = process.env.LANGSMITH_WORKSPACE_ID }
const sandbox = await daytona.v0.create({ language: 'typescript', secrets: { LLM_API_KEY: 'llm-api-key', LANGSMITH_API_KEY: 'langsmith-api-key' }, envVars, }) console.log(`Sandbox ID: ${sandbox.id}`)
try { await sandbox.fs.uploadFile('agent.ts', 'agent.ts') await sandbox.process.executeCommand('npm install langsmith openai tsx', undefined, undefined, 300) const response = await sandbox.process.executeCommand('npx tsx agent.ts', undefined, { SANDBOX_ID: sandbox.id }, 120) console.log(response.result) process.exitCode = response.exitCode } finally { await sandbox.delete() }}
main()View the trace
Section titled “View the trace”- In LangSmith, open the project named by
LANGSMITH_PROJECT,weather-agent. - Click the
weather-agentrow to open the trace. - Select the Details tab to see the full run tree: the
weather-agentrun with the two model calls and theget_weathertool call nested inside it. - Find the sandbox ID in the metadata of the
weather-agentrun under the keysandbox_id, next to the model provider name underllm_provider.
Datadog
Section titled “Datadog”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.
| Setting | Value | Type |
|---|---|---|
llm-api-key | Your model provider’s API key, read from LLM_API_KEY | Secret |
datadog-api-key | Your Datadog API key, read from DD_API_KEY | Secret |
LLM_BASE_URL | The base URL of your model provider’s OpenAI-compatible endpoint | Environment variable |
LLM_MODEL | A model that accepts tool calls on the Chat Completions API | Environment variable |
LLM_PROVIDER | The model provider name recorded in the trace | Environment variable |
DD_SITE | Your Datadog site, such as datadoghq.com for US1 or datadoghq.eu for EU1 | Environment variable |
DD_APM_TRACING_ENABLED | false, set by the launcher to turn off APM tracing | Environment variable |
DD_INSTRUMENTATION_TELEMETRY_ENABLED | false, set by the launcher to turn off the SDK’s telemetry | Environment variable |
DD_REMOTE_CONFIGURATION_ENABLED | false, set by the launcher to turn off Remote Configuration | Environment variable |
DD_LLMOBS_ENABLED | 1, set by the TypeScript launcher to turn on Agent Observability | Environment variable |
DD_LLMOBS_ML_APP | weather-agent, set by the TypeScript launcher as the application that receives the traces | Environment variable |
DD_LLMOBS_AGENTLESS_ENABLED | 1, set by the TypeScript launcher to send traces without a Datadog Agent | Environment variable |
NODE_OPTIONS | --import dd-trace/initialize.mjs, set by the TypeScript launcher to load the Datadog SDK before the agent | Environment variable |
<provider host> | Host of LLM_BASE_URL, on the allowlist of llm-api-key | Allowed host |
llmobs-intake.<DD_SITE> | Agent Observability intake for your site, on the allowlist of datadog-api-key | Allowed host |
public-trace-http-intake.logs.<DD_SITE> | Trace intake that the TypeScript SDK also sends to, on the allowlist of datadog-api-key | Allowed host |
- Install the Daytona SDK on your machine:
pip install "daytona[v0-sdk]>=2,<3"for Python, ornpm install @daytona/sdk@2 tsxfor TypeScript. The TypeScript SDK requires Node.js 22.15 or later. - Set these environment variables on your machine:
DAYTONA_API_KEY,LLM_API_KEY,LLM_BASE_URL,DD_API_KEY,DD_SITE,LLM_MODEL, andLLM_PROVIDER. - Save the secrets file as
store_secrets.pyorstore_secrets.tsand run it once to store the keys:python store_secrets.pyornpx tsx store_secrets.ts. - Save the agent file as
agent.pyoragent.tsin the same directory. - Save the launcher as
run.pyorrun.tsin the same directory and run it:python run.pyornpx 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. - View the trace in Datadog as described below.
Secrets file
Section titled “Secrets file”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.
import osfrom urllib.parse import urlparse
from daytona import Daytonafrom 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']}"],))import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { await daytona.v0.secret.create({ name: 'llm-api-key', value: process.env.LLM_API_KEY!, hosts: [new URL(process.env.LLM_BASE_URL!).hostname], }) await daytona.v0.secret.create({ name: 'datadog-api-key', value: process.env.DD_API_KEY!, hosts: [`llmobs-intake.${process.env.DD_SITE}`, `public-trace-http-intake.logs.${process.env.DD_SITE}`], })}
main()Agent file
Section titled “Agent file”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.
import jsonimport os
from ddtrace.llmobs import LLMObsfrom 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].messageprint(message.content)LLMObs.flush()import tracer from 'dd-trace'import OpenAI from 'openai'
const llmobs = tracer.llmobsconst client = new OpenAI({ apiKey: process.env.LLM_API_KEY, baseURL: process.env.LLM_BASE_URL })const model = process.env.LLM_MODEL!
function getWeather(city: string) { return 'sunny, 64 degrees Fahrenheit'}
const tools: OpenAI.ChatCompletionTool[] = [{ type: 'function', function: { name: 'get_weather', description: 'Get the current weather in a city.', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, },}]
async function main() { const answer = await llmobs.trace({ kind: 'agent', name: 'weather-agent' }, async (span) => { llmobs.annotate(span, { tags: { sandbox_id: process.env.SANDBOX_ID, llm_provider: process.env.LLM_PROVIDER } }) const messages: OpenAI.ChatCompletionMessageParam[] = [{ role: 'user', content: 'What is the weather in San Francisco?' }]
let response = await client.chat.completions.create({ model, messages, tools }) let message = response.choices[0].message const calls = (message.tool_calls ?? []).filter((call) => call.type === 'function') if (calls.length > 0) { messages.push({ role: 'assistant', content: message.content, tool_calls: calls.map((call) => ({ id: call.id, type: 'function', function: { name: call.function.name, arguments: call.function.arguments }, })), }) for (const call of calls) { const result = llmobs.trace({ kind: 'tool', name: 'get_weather' }, (toolSpan) => { const weather = getWeather(JSON.parse(call.function.arguments).city) llmobs.annotate(toolSpan, { inputData: call.function.arguments, outputData: weather }) return weather }) messages.push({ role: 'tool', tool_call_id: call.id, content: result }) } response = await client.chat.completions.create({ model, messages, tools }) message = response.choices[0].message } return message.content }) console.log(answer) llmobs.flush()}
main()Launcher
Section titled “Launcher”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.
import osimport sys
from daytona import Daytonafrom 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()import { Daytona } from '@daytona/sdk'
const daytona = new Daytona()
async function main() { const envVars: Record<string, string> = { LLM_BASE_URL: process.env.LLM_BASE_URL!, LLM_MODEL: process.env.LLM_MODEL!, LLM_PROVIDER: process.env.LLM_PROVIDER!, DD_SITE: process.env.DD_SITE!, DD_APM_TRACING_ENABLED: 'false', DD_INSTRUMENTATION_TELEMETRY_ENABLED: 'false', DD_REMOTE_CONFIGURATION_ENABLED: 'false', NODE_USE_ENV_PROXY: '1', }
const sandbox = await daytona.v0.create({ language: 'typescript', secrets: { LLM_API_KEY: 'llm-api-key', DD_API_KEY: 'datadog-api-key' }, envVars, }) console.log(`Sandbox ID: ${sandbox.id}`)
try { await sandbox.fs.uploadFile('agent.ts', 'agent.ts') await sandbox.process.executeCommand('npm install dd-trace openai tsx', undefined, undefined, 300) const response = await sandbox.process.executeCommand('npx tsx agent.ts', undefined, { SANDBOX_ID: sandbox.id, NODE_OPTIONS: '--import dd-trace/initialize.mjs', DD_LLMOBS_ENABLED: '1', DD_LLMOBS_ML_APP: 'weather-agent', DD_LLMOBS_AGENTLESS_ENABLED: '1', }, 120) console.log(response.result) process.exitCode = response.exitCode } finally { await sandbox.delete() }}
main()View the trace
Section titled “View the trace”- In Datadog, open Agent Observability and select Traces.
- Search for
sandbox_id:<id>with the sandbox ID the launcher printed. A trace can take up to a minute to appear. - Open the
weather-agenttrace to see the two model calls and theget_weathertool call nested inside it. - Find the sandbox ID among the tags of the
weather-agentspan undersandbox_id, next to the model provider name underllm_provider.
Troubleshooting
Section titled “Troubleshooting”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:
- End the agent with the platform’s flush call, as the examples do
- For Grafana Cloud, set
agento11y.recordtotrueon the spans - For LangSmith, set
LANGSMITH_TRACINGtotrue - For a direct OpenTelemetry export to Langfuse, send the
x-langfuse-ingestion-versionheader with the value4, 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 - For Datadog in TypeScript, set
DD_TRACE_DEBUGtotrueandDD_TRACE_LOG_LEVELtoerrorin the agent’s environment. The SDK does not report a failed export otherwise - Look for an export error in the agent’s output. The exit code does not always show a failed export
See Flushing.
Symptom: The agent’s output shows an authentication error from the platform or from the model provider, and no trace appears. The Datadog TypeScript example shows the platform’s error only with debug logging turned on. When the platform rejects its key, the agent still prints its answer. When the model provider rejects its key, the agent stops at its first model call with a 401 error and prints no answer.
Cause: The key is wrong, or the request carries the secret’s placeholder instead of the key, and the platform or provider rejects it. The placeholder reaches the platform for one of two reasons. The request bypasses the sandbox proxy, when Node.js runs without NODE_USE_ENV_PROXY set to 1 or when an OpenTelemetry exporter opens its connections through its own pool instead of https.globalAgent. Or the request goes through the proxy, but the proxy forwards the placeholder unchanged because the host is not on the secret’s host allowlist.
Solution:
- Compare the error with the table below to find which key the platform rejected
- Verify that the key stored in the secret is valid for the platform
- Add the platform host to the secret’s host allowlist
- In Node.js, set
NODE_USE_ENV_PROXYto1, and give an OpenTelemetry exporterhttps.globalAgentto use, as the examples do
| Platform | Language | Error in the agent’s output |
|---|---|---|
| Grafana Cloud | Python | Failed to export spans batch code: 401, reason: Unauthorized |
| Grafana Cloud | TypeScript | OTLPExporterError: Unauthorized with code: 401 |
| Arize | Python | Failed to export spans batch code: 403, reason: Forbidden |
| Arize | TypeScript | UnhandledPromiseRejection with the reason "[object Array]", which does not name the status |
| Langfuse | Python | Failed to export spans batch code: 401, reason: Unauthorized |
| Langfuse | TypeScript | OTLPExporterError: Unauthorized with code: 401 |
| LangSmith | Python | 403 Client Error: Forbidden on the /runs/multipart request |
| LangSmith | TypeScript | Failed to send multipart request. Received status [403]: Forbidden |
| Datadog | Python | got response code 403 with API key is missing or invalid |
| Datadog | TypeScript | No error unless DD_TRACE_DEBUG is true, then 403 Forbidden with API key is missing or invalid |
See Credentials.