← Guides
Setup8 min read
Tracking OpenAI Costs with CostLynx
Three ways to track OpenAI spend: automatic provider sync, the TypeScript SDK helper, and the Python SDK helper — with attribution per feature and user.
Option A: Provider sync (OpenAI only)
CostLynx can pull usage directly from the OpenAI API on a scheduled basis. This requires no code changes but provides org-level totals only — no project or feature attribution.
- 1
- Go to Settings → Configure → Provider Connections.
- 2
- Click Add connection, choose OpenAI, and paste your OpenAI API key.
- 3
- Click Test to verify. Sync runs automatically on schedule.
Warning
Provider sync gives totals without feature or project breakdown. For attribution, use SDK ingestion (Option B or C) alongside or instead of sync.
Option B: Python SDK (recommended for Python apps)
Install
pip install "costlynx[openai]"Python — track after every call
import os
from openai import OpenAI
from costlynx import CostLynx
clx = CostLynx(
ingestion_key=os.environ["COSTLYNX_INGESTION_KEY"],
default_project="my-app",
default_environment="prod",
)
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}],
)
# One line — extracts tokens and cost automatically
clx.track_openai_response(response, feature="chat")Tip
The SDK never raises. Network errors and API failures are swallowed silently. Enable debug=True in development to see them printed to stderr.
Option C: TypeScript SDK
Install
npm install @costlynx/sdkTypeScript — track after every call
import OpenAI from "openai";
import { CostLynx } from "@costlynx/sdk";
const clx = new CostLynx({
ingestionKey: process.env.COSTLYNX_INGESTION_KEY!,
defaultProject: "my-app",
defaultEnvironment: "prod",
});
const openai = new OpenAI();
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello" }],
});
await clx.trackOpenAIResponse(response, { feature: "chat" });Attribution fields
| Field | Type | Description |
|---|---|---|
| project | string (slug) | Maps to a project you created in Settings → Configure |
| environment | string (slug) | prod, staging, dev, or custom slug |
| feature | string | Free-form label: chat, summariser, copilot, etc. |
| userIdentifier | string | Opaque user ID for per-user spend breakdown |
| requestId | string | Idempotency key — use the OpenAI response ID (chatcmpl-...) |