@trackyourapi/sdk
v0.3.0
Published
Official JavaScript/TypeScript SDK for TrackYourAPI — AI API usage tracking
Maintainers
Readme
@trackyourapi/sdk
Official JavaScript/TypeScript SDK for TrackYourAPI: LLM cost, usage, latency and error tracking.
Wrap your OpenAI, Anthropic or Gemini client once. Every call is tracked, including streaming responses and failed requests. Zero hard dependencies.
Installation
npm install @trackyourapi/sdk
# or
bun add @trackyourapi/sdkQuick start
- Sign in to your TrackYourAPI dashboard, open API Keys, and generate a key (
qt_...). It is shown once. - Your
endpointis your TrackYourAPI Supabase project URL, e.g.https://xxxx.supabase.co.
OpenAI (and OpenAI-compatible APIs)
import OpenAI from 'openai'
import { wrapOpenAI } from '@trackyourapi/sdk'
const openai = wrapOpenAI(new OpenAI(), {
apiKey: process.env.TRACKYOURAPI_KEY!,
endpoint: 'https://YOUR-PROJECT.supabase.co',
})
// Regular and streaming calls are both tracked
const res = await openai.chat.completions.create({ model: 'gpt-4o', messages: [...] })
const stream = await openai.chat.completions.create({ model: 'gpt-4o', messages: [...], stream: true })
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? '')DeepSeek, Groq, Mistral, OpenRouter, Ollama and others speak the OpenAI protocol. Pass provider so they are labelled correctly:
const deepseek = wrapOpenAI(
new OpenAI({ baseURL: 'https://api.deepseek.com', apiKey: process.env.DEEPSEEK_API_KEY }),
{ apiKey: 'qt_...', endpoint: 'https://YOUR-PROJECT.supabase.co', provider: 'deepseek' },
)Anthropic
import Anthropic from '@anthropic-ai/sdk'
import { wrapAnthropic } from '@trackyourapi/sdk'
const anthropic = wrapAnthropic(new Anthropic(), {
apiKey: 'qt_...',
endpoint: 'https://YOUR-PROJECT.supabase.co',
})
const msg = await anthropic.messages.create({ model: 'claude-sonnet-4-0', max_tokens: 1024, messages: [...] })
// stream: true and the messages.stream() helper are tracked tooGoogle Gemini
import { GoogleGenerativeAI } from '@google/generative-ai'
import { wrapGemini } from '@trackyourapi/sdk'
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!)
const model = wrapGemini(genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }), {
apiKey: 'qt_...',
endpoint: 'https://YOUR-PROJECT.supabase.co',
})
const result = await model.generateContent('Explain quantum computing')Also supported
- Google GenAI (
@google/genai):wrapGoogleGenAI(new GoogleGenAI({...}), opts)tracksmodels.generateContentandgenerateContentStream. - OpenAI Responses API:
responses.createis tracked when present, including streaming. - Anthropic
messages.stream()helper is tracked via itsfinalMessage(). - Vercel AI SDK:
import { trackYourAPIMiddleware } from '@trackyourapi/sdk/vercel-ai'and pass it towrapLanguageModel({ model, middleware }). - LangChain.js:
import { trackYourAPICallbacks } from '@trackyourapi/sdk/langchain'and passcallbacks: [trackYourAPICallbacks(opts)].
Prompt and response capture
Off by default. Set captureContent: true on the wrapper to send prompt and completion text with each event. The server only stores it when the project has content capture enabled in Settings, truncated to the project's limit. Never enable it for projects that handle sensitive data.
Cost attribution with metadata
Tag calls so the dashboard can break spend down by customer, feature or environment.
// Applied to every event from this client
const openai = wrapOpenAI(new OpenAI(), { apiKey, endpoint, metadata: { environment: 'production' } })
// Per call: pass a `trackyourapi` field, it is stripped before the request is sent
await openai.chat.completions.create({
model: 'gpt-4o',
messages: [...],
trackyourapi: { customerId: 'acme', feature: 'summarize' },
} as any)What gets tracked
| Field | Description |
|---|---|
| provider, model | Provider label and the exact model the API reported |
| prompt_tokens, completion_tokens | Real split from the provider (cached prompt tokens count as input) |
| latency | Request duration in ms. For streams, time until the stream finished |
| status, error_message | error when the call threw (rate limits, timeouts, bad requests) |
| metadata | Your tags, merged from client and per-call metadata |
Cost is computed server-side from TrackYourAPI's pricing table, so prices can be corrected without updating the SDK. For custom providers the server does not know, send cost yourself via manual tracking.
Manual tracking (any provider)
import { TrackYourAPIClient } from '@trackyourapi/sdk'
const tracker = new TrackYourAPIClient({ apiKey: 'qt_...', endpoint: 'https://YOUR-PROJECT.supabase.co' })
tracker.track({
provider: 'mistral',
model: 'mistral-large',
promptTokens: 1200,
completionTokens: 300,
cost: 0.004, // USD, optional for known models
latency: 320,
metadata: { customerId: 'acme' },
})track() never throws and never blocks. Set debug: true to log delivery failures.
Options
interface TrackYourAPIOptions {
apiKey: string // Required. Your qt_... key
endpoint: string // Required. https://YOUR-PROJECT.supabase.co
debug?: boolean // Log tracking errors (default false)
metadata?: Record<string, unknown> // Tags attached to every event
captureContent?: boolean // Send prompt/completion text (default false)
}wrapOpenAI also accepts provider?: string; wrapGemini accepts modelName?: string.
Python
See sdk-python/ for the equivalent pip install trackyourapi.
License
MIT
