@lelemon-ai/trace 0.0.0-stage → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1183 -2
- package/dist/anthropic.d.mts +25 -0
- package/dist/anthropic.d.ts +25 -0
- package/dist/anthropic.js +4 -0
- package/dist/anthropic.mjs +4 -0
- package/dist/bedrock.d.mts +25 -0
- package/dist/bedrock.d.ts +25 -0
- package/dist/bedrock.js +4 -0
- package/dist/bedrock.mjs +4 -0
- package/dist/capture-CC6pIfa4.d.mts +354 -0
- package/dist/capture-CC6pIfa4.d.ts +354 -0
- package/dist/express-BrfMWEVl.d.mts +67 -0
- package/dist/express-BrfMWEVl.d.ts +67 -0
- package/dist/express.d.mts +1 -0
- package/dist/express.d.ts +1 -0
- package/dist/express.js +3 -0
- package/dist/express.mjs +3 -0
- package/dist/gemini.d.mts +28 -0
- package/dist/gemini.d.ts +28 -0
- package/dist/gemini.js +4 -0
- package/dist/gemini.mjs +4 -0
- package/dist/google-genai.d.mts +31 -0
- package/dist/google-genai.d.ts +31 -0
- package/dist/google-genai.js +4 -0
- package/dist/google-genai.mjs +4 -0
- package/dist/hono-MTDbviM5.d.mts +80 -0
- package/dist/hono-MTDbviM5.d.ts +80 -0
- package/dist/hono.d.mts +1 -0
- package/dist/hono.d.ts +1 -0
- package/dist/hono.js +3 -0
- package/dist/hono.mjs +3 -0
- package/dist/index.d.mts +40 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +4 -0
- package/dist/integrations.d.mts +4 -0
- package/dist/integrations.d.ts +4 -0
- package/dist/integrations.js +3 -0
- package/dist/integrations.mjs +3 -0
- package/dist/lambda-Drx54kXf.d.mts +79 -0
- package/dist/lambda-Drx54kXf.d.ts +79 -0
- package/dist/lambda.d.mts +1 -0
- package/dist/lambda.d.ts +1 -0
- package/dist/lambda.js +3 -0
- package/dist/lambda.mjs +3 -0
- package/dist/next-DONwf0f5.d.mts +100 -0
- package/dist/next-DONwf0f5.d.ts +100 -0
- package/dist/next.d.mts +1 -0
- package/dist/next.d.ts +1 -0
- package/dist/next.js +3 -0
- package/dist/next.mjs +3 -0
- package/dist/openai.d.mts +25 -0
- package/dist/openai.d.ts +25 -0
- package/dist/openai.js +4 -0
- package/dist/openai.mjs +4 -0
- package/dist/openrouter.d.mts +33 -0
- package/dist/openrouter.d.ts +33 -0
- package/dist/openrouter.js +4 -0
- package/dist/openrouter.mjs +4 -0
- package/package.json +173 -4
package/README.md
CHANGED
|
@@ -1,3 +1,1184 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lelemon-ai/trace
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@lelemon-ai/trace)
|
|
4
|
+
[](https://github.com/Lelemon-studio/lelemondev-sdk/actions/workflows/ci.yml)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
|
|
7
|
+
Automatic LLM observability for Node.js. Wrap your client, everything is traced.
|
|
8
|
+
|
|
9
|
+
## LLM Agent Docs
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
https://lelemon-studio.github.io/lelemondev-sdk/llms.txt
|
|
13
|
+
https://lelemon-studio.github.io/lelemondev-sdk/llms-full.txt
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Features
|
|
17
|
+
|
|
18
|
+
- **Automatic Tracing** - Wrap your client, all calls are traced
|
|
19
|
+
- **Zero Config** - Works out of the box
|
|
20
|
+
- **Framework Integrations** - Next.js, Express, Lambda, Hono
|
|
21
|
+
- **Streaming Support** - Full support for streaming responses
|
|
22
|
+
- **Type-safe** - Preserves your client's TypeScript types
|
|
23
|
+
- **PII Redaction** - Optional email, phone, and custom pattern redaction
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install @lelemon-ai/trace
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quick Start
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { init, observe } from '@lelemon-ai/trace/openai';
|
|
35
|
+
import OpenAI from 'openai';
|
|
36
|
+
|
|
37
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
38
|
+
|
|
39
|
+
const openai = observe(new OpenAI());
|
|
40
|
+
|
|
41
|
+
const response = await openai.chat.completions.create({
|
|
42
|
+
model: 'gpt-4',
|
|
43
|
+
messages: [{ role: 'user', content: 'Hello!' }],
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
That's the bare minimum — it works, but your traces will be flat and anonymous. The next section shows you how to get **structured, beautiful traces** in your dashboard from day one.
|
|
48
|
+
|
|
49
|
+
## Recommended Usage
|
|
50
|
+
|
|
51
|
+
The difference between messy traces and clear, actionable ones comes down to three things: **naming your traces**, **identifying users and sessions**, and **grouping related calls together**.
|
|
52
|
+
|
|
53
|
+
### 1. Wrap your workflow with `trace()`
|
|
54
|
+
|
|
55
|
+
Without `trace()`, each LLM call shows up as an isolated entry. With it, you get a hierarchical view that shows exactly what happened and why.
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
import { init, observe, trace, span, flush } from '@lelemon-ai/trace/openai';
|
|
59
|
+
import OpenAI from 'openai';
|
|
60
|
+
|
|
61
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
62
|
+
const openai = observe(new OpenAI());
|
|
63
|
+
|
|
64
|
+
// ✅ Named trace groups everything into a clear hierarchy
|
|
65
|
+
const result = await trace('answer-question', async () => {
|
|
66
|
+
// This LLM call appears as a child span — you can see it nested
|
|
67
|
+
const response = await openai.chat.completions.create({
|
|
68
|
+
model: 'gpt-4',
|
|
69
|
+
messages: [{ role: 'user', content: 'What is observability?' }],
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
return response.choices[0].message.content;
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
**In the dashboard, this renders as:**
|
|
77
|
+
```
|
|
78
|
+
▼ answer-question (trace) 1.2s $0.003
|
|
79
|
+
▼ gpt-4 (llm) 1.2s $0.003 320 tokens
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Without `trace()`, you'd just see a flat `gpt-4` entry with no context.
|
|
83
|
+
|
|
84
|
+
### 2. Add `userId` and `sessionId`
|
|
85
|
+
|
|
86
|
+
These two fields unlock filtering, conversation grouping, and per-user analytics in the dashboard.
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
// ✅ Always pass userId and sessionId — this is what makes the dashboard useful
|
|
90
|
+
const openai = observe(new OpenAI(), {
|
|
91
|
+
userId: 'user-123', // Who is making this request
|
|
92
|
+
sessionId: 'conversation-abc', // Groups multi-turn conversations together
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
- **`userId`** → Filter traces by user, track costs per user, debug specific user issues
|
|
97
|
+
- **`sessionId`** → See an entire conversation across multiple requests as one session
|
|
98
|
+
|
|
99
|
+
### 3. Add spans for non-LLM operations
|
|
100
|
+
|
|
101
|
+
LLM calls are traced automatically, but your pipeline probably does more: vector search, tool calls, reranking, guardrails. Use `span()` to capture these so the full picture shows up in the dashboard.
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
import { trace, span } from '@lelemon-ai/trace/openai';
|
|
105
|
+
|
|
106
|
+
await trace('rag-pipeline', async () => {
|
|
107
|
+
// Capture vector search as a retrieval span
|
|
108
|
+
const t0 = Date.now();
|
|
109
|
+
const docs = await vectorDB.search(query, { topK: 5 });
|
|
110
|
+
span({
|
|
111
|
+
type: 'retrieval', // Shows with a blue badge in dashboard
|
|
112
|
+
name: 'vector-search', // Descriptive name — not "search" or "step-1"
|
|
113
|
+
input: { query, topK: 5 },
|
|
114
|
+
output: { count: docs.length },
|
|
115
|
+
durationMs: Date.now() - t0,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// LLM call is captured automatically as a child
|
|
119
|
+
const response = await openai.chat.completions.create({
|
|
120
|
+
model: 'gpt-4',
|
|
121
|
+
messages: [
|
|
122
|
+
{ role: 'system', content: 'Answer based on the provided context.' },
|
|
123
|
+
{ role: 'user', content: `Context: ${docs.join('\n')}\n\nQuestion: ${query}` },
|
|
124
|
+
],
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
return response.choices[0].message.content;
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
**In the dashboard:**
|
|
132
|
+
```
|
|
133
|
+
▼ rag-pipeline (trace) 2.4s $0.005
|
|
134
|
+
▼ vector-search (retrieval) 0.3s
|
|
135
|
+
▼ gpt-4 (llm) 2.1s $0.005 580 tokens
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
**Available span types:** `retrieval`, `embedding`, `tool`, `guardrail`, `rerank`, `custom`
|
|
139
|
+
|
|
140
|
+
### 4. Use descriptive names
|
|
141
|
+
|
|
142
|
+
Names are the first thing you see in the dashboard. Good names make traces scannable; bad names make them useless.
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
// ❌ Bad — these all look the same in the dashboard
|
|
146
|
+
await trace('process', async () => { ... });
|
|
147
|
+
await trace('handle', async () => { ... });
|
|
148
|
+
span({ type: 'tool', name: 'function' });
|
|
149
|
+
|
|
150
|
+
// ✅ Good — you can immediately understand what happened
|
|
151
|
+
await trace('sales-agent', async () => { ... });
|
|
152
|
+
await trace('summarize-document', async () => { ... });
|
|
153
|
+
span({ type: 'tool', name: 'get-weather-forecast' });
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Full example: AI agent with everything wired up
|
|
157
|
+
|
|
158
|
+
Here's a complete example combining all the best practices — this is what we recommend as the starting point for any production app:
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
import { init, observe, trace, span, flush } from '@lelemon-ai/trace/openai';
|
|
162
|
+
import OpenAI from 'openai';
|
|
163
|
+
|
|
164
|
+
// 1. Initialize once at app startup
|
|
165
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
166
|
+
|
|
167
|
+
async function handleChat(userId: string, sessionId: string, message: string) {
|
|
168
|
+
// 2. Wrap client with user context
|
|
169
|
+
const openai = observe(new OpenAI(), { userId, sessionId });
|
|
170
|
+
|
|
171
|
+
// 3. Wrap the full workflow in a named trace
|
|
172
|
+
const result = await trace('customer-support-agent', async () => {
|
|
173
|
+
// 4. Capture non-LLM operations as typed spans
|
|
174
|
+
const t0 = Date.now();
|
|
175
|
+
const history = await db.getChatHistory(sessionId);
|
|
176
|
+
span({
|
|
177
|
+
type: 'retrieval',
|
|
178
|
+
name: 'load-chat-history',
|
|
179
|
+
input: { sessionId },
|
|
180
|
+
output: { messageCount: history.length },
|
|
181
|
+
durationMs: Date.now() - t0,
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// 5. LLM call is automatically captured as a child span
|
|
185
|
+
const response = await openai.chat.completions.create({
|
|
186
|
+
model: 'gpt-4',
|
|
187
|
+
messages: [
|
|
188
|
+
{ role: 'system', content: 'You are a helpful customer support agent.' },
|
|
189
|
+
...history,
|
|
190
|
+
{ role: 'user', content: message },
|
|
191
|
+
],
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
return response.choices[0].message.content;
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// In your server:
|
|
201
|
+
app.post('/chat', async (req, res) => {
|
|
202
|
+
const { message, conversationId } = req.body;
|
|
203
|
+
const answer = await handleChat(req.user.id, conversationId, message);
|
|
204
|
+
res.json({ answer });
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
**In the dashboard, each request renders as:**
|
|
209
|
+
```
|
|
210
|
+
▼ customer-support-agent (trace) 1.8s $0.004 user: user-123 session: conv-abc
|
|
211
|
+
▼ load-chat-history (retrieval) 0.1s
|
|
212
|
+
▼ gpt-4 (llm) 1.7s $0.004 420 tokens
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
And because you set `sessionId`, all turns of the same conversation are grouped together — you can click into a session and see the entire conversation flow.
|
|
216
|
+
|
|
217
|
+
### Provider-Specific Imports
|
|
218
|
+
|
|
219
|
+
Each provider has its own entry point for optimal bundle size:
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
// OpenAI
|
|
223
|
+
import { init, observe, flush } from '@lelemon-ai/trace/openai';
|
|
224
|
+
|
|
225
|
+
// Anthropic
|
|
226
|
+
import { init, observe, flush } from '@lelemon-ai/trace/anthropic';
|
|
227
|
+
|
|
228
|
+
// AWS Bedrock
|
|
229
|
+
import { init, observe, flush } from '@lelemon-ai/trace/bedrock';
|
|
230
|
+
|
|
231
|
+
// Google Gemini (supports both @google/genai and @google/generative-ai)
|
|
232
|
+
import { init, observe, flush } from '@lelemon-ai/trace/gemini';
|
|
233
|
+
|
|
234
|
+
// Google GenAI (dedicated entry point for @google/genai)
|
|
235
|
+
import { init, observe, flush } from '@lelemon-ai/trace/google-genai';
|
|
236
|
+
|
|
237
|
+
// OpenRouter
|
|
238
|
+
import { init, observe, flush } from '@lelemon-ai/trace/openrouter';
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Supported Providers
|
|
242
|
+
|
|
243
|
+
| Provider | Status | Methods |
|
|
244
|
+
|----------|--------|---------|
|
|
245
|
+
| OpenAI | ✅ | `chat.completions.create()`, `responses.create()`, `completions.create()`, `embeddings.create()` |
|
|
246
|
+
| OpenRouter | ✅ | `chat.completions.create()` (access to 400+ models) |
|
|
247
|
+
| Anthropic | ✅ | `messages.create()`, `messages.stream()` |
|
|
248
|
+
| AWS Bedrock | ✅ | `ConverseCommand`, `ConverseStreamCommand`, `InvokeModelCommand` |
|
|
249
|
+
| Google Gemini (`@google/generative-ai`) | ✅ | `generateContent()`, `generateContentStream()`, `chat.sendMessage()` |
|
|
250
|
+
| Google GenAI (`@google/genai`) | ✅ | `models.generateContent()`, `models.generateContentStream()`, `chats.create()`, `chat.sendMessage()` |
|
|
251
|
+
|
|
252
|
+
### OpenRouter
|
|
253
|
+
|
|
254
|
+
[OpenRouter](https://openrouter.ai) provides unified access to 400+ models from OpenAI, Anthropic, Google, Meta, Mistral, and more through a single API.
|
|
255
|
+
|
|
256
|
+
```typescript
|
|
257
|
+
import { init, observe } from '@lelemon-ai/trace/openrouter';
|
|
258
|
+
import OpenAI from 'openai';
|
|
259
|
+
|
|
260
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
261
|
+
|
|
262
|
+
// Configure OpenAI SDK to use OpenRouter
|
|
263
|
+
const openrouter = observe(new OpenAI({
|
|
264
|
+
baseURL: 'https://openrouter.ai/api/v1',
|
|
265
|
+
apiKey: process.env.OPENROUTER_API_KEY,
|
|
266
|
+
defaultHeaders: {
|
|
267
|
+
'HTTP-Referer': 'https://your-app.com', // Optional: for OpenRouter rankings
|
|
268
|
+
'X-Title': 'Your App Name', // Optional: for OpenRouter rankings
|
|
269
|
+
},
|
|
270
|
+
}));
|
|
271
|
+
|
|
272
|
+
// Access any model through OpenRouter
|
|
273
|
+
const response = await openrouter.chat.completions.create({
|
|
274
|
+
model: 'anthropic/claude-3-opus', // or 'openai/gpt-4', 'google/gemini-pro', etc.
|
|
275
|
+
messages: [{ role: 'user', content: 'Hello!' }],
|
|
276
|
+
});
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
Models are specified in `provider/model` format (e.g., `anthropic/claude-3-opus`, `openai/gpt-4`, `meta-llama/llama-3-70b`). See [OpenRouter Models](https://openrouter.ai/models) for the full list.
|
|
280
|
+
|
|
281
|
+
### Google Gemini
|
|
282
|
+
|
|
283
|
+
The SDK supports both the **new** `@google/genai` (recommended) and the **old** `@google/generative-ai` packages. Both are auto-detected by `observe()`.
|
|
284
|
+
|
|
285
|
+
#### Recommended: `@google/genai` (new SDK)
|
|
286
|
+
|
|
287
|
+
```bash
|
|
288
|
+
npm install @google/genai
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
```typescript
|
|
292
|
+
import { init, observe, flush } from '@lelemon-ai/trace/google-genai';
|
|
293
|
+
import { GoogleGenAI } from '@google/genai';
|
|
294
|
+
|
|
295
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
296
|
+
|
|
297
|
+
const ai = observe(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }));
|
|
298
|
+
|
|
299
|
+
// Generate content
|
|
300
|
+
const response = await ai.models.generateContent({
|
|
301
|
+
model: 'gemini-2.5-flash',
|
|
302
|
+
contents: 'Explain how observability works',
|
|
303
|
+
});
|
|
304
|
+
console.log(response.text);
|
|
305
|
+
|
|
306
|
+
// Streaming
|
|
307
|
+
const stream = await ai.models.generateContentStream({
|
|
308
|
+
model: 'gemini-2.5-flash',
|
|
309
|
+
contents: 'Write a short poem about monitoring',
|
|
310
|
+
});
|
|
311
|
+
for await (const chunk of stream) {
|
|
312
|
+
process.stdout.write(chunk.text ?? '');
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Chat (multi-turn)
|
|
316
|
+
const chat = ai.chats.create({
|
|
317
|
+
model: 'gemini-2.5-flash',
|
|
318
|
+
history: [
|
|
319
|
+
{ role: 'user', parts: [{ text: 'Hello' }] },
|
|
320
|
+
{ role: 'model', parts: [{ text: 'Hi! How can I help?' }] },
|
|
321
|
+
],
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
const reply = await chat.sendMessage({ message: 'What can you do?' });
|
|
325
|
+
console.log(reply.text);
|
|
326
|
+
|
|
327
|
+
// Streaming chat
|
|
328
|
+
const chatStream = await chat.sendMessageStream({ message: 'Tell me more' });
|
|
329
|
+
for await (const chunk of chatStream) {
|
|
330
|
+
process.stdout.write(chunk.text ?? '');
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
await flush();
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
#### With config (system instructions, temperature, tools)
|
|
337
|
+
|
|
338
|
+
```typescript
|
|
339
|
+
const response = await ai.models.generateContent({
|
|
340
|
+
model: 'gemini-2.5-flash',
|
|
341
|
+
contents: 'Analyze this data',
|
|
342
|
+
config: {
|
|
343
|
+
systemInstruction: 'You are a data analyst. Be concise.',
|
|
344
|
+
temperature: 0.3,
|
|
345
|
+
maxOutputTokens: 1000,
|
|
346
|
+
tools: [{ functionDeclarations: [myFunctionDecl] }],
|
|
347
|
+
},
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
// Access function calls if tools were used
|
|
351
|
+
if (response.functionCalls) {
|
|
352
|
+
console.log(response.functionCalls);
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
#### Legacy: `@google/generative-ai` (old SDK)
|
|
357
|
+
|
|
358
|
+
Still supported but not recommended for new projects:
|
|
359
|
+
|
|
360
|
+
```typescript
|
|
361
|
+
import { init, observe, flush } from '@lelemon-ai/trace/gemini';
|
|
362
|
+
import { GoogleGenerativeAI } from '@google/generative-ai';
|
|
363
|
+
|
|
364
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
365
|
+
|
|
366
|
+
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
|
|
367
|
+
|
|
368
|
+
// You can observe the client or the model directly
|
|
369
|
+
const model = observe(genAI.getGenerativeModel({ model: 'gemini-2.5-flash' }));
|
|
370
|
+
|
|
371
|
+
const result = await model.generateContent('Hello!');
|
|
372
|
+
console.log(result.response.text());
|
|
373
|
+
|
|
374
|
+
await flush();
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
#### Auto-detection with generic `observe()`
|
|
378
|
+
|
|
379
|
+
Both SDKs work with the generic entry point too:
|
|
380
|
+
|
|
381
|
+
```typescript
|
|
382
|
+
import { init, observe } from '@lelemon-ai/trace';
|
|
383
|
+
import { GoogleGenAI } from '@google/genai';
|
|
384
|
+
|
|
385
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
386
|
+
|
|
387
|
+
// Auto-detects @google/genai
|
|
388
|
+
const ai = observe(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }));
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
## Usage Without Framework Integrations
|
|
392
|
+
|
|
393
|
+
The SDK works with **any Node.js application**. Framework integrations are optional - they just automate the `flush()` call.
|
|
394
|
+
|
|
395
|
+
### Long-running Processes (Servers, Workers)
|
|
396
|
+
|
|
397
|
+
For long-running processes, the SDK auto-flushes every second (configurable via `flushIntervalMs`):
|
|
398
|
+
|
|
399
|
+
```typescript
|
|
400
|
+
import { init, observe } from '@lelemon-ai/trace/openai';
|
|
401
|
+
import OpenAI from 'openai';
|
|
402
|
+
|
|
403
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
404
|
+
const openai = observe(new OpenAI());
|
|
405
|
+
|
|
406
|
+
// In your HTTP server, WebSocket handler, queue worker, etc.
|
|
407
|
+
async function handleRequest(userId: string, message: string) {
|
|
408
|
+
const client = observe(new OpenAI(), { userId });
|
|
409
|
+
|
|
410
|
+
const result = await client.chat.completions.create({
|
|
411
|
+
model: 'gpt-4',
|
|
412
|
+
messages: [{ role: 'user', content: message }],
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
return result.choices[0].message;
|
|
416
|
+
// Traces are auto-flushed in the background (every 1s by default)
|
|
417
|
+
}
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
### Short-lived Processes (Scripts, Serverless, CLI)
|
|
421
|
+
|
|
422
|
+
For scripts or serverless functions, call `flush()` before the process exits:
|
|
423
|
+
|
|
424
|
+
```typescript
|
|
425
|
+
import { init, observe, flush } from '@lelemon-ai/trace/openai';
|
|
426
|
+
import OpenAI from 'openai';
|
|
427
|
+
|
|
428
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
429
|
+
const openai = observe(new OpenAI());
|
|
430
|
+
|
|
431
|
+
async function main() {
|
|
432
|
+
const result = await openai.chat.completions.create({
|
|
433
|
+
model: 'gpt-4',
|
|
434
|
+
messages: [{ role: 'user', content: 'Hello!' }],
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
console.log(result.choices[0].message.content);
|
|
438
|
+
|
|
439
|
+
// IMPORTANT: Flush before exit to ensure traces are sent
|
|
440
|
+
await flush();
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
main();
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
### Custom HTTP Server (No Framework)
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
import http from 'http';
|
|
450
|
+
import { init, observe, flush } from '@lelemon-ai/trace/openai';
|
|
451
|
+
import OpenAI from 'openai';
|
|
452
|
+
|
|
453
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
454
|
+
|
|
455
|
+
const server = http.createServer(async (req, res) => {
|
|
456
|
+
if (req.method === 'POST' && req.url === '/chat') {
|
|
457
|
+
const openai = observe(new OpenAI(), {
|
|
458
|
+
userId: req.headers['x-user-id'] as string,
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
const result = await openai.chat.completions.create({
|
|
462
|
+
model: 'gpt-4',
|
|
463
|
+
messages: [{ role: 'user', content: 'Hello!' }],
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
467
|
+
res.end(JSON.stringify(result.choices[0].message));
|
|
468
|
+
// Auto-flush handles this in background
|
|
469
|
+
}
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
// Graceful shutdown - flush remaining traces
|
|
473
|
+
process.on('SIGTERM', async () => {
|
|
474
|
+
await flush();
|
|
475
|
+
server.close();
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
server.listen(3000);
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
### When to Use Framework Integrations vs Manual
|
|
482
|
+
|
|
483
|
+
| Scenario | Recommendation |
|
|
484
|
+
|----------|----------------|
|
|
485
|
+
| Next.js, Express, Hono, Lambda | Use framework integration (auto-flush) |
|
|
486
|
+
| Custom HTTP server | Auto-flush works, add `flush()` on shutdown |
|
|
487
|
+
| CLI scripts | Always call `flush()` before exit |
|
|
488
|
+
| Background workers (Bull, BullMQ) | Auto-flush works, add `flush()` on shutdown |
|
|
489
|
+
| One-off scripts | Always call `flush()` before exit |
|
|
490
|
+
| Long-running daemons | Auto-flush works |
|
|
491
|
+
|
|
492
|
+
## Framework Integrations
|
|
493
|
+
|
|
494
|
+
Framework integrations automate the `flush()` call so you don't have to think about it.
|
|
495
|
+
|
|
496
|
+
### Next.js App Router
|
|
497
|
+
|
|
498
|
+
```typescript
|
|
499
|
+
// app/api/chat/route.ts
|
|
500
|
+
import { init, observe } from '@lelemon-ai/trace/openai';
|
|
501
|
+
import { withObserve } from '@lelemon-ai/trace/next';
|
|
502
|
+
import { after } from 'next/server';
|
|
503
|
+
import OpenAI from 'openai';
|
|
504
|
+
|
|
505
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
506
|
+
const openai = observe(new OpenAI());
|
|
507
|
+
|
|
508
|
+
export const POST = withObserve(
|
|
509
|
+
async (req) => {
|
|
510
|
+
const { message } = await req.json();
|
|
511
|
+
const result = await openai.chat.completions.create({
|
|
512
|
+
model: 'gpt-4',
|
|
513
|
+
messages: [{ role: 'user', content: message }],
|
|
514
|
+
});
|
|
515
|
+
return Response.json(result.choices[0].message);
|
|
516
|
+
},
|
|
517
|
+
{ after } // Non-blocking flush (Next.js 15+)
|
|
518
|
+
);
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
### Express
|
|
522
|
+
|
|
523
|
+
```typescript
|
|
524
|
+
import express from 'express';
|
|
525
|
+
import { init, observe } from '@lelemon-ai/trace/openai';
|
|
526
|
+
import { createMiddleware } from '@lelemon-ai/trace/express';
|
|
527
|
+
import OpenAI from 'openai';
|
|
528
|
+
|
|
529
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
530
|
+
const openai = observe(new OpenAI());
|
|
531
|
+
|
|
532
|
+
const app = express();
|
|
533
|
+
app.use(createMiddleware()); // Auto-flush on response finish
|
|
534
|
+
|
|
535
|
+
app.post('/chat', async (req, res) => {
|
|
536
|
+
const result = await openai.chat.completions.create({
|
|
537
|
+
model: 'gpt-4',
|
|
538
|
+
messages: [{ role: 'user', content: req.body.message }],
|
|
539
|
+
});
|
|
540
|
+
res.json(result.choices[0].message);
|
|
541
|
+
});
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
### AWS Lambda
|
|
545
|
+
|
|
546
|
+
```typescript
|
|
547
|
+
import { init, observe } from '@lelemon-ai/trace/openai';
|
|
548
|
+
import { withObserve } from '@lelemon-ai/trace/lambda';
|
|
549
|
+
import OpenAI from 'openai';
|
|
550
|
+
|
|
551
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
552
|
+
const openai = observe(new OpenAI());
|
|
553
|
+
|
|
554
|
+
export const handler = withObserve(async (event) => {
|
|
555
|
+
const body = JSON.parse(event.body);
|
|
556
|
+
const result = await openai.chat.completions.create({
|
|
557
|
+
model: 'gpt-4',
|
|
558
|
+
messages: [{ role: 'user', content: body.message }],
|
|
559
|
+
});
|
|
560
|
+
return {
|
|
561
|
+
statusCode: 200,
|
|
562
|
+
body: JSON.stringify(result.choices[0].message),
|
|
563
|
+
};
|
|
564
|
+
});
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
### Hono (Cloudflare Workers, Deno, Bun)
|
|
568
|
+
|
|
569
|
+
```typescript
|
|
570
|
+
import { Hono } from 'hono';
|
|
571
|
+
import { init, observe } from '@lelemon-ai/trace/openai';
|
|
572
|
+
import { createMiddleware } from '@lelemon-ai/trace/hono';
|
|
573
|
+
import OpenAI from 'openai';
|
|
574
|
+
|
|
575
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
576
|
+
const openai = observe(new OpenAI());
|
|
577
|
+
|
|
578
|
+
const app = new Hono();
|
|
579
|
+
app.use(createMiddleware()); // Uses waitUntil on Workers
|
|
580
|
+
|
|
581
|
+
app.post('/chat', async (c) => {
|
|
582
|
+
const { message } = await c.req.json();
|
|
583
|
+
const result = await openai.chat.completions.create({
|
|
584
|
+
model: 'gpt-4',
|
|
585
|
+
messages: [{ role: 'user', content: message }],
|
|
586
|
+
});
|
|
587
|
+
return c.json(result.choices[0].message);
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
export default app;
|
|
591
|
+
```
|
|
592
|
+
|
|
593
|
+
## API Reference
|
|
594
|
+
|
|
595
|
+
### `init(config)`
|
|
596
|
+
|
|
597
|
+
Initialize the SDK. Call once at app startup.
|
|
598
|
+
|
|
599
|
+
```typescript
|
|
600
|
+
init({
|
|
601
|
+
apiKey: 'le_xxx', // Required (or LELEMON_API_KEY env var)
|
|
602
|
+
endpoint: 'https://...', // Optional, custom endpoint
|
|
603
|
+
debug: false, // Optional, enable debug logs
|
|
604
|
+
disabled: false, // Optional, disable tracing
|
|
605
|
+
batchSize: 10, // Optional, items per batch (default: 10)
|
|
606
|
+
flushIntervalMs: 1000, // Optional, auto-flush interval in ms (default: 1000)
|
|
607
|
+
requestTimeoutMs: 10000, // Optional, HTTP request timeout in ms (default: 10000)
|
|
608
|
+
service: { // Optional, service metadata for telemetry
|
|
609
|
+
name: 'my-ai-app', // Service name
|
|
610
|
+
version: '1.0.0', // Service version
|
|
611
|
+
environment: 'production' // Deployment environment
|
|
612
|
+
},
|
|
613
|
+
redaction: { // Optional, PII redaction config
|
|
614
|
+
emails: true, // Redact email addresses → [EMAIL]
|
|
615
|
+
phones: true, // Redact 9+ digit numbers → [PHONE]
|
|
616
|
+
patterns: [/SSN-\d{9}/g], // Custom regex patterns → [REDACTED]
|
|
617
|
+
keys: ['cpf', 'rut'], // Additional sensitive key names
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
### `observe(client, options?)`
|
|
623
|
+
|
|
624
|
+
Wrap an LLM client with automatic tracing.
|
|
625
|
+
|
|
626
|
+
```typescript
|
|
627
|
+
const openai = observe(new OpenAI(), {
|
|
628
|
+
sessionId: 'session-123',
|
|
629
|
+
userId: 'user-456',
|
|
630
|
+
metadata: { source: 'api' },
|
|
631
|
+
tags: ['production'],
|
|
632
|
+
});
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
#### Multi-Tenant Servers (Important!)
|
|
636
|
+
|
|
637
|
+
For multi-tenant servers handling concurrent requests from different users, **create a new observed client per-request** with the user's context:
|
|
638
|
+
|
|
639
|
+
```typescript
|
|
640
|
+
// ❌ WRONG - Global client with no context
|
|
641
|
+
const client = observe(new BedrockRuntimeClient());
|
|
642
|
+
|
|
643
|
+
async function handleRequest(userId: string, sessionId: string) {
|
|
644
|
+
await client.send(command); // No user/session info!
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// ✅ CORRECT - Observed client per-request with context
|
|
648
|
+
const rawClient = new BedrockRuntimeClient();
|
|
649
|
+
|
|
650
|
+
async function handleRequest(userId: string, sessionId: string) {
|
|
651
|
+
const client = observe(rawClient, {
|
|
652
|
+
userId,
|
|
653
|
+
sessionId,
|
|
654
|
+
metadata: { tenantId },
|
|
655
|
+
});
|
|
656
|
+
await client.send(command); // Traces include user/session!
|
|
657
|
+
}
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
**Recommended pattern for NestJS/Express:**
|
|
661
|
+
|
|
662
|
+
```typescript
|
|
663
|
+
// llm.provider.ts
|
|
664
|
+
@Injectable()
|
|
665
|
+
export class LlmProvider {
|
|
666
|
+
private rawClient: BedrockRuntimeClient;
|
|
667
|
+
|
|
668
|
+
constructor() {
|
|
669
|
+
this.rawClient = new BedrockRuntimeClient({ region: 'us-east-1' });
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// Create observed client with per-request context
|
|
673
|
+
getClient(ctx: { userId: string; sessionId: string; tenantId?: string }) {
|
|
674
|
+
return observe(this.rawClient, {
|
|
675
|
+
userId: ctx.userId,
|
|
676
|
+
sessionId: ctx.sessionId,
|
|
677
|
+
metadata: { tenantId: ctx.tenantId },
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// Usage in service
|
|
683
|
+
const client = this.llmProvider.getClient({
|
|
684
|
+
userId: request.userId,
|
|
685
|
+
sessionId: request.conversationId,
|
|
686
|
+
tenantId: request.tenantId,
|
|
687
|
+
});
|
|
688
|
+
await client.send(command);
|
|
689
|
+
```
|
|
690
|
+
|
|
691
|
+
### `flush()`
|
|
692
|
+
|
|
693
|
+
Manually flush pending traces. Use in serverless without framework integration.
|
|
694
|
+
|
|
695
|
+
```typescript
|
|
696
|
+
await flush();
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
### `isEnabled()`
|
|
700
|
+
|
|
701
|
+
Check if tracing is enabled (useful for conditional logic).
|
|
702
|
+
|
|
703
|
+
```typescript
|
|
704
|
+
import { isEnabled } from '@lelemon-ai/trace/openai';
|
|
705
|
+
|
|
706
|
+
if (isEnabled()) {
|
|
707
|
+
console.log('Tracing is active');
|
|
708
|
+
}
|
|
709
|
+
```
|
|
710
|
+
|
|
711
|
+
### `trace(name, fn)` / `trace(options, fn)`
|
|
712
|
+
|
|
713
|
+
Group multiple LLM calls under a single trace. Useful for agents, RAG pipelines, and multi-step workflows.
|
|
714
|
+
|
|
715
|
+
```typescript
|
|
716
|
+
import { trace, span } from '@lelemon-ai/trace/openai';
|
|
717
|
+
|
|
718
|
+
// Simple usage
|
|
719
|
+
await trace('sales-agent', async () => {
|
|
720
|
+
const response = await openai.chat.completions.create({...});
|
|
721
|
+
return response;
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
// With options
|
|
725
|
+
await trace({
|
|
726
|
+
name: 'rag-query',
|
|
727
|
+
input: userQuestion,
|
|
728
|
+
metadata: { source: 'api' },
|
|
729
|
+
tags: ['production']
|
|
730
|
+
}, async () => {
|
|
731
|
+
// All LLM calls inside become children of this trace
|
|
732
|
+
const docs = await searchVectors(userQuestion);
|
|
733
|
+
const response = await openai.chat.completions.create({...});
|
|
734
|
+
return response;
|
|
735
|
+
});
|
|
736
|
+
```
|
|
737
|
+
|
|
738
|
+
### `span(options)`
|
|
739
|
+
|
|
740
|
+
Manually capture a span for non-LLM operations (retrieval, embedding, tool calls). Must be called within a `trace()` block.
|
|
741
|
+
|
|
742
|
+
```typescript
|
|
743
|
+
import { trace, span } from '@lelemon-ai/trace/openai';
|
|
744
|
+
|
|
745
|
+
await trace('rag-pipeline', async () => {
|
|
746
|
+
// Capture a retrieval span
|
|
747
|
+
const t0 = Date.now();
|
|
748
|
+
const docs = await pinecone.query({ vector, topK: 5 });
|
|
749
|
+
span({
|
|
750
|
+
type: 'retrieval',
|
|
751
|
+
name: 'pinecone-search',
|
|
752
|
+
input: { topK: 5 },
|
|
753
|
+
output: { count: docs.length },
|
|
754
|
+
durationMs: Date.now() - t0,
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
// LLM call is automatically captured
|
|
758
|
+
return openai.chat.completions.create({...});
|
|
759
|
+
});
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
**Span types:** `retrieval`, `embedding`, `tool`, `guardrail`, `rerank`, `custom`
|
|
763
|
+
|
|
764
|
+
### `captureSpan(options)`
|
|
765
|
+
|
|
766
|
+
Lower-level API for manual span capture. Works both inside and outside `trace()` blocks. Inside a trace the span takes the trace's session and user; outside one, pass them in `context`.
|
|
767
|
+
|
|
768
|
+
```typescript
|
|
769
|
+
import { captureSpan } from '@lelemon-ai/trace/openai';
|
|
770
|
+
|
|
771
|
+
captureSpan({
|
|
772
|
+
type: 'tool',
|
|
773
|
+
name: 'get_weather',
|
|
774
|
+
input: { location: 'San Francisco' },
|
|
775
|
+
output: { temperature: 72, conditions: 'sunny' },
|
|
776
|
+
durationMs: 150,
|
|
777
|
+
status: 'success', // or 'error'
|
|
778
|
+
context: { sessionId: 'conversation-abc', userId: 'user-123' }, // only needed outside trace()
|
|
779
|
+
});
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
### `getTraceContext()`
|
|
783
|
+
|
|
784
|
+
Get the current trace context (useful for advanced scenarios).
|
|
785
|
+
|
|
786
|
+
```typescript
|
|
787
|
+
import { getTraceContext } from '@lelemon-ai/trace/openai';
|
|
788
|
+
|
|
789
|
+
const ctx = getTraceContext();
|
|
790
|
+
if (ctx) {
|
|
791
|
+
console.log('Inside trace:', ctx.name, ctx.traceId);
|
|
792
|
+
}
|
|
793
|
+
```
|
|
794
|
+
|
|
795
|
+
## User & Session Tracking
|
|
796
|
+
|
|
797
|
+
Track which user generated each trace and group related conversations.
|
|
798
|
+
|
|
799
|
+
### Available Fields
|
|
800
|
+
|
|
801
|
+
| Field | Purpose | In Dashboard |
|
|
802
|
+
|-------|---------|--------------|
|
|
803
|
+
| `userId` | Identify the end user | Shown in "User" column, searchable |
|
|
804
|
+
| `sessionId` | Group related traces (e.g., a conversation) | Shown in "Session" column, searchable |
|
|
805
|
+
| `metadata` | Custom data attached to the trace | Visible in trace detail view |
|
|
806
|
+
| `tags` | Labels for categorization | Shown as badges, filterable dropdown |
|
|
807
|
+
|
|
808
|
+
#### Field Details
|
|
809
|
+
|
|
810
|
+
**`userId`** - Identifies who made the request
|
|
811
|
+
```typescript
|
|
812
|
+
userId: req.user.id // From your auth system
|
|
813
|
+
userId: 'user-123' // Any string identifier
|
|
814
|
+
userId: req.user.email // Email works too
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
**`sessionId`** - Groups multiple calls into one conversation/session
|
|
818
|
+
```typescript
|
|
819
|
+
sessionId: req.body.conversationId // Chat conversation ID
|
|
820
|
+
sessionId: req.headers['x-session-id'] // From client header
|
|
821
|
+
sessionId: crypto.randomUUID() // Generate per session
|
|
822
|
+
```
|
|
823
|
+
|
|
824
|
+
**`metadata`** - Any extra data you want to attach (stored as JSON)
|
|
825
|
+
```typescript
|
|
826
|
+
metadata: {
|
|
827
|
+
plan: 'premium', // User's subscription plan
|
|
828
|
+
feature: 'chat', // Which feature triggered this
|
|
829
|
+
version: '2.1.0', // Your app version
|
|
830
|
+
environment: 'production', // Environment
|
|
831
|
+
ip: req.ip, // Client IP (for debugging)
|
|
832
|
+
customField: 'any value', // Anything you need
|
|
833
|
+
}
|
|
834
|
+
```
|
|
835
|
+
|
|
836
|
+
**`tags`** - Quick labels for filtering (array of strings)
|
|
837
|
+
```typescript
|
|
838
|
+
tags: ['production'] // Environment
|
|
839
|
+
tags: ['chat', 'premium'] // Feature + plan
|
|
840
|
+
tags: ['api', 'v2'] // Service + version
|
|
841
|
+
tags: [tenantId, 'high-priority'] // Multi-tenant + priority
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
### Basic Usage
|
|
845
|
+
|
|
846
|
+
```typescript
|
|
847
|
+
const openai = observe(new OpenAI(), {
|
|
848
|
+
userId: 'user-123',
|
|
849
|
+
sessionId: 'conversation-abc',
|
|
850
|
+
});
|
|
851
|
+
```
|
|
852
|
+
|
|
853
|
+
### In an API Endpoint
|
|
854
|
+
|
|
855
|
+
```typescript
|
|
856
|
+
// Express
|
|
857
|
+
app.post('/chat', async (req, res) => {
|
|
858
|
+
// Create client with user context from the request
|
|
859
|
+
const openai = observe(new OpenAI(), {
|
|
860
|
+
userId: req.user.id,
|
|
861
|
+
sessionId: req.headers['x-session-id'],
|
|
862
|
+
metadata: {
|
|
863
|
+
plan: req.user.plan,
|
|
864
|
+
endpoint: '/chat'
|
|
865
|
+
},
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
const result = await openai.chat.completions.create({
|
|
869
|
+
model: 'gpt-4',
|
|
870
|
+
messages: [{ role: 'user', content: req.body.message }],
|
|
871
|
+
});
|
|
872
|
+
|
|
873
|
+
res.json(result.choices[0].message);
|
|
874
|
+
});
|
|
875
|
+
```
|
|
876
|
+
|
|
877
|
+
### Reusable Context with createObserve()
|
|
878
|
+
|
|
879
|
+
When you have multiple LLM clients or make calls from different places, use `createObserve()` to avoid repeating context.
|
|
880
|
+
|
|
881
|
+
> **Note:** `createObserve` is imported from the generic `@lelemon-ai/trace` entry point (not provider-specific) because it works with any provider.
|
|
882
|
+
|
|
883
|
+
```typescript
|
|
884
|
+
import { init, createObserve } from '@lelemon-ai/trace';
|
|
885
|
+
import OpenAI from 'openai';
|
|
886
|
+
import { GoogleGenAI } from '@google/genai';
|
|
887
|
+
import { BedrockRuntimeClient } from '@aws-sdk/client-bedrock-runtime';
|
|
888
|
+
|
|
889
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
890
|
+
|
|
891
|
+
// Create a scoped observe function with user context
|
|
892
|
+
const observeForUser = createObserve({
|
|
893
|
+
userId: 'user-123',
|
|
894
|
+
sessionId: 'session-456',
|
|
895
|
+
tags: ['premium'],
|
|
896
|
+
});
|
|
897
|
+
|
|
898
|
+
// All clients inherit the same context
|
|
899
|
+
const openai = observeForUser(new OpenAI());
|
|
900
|
+
const ai = observeForUser(new GoogleGenAI({ apiKey }));
|
|
901
|
+
const bedrock = observeForUser(new BedrockRuntimeClient({}));
|
|
902
|
+
|
|
903
|
+
// All these calls will be associated with user-123
|
|
904
|
+
await openai.chat.completions.create({ ... });
|
|
905
|
+
await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: '...' });
|
|
906
|
+
```
|
|
907
|
+
|
|
908
|
+
### In Middleware (Express)
|
|
909
|
+
|
|
910
|
+
Set up user context once, use it everywhere:
|
|
911
|
+
|
|
912
|
+
```typescript
|
|
913
|
+
import { init, createObserve } from '@lelemon-ai/trace';
|
|
914
|
+
|
|
915
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
916
|
+
|
|
917
|
+
// Middleware to attach observe function to request
|
|
918
|
+
app.use((req, res, next) => {
|
|
919
|
+
req.observe = createObserve({
|
|
920
|
+
userId: req.user?.id,
|
|
921
|
+
sessionId: req.headers['x-session-id'] || crypto.randomUUID(),
|
|
922
|
+
metadata: {
|
|
923
|
+
ip: req.ip,
|
|
924
|
+
userAgent: req.headers['user-agent'],
|
|
925
|
+
},
|
|
926
|
+
});
|
|
927
|
+
next();
|
|
928
|
+
});
|
|
929
|
+
|
|
930
|
+
// In any route handler
|
|
931
|
+
app.post('/chat', async (req, res) => {
|
|
932
|
+
const openai = req.observe(new OpenAI());
|
|
933
|
+
// Calls are automatically associated with the user
|
|
934
|
+
});
|
|
935
|
+
|
|
936
|
+
app.post('/summarize', async (req, res) => {
|
|
937
|
+
const ai = req.observe(new GoogleGenAI({ apiKey }));
|
|
938
|
+
// Same user context, different endpoint
|
|
939
|
+
});
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
### Multi-tenant Application
|
|
943
|
+
|
|
944
|
+
```typescript
|
|
945
|
+
import { observe } from '@lelemon-ai/trace/openai';
|
|
946
|
+
|
|
947
|
+
app.post('/api/:tenantId/chat', async (req, res) => {
|
|
948
|
+
const openai = observe(new OpenAI(), {
|
|
949
|
+
userId: req.user.id,
|
|
950
|
+
sessionId: req.body.conversationId,
|
|
951
|
+
metadata: {
|
|
952
|
+
tenantId: req.params.tenantId,
|
|
953
|
+
environment: process.env.NODE_ENV,
|
|
954
|
+
},
|
|
955
|
+
tags: [req.params.tenantId, req.user.plan],
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
// Traces can be filtered by tenant, user, or conversation
|
|
959
|
+
});
|
|
960
|
+
```
|
|
961
|
+
|
|
962
|
+
### Distributed Systems (API + WebSocket)
|
|
963
|
+
|
|
964
|
+
When your application spans multiple services (REST API, WebSocket server, background workers), use consistent identifiers across all of them:
|
|
965
|
+
|
|
966
|
+
```typescript
|
|
967
|
+
// Shared utility for creating observe context
|
|
968
|
+
// utils/observe-context.ts
|
|
969
|
+
import { init, createObserve } from '@lelemon-ai/trace';
|
|
970
|
+
|
|
971
|
+
init({ apiKey: process.env.LELEMON_API_KEY });
|
|
972
|
+
|
|
973
|
+
export function createUserObserve(userId: string, sessionId: string, service: string) {
|
|
974
|
+
return createObserve({
|
|
975
|
+
userId,
|
|
976
|
+
sessionId,
|
|
977
|
+
metadata: { service },
|
|
978
|
+
tags: [service],
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
**REST API Server:**
|
|
984
|
+
|
|
985
|
+
```typescript
|
|
986
|
+
// api-server.ts
|
|
987
|
+
import { createUserObserve } from './utils/observe-context';
|
|
988
|
+
|
|
989
|
+
app.post('/chat/start', async (req, res) => {
|
|
990
|
+
const { userId, sessionId } = req.body;
|
|
991
|
+
|
|
992
|
+
const observe = createUserObserve(userId, sessionId, 'api');
|
|
993
|
+
const openai = observe(new OpenAI());
|
|
994
|
+
|
|
995
|
+
const result = await openai.chat.completions.create({
|
|
996
|
+
model: 'gpt-4',
|
|
997
|
+
messages: [{ role: 'user', content: req.body.message }],
|
|
998
|
+
});
|
|
999
|
+
|
|
1000
|
+
res.json({
|
|
1001
|
+
response: result.choices[0].message,
|
|
1002
|
+
sessionId, // Return sessionId for client to use in WebSocket
|
|
1003
|
+
});
|
|
1004
|
+
});
|
|
1005
|
+
```
|
|
1006
|
+
|
|
1007
|
+
**WebSocket Server:**
|
|
1008
|
+
|
|
1009
|
+
```typescript
|
|
1010
|
+
// ws-server.ts
|
|
1011
|
+
import { createUserObserve } from './utils/observe-context';
|
|
1012
|
+
|
|
1013
|
+
wss.on('connection', (ws, req) => {
|
|
1014
|
+
// Get userId and sessionId from connection (query params, auth token, etc.)
|
|
1015
|
+
const userId = getUserFromToken(req);
|
|
1016
|
+
const sessionId = new URL(req.url, 'http://localhost').searchParams.get('sessionId');
|
|
1017
|
+
|
|
1018
|
+
// Create observe function for this connection
|
|
1019
|
+
const observe = createUserObserve(userId, sessionId, 'websocket');
|
|
1020
|
+
const ai = observe(new GoogleGenAI({ apiKey }));
|
|
1021
|
+
|
|
1022
|
+
ws.on('message', async (data) => {
|
|
1023
|
+
const { message } = JSON.parse(data);
|
|
1024
|
+
|
|
1025
|
+
// This trace will be linked to the same session as the API calls
|
|
1026
|
+
const result = await ai.models.generateContent({
|
|
1027
|
+
model: 'gemini-2.5-flash',
|
|
1028
|
+
contents: message,
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
ws.send(JSON.stringify({ response: result.text }));
|
|
1032
|
+
});
|
|
1033
|
+
});
|
|
1034
|
+
```
|
|
1035
|
+
|
|
1036
|
+
**Background Worker / Queue Consumer:**
|
|
1037
|
+
|
|
1038
|
+
```typescript
|
|
1039
|
+
// worker.ts
|
|
1040
|
+
import { createUserObserve } from './utils/observe-context';
|
|
1041
|
+
|
|
1042
|
+
queue.process('ai-task', async (job) => {
|
|
1043
|
+
const { userId, sessionId, prompt } = job.data;
|
|
1044
|
+
|
|
1045
|
+
const observe = createUserObserve(userId, sessionId, 'worker');
|
|
1046
|
+
const bedrock = observe(new BedrockRuntimeClient({}));
|
|
1047
|
+
|
|
1048
|
+
const command = new ConverseCommand({
|
|
1049
|
+
modelId: 'anthropic.claude-3-sonnet-20240229-v1:0',
|
|
1050
|
+
messages: [{ role: 'user', content: [{ text: prompt }] }],
|
|
1051
|
+
});
|
|
1052
|
+
|
|
1053
|
+
const result = await bedrock.send(command);
|
|
1054
|
+
return result.output.message.content[0].text;
|
|
1055
|
+
});
|
|
1056
|
+
```
|
|
1057
|
+
|
|
1058
|
+
**Client-side (passing sessionId between services):**
|
|
1059
|
+
|
|
1060
|
+
```typescript
|
|
1061
|
+
// Frontend - maintains sessionId across API and WebSocket
|
|
1062
|
+
const sessionId = crypto.randomUUID(); // Or from your session management
|
|
1063
|
+
|
|
1064
|
+
// REST API call
|
|
1065
|
+
const response = await fetch('/chat/start', {
|
|
1066
|
+
method: 'POST',
|
|
1067
|
+
body: JSON.stringify({ userId, sessionId, message: 'Hello' }),
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
// WebSocket connection with same sessionId
|
|
1071
|
+
const ws = new WebSocket(`wss://your-app.com/ws?sessionId=${sessionId}`);
|
|
1072
|
+
|
|
1073
|
+
// Both API and WebSocket traces will be grouped under the same session
|
|
1074
|
+
```
|
|
1075
|
+
|
|
1076
|
+
**Viewing in Dashboard:**
|
|
1077
|
+
|
|
1078
|
+
With consistent `userId` and `sessionId` across services, you can:
|
|
1079
|
+
- See a user's complete journey across API → WebSocket → Background jobs
|
|
1080
|
+
- Filter by service (`metadata.service`) to isolate issues
|
|
1081
|
+
- Track a conversation that spans multiple services
|
|
1082
|
+
|
|
1083
|
+
### What This Enables
|
|
1084
|
+
|
|
1085
|
+
With proper user/session tracking you can:
|
|
1086
|
+
|
|
1087
|
+
- **Filter traces by user** - See all LLM calls from a specific user
|
|
1088
|
+
- **View full conversations** - Group all calls in a session together
|
|
1089
|
+
- **Debug issues** - Find exactly what happened for a specific user request
|
|
1090
|
+
- **Analyze usage patterns** - Understand how different user segments use your AI features
|
|
1091
|
+
- **Cost attribution** - Track token usage per user, tenant, or feature
|
|
1092
|
+
|
|
1093
|
+
## Streaming
|
|
1094
|
+
|
|
1095
|
+
All providers support streaming:
|
|
1096
|
+
|
|
1097
|
+
```typescript
|
|
1098
|
+
const stream = await openai.chat.completions.create({
|
|
1099
|
+
model: 'gpt-4',
|
|
1100
|
+
messages: [{ role: 'user', content: 'Hello!' }],
|
|
1101
|
+
stream: true,
|
|
1102
|
+
});
|
|
1103
|
+
|
|
1104
|
+
for await (const chunk of stream) {
|
|
1105
|
+
process.stdout.write(chunk.choices[0]?.delta?.content || '');
|
|
1106
|
+
}
|
|
1107
|
+
// Trace captured automatically when stream completes
|
|
1108
|
+
```
|
|
1109
|
+
|
|
1110
|
+
## What Gets Traced
|
|
1111
|
+
|
|
1112
|
+
Each LLM call automatically captures:
|
|
1113
|
+
|
|
1114
|
+
- **Provider** - openai, anthropic, bedrock, gemini, openrouter
|
|
1115
|
+
- **Model** - gpt-4, claude-3-opus, gemini-pro, etc.
|
|
1116
|
+
- **Input** - Messages/prompt (sanitized)
|
|
1117
|
+
- **Output** - Response content
|
|
1118
|
+
- **Tokens** - Input and output counts
|
|
1119
|
+
- **Duration** - Request latency in ms
|
|
1120
|
+
- **Status** - success or error
|
|
1121
|
+
- **Streaming** - Whether streaming was used
|
|
1122
|
+
|
|
1123
|
+
## Security
|
|
1124
|
+
|
|
1125
|
+
The SDK automatically sanitizes sensitive data:
|
|
1126
|
+
|
|
1127
|
+
- API keys and tokens are redacted
|
|
1128
|
+
- Large payloads are truncated (100KB limit per field)
|
|
1129
|
+
- Errors are captured safely
|
|
1130
|
+
|
|
1131
|
+
### PII Redaction
|
|
1132
|
+
|
|
1133
|
+
Optionally redact personally identifiable information before traces are sent:
|
|
1134
|
+
|
|
1135
|
+
```typescript
|
|
1136
|
+
init({
|
|
1137
|
+
apiKey: process.env.LELEMON_API_KEY,
|
|
1138
|
+
redaction: {
|
|
1139
|
+
emails: true, // user@example.com → [EMAIL]
|
|
1140
|
+
phones: true, // 123456789 → [PHONE] (9+ digits)
|
|
1141
|
+
}
|
|
1142
|
+
});
|
|
1143
|
+
```
|
|
1144
|
+
|
|
1145
|
+
**Custom patterns** for domain-specific PII:
|
|
1146
|
+
|
|
1147
|
+
```typescript
|
|
1148
|
+
init({
|
|
1149
|
+
redaction: {
|
|
1150
|
+
// Regex patterns (replaced with [REDACTED])
|
|
1151
|
+
patterns: [
|
|
1152
|
+
/SSN-\d{9}/g, // Social Security Numbers
|
|
1153
|
+
/CARD-\d{16}/g, // Credit card numbers
|
|
1154
|
+
/CPF-\d{11}/g, // Brazilian CPF
|
|
1155
|
+
],
|
|
1156
|
+
// Additional key names to redact (case-insensitive, partial match)
|
|
1157
|
+
keys: ['cpf', 'rut', 'dni', 'national_id'],
|
|
1158
|
+
}
|
|
1159
|
+
});
|
|
1160
|
+
```
|
|
1161
|
+
|
|
1162
|
+
**Default redacted keys** (always active):
|
|
1163
|
+
- `api_key`, `apikey`, `password`, `secret`, `authorization`
|
|
1164
|
+
- `access_token`, `auth_token`, `bearer_token`, `refresh_token`, `id_token`, `session_token`
|
|
1165
|
+
|
|
1166
|
+
**Safe keys** (never redacted even if containing "token"):
|
|
1167
|
+
- `inputTokens`, `outputTokens`, `totalTokens`, `promptTokens`, `completionTokens`, etc.
|
|
1168
|
+
|
|
1169
|
+
## Environment Variables
|
|
1170
|
+
|
|
1171
|
+
| Variable | Description |
|
|
1172
|
+
|----------|-------------|
|
|
1173
|
+
| `LELEMON_API_KEY` | Your API key (starts with `le_`) |
|
|
1174
|
+
|
|
1175
|
+
## License
|
|
1176
|
+
|
|
1177
|
+
MIT
|
|
1178
|
+
|
|
1179
|
+
## Sources
|
|
1180
|
+
|
|
1181
|
+
Framework integration patterns based on:
|
|
1182
|
+
- [Next.js after() docs](https://nextjs.org/docs/app/api-reference/functions/after)
|
|
1183
|
+
- [Vercel waitUntil](https://www.inngest.com/blog/vercel-cloudflare-wait-until)
|
|
1184
|
+
- [Langfuse SDK patterns](https://langfuse.com/docs/observability/sdk/typescript/advanced-usage)
|