npm package: @obsai/sdk
Description: Lightweight observability SDK for API and AI/LLM applications
Latest version: 0.1.0

# @obsai/sdk

Lightweight observability SDK for API and AI/LLM applications. Track HTTP requests and AI/LLM calls with automatic cost calculation.

## Installation

```bash
npm install @obsai/sdk
# or
yarn add @obsai/sdk
```

## Quick Start

### 1. Initialize the SDK

```typescript
import { init } from '@obsai/sdk';

init({
  apiKey: 'obs_your_api_key', // Get this from your project settings
  service: 'my-app',
  debug: true, // optional - logs events to console
});
```

### 2. HTTP Middleware (Express)

Automatically track all HTTP requests:

```typescript
import express from 'express';
import { init } from '@obsai/sdk';
import { httpMiddleware } from '@obsai/sdk/http';

init({
  apiKey: 'obs_your_api_key',
  service: 'api-server',
});

const app = express();

app.use(httpMiddleware({
  excludePaths: ['/health', '/metrics'],
  excludePatterns: [/^\/static/],
}));

app.get('/api/users', (req, res) => {
  res.json({ users: [] });
});
```

### 3. AI/LLM Wrapper (OpenAI)

Automatically track all OpenAI calls with token usage and cost:

```typescript
import OpenAI from 'openai';
import { init } from '@obsai/sdk';
import { wrapOpenAI } from '@obsai/sdk/llm';

init({
  apiKey: 'obs_your_api_key',
  service: 'ai-service',
});

const openai = wrapOpenAI(new OpenAI());

// All calls are automatically tracked
const response = await openai.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Hello!' }],
});
```

### 4. AI/LLM Wrapper (Anthropic)

```typescript
import Anthropic from '@anthropic-ai/sdk';
import { init } from '@obsai/sdk';
import { wrapAnthropic } from '@obsai/sdk/llm';

init({
  apiKey: 'obs_your_api_key',
});

const anthropic = wrapAnthropic(new Anthropic());

const response = await anthropic.messages.create({
  model: 'claude-3-sonnet-20240229',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello!' }],
});
```

### 5. Manual Tracking

For custom events or other providers:

```typescript
import { init, track } from '@obsai/sdk';
import { trackLLMCall } from '@obsai/sdk/llm';

init({ apiKey: 'obs_your_api_key' });

// Track custom HTTP events
await track({
  kind: 'http',
  name: 'GET /api/users',
  status: 'ok',
  durationMs: 45,
  attrs: { userId: '123' },
});

// Track custom AI/LLM calls
await trackLLMCall({
  provider: 'gemini',
  model: 'gemini-pro',
  tokensIn: 150,
  tokensOut: 500,
  durationMs: 1200,
  status: 'ok',
});
```

## SDK-Free Integration

### Universal AI Gateway

Use Observa as an OpenAI-compatible proxy. No SDK needed!

```typescript
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://obsai.strateogi.com/api/v1/gateway',
  apiKey: 'obs_your_api_key', // Your Observa API key
  defaultHeaders: {
    'x-provider-key': process.env.OPENAI_API_KEY, // Your real provider key
    'x-provider': 'openai', // Optional: auto-detected from model
  },
});

// Works exactly like normal OpenAI
const response = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Hello!' }],
});
```

Supported providers: OpenAI, Anthropic (Claude), Google (Gemini)

### Direct API Ingestion

Send events directly via HTTP:

```bash
curl -X POST https://obsai.strateogi.com/api/ingest \
  -H "Authorization: Bearer obs_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [{
      "kind": "ai",
      "name": "gpt-4o-mini",
      "trace_id": "trace-123",
      "status": "ok",
      "duration_ms": 1500,
      "attrs": {
        "provider": "openai",
        "prompt_tokens": 100,
        "completion_tokens": 250
      }
    }]
  }'
```

## Privacy Modes

Configure per-project privacy level in your Observa dashboard:

- **Metadata Only** (default): Only track latency, tokens, costs, status. No prompts/responses stored.
- **Full Logging**: Track everything including prompts and responses for debugging.

## Configuration Options

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `apiKey` | string | Yes | Your project API key from Observa |
| `service` | string | No | Service name for grouping events (default: "default") |
| `baseUrl` | string | No | Custom Observa instance URL (default: https://obsai.strateogi.com) |
| `debug` | boolean | No | Log events to console (default: false) |

## Supported AI Providers

| Provider | Models | Auto Cost Calculation |
|----------|--------|----------------------|
| OpenAI | GPT-4o, GPT-4o-mini, GPT-4, GPT-3.5-turbo, etc. | Yes |
| Anthropic | Claude 3.5, Claude 3, etc. | Yes |
| Google | Gemini Pro, Gemini Flash, etc. | Yes |
| Custom | Any | Manual via attrs |

## Get Your API Key

1. Sign up at [obsai.strateogi.com](https://obsai.strateogi.com)
2. Create a project
3. Go to Integrations tab
4. Generate an API key

## License

MIT