Skip to content

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/sdk

Quick 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:

OptionTypeDefaultDescription
agentwatch_api_keystringrequiredYour AgentWatch API key
projectstringnullProject name for attribution
teamstringnullTeam name for team budget enforcement
sessionIdstringrandom UUIDSession identifier
sessionBudgetUsdnumbernullPer-session budget ceiling
monthlyBudgetUsdnumbernullMonthly budget (reserved)
enforcementModebooleanfalseEnable pre-call budget checks
enforcementFailOpenbooleantrueFail open on AgentWatch outage
ingestUrlstringdefaultAgentWatch ingest endpoint
timeoutSecondsnumber2.0HTTP 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)}`);
    }
}
PropertyTypeDescription
sessionIdstringThe session that exceeded the budget
spentnumberAmount spent in USD
limitnumberBudget 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.