Skip to main content
Go from install to live trace in under 5 minutes. This guide gets your OpenAI agent fully instrumented with structured spans, cost tracking, and one-click replay.

Prerequisites

  • A Node.js or TypeScript project using the OpenAI SDK
  • An OpenAI API key
  • Node.js 18+

1. Install

2. Add your API key

Get your key from tracepilotai.com → Account Settings.
.env
Never commit API keys. Use environment variables. In production, inject them via your platform’s secret manager.

3. Initialize the OpenAI client

lib/clients.ts
Instantiate once. Import everywhere.

4. Wrap your first completion

agent.ts
Your existing code is unchanged. tp.wrapOpenAI returns the original result untouched — plus a spanId for chaining.

5. Trace a multi-step agent

agent.ts

Expected dashboard output

After running your agent, open tracepilotai.com/dashboard:
Every span shows: model, latency, token count, estimated cost, input messages, and output. If any span fails, it shows the error inline.
Screenshot pending: TracePilot dashboard showing a 3-step OpenAI agent trace.

6. Replay a failing span

When a span fails in production, you don’t need to redeploy to debug it.
1

Find the failing trace

Go to tracepilotai.com/dashboard. Failed traces are marked with a red ✗. Click the trace.
2

Open the failing span

Expand the span tree and click the span where the failure occurred. You’ll see the exact messages array, model parameters, token usage, and error output.
3

Fork & Rerun

Click Fork & Rerun. Edit the prompt, swap the model, or adjust parameters. Click Run.
4

Ship the fix

Once the replay succeeds, apply the same change to your codebase and deploy.
Replay example — what TracePilot captures per span

Troubleshooting

  • Confirm TRACEPILOT_API_KEY starts with tp_live_.
  • tp.startTrace() must be called before any wrapOpenAI call in the same execution.
  • Check your network: TracePilot ships spans over HTTPS to ingest.tracepilotai.com. Ensure it’s not blocked by a firewall or proxy.
tp.wrapOpenAI() always returns a spanId. If it’s undefined, the call threw before TracePilot could create the span. Check for initialization errors — missing API key is the most common cause.
Make sure tp.wrapToolCall receives the parentSpanId from the preceding wrapOpenAI call. A missing parentSpanId creates an orphaned span that may not render in the tree view.
Cost tracking is based on the model string. Pass the exact OpenAI model name (gpt-4o, gpt-4o-mini, gpt-3.5-turbo). Custom or fine-tuned model IDs are not mapped automatically.

Next steps

Debug OpenAI agent infinite loops

Detect, trace, and replay runaway agent loops before they drain your budget.

Tracing tool calls

Instrument every tool, function, and external API your agent calls.

Time-travel debugging

Fork any span and rerun it with edited inputs — no redeployment.

Cost tracking

Monitor token spend per span and catch runaway costs early.