@uselemma/tracing 4.0.1 → 4.1.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @uselemma/tracing
2
2
 
3
- HTTP tracing SDK for AI agents. No OpenTelemetry setup is required: the SDK sends completed trace payloads directly to the Lemma API.
3
+ HTTP tracing SDK for AI agents. No OpenTelemetry setup is required: the SDK sends trace payloads directly to the Lemma API.
4
4
 
5
5
  ## Installation
6
6
 
@@ -74,6 +74,7 @@ trace.recordGeneration({
74
74
  input: messages,
75
75
  output: text,
76
76
  model: "gpt-4o",
77
+ durationMs: measuredModelMs,
77
78
  llmInputMessages: [{ role: "user", content: userMessage }],
78
79
  llmInvocationParameters: { temperature: 0.2 },
79
80
  });
@@ -89,7 +90,7 @@ Use `startSpan()`, `startTool()`, or `startGeneration()` when you want the SDK t
89
90
  const span = trace.startSpan({ name: "retrieve-context", input: query });
90
91
  try {
91
92
  const docs = await retrieve(query);
92
- span.end({ output: docs, durationMs: 250 });
93
+ span.end({ output: docs });
93
94
  } catch (error) {
94
95
  span.end({ error });
95
96
  throw error;
@@ -99,7 +100,7 @@ try {
99
100
  ```typescript
100
101
  const tool = trace.startTool({ name: "search_docs", input: { query } });
101
102
  const docs = await searchDocs(query);
102
- tool.end({ output: docs, durationMs: 25 });
103
+ tool.end({ output: docs });
103
104
 
104
105
  const generation = trace.startGeneration({
105
106
  name: "answer",
@@ -107,10 +108,10 @@ const generation = trace.startGeneration({
107
108
  model: "gpt-4o",
108
109
  });
109
110
  const response = await callModel(messages);
110
- generation.end({ output: response.text, durationMs: response.durationMs });
111
+ generation.end({ output: response.text, usage: response.usage });
111
112
  ```
112
113
 
113
- The SDK measures trace durations from timestamps. Pass `durationMs` on callback traces, spans, generations, tools, `span.end({ durationMs })`, or `trace.end({ durationMs })` when you already measured the work yourself. When child spans, generations, or tools omit `durationMs`, Lemma splits the parent's remaining unclaimed duration equally across siblings that also omitted duration.
114
+ The SDK measures live handle durations from start and end timestamps. Pass `durationMs` only when replaying historical work or overriding the measured duration with a value from another timer. When child spans, generations, or tools omit `durationMs`, Lemma derives timing from timestamps during ingest.
114
115
 
115
116
  You can also create a trace handle first and record work on it over time:
116
117
 
@@ -127,7 +128,6 @@ span.recordTool({
127
128
  });
128
129
  span.end({
129
130
  output: { count: docs.length },
130
- durationMs: 250,
131
131
  retrievalDocuments: docs.map((doc) => ({
132
132
  id: doc.id,
133
133
  content: doc.text,
@@ -135,9 +135,11 @@ span.end({
135
135
  })),
136
136
  });
137
137
 
138
- await trace.end({ output: "final answer", durationMs: 1234 });
138
+ await trace.end({ output: "final answer" });
139
139
  ```
140
140
 
141
+ For live trace handles, `trace.end({ output })` is usually enough. Pass `durationMs` to `trace.end()` only when you need to override the measured trace duration.
142
+
141
143
  ## Vercel AI SDK
142
144
 
143
145
  Pass `vercelAI()` to the AI SDK telemetry integrations option while the call runs inside a Lemma trace. AI SDK v7 uses `telemetry`; AI SDK v6 uses `experimental_telemetry`.
@@ -180,6 +182,35 @@ The integration records model calls as generations and tool executions as tool c
180
182
 
181
183
  When you pass a trace handle with `vercelAI({ trace })`, the integration ends it from the AI SDK terminal callback: `onEnd` in AI SDK v7 and `onFinish` in AI SDK v6. When you use the callback form of `lemma.trace()`, the callback still owns trace closure.
182
184
 
185
+ ## OpenAI Agents SDK
186
+
187
+ Register the Lemma processor with the OpenAI Agents SDK tracing provider:
188
+
189
+ ```typescript
190
+ import { addTraceProcessor } from "@openai/agents";
191
+ import { openAIAgents } from "@uselemma/tracing";
192
+
193
+ addTraceProcessor(openAIAgents());
194
+ ```
195
+
196
+ The processor creates one Lemma trace for each OpenAI Agents trace. OpenAI
197
+ generation spans become Lemma generations, function spans become Lemma tool
198
+ spans, and other OpenAI Agents spans are preserved as regular spans with the
199
+ original OpenAI trace/span fields in attributes.
200
+
201
+ Function spans stay nested under their OpenAI parent span. To verify nesting
202
+ locally, enable debug mode and check that the tool span log includes the
203
+ generation span ID as `parentId`:
204
+
205
+ ```typescript
206
+ import { enableDebugMode } from "@uselemma/tracing";
207
+
208
+ enableDebugMode();
209
+ ```
210
+
211
+ Use `openAIAgents({ recordInputs: false, recordOutputs: false })` to avoid
212
+ sending prompts, tool inputs, tool outputs, or model output text.
213
+
183
214
  When a helper only has IDs, use the client-level methods:
184
215
 
185
216
  ```typescript
@@ -220,6 +251,49 @@ export function recordSearch(docs: unknown[]) {
220
251
  | `projectId` | `LEMMA_PROJECT_ID` | Required |
221
252
  | `baseUrl` | none | `https://api.uselemma.ai` |
222
253
 
254
+ The SDK sends to `${baseUrl}/traces/ingest`.
255
+
256
+ You can pass configuration directly to the constructor instead of using
257
+ environment variables:
258
+
259
+ ```typescript
260
+ const lemma = new Lemma({
261
+ apiKey: "sk_...",
262
+ projectId: "proj_...",
263
+ baseUrl: "https://api.uselemma.ai",
264
+ });
265
+ ```
266
+
267
+ ## Debug Mode
268
+
269
+ Debug mode logs trace starts, span starts, span completions, send attempts, and
270
+ send results as they happen:
271
+
272
+ ```typescript
273
+ import { enableDebugMode } from "@uselemma/tracing";
274
+
275
+ enableDebugMode();
276
+ ```
277
+
278
+ You can also set `LEMMA_DEBUG=true`. Use this when validating that spans arrive
279
+ in the expected order, parent IDs are attached, and the SDK is sending to the
280
+ right URL.
281
+
282
+ ## Supported Contract Fields
283
+
284
+ Use native SDK props for OpenInference-style fields:
285
+
286
+ - LLM: `llmModelName`, `llmProvider`, `llmSystem`,
287
+ `llmInvocationParameters`, `llmInputMessages`, `llmOutputMessages`,
288
+ `llmTools`, token counts, and prompt template fields
289
+ - tools: `toolName`, `toolDescription`, `toolParameters`
290
+ - retrieval: `retrievalDocuments`
291
+ - embeddings and rerankers: `embeddingModelName`,
292
+ `embeddingInvocationParameters`, `embeddingEmbeddings`,
293
+ `rerankerModelName`, `rerankerInputDocuments`, `rerankerOutputDocuments`
294
+
295
+ Use `attributes` for raw attributes that do not yet have a native SDK prop.
296
+
223
297
  ## Documentation
224
298
 
225
299
  - [Quickstart](https://docs.uselemma.ai/getting-started/quickstart)
@@ -227,7 +301,8 @@ export function recordSearch(docs: unknown[]) {
227
301
 
228
302
  ## Examples
229
303
 
230
- See [`examples/`](./examples) for complete callback tracing, trace handle, record-by-ID, and Vercel AI SDK v6/v7 examples.
304
+ See [`examples/`](./examples) for complete callback tracing, trace handle,
305
+ record-by-ID, Vercel AI SDK v6/v7, and OpenAI Agents SDK examples.
231
306
 
232
307
  ## License
233
308
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { Lemma, NoopSpanHandle, SpanHandle, TraceContext, TraceHandle, active, type DetachedGenerationOptions, type DetachedSpanOptions, type DetachedToolOptions, type GenerationOptions, type JsonValue, type LemmaClientOptions, type SpanOptions, type ToolOptions, type TraceEndOptions, type TraceOptions, } from "./client";
2
2
  export { disableDebugMode, enableDebugMode, isDebugModeEnabled, lemmaDebug, } from "./debug-mode";
3
+ export { openAIAgents, type OpenAIAgentsIntegrationOptions, type OpenAIAgentsSpan, type OpenAIAgentsSpanData, type OpenAIAgentsTrace, type OpenAIAgentsTracingProcessor, } from "./openai-agents";
3
4
  export { vercelAI, type LemmaVercelAIIntegrationOptions, type VercelAIIntegrationOptions, type VercelAITelemetryIntegration, } from "./vercel-ai";
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,cAAc,EACd,UAAU,EACV,YAAY,EACZ,WAAW,EACX,MAAM,EACN,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,SAAS,EACd,KAAK,kBAAkB,EACvB,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,YAAY,GAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,QAAQ,EACR,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,GAClC,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,cAAc,EACd,UAAU,EACV,YAAY,EACZ,WAAW,EACX,MAAM,EACN,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,SAAS,EACd,KAAK,kBAAkB,EACvB,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,YAAY,GAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,YAAY,EACZ,KAAK,8BAA8B,EACnC,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,KAAK,4BAA4B,GAClC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,QAAQ,EACR,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,GAClC,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.vercelAI = exports.lemmaDebug = exports.isDebugModeEnabled = exports.enableDebugMode = exports.disableDebugMode = exports.active = exports.TraceHandle = exports.TraceContext = exports.SpanHandle = exports.NoopSpanHandle = exports.Lemma = void 0;
3
+ exports.vercelAI = exports.openAIAgents = exports.lemmaDebug = exports.isDebugModeEnabled = exports.enableDebugMode = exports.disableDebugMode = exports.active = exports.TraceHandle = exports.TraceContext = exports.SpanHandle = exports.NoopSpanHandle = exports.Lemma = void 0;
4
4
  var client_1 = require("./client");
5
5
  Object.defineProperty(exports, "Lemma", { enumerable: true, get: function () { return client_1.Lemma; } });
6
6
  Object.defineProperty(exports, "NoopSpanHandle", { enumerable: true, get: function () { return client_1.NoopSpanHandle; } });
@@ -13,6 +13,8 @@ Object.defineProperty(exports, "disableDebugMode", { enumerable: true, get: func
13
13
  Object.defineProperty(exports, "enableDebugMode", { enumerable: true, get: function () { return debug_mode_1.enableDebugMode; } });
14
14
  Object.defineProperty(exports, "isDebugModeEnabled", { enumerable: true, get: function () { return debug_mode_1.isDebugModeEnabled; } });
15
15
  Object.defineProperty(exports, "lemmaDebug", { enumerable: true, get: function () { return debug_mode_1.lemmaDebug; } });
16
+ var openai_agents_1 = require("./openai-agents");
17
+ Object.defineProperty(exports, "openAIAgents", { enumerable: true, get: function () { return openai_agents_1.openAIAgents; } });
16
18
  var vercel_ai_1 = require("./vercel-ai");
17
19
  Object.defineProperty(exports, "vercelAI", { enumerable: true, get: function () { return vercel_ai_1.vercelAI; } });
18
20
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,mCAiBkB;AAhBhB,+FAAA,KAAK,OAAA;AACL,wGAAA,cAAc,OAAA;AACd,oGAAA,UAAU,OAAA;AACV,sGAAA,YAAY,OAAA;AACZ,qGAAA,WAAW,OAAA;AACX,gGAAA,MAAM,OAAA;AAYR,2CAKsB;AAJpB,8GAAA,gBAAgB,OAAA;AAChB,6GAAA,eAAe,OAAA;AACf,gHAAA,kBAAkB,OAAA;AAClB,wGAAA,UAAU,OAAA;AAEZ,yCAKqB;AAJnB,qGAAA,QAAQ,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,mCAiBkB;AAhBhB,+FAAA,KAAK,OAAA;AACL,wGAAA,cAAc,OAAA;AACd,oGAAA,UAAU,OAAA;AACV,sGAAA,YAAY,OAAA;AACZ,qGAAA,WAAW,OAAA;AACX,gGAAA,MAAM,OAAA;AAYR,2CAKsB;AAJpB,8GAAA,gBAAgB,OAAA;AAChB,6GAAA,eAAe,OAAA;AACf,gHAAA,kBAAkB,OAAA;AAClB,wGAAA,UAAU,OAAA;AAEZ,iDAOyB;AANvB,6GAAA,YAAY,OAAA;AAOd,yCAKqB;AAJnB,qGAAA,QAAQ,OAAA"}
@@ -0,0 +1,45 @@
1
+ import { Lemma } from "./client";
2
+ export type OpenAIAgentsTrace = {
3
+ traceId: string;
4
+ name: string;
5
+ groupId?: string | null;
6
+ metadata?: Record<string, unknown>;
7
+ };
8
+ export type OpenAIAgentsSpanData = {
9
+ type: string;
10
+ [key: string]: unknown;
11
+ };
12
+ export type OpenAIAgentsSpan = {
13
+ traceId: string;
14
+ spanId: string;
15
+ parentId?: string | null;
16
+ spanData: OpenAIAgentsSpanData;
17
+ traceMetadata?: Record<string, unknown>;
18
+ startedAt?: string | null;
19
+ endedAt?: string | null;
20
+ error?: {
21
+ message?: string;
22
+ data?: Record<string, unknown>;
23
+ } | null;
24
+ };
25
+ export type OpenAIAgentsTracingProcessor = {
26
+ start?: () => void;
27
+ onTraceStart: (trace: OpenAIAgentsTrace) => Promise<void>;
28
+ onTraceEnd: (trace: OpenAIAgentsTrace) => Promise<void>;
29
+ onSpanStart: (span: OpenAIAgentsSpan) => Promise<void>;
30
+ onSpanEnd: (span: OpenAIAgentsSpan) => Promise<void>;
31
+ shutdown: (timeout?: number) => Promise<void>;
32
+ forceFlush: () => Promise<void>;
33
+ };
34
+ export type OpenAIAgentsIntegrationOptions = {
35
+ lemma?: Lemma;
36
+ apiKey?: string;
37
+ projectId?: string;
38
+ baseUrl?: string;
39
+ fetch?: typeof fetch;
40
+ metadata?: Record<string, unknown>;
41
+ recordInputs?: boolean;
42
+ recordOutputs?: boolean;
43
+ };
44
+ export declare function openAIAgents(options?: OpenAIAgentsIntegrationOptions): OpenAIAgentsTracingProcessor;
45
+ //# sourceMappingURL=openai-agents.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-agents.d.ts","sourceRoot":"","sources":["../src/openai-agents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqC,MAAM,UAAU,CAAC;AAIpE,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACxC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,KAAK,CAAC,EAAE;QACN,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KAChC,GAAG,IAAI,CAAC;CACV,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;IACnB,YAAY,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,UAAU,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACxD,WAAW,EAAE,CAAC,IAAI,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACvD,SAAS,EAAE,CAAC,IAAI,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,8BAA8B,GAAG;IAC3C,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAoFF,wBAAgB,YAAY,CAC1B,OAAO,GAAE,8BAAmC,GAC3C,4BAA4B,CA8H9B"}
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openAIAgents = openAIAgents;
4
+ const client_1 = require("./client");
5
+ function parseMaybeJson(value) {
6
+ if (typeof value !== "string")
7
+ return value;
8
+ try {
9
+ return JSON.parse(value);
10
+ }
11
+ catch {
12
+ return value;
13
+ }
14
+ }
15
+ function textFromGenerationOutput(output) {
16
+ if (!Array.isArray(output))
17
+ return output;
18
+ const text = output
19
+ .map((item) => {
20
+ if (!item || typeof item !== "object")
21
+ return "";
22
+ const record = item;
23
+ if (typeof record["text"] === "string")
24
+ return record["text"];
25
+ if (typeof record["content"] === "string")
26
+ return record["content"];
27
+ return "";
28
+ })
29
+ .join("");
30
+ return text || output;
31
+ }
32
+ function spanName(data) {
33
+ if (typeof data["name"] === "string" && data["name"]) {
34
+ return data["name"];
35
+ }
36
+ if (data.type === "generation")
37
+ return "openai-agents-generation";
38
+ if (data.type === "response")
39
+ return "openai-agents-response";
40
+ if (data.type === "handoff") {
41
+ const from = typeof data["from_agent"] === "string" ? data["from_agent"] : "";
42
+ const to = typeof data["to_agent"] === "string" ? data["to_agent"] : "";
43
+ return from && to ? `${from} to ${to}` : "openai-agents-handoff";
44
+ }
45
+ return `openai-agents-${data.type || "span"}`;
46
+ }
47
+ function openAIAttributes(span) {
48
+ return Object.fromEntries(Object.entries({
49
+ "openai.agents.trace_id": span.traceId,
50
+ "openai.agents.span_id": span.spanId,
51
+ "openai.agents.parent_id": span.parentId,
52
+ "openai.agents.span_type": span.spanData.type,
53
+ "openai.agents.trace_metadata": span.traceMetadata
54
+ ? JSON.stringify(span.traceMetadata)
55
+ : undefined,
56
+ "openai.agents.span_data": JSON.stringify(span.spanData),
57
+ }).filter(([, value]) => value !== undefined && value !== null));
58
+ }
59
+ function usage(data) {
60
+ const raw = data["usage"];
61
+ if (!raw || typeof raw !== "object")
62
+ return undefined;
63
+ const usageData = raw;
64
+ return {
65
+ inputTokens: typeof usageData["input_tokens"] === "number"
66
+ ? usageData["input_tokens"]
67
+ : undefined,
68
+ outputTokens: typeof usageData["output_tokens"] === "number"
69
+ ? usageData["output_tokens"]
70
+ : undefined,
71
+ };
72
+ }
73
+ function startedAt(span) {
74
+ return span.startedAt ?? new Date();
75
+ }
76
+ function endedAt(span) {
77
+ return span.endedAt ?? new Date();
78
+ }
79
+ function openAIAgents(options = {}) {
80
+ const lemma = options.lemma ??
81
+ new client_1.Lemma({
82
+ apiKey: options.apiKey,
83
+ projectId: options.projectId,
84
+ baseUrl: options.baseUrl,
85
+ fetch: options.fetch,
86
+ });
87
+ const traces = new Map();
88
+ const spans = new Map();
89
+ function ensureTrace(trace) {
90
+ const existing = traces.get(trace.traceId);
91
+ if (existing)
92
+ return existing;
93
+ const handle = lemma.trace({
94
+ name: trace.name || "openai-agents-trace",
95
+ metadata: {
96
+ ...options.metadata,
97
+ ...(trace.metadata ?? {}),
98
+ openaiAgentsTraceId: trace.traceId,
99
+ openaiAgentsGroupId: trace.groupId ?? undefined,
100
+ },
101
+ threadId: trace.groupId ?? undefined,
102
+ });
103
+ const stored = { handle, ended: false };
104
+ traces.set(trace.traceId, stored);
105
+ return stored;
106
+ }
107
+ function startSpan(span) {
108
+ const trace = traces.get(span.traceId);
109
+ if (!trace)
110
+ return undefined;
111
+ const data = span.spanData;
112
+ const base = {
113
+ id: span.spanId,
114
+ parentId: span.parentId ?? null,
115
+ name: spanName(data),
116
+ input: options.recordInputs === false
117
+ ? undefined
118
+ : parseMaybeJson(data["input"] ?? data["_input"]),
119
+ metadata: options.metadata,
120
+ attributes: openAIAttributes(span),
121
+ startedAt: startedAt(span),
122
+ };
123
+ if (data.type === "generation" || data.type === "response") {
124
+ return trace.handle.startGeneration({
125
+ ...base,
126
+ model: typeof data["model"] === "string" ? data["model"] : undefined,
127
+ llmProvider: "openai",
128
+ llmInputMessages: options.recordInputs === false || !Array.isArray(data["input"])
129
+ ? undefined
130
+ : data["input"],
131
+ llmInvocationParameters: data["model_config"],
132
+ });
133
+ }
134
+ if (data.type === "function") {
135
+ return trace.handle.startTool({
136
+ ...base,
137
+ toolName: typeof data["name"] === "string" ? data["name"] : undefined,
138
+ });
139
+ }
140
+ return trace.handle.startSpan(base);
141
+ }
142
+ function endSpan(span) {
143
+ const handle = spans.get(span.spanId) ?? startSpan(span);
144
+ if (!handle)
145
+ return;
146
+ spans.delete(span.spanId);
147
+ const data = span.spanData;
148
+ const output = options.recordOutputs === false
149
+ ? undefined
150
+ : data.type === "generation"
151
+ ? textFromGenerationOutput(data["output"])
152
+ : parseMaybeJson(data["output"] ?? data["_response"]);
153
+ handle.end({
154
+ output,
155
+ error: span.error?.message,
156
+ status: span.error ? "ERROR" : undefined,
157
+ model: typeof data["model"] === "string" ? data["model"] : undefined,
158
+ usage: usage(data),
159
+ endedAt: endedAt(span),
160
+ llmOutputMessages: options.recordOutputs === false || !Array.isArray(data["output"])
161
+ ? undefined
162
+ : data["output"],
163
+ });
164
+ }
165
+ async function forEachTrace(fn) {
166
+ await Promise.all(Array.from(traces.values(), fn));
167
+ }
168
+ return {
169
+ onTraceStart: async (trace) => {
170
+ ensureTrace(trace);
171
+ },
172
+ onTraceEnd: async (trace) => {
173
+ const stored = ensureTrace(trace);
174
+ if (stored.ended)
175
+ return;
176
+ stored.ended = true;
177
+ await stored.handle.end();
178
+ },
179
+ onSpanStart: async (span) => {
180
+ const handle = startSpan(span);
181
+ if (handle)
182
+ spans.set(span.spanId, handle);
183
+ },
184
+ onSpanEnd: async (span) => {
185
+ endSpan(span);
186
+ },
187
+ shutdown: async () => {
188
+ await forEachTrace((trace) => trace.handle.flush());
189
+ },
190
+ forceFlush: async () => {
191
+ await forEachTrace((trace) => trace.handle.flush());
192
+ },
193
+ };
194
+ }
195
+ //# sourceMappingURL=openai-agents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-agents.js","sourceRoot":"","sources":["../src/openai-agents.ts"],"names":[],"mappings":";;AAqIA,oCAgIC;AArQD,qCAAoE;AAwDpE,SAAS,cAAc,CAAC,KAAc;IACpC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,SAAS,wBAAwB,CAAC,MAAe;IAC/C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC;IAC1C,MAAM,IAAI,GAAG,MAAM;SAChB,GAAG,CAAC,CAAC,IAAI,EAAE,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C,KAAK,EAAE,CAAC,CAAC;QACtD,CAAC;QACD,UAAU,EAAE,KAAK,IAAI,EAAE;YACrB,MAAM,YAAY,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;QACtD,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { Agent, addTraceProcessor, run } from "@openai/agents";
2
+ import { openAIAgents } from "@uselemma/tracing";
3
+
4
+ addTraceProcessor(openAIAgents());
5
+
6
+ const agent = new Agent({
7
+ name: "support-agent",
8
+ instructions: "Answer customer questions clearly and concisely.",
9
+ });
10
+
11
+ const result = await run(agent, "Where is my order?");
12
+
13
+ console.log(result.finalOutput);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uselemma/tracing",
3
- "version": "4.0.1",
3
+ "version": "4.1.0",
4
4
  "description": "HTTP tracing SDK for Lemma",
5
5
  "license": "MIT",
6
6
  "author": "Lemma",