Skip to main content

Trace OpenAI API calls with EvalGate

Wrap the OpenAI client to automatically capture prompts, responses, token usage, latency, and cost estimation for every API request you make.
The EvalGate SDK integrates with the OpenAI client through a thin wrapper that intercepts every API call and records it as a trace — no manual instrumentation required. Chat completions, streaming responses, function calls, and embeddings are all captured automatically. This guide shows you how to set up the wrapper and use it for multi-turn conversations, model A/B testing, and error tracking.

Install dependencies

Wrap the OpenAI client

Replace your existing OpenAI client initialization with the traced version. All subsequent calls through this client are automatically recorded:
Make sure EVALGATE_API_KEY and EVALGATE_ORGANIZATION_ID are set in your .env file before initializing the client.

Chat completions

Call the OpenAI API exactly as you normally would. EvalGate captures the full interaction in the background:
Every chat completion automatically records: full prompt and response, token usage (input and output), latency, model name and parameters, and cost estimation.

Streaming responses

Streaming works exactly the same way. The SDK buffers the full response as it streams so the complete output appears in the trace:

Function calling

Function calls are traced like any other completion. The tool definitions, selected function, and arguments all appear in the trace:
TypeScript

Multi-turn conversations

Use WorkflowTracer to group multiple turns of a conversation into a single workflow trace with per-turn spans:
TypeScript

A/B testing models

Trace model variants with metadata so you can compare quality, latency, and cost across experiments in the dashboard:
TypeScript

What gets tracked automatically

Troubleshooting

Traces not capturing token usage? Ensure you are on the latest version of @evalgate/sdk or evalgate-sdk. Older versions may not parse the usage fields correctly. Noticing high latency in traces? Make sure you are using async/await consistently. Synchronous operations block the event loop and inflate latency measurements. Missing streaming response data? The SDK automatically buffers streaming responses. If data appears missing, confirm the stream iterator is fully consumed (the for await loop completes) before the process exits.