Appearance
TypeScript SDK Reference
The AgentWatch TypeScript SDK provides a drop-in replacement for the OpenAI client with built-in budget enforcement, telemetry, and anomaly detection.
Installation
bash
npm install @agentwatch-sdk/sdkQuick Start
typescript
import { WatchedOpenAI } from "@agentwatch-sdk/sdk";
const client = new WatchedOpenAI({
apiKey: "your-openai-key",
agentwatch_api_key: "aw_live_xxx",
sessionId: "my-session",
sessionBudgetUsd: 2.00,
enforcementMode: true,
});
try {
const response = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello" }],
});
console.log(response.choices[0].message.content);
} catch (e) {
if (e instanceof AgentBudgetExceeded) {
console.log(`Blocked: $${e.spent.toFixed(4)} / $${e.limit.toFixed(4)}`);
}
}API Reference
WatchedOpenAI
Extends OpenAI from the openai package with built-in telemetry.
Constructor Options:
| Option | Type | Default | Description |
|---|---|---|---|
agentwatch_api_key | string | required | Your AgentWatch API key |
project | string | null | Project name for attribution |
team | string | null | Team name for team budget enforcement |
sessionId | string | random UUID | Session identifier |
sessionBudgetUsd | number | null | Per-session budget ceiling |
monthlyBudgetUsd | number | null | Monthly budget (reserved) |
enforcementMode | boolean | false | Enable pre-call budget checks |
enforcementFailOpen | boolean | true | Fail open on AgentWatch outage |
ingestUrl | string | default | AgentWatch ingest endpoint |
timeoutSeconds | number | 2.0 | HTTP timeout for AgentWatch calls |
All other options are passed to the OpenAI constructor.
Methods:
All OpenAI methods are available. chat.completions.create() is wrapped with budget enforcement.
Exceptions
AgentBudgetExceeded
typescript
catch (e) {
if (e instanceof AgentBudgetExceeded) {
console.log(`Session: ${e.sessionId}`);
console.log(`Spent: $${e.spent.toFixed(4)}`);
console.log(`Limit: $${e.limit.toFixed(4)}`);
}
}| Property | Type | Description |
|---|---|---|
sessionId | string | The session that exceeded the budget |
spent | number | Amount spent in USD |
limit | number | Budget limit in USD |
AgentBudgetCheckUnavailable
Raised when enforcementFailOpen=false and the budget check endpoint is unreachable.
analyzeText()
Scan text for PII and secret risks.
typescript
import { analyzeText } from "@agentwatch-sdk/sdk";
const risks = analyzeText("Contact user@example.com");
// Returns: ["PII_EMAIL"]Streaming Support
Budget enforcement works with streaming responses:
typescript
const stream = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Write a long story" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}WARNING
Budget enforcement for streaming uses estimated token counts. The stream may be terminated mid-response if the budget is exceeded.
AsyncLogger
The SDK uses an AsyncLogger for telemetry that:
- Maintains a bounded queue (max 1024 pending items)
- Drops oldest items when queue is full (no memory leak)
- Sends telemetry in background without blocking the main thread
- Silently handles network errors
Token Estimation
For streaming responses where actual token counts aren't available until completion, the SDK estimates tokens using a ~3.5 chars/token heuristic for English text.