TypeScript SDK
TypeScript / JavaScript SDK
Track OpenAI, Anthropic, Google Gen AI, LangChain.js and Vercel AI SDK calls from Node.js, attributed to the agent, job and step that made them.
Installation
npm install @agentcost/sdkNode.js 18 or later. ESM and CommonJS, with types. No runtime dependencies: provider SDKs are optional peer dependencies. Server-side only; never ship your AgentCost API key to a browser.
Quick start
Initialise once, then wrap each client you want tracked:
import OpenAI from "openai";
import * as agentcost from "@agentcost/sdk";
// Reads AGENTCOST_API_KEY and AGENTCOST_PROJECT_ID from the environment.
agentcost.init();
const client = agentcost.instrumentOpenAI(new OpenAI());
await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
});Your calls, responses and errors are unchanged. Events are sent in the background in batches. Short-lived scripts and serverless functions should flush before they exit:
await agentcost.flush(); // or: ctx.waitUntil(agentcost.flush())
await agentcost.shutdown(); // flush and stop, at process endIntegrations
OpenAI
const client = agentcost.instrumentOpenAI(new OpenAI());
// also AzureOpenAI, and any OpenAI-compatible base URL:
const viaGateway = agentcost.instrumentOpenAI(new OpenAI({ baseURL: "https://your-gateway.example/v1", apiKey }));Tracks chat.completions, responses, legacy completions and embeddings: awaited, streamed, withResponse(), and the helpers built on them (parse(), stream(), runTools()). Streamed chat calls get stream_options.include_usage so usage is reported; if an endpoint refuses it, the call is resent once exactly as written. Tested with openai 4, 5, 6 and 7.
Anthropic
import Anthropic from "@anthropic-ai/sdk";
const anthropic = agentcost.instrumentAnthropic(new Anthropic());Tracks messages.create and beta.messages.create, streamed or not, and messages.stream(). Cache reads are counted as cached input; cache writes are priced at the cache-write rate.
Google Gen AI (Gemini)
import { GoogleGenAI } from "@google/genai";
const ai = agentcost.instrumentGoogleGenAI(new GoogleGenAI({ apiKey }));Tracks models.generateContent, models.generateContentStream and chats. Thinking tokens are counted as output, as Gemini bills them.
LangChain.js / LangGraph
import { ChatOpenAI } from "@langchain/openai";
const model = new ChatOpenAI({ model: "gpt-4o", callbacks: [agentcost.agentcostCallbacks()] });Works with any LangChain chat model. Do not also instrument the provider client LangChain uses internally, or calls are counted twice.
Vercel AI SDK
import { wrapLanguageModel, generateText } from "ai";
import { openai } from "@ai-sdk/openai";
const model = wrapLanguageModel({ model: openai("gpt-4o"), middleware: agentcost.agentcostMiddleware() });
await generateText({ model, prompt: "Hello!" });Works with any AI SDK provider; each model request is one event. Embedding models use agentcostEmbeddingMiddleware() with wrapEmbeddingModel (AI SDK 6+).
Agents, jobs and steps
await agentcost.agent("researcher", () =>
agentcost.workflow("nightly-report", async (traceId) => { // one run = one trace
await agentcost.step("draft", () => client.chat.completions.create({ ... }));
await agentcost.tool("web_search", () => search(query));
agentcost.outcome(true, "published");
}),
);
await agentcost.metadata({ customer_id: "c_42" }, () => client.chat.completions.create({ ... }));Each function takes a callback and returns its result. Context follows async calls, so concurrent requests never share attribution, and a stream is attributed to where it was created. These map to the same fields as the Python SDK: agent_name, workflow, trace_id, step_name, tool_name.
Gateways and proxies
A client pointed at an OpenAI-compatible gateway, proxy or self-hosted endpoint is tracked like any other. Each event also records, in metadata:
gateway_host: the base URL's host (never the path), when it is not the provider's ownresponse_model: the model the endpoint said it served. The requestedmodelstays the priced field.response_id: the endpoint's id for the call, to match it against the gateway's own console
AgentCost prices each call from its own model catalogue and the token counts the endpoint reports, so a gateway that bills with its own rates will show a different total.
What is recorded
Per call: the requested model, input, output, cached and cache-write tokens, latency, success, the attribution above, and an event_id so a resent batch is never counted twice. In metadata:
usage_source:response(counts from the endpoint),missing(none arrived; the zeros are placeholders, not zero usage) orestimated(LangChain's own estimate)_ac_caps: what the call needed (vision, tools, structured output), as booleans and counts only- your own
metadata()andglobalMetadatakeys
Never sent
Prompts, completions, tool definitions or arguments, images, API keys, or error message text. Failed calls carry only the error class, HTTP status and error code.
Configuration
agentcost.init({
apiKey, // default: AGENTCOST_API_KEY
projectId, // default: AGENTCOST_PROJECT_ID (the project UUID)
baseUrl, // default: AGENTCOST_API_URL or https://api.agentcost.tech
enabled: true, // false: keep the instrumentation, record nothing
batchSize: 10, // max 100
flushIntervalMs: 5000,
defaultAgentName: "default",
globalMetadata: { env: "prod" },
localMode: false, // keep events in memory (getLocalEvents()), send nothing
onError: (msg) => console.warn(msg), // delivery problems; never contains content
});Network errors, timeouts, 429 and 5xx responses keep the batch and retry it with the same event ids. Other 4xx responses (a wrong key or project) drop it with a warning. Tracking never throws into your code.
Not tracked
- OpenAI images, audio, moderation, realtime and the Assistants API.
- Google Gen AI embeddings, image and video generation, and the Live API.
asResponse()returns the raw HTTP response, so its usage cannot be read; the call is recorded withusage_source: "missing".- Bun, Deno and edge runtimes are not tested yet; the package needs
node:async_hooks.
Source, changelog and issues: github.com/agentcost-ai/agentcost-js. Package: npmjs.com/package/@agentcost/sdk.