@lelemondev/sdk 0.9.3 → 0.9.5
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 +148 -15
- package/dist/anthropic.d.mts +2 -2
- package/dist/anthropic.d.ts +2 -2
- package/dist/anthropic.js +1 -1
- package/dist/anthropic.mjs +1 -1
- package/dist/bedrock.d.mts +2 -2
- package/dist/bedrock.d.ts +2 -2
- package/dist/bedrock.js +1 -1
- package/dist/bedrock.mjs +1 -1
- package/dist/capture-ChybLulj.d.mts +264 -0
- package/dist/capture-ChybLulj.d.ts +264 -0
- package/dist/gemini.d.mts +2 -2
- package/dist/gemini.d.ts +2 -2
- package/dist/gemini.js +1 -1
- package/dist/gemini.mjs +1 -1
- package/dist/index.d.mts +21 -245
- package/dist/index.d.ts +21 -245
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/integrations.js +1 -1
- package/dist/next.js +1 -1
- package/dist/openai.d.mts +2 -2
- package/dist/openai.d.ts +2 -2
- package/dist/openai.js +1 -1
- package/dist/openai.mjs +1 -1
- package/dist/openrouter.d.mts +2 -2
- package/dist/openrouter.d.ts +2 -2
- package/dist/openrouter.js +1 -1
- package/dist/openrouter.mjs +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core types for Lelemon SDK
|
|
3
|
+
*/
|
|
4
|
+
interface ServiceConfig {
|
|
5
|
+
/** Service name (e.g., "my-ai-chatbot") */
|
|
6
|
+
name?: string;
|
|
7
|
+
/** Service version (e.g., "1.2.3") */
|
|
8
|
+
version?: string;
|
|
9
|
+
/** Deployment environment (e.g., "production", "staging", "development") */
|
|
10
|
+
environment?: string;
|
|
11
|
+
}
|
|
12
|
+
interface LelemonConfig {
|
|
13
|
+
/** API key (or set LELEMON_API_KEY env var) */
|
|
14
|
+
apiKey?: string;
|
|
15
|
+
/** API endpoint (default: https://api.lelemon.dev) */
|
|
16
|
+
endpoint?: string;
|
|
17
|
+
/** Enable debug logging */
|
|
18
|
+
debug?: boolean;
|
|
19
|
+
/** Disable tracing */
|
|
20
|
+
disabled?: boolean;
|
|
21
|
+
/** Batch size before flush (default: 10) */
|
|
22
|
+
batchSize?: number;
|
|
23
|
+
/** Auto-flush interval in ms (default: 1000) */
|
|
24
|
+
flushIntervalMs?: number;
|
|
25
|
+
/** Request timeout in ms (default: 10000) */
|
|
26
|
+
requestTimeoutMs?: number;
|
|
27
|
+
/** Service metadata for telemetry */
|
|
28
|
+
service?: ServiceConfig;
|
|
29
|
+
}
|
|
30
|
+
interface SDKTelemetry {
|
|
31
|
+
/** SDK name */
|
|
32
|
+
'telemetry.sdk.name': string;
|
|
33
|
+
/** SDK version */
|
|
34
|
+
'telemetry.sdk.version': string;
|
|
35
|
+
/** SDK language */
|
|
36
|
+
'telemetry.sdk.language': string;
|
|
37
|
+
/** Runtime name (nodejs, deno, bun, browser) */
|
|
38
|
+
'process.runtime.name'?: string;
|
|
39
|
+
/** Runtime version */
|
|
40
|
+
'process.runtime.version'?: string;
|
|
41
|
+
/** OS type (linux, darwin, windows) */
|
|
42
|
+
'os.type'?: string;
|
|
43
|
+
/** Service name */
|
|
44
|
+
'service.name'?: string;
|
|
45
|
+
/** Service version */
|
|
46
|
+
'service.version'?: string;
|
|
47
|
+
/** Deployment environment */
|
|
48
|
+
'deployment.environment'?: string;
|
|
49
|
+
}
|
|
50
|
+
type ProviderName = 'openai' | 'anthropic' | 'gemini' | 'bedrock' | 'openrouter' | 'agent' | 'unknown';
|
|
51
|
+
interface ObserveOptions {
|
|
52
|
+
/** Session ID to group related calls */
|
|
53
|
+
sessionId?: string;
|
|
54
|
+
/** User ID for the end user */
|
|
55
|
+
userId?: string;
|
|
56
|
+
/** Custom metadata added to all traces */
|
|
57
|
+
metadata?: Record<string, unknown>;
|
|
58
|
+
/** Tags for filtering */
|
|
59
|
+
tags?: string[];
|
|
60
|
+
}
|
|
61
|
+
type SpanType = 'llm' | 'agent' | 'tool' | 'retrieval' | 'embedding' | 'guardrail' | 'rerank' | 'custom';
|
|
62
|
+
interface CaptureSpanOptions {
|
|
63
|
+
/** Span type */
|
|
64
|
+
type: SpanType;
|
|
65
|
+
/** Span name (tool name, retrieval source, custom name) */
|
|
66
|
+
name: string;
|
|
67
|
+
/** Input data */
|
|
68
|
+
input: unknown;
|
|
69
|
+
/** Output data */
|
|
70
|
+
output: unknown;
|
|
71
|
+
/** Duration in milliseconds */
|
|
72
|
+
durationMs: number;
|
|
73
|
+
/** Status */
|
|
74
|
+
status?: 'success' | 'error';
|
|
75
|
+
/** Error message if status is 'error' */
|
|
76
|
+
errorMessage?: string;
|
|
77
|
+
/** Tool call ID (for linking tool results) */
|
|
78
|
+
toolCallId?: string;
|
|
79
|
+
/** Custom metadata */
|
|
80
|
+
metadata?: Record<string, unknown>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Global Configuration
|
|
85
|
+
*
|
|
86
|
+
* Manages SDK configuration and transport instance.
|
|
87
|
+
*/
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Initialize the SDK
|
|
91
|
+
* Call once at app startup
|
|
92
|
+
*/
|
|
93
|
+
declare function init(config?: LelemonConfig): void;
|
|
94
|
+
/**
|
|
95
|
+
* Check if SDK is enabled
|
|
96
|
+
*/
|
|
97
|
+
declare function isEnabled(): boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Flush all pending traces
|
|
100
|
+
*/
|
|
101
|
+
declare function flush(): Promise<void>;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Trace Context Module
|
|
105
|
+
*
|
|
106
|
+
* Provides AsyncLocalStorage-based context for grouping spans under a parent trace.
|
|
107
|
+
* Supports hierarchical tracing where:
|
|
108
|
+
* - trace() creates a root "agent" span
|
|
109
|
+
* - LLM calls become children of the root
|
|
110
|
+
* - Tool calls become children of the LLM that triggered them (via toolCallId linking)
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* import { trace, span } from '@lelemondev/sdk';
|
|
115
|
+
*
|
|
116
|
+
* await trace({ name: 'sales-agent', input: userMessage }, async () => {
|
|
117
|
+
* const response = await client.send(new ConverseCommand({...}));
|
|
118
|
+
* // Tools automatically linked to their parent LLM via toolCallId
|
|
119
|
+
* return response;
|
|
120
|
+
* });
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
interface TraceContext {
|
|
124
|
+
/** Unique trace ID (shared by all spans in this trace) */
|
|
125
|
+
traceId: string;
|
|
126
|
+
/** Root span ID (the agent/workflow span) */
|
|
127
|
+
rootSpanId: string;
|
|
128
|
+
/** Current span ID (for nesting - LLM calls become children of this) */
|
|
129
|
+
currentSpanId: string;
|
|
130
|
+
/** Parent span ID (for nested trace() calls) */
|
|
131
|
+
parentSpanId?: string;
|
|
132
|
+
/** Trace name */
|
|
133
|
+
name: string;
|
|
134
|
+
/** Start time in ms */
|
|
135
|
+
startTime: number;
|
|
136
|
+
/** Input data */
|
|
137
|
+
input?: unknown;
|
|
138
|
+
/** Trace metadata */
|
|
139
|
+
metadata?: Record<string, unknown>;
|
|
140
|
+
/** Trace tags */
|
|
141
|
+
tags?: string[];
|
|
142
|
+
/** Map of toolCallId → llmSpanId for linking tool spans to their parent LLM */
|
|
143
|
+
pendingToolCalls: Map<string, string>;
|
|
144
|
+
}
|
|
145
|
+
interface TraceOptions {
|
|
146
|
+
/** Name for the trace (e.g., 'sales-agent', 'rag-query') */
|
|
147
|
+
name: string;
|
|
148
|
+
/** Input data for the trace */
|
|
149
|
+
input?: unknown;
|
|
150
|
+
/** Custom metadata */
|
|
151
|
+
metadata?: Record<string, unknown>;
|
|
152
|
+
/** Tags for filtering */
|
|
153
|
+
tags?: string[];
|
|
154
|
+
}
|
|
155
|
+
interface SpanOptions {
|
|
156
|
+
/** Span type */
|
|
157
|
+
type: 'retrieval' | 'embedding' | 'tool' | 'guardrail' | 'rerank' | 'custom';
|
|
158
|
+
/** Span name (e.g., 'pinecone-search', 'cohere-rerank') */
|
|
159
|
+
name: string;
|
|
160
|
+
/** Input data */
|
|
161
|
+
input?: unknown;
|
|
162
|
+
/** Output data */
|
|
163
|
+
output?: unknown;
|
|
164
|
+
/** Duration in milliseconds (optional, will be set automatically if not provided) */
|
|
165
|
+
durationMs?: number;
|
|
166
|
+
/** Status */
|
|
167
|
+
status?: 'success' | 'error';
|
|
168
|
+
/** Error message if status is 'error' */
|
|
169
|
+
errorMessage?: string;
|
|
170
|
+
/** Tool call ID (links this tool span to the LLM that requested it) */
|
|
171
|
+
toolCallId?: string;
|
|
172
|
+
/** Custom metadata */
|
|
173
|
+
metadata?: Record<string, unknown>;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Get the current trace context, if any
|
|
177
|
+
*/
|
|
178
|
+
declare function getTraceContext(): TraceContext | undefined;
|
|
179
|
+
/**
|
|
180
|
+
* Execute a function within a trace context.
|
|
181
|
+
* Creates a root "agent" span that contains all LLM calls and tool executions.
|
|
182
|
+
* The result of the function becomes the output of the root span.
|
|
183
|
+
*
|
|
184
|
+
* @example Simple usage (just name)
|
|
185
|
+
* ```typescript
|
|
186
|
+
* await trace('sales-agent', async () => {
|
|
187
|
+
* await client.send(new ConverseCommand({...}));
|
|
188
|
+
* return finalResponse;
|
|
189
|
+
* });
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* @example With options
|
|
193
|
+
* ```typescript
|
|
194
|
+
* await trace({ name: 'rag-query', input: question, tags: ['production'] }, async () => {
|
|
195
|
+
* const docs = await search(question);
|
|
196
|
+
* span({ type: 'retrieval', name: 'pinecone', output: { count: docs.length } });
|
|
197
|
+
* return client.send(new ConverseCommand({...}));
|
|
198
|
+
* });
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
declare function trace<T>(nameOrOptions: string | TraceOptions, fn: () => Promise<T>): Promise<T>;
|
|
202
|
+
/**
|
|
203
|
+
* Manually capture a span for non-LLM operations (retrieval, embedding, tool, etc.)
|
|
204
|
+
* Must be called within a trace() block.
|
|
205
|
+
*
|
|
206
|
+
* @example Tool with toolCallId (links to parent LLM)
|
|
207
|
+
* ```typescript
|
|
208
|
+
* span({
|
|
209
|
+
* type: 'tool',
|
|
210
|
+
* name: 'query_database',
|
|
211
|
+
* toolCallId: 'tooluse_abc123', // Links to LLM that requested this
|
|
212
|
+
* input: { sql: 'SELECT ...' },
|
|
213
|
+
* output: { rows: [...] },
|
|
214
|
+
* durationMs: 15,
|
|
215
|
+
* });
|
|
216
|
+
* ```
|
|
217
|
+
*
|
|
218
|
+
* @example Retrieval without toolCallId
|
|
219
|
+
* ```typescript
|
|
220
|
+
* span({
|
|
221
|
+
* type: 'retrieval',
|
|
222
|
+
* name: 'pinecone-search',
|
|
223
|
+
* input: { topK: 5 },
|
|
224
|
+
* output: { count: 10 },
|
|
225
|
+
* durationMs: 50,
|
|
226
|
+
* });
|
|
227
|
+
* ```
|
|
228
|
+
*/
|
|
229
|
+
declare function span(options: SpanOptions): void;
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Capture Module
|
|
233
|
+
*
|
|
234
|
+
* Handles trace capture and batching.
|
|
235
|
+
* Called by providers to record LLM calls.
|
|
236
|
+
*/
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Manually capture a span (tool call, retrieval, custom)
|
|
240
|
+
* Use this when auto-detection doesn't cover your use case
|
|
241
|
+
*
|
|
242
|
+
* @example
|
|
243
|
+
* // Capture a tool call
|
|
244
|
+
* captureSpan({
|
|
245
|
+
* type: 'tool',
|
|
246
|
+
* name: 'get_weather',
|
|
247
|
+
* input: { location: 'San Francisco' },
|
|
248
|
+
* output: { temperature: 72, conditions: 'sunny' },
|
|
249
|
+
* durationMs: 150,
|
|
250
|
+
* });
|
|
251
|
+
*
|
|
252
|
+
* @example
|
|
253
|
+
* // Capture a retrieval/RAG operation
|
|
254
|
+
* captureSpan({
|
|
255
|
+
* type: 'retrieval',
|
|
256
|
+
* name: 'vector_search',
|
|
257
|
+
* input: { query: 'user question', k: 5 },
|
|
258
|
+
* output: { documents: [...] },
|
|
259
|
+
* durationMs: 50,
|
|
260
|
+
* });
|
|
261
|
+
*/
|
|
262
|
+
declare function captureSpan(options: CaptureSpanOptions): void;
|
|
263
|
+
|
|
264
|
+
export { type CaptureSpanOptions as C, type LelemonConfig as L, type ObserveOptions as O, type ProviderName as P, type ServiceConfig as S, type TraceContext as T, isEnabled as a, type SDKTelemetry as b, captureSpan as c, type SpanType as d, type TraceOptions as e, flush as f, getTraceContext as g, type SpanOptions as h, init as i, span as s, trace as t };
|
package/dist/gemini.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ObserveOptions } from './
|
|
2
|
-
export { CaptureSpanOptions, LelemonConfig, SpanOptions, SpanType, TraceContext, TraceOptions, captureSpan, flush, getTraceContext, init, isEnabled, span, trace } from './
|
|
1
|
+
import { O as ObserveOptions } from './capture-ChybLulj.mjs';
|
|
2
|
+
export { C as CaptureSpanOptions, L as LelemonConfig, h as SpanOptions, d as SpanType, T as TraceContext, e as TraceOptions, c as captureSpan, f as flush, g as getTraceContext, i as init, a as isEnabled, s as span, t as trace } from './capture-ChybLulj.mjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Google Gemini Provider Entry Point
|
package/dist/gemini.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ObserveOptions } from './
|
|
2
|
-
export { CaptureSpanOptions, LelemonConfig, SpanOptions, SpanType, TraceContext, TraceOptions, captureSpan, flush, getTraceContext, init, isEnabled, span, trace } from './
|
|
1
|
+
import { O as ObserveOptions } from './capture-ChybLulj.js';
|
|
2
|
+
export { C as CaptureSpanOptions, L as LelemonConfig, h as SpanOptions, d as SpanType, T as TraceContext, e as TraceOptions, c as captureSpan, f as flush, g as getTraceContext, i as init, a as isEnabled, s as span, t as trace } from './capture-ChybLulj.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Google Gemini Provider Entry Point
|
package/dist/gemini.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
'use strict';var async_hooks=require('async_hooks');/* @lelemondev/sdk - LLM Observability */
|
|
2
|
-
var ce=Object.defineProperty;var le=(e,t,n)=>t in e?ce(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var K=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var v=(e,t,n)=>le(e,typeof t!="symbol"?t+"":t,n);var W=pe((nt,Ce)=>{Ce.exports={name:"@lelemondev/sdk",version:"0.9.3",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/generative-ai":"^0.24.1","@types/node":"^20.0.0","@vitest/coverage-v8":"^2.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.15",typescript:"^5.9.3",vitest:"^2.0.0"}};});var L=false;function N(e){L=e;}function g(){return L?true:fe("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function l(e,t){g()&&_("debug",e,t);}function q(e,t){g()&&_("info",e,t);}function I(e,t){_("warn",e,t);}function D(e,t,n,r){g()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function M(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function U(e){g()&&console.log(`${p} Wrapped client: provider=${e}`);}function z(e,t){g()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function F(e,t){g()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function V(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function B(e,t,n){g()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function H(e,t){g()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function _(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function fe(e){if(typeof process<"u"&&process.env)return process.env[e]}var ge=10,me=1e3,he=1e4,E=class{constructor(t){v(this,"config");v(this,"queue",[]);v(this,"flushPromise",null);v(this,"flushTimer",null);this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??ge,flushIntervalMs:t.flushIntervalMs??me,requestTimeoutMs:t.requestTimeoutMs??he};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();z(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),F(t.length,Date.now()-n);}catch(r){V(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,s=new AbortController,i=r?JSON.stringify(r):void 0;B(t,o,i?.length??0);let d=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),u=Date.now();try{let a=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:s.signal});if(clearTimeout(d),H(a.status,Date.now()-u),!a.ok){let x=await a.text().catch(()=>"Unknown error");throw new Error(`HTTP ${a.status}: ${x}`)}let c=await a.text();return c?JSON.parse(c):{}}catch(a){throw clearTimeout(d),a instanceof Error&&a.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):a}}};var ye="@lelemondev/sdk",we="nodejs";function be(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function Te(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function ve(){try{if(typeof K<"u")return W().version??"unknown"}catch{}return "unknown"}var w=null;function J(e){if(!w){let n=be(),r=Te();w={"telemetry.sdk.name":ye,"telemetry.sdk.version":ve(),"telemetry.sdk.language":we},n&&(w["process.runtime.name"]=n.name,w["process.runtime.version"]=n.version),r&&(w["os.type"]=r);}let t={...w};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var O={},C=null,$=null,X="https://www.lelemon.dev";function ke(e={}){O=e,e.debug&&N(true),$=J(e.service),q("Initializing SDK",{endpoint:e.endpoint??X,debug:e.debug??false,disabled:e.disabled??false,telemetry:$}),C=Z(e),C.isEnabled()?q("SDK initialized - tracing enabled"):l("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function Q(){return O}function R(){return $}function xe(){return y().isEnabled()}function y(){return C||(C=Z(O)),C}async function Ie(){C&&await C.flush();}function Z(e){let t=e.apiKey??Me("LELEMON_API_KEY");return !t&&!e.disabled&&I("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new E({apiKey:t??"",endpoint:e.endpoint??X,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Me(e){if(typeof process<"u"&&process.env)return process.env[e]}var te={};function ne(e){te=e,l("Global context updated",e);}function k(){return te}function G(e){try{let t=y();if(!t.isEnabled()){l("Transport disabled, skipping trace capture");return}let n=k(),r=f(),o=T(),s=R(),i={provider:e.provider,model:e.model,input:A(e.input),rawResponse:e.rawResponse?S(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags,spanType:e.spanType,name:e.name};return D(e.provider,e.model,e.durationMs,e.status),t.enqueue(i),o}catch(t){M(e.provider,t instanceof Error?t:new Error(String(t)));return}}function b(e){try{let t=y();if(!t.isEnabled()){l("Transport disabled, skipping error capture");return}let n=k(),r=f(),o=R(),s={provider:e.provider,model:e.model,input:A(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:T(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:n.tags};D(e.provider,e.model,e.durationMs,"error"),l("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(s);}catch(t){M(e.provider,t instanceof Error?t:new Error(String(t)));}}function j(e){try{let t=y();if(!t.isEnabled()){l("Transport disabled, skipping span capture");return}let n=k(),r=f(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,i=R(),d={...n.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete d._traceId,delete d._parentSpanId;let u={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:A(e.input),output:S(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:n.sessionId,userId:n.userId,traceId:o??r?.traceId,spanId:T(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:d,tags:n.tags};l(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(u);}catch(t){M("unknown",t instanceof Error?t:new Error(String(t)));}}var ee=1e5,Ee=["api_key","apikey","password","secret","authorization"],Re=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Ge=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"];function Pe(e){let t=e.toLowerCase();return Ge.includes(t)?false:!!(Ee.some(n=>t.includes(n))||Re.some(n=>t.includes(n)))}function A(e){return S(e,0)}function S(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string")return e.length>ee?e.slice(0,ee)+"...[truncated]":e;if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>S(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))Pe(r)?n[r]="[REDACTED]":n[r]=S(o,t+1);return n}return String(e)}var re=new async_hooks.AsyncLocalStorage;function T(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function f(){return re.getStore()}function P(e,t){let n=f();if(n)for(let r of e)n.pendingToolCalls.set(r,t),l(`Registered tool call ${r} \u2192 LLM span ${t}`);}function De(e){let t=f();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function _e(e){let t=f();t&&t.pendingToolCalls.delete(e);}async function $e(e,t){let n=typeof e=="string"?{name:e}:e,r=f(),o=r?.traceId??T(),s=T(),i={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,pendingToolCalls:new Map};return re.run(i,async()=>{let d,u;try{return d=await t(),d}catch(a){throw u=a instanceof Error?a:new Error(String(a)),a}finally{Oe(i,u?void 0:d,u);}})}function Oe(e,t,n){let r=y();if(!r.isEnabled()){l("Transport disabled, skipping root span");return}let o=k(),s=Date.now()-e.startTime,i=n?null:t,d={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:i,inputTokens:0,outputTokens:0,durationMs:s,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:o.sessionId,userId:o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};l(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(d);}function je(e){let t=f();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=De(e.toolCallId);j({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n}}),e.toolCallId&&_e(e.toolCallId);}var m="gemini";function oe(e){if(!e||typeof e!="object")return false;let t=e.constructor?.name;if(t==="GoogleGenerativeAI"||t==="GoogleGenAI")return true;let n=e;return !!(typeof n.getGenerativeModel=="function"||n.models&&typeof n.models.generate=="function")}function se(e){let t=e;return new Proxy(t,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="getGenerativeModel"&&typeof s=="function"?Ae(s.bind(n)):s}})}function Ae(e){return function(n){let r=e(n);return Ke(r,n.model)}}function Ke(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="generateContent"&&typeof s=="function"?Le(s.bind(n),t):r==="generateContentStream"&&typeof s=="function"?Ne(s.bind(n),t):r==="startChat"&&typeof s=="function"?Ue(s.bind(n),t):s}})}function Le(e,t){return async function(r){let o=Date.now(),s=ae(r);try{let i=await e(r),d=Date.now()-o,u=ue(i.response),a=G({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=de(i.response);c.length>0&&P(c,a);}return i}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Ne(e,t){return async function(r){let o=Date.now(),s=ae(r);try{let i=await e(r),d=ie(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}async function*ie(e,t,n,r){let o={candidates:[{content:{parts:[]}}]},s=null,i,d=false;try{for await(let u of e){try{let a=u.text();if(a){d||(d=!0,i=Date.now()-r);let c=o.candidates[0].content?.parts||[],x=c[c.length-1];x?.text!==void 0?x.text+=a:c.push({text:a});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let a of u.candidates[0].content.parts)a.functionCall&&o.candidates[0].content?.parts?.push(a);u.usageMetadata&&(o.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw s=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(s)b({provider:m,model:t,input:n,error:s,durationMs:u,streaming:true});else {let a=G({provider:m,model:t,input:n,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:i});if(a){let c=Be(o.candidates);c.length>0&&P(c,a);}}}}function Ue(e,t){return function(r){let o=e(r);return ze(o,t)}}function ze(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="sendMessage"&&typeof s=="function"?Fe(s.bind(n),t):r==="sendMessageStream"&&typeof s=="function"?Ve(s.bind(n),t):s}})}function Fe(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=Date.now()-o,u=ue(i.response),a=G({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=de(i.response);c.length>0&&P(c,a);}return i}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Ve(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=ie(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}function ae(e){return typeof e=="string"?e:e.contents?e.contents:e}function ue(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function de(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Be(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Rt(e,t){return t&&ne(t),Q().disabled?(l("Tracing disabled, returning unwrapped client"),e):oe(e)?(U("gemini"),se(e)):(I("Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK."),e)}
|
|
2
|
+
var ce=Object.defineProperty;var le=(e,t,n)=>t in e?ce(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var K=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var v=(e,t,n)=>le(e,typeof t!="symbol"?t+"":t,n);var W=pe((nt,Ce)=>{Ce.exports={name:"@lelemondev/sdk",version:"0.9.5",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/generative-ai":"^0.24.1","@types/node":"^20.0.0","@vitest/coverage-v8":"^2.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.15",typescript:"^5.9.3",vitest:"^2.0.0"}};});var L=false;function N(e){L=e;}function g(){return L?true:fe("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function l(e,t){g()&&_("debug",e,t);}function q(e,t){g()&&_("info",e,t);}function I(e,t){_("warn",e,t);}function D(e,t,n,r){g()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function M(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function U(e){g()&&console.log(`${p} Wrapped client: provider=${e}`);}function z(e,t){g()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function F(e,t){g()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function V(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function B(e,t,n){g()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function H(e,t){g()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function _(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function fe(e){if(typeof process<"u"&&process.env)return process.env[e]}var ge=10,me=1e3,he=1e4,E=class{constructor(t){v(this,"config");v(this,"queue",[]);v(this,"flushPromise",null);v(this,"flushTimer",null);this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??ge,flushIntervalMs:t.flushIntervalMs??me,requestTimeoutMs:t.requestTimeoutMs??he};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();z(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),F(t.length,Date.now()-n);}catch(r){V(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,s=new AbortController,i=r?JSON.stringify(r):void 0;B(t,o,i?.length??0);let d=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),u=Date.now();try{let a=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:s.signal});if(clearTimeout(d),H(a.status,Date.now()-u),!a.ok){let x=await a.text().catch(()=>"Unknown error");throw new Error(`HTTP ${a.status}: ${x}`)}let c=await a.text();return c?JSON.parse(c):{}}catch(a){throw clearTimeout(d),a instanceof Error&&a.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):a}}};var ye="@lelemondev/sdk",we="nodejs";function be(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function Te(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function ve(){try{if(typeof K<"u")return W().version??"unknown"}catch{}return "unknown"}var w=null;function J(e){if(!w){let n=be(),r=Te();w={"telemetry.sdk.name":ye,"telemetry.sdk.version":ve(),"telemetry.sdk.language":we},n&&(w["process.runtime.name"]=n.name,w["process.runtime.version"]=n.version),r&&(w["os.type"]=r);}let t={...w};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var O={},C=null,$=null,X="https://api.lelemon.dev";function ke(e={}){O=e,e.debug&&N(true),$=J(e.service),q("Initializing SDK",{endpoint:e.endpoint??X,debug:e.debug??false,disabled:e.disabled??false,telemetry:$}),C=Z(e),C.isEnabled()?q("SDK initialized - tracing enabled"):l("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function Q(){return O}function R(){return $}function xe(){return y().isEnabled()}function y(){return C||(C=Z(O)),C}async function Ie(){C&&await C.flush();}function Z(e){let t=e.apiKey??Me("LELEMON_API_KEY");return !t&&!e.disabled&&I("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new E({apiKey:t??"",endpoint:e.endpoint??X,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Me(e){if(typeof process<"u"&&process.env)return process.env[e]}var te={};function ne(e){te=e,l("Global context updated",e);}function k(){return te}function G(e){try{let t=y();if(!t.isEnabled()){l("Transport disabled, skipping trace capture");return}let n=k(),r=f(),o=T(),s=R(),i={provider:e.provider,model:e.model,input:A(e.input),rawResponse:e.rawResponse?S(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags,spanType:e.spanType,name:e.name};return D(e.provider,e.model,e.durationMs,e.status),t.enqueue(i),o}catch(t){M(e.provider,t instanceof Error?t:new Error(String(t)));return}}function b(e){try{let t=y();if(!t.isEnabled()){l("Transport disabled, skipping error capture");return}let n=k(),r=f(),o=R(),s={provider:e.provider,model:e.model,input:A(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:T(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:n.tags};D(e.provider,e.model,e.durationMs,"error"),l("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(s);}catch(t){M(e.provider,t instanceof Error?t:new Error(String(t)));}}function j(e){try{let t=y();if(!t.isEnabled()){l("Transport disabled, skipping span capture");return}let n=k(),r=f(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,i=R(),d={...n.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete d._traceId,delete d._parentSpanId;let u={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:A(e.input),output:S(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:n.sessionId,userId:n.userId,traceId:o??r?.traceId,spanId:T(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:d,tags:n.tags};l(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(u);}catch(t){M("unknown",t instanceof Error?t:new Error(String(t)));}}var ee=1e5,Ee=["api_key","apikey","password","secret","authorization"],Re=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Ge=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"];function Pe(e){let t=e.toLowerCase();return Ge.includes(t)?false:!!(Ee.some(n=>t.includes(n))||Re.some(n=>t.includes(n)))}function A(e){return S(e,0)}function S(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string")return e.length>ee?e.slice(0,ee)+"...[truncated]":e;if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>S(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))Pe(r)?n[r]="[REDACTED]":n[r]=S(o,t+1);return n}return String(e)}var re=new async_hooks.AsyncLocalStorage;function T(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function f(){return re.getStore()}function P(e,t){let n=f();if(n)for(let r of e)n.pendingToolCalls.set(r,t),l(`Registered tool call ${r} \u2192 LLM span ${t}`);}function De(e){let t=f();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function _e(e){let t=f();t&&t.pendingToolCalls.delete(e);}async function $e(e,t){let n=typeof e=="string"?{name:e}:e,r=f(),o=r?.traceId??T(),s=T(),i={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,pendingToolCalls:new Map};return re.run(i,async()=>{let d,u;try{return d=await t(),d}catch(a){throw u=a instanceof Error?a:new Error(String(a)),a}finally{Oe(i,u?void 0:d,u);}})}function Oe(e,t,n){let r=y();if(!r.isEnabled()){l("Transport disabled, skipping root span");return}let o=k(),s=Date.now()-e.startTime,i=n?null:t,d={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:i,inputTokens:0,outputTokens:0,durationMs:s,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:o.sessionId,userId:o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};l(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(d);}function je(e){let t=f();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=De(e.toolCallId);j({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n}}),e.toolCallId&&_e(e.toolCallId);}var m="gemini";function oe(e){if(!e||typeof e!="object")return false;let t=e.constructor?.name;if(t==="GoogleGenerativeAI"||t==="GoogleGenAI")return true;let n=e;return !!(typeof n.getGenerativeModel=="function"||n.models&&typeof n.models.generate=="function")}function se(e){let t=e;return new Proxy(t,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="getGenerativeModel"&&typeof s=="function"?Ae(s.bind(n)):s}})}function Ae(e){return function(n){let r=e(n);return Ke(r,n.model)}}function Ke(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="generateContent"&&typeof s=="function"?Le(s.bind(n),t):r==="generateContentStream"&&typeof s=="function"?Ne(s.bind(n),t):r==="startChat"&&typeof s=="function"?Ue(s.bind(n),t):s}})}function Le(e,t){return async function(r){let o=Date.now(),s=ae(r);try{let i=await e(r),d=Date.now()-o,u=ue(i.response),a=G({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=de(i.response);c.length>0&&P(c,a);}return i}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Ne(e,t){return async function(r){let o=Date.now(),s=ae(r);try{let i=await e(r),d=ie(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}async function*ie(e,t,n,r){let o={candidates:[{content:{parts:[]}}]},s=null,i,d=false;try{for await(let u of e){try{let a=u.text();if(a){d||(d=!0,i=Date.now()-r);let c=o.candidates[0].content?.parts||[],x=c[c.length-1];x?.text!==void 0?x.text+=a:c.push({text:a});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let a of u.candidates[0].content.parts)a.functionCall&&o.candidates[0].content?.parts?.push(a);u.usageMetadata&&(o.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw s=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(s)b({provider:m,model:t,input:n,error:s,durationMs:u,streaming:true});else {let a=G({provider:m,model:t,input:n,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:i});if(a){let c=Be(o.candidates);c.length>0&&P(c,a);}}}}function Ue(e,t){return function(r){let o=e(r);return ze(o,t)}}function ze(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="sendMessage"&&typeof s=="function"?Fe(s.bind(n),t):r==="sendMessageStream"&&typeof s=="function"?Ve(s.bind(n),t):s}})}function Fe(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=Date.now()-o,u=ue(i.response),a=G({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=de(i.response);c.length>0&&P(c,a);}return i}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Ve(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=ie(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw b({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}function ae(e){return typeof e=="string"?e:e.contents?e.contents:e}function ue(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function de(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Be(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Rt(e,t){return t&&ne(t),Q().disabled?(l("Tracing disabled, returning unwrapped client"),e):oe(e)?(U("gemini"),se(e)):(I("Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK."),e)}
|
|
3
3
|
exports.captureSpan=j;exports.flush=Ie;exports.getTraceContext=f;exports.init=ke;exports.isEnabled=xe;exports.observe=Rt;exports.span=je;exports.trace=$e;//# sourceMappingURL=gemini.js.map
|
|
4
4
|
//# sourceMappingURL=gemini.js.map
|
package/dist/gemini.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import {AsyncLocalStorage}from'async_hooks';/* @lelemondev/sdk - LLM Observability */
|
|
2
|
-
var de=Object.defineProperty;var ce=(e,t,n)=>t in e?de(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var le=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var T=(e,t,n)=>ce(e,typeof t!="symbol"?t+"":t,n);var H=le((Ze,he)=>{he.exports={name:"@lelemondev/sdk",version:"0.9.3",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/generative-ai":"^0.24.1","@types/node":"^20.0.0","@vitest/coverage-v8":"^2.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.15",typescript:"^5.9.3",vitest:"^2.0.0"}};});var K=false;function L(e){K=e;}function g(){return K?true:pe("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function l(e,t){g()&&D("debug",e,t);}function P(e,t){g()&&D("info",e,t);}function x(e,t){D("warn",e,t);}function q(e,t,n,r){g()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function I(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function N(e){g()&&console.log(`${p} Wrapped client: provider=${e}`);}function U(e,t){g()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function z(e,t){g()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function F(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function V(e,t,n){g()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function B(e,t){g()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function D(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function pe(e){if(typeof process<"u"&&process.env)return process.env[e]}var fe=10,ge=1e3,me=1e4,M=class{constructor(t){T(this,"config");T(this,"queue",[]);T(this,"flushPromise",null);T(this,"flushTimer",null);this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??fe,flushIntervalMs:t.flushIntervalMs??ge,requestTimeoutMs:t.requestTimeoutMs??me};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();U(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),z(t.length,Date.now()-n);}catch(r){F(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,s=new AbortController,i=r?JSON.stringify(r):void 0;V(t,o,i?.length??0);let d=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),u=Date.now();try{let a=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:s.signal});if(clearTimeout(d),B(a.status,Date.now()-u),!a.ok){let k=await a.text().catch(()=>"Unknown error");throw new Error(`HTTP ${a.status}: ${k}`)}let c=await a.text();return c?JSON.parse(c):{}}catch(a){throw clearTimeout(d),a instanceof Error&&a.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):a}}};var Ce="@lelemondev/sdk",ye="nodejs";function we(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function be(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function Te(){try{if(typeof A<"u")return H().version??"unknown"}catch{}return "unknown"}var y=null;function Y(e){if(!y){let n=we(),r=be();y={"telemetry.sdk.name":Ce,"telemetry.sdk.version":Te(),"telemetry.sdk.language":ye},n&&(y["process.runtime.name"]=n.name,y["process.runtime.version"]=n.version),r&&(y["os.type"]=r);}let t={...y};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var $={},h=null,_=null,J="https://www.lelemon.dev";function Se(e={}){$=e,e.debug&&L(true),_=Y(e.service),P("Initializing SDK",{endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??false,telemetry:_}),h=Q(e),h.isEnabled()?P("SDK initialized - tracing enabled"):l("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function X(){return $}function E(){return _}function ke(){return C().isEnabled()}function C(){return h||(h=Q($)),h}async function xe(){h&&await h.flush();}function Q(e){let t=e.apiKey??Ie("LELEMON_API_KEY");return !t&&!e.disabled&&x("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new M({apiKey:t??"",endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Ie(e){if(typeof process<"u"&&process.env)return process.env[e]}var ee={};function te(e){ee=e,l("Global context updated",e);}function S(){return ee}function R(e){try{let t=C();if(!t.isEnabled()){l("Transport disabled, skipping trace capture");return}let n=S(),r=f(),o=b(),s=E(),i={provider:e.provider,model:e.model,input:j(e.input),rawResponse:e.rawResponse?v(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags,spanType:e.spanType,name:e.name};return q(e.provider,e.model,e.durationMs,e.status),t.enqueue(i),o}catch(t){I(e.provider,t instanceof Error?t:new Error(String(t)));return}}function w(e){try{let t=C();if(!t.isEnabled()){l("Transport disabled, skipping error capture");return}let n=S(),r=f(),o=E(),s={provider:e.provider,model:e.model,input:j(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:b(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:n.tags};q(e.provider,e.model,e.durationMs,"error"),l("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(s);}catch(t){I(e.provider,t instanceof Error?t:new Error(String(t)));}}function O(e){try{let t=C();if(!t.isEnabled()){l("Transport disabled, skipping span capture");return}let n=S(),r=f(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,i=E(),d={...n.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete d._traceId,delete d._parentSpanId;let u={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:j(e.input),output:v(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:n.sessionId,userId:n.userId,traceId:o??r?.traceId,spanId:b(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:d,tags:n.tags};l(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(u);}catch(t){I("unknown",t instanceof Error?t:new Error(String(t)));}}var Z=1e5,Me=["api_key","apikey","password","secret","authorization"],Ee=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Re=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"];function Ge(e){let t=e.toLowerCase();return Re.includes(t)?false:!!(Me.some(n=>t.includes(n))||Ee.some(n=>t.includes(n)))}function j(e){return v(e,0)}function v(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string")return e.length>Z?e.slice(0,Z)+"...[truncated]":e;if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>v(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))Ge(r)?n[r]="[REDACTED]":n[r]=v(o,t+1);return n}return String(e)}var ne=new AsyncLocalStorage;function b(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function f(){return ne.getStore()}function G(e,t){let n=f();if(n)for(let r of e)n.pendingToolCalls.set(r,t),l(`Registered tool call ${r} \u2192 LLM span ${t}`);}function qe(e){let t=f();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function De(e){let t=f();t&&t.pendingToolCalls.delete(e);}async function _e(e,t){let n=typeof e=="string"?{name:e}:e,r=f(),o=r?.traceId??b(),s=b(),i={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,pendingToolCalls:new Map};return ne.run(i,async()=>{let d,u;try{return d=await t(),d}catch(a){throw u=a instanceof Error?a:new Error(String(a)),a}finally{$e(i,u?void 0:d,u);}})}function $e(e,t,n){let r=C();if(!r.isEnabled()){l("Transport disabled, skipping root span");return}let o=S(),s=Date.now()-e.startTime,i=n?null:t,d={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:i,inputTokens:0,outputTokens:0,durationMs:s,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:o.sessionId,userId:o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};l(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(d);}function Oe(e){let t=f();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=qe(e.toolCallId);O({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n}}),e.toolCallId&&De(e.toolCallId);}var m="gemini";function re(e){if(!e||typeof e!="object")return false;let t=e.constructor?.name;if(t==="GoogleGenerativeAI"||t==="GoogleGenAI")return true;let n=e;return !!(typeof n.getGenerativeModel=="function"||n.models&&typeof n.models.generate=="function")}function oe(e){let t=e;return new Proxy(t,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="getGenerativeModel"&&typeof s=="function"?je(s.bind(n)):s}})}function je(e){return function(n){let r=e(n);return Ae(r,n.model)}}function Ae(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="generateContent"&&typeof s=="function"?Ke(s.bind(n),t):r==="generateContentStream"&&typeof s=="function"?Le(s.bind(n),t):r==="startChat"&&typeof s=="function"?Ne(s.bind(n),t):s}})}function Ke(e,t){return async function(r){let o=Date.now(),s=ie(r);try{let i=await e(r),d=Date.now()-o,u=ae(i.response),a=R({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=ue(i.response);c.length>0&&G(c,a);}return i}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Le(e,t){return async function(r){let o=Date.now(),s=ie(r);try{let i=await e(r),d=se(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}async function*se(e,t,n,r){let o={candidates:[{content:{parts:[]}}]},s=null,i,d=false;try{for await(let u of e){try{let a=u.text();if(a){d||(d=!0,i=Date.now()-r);let c=o.candidates[0].content?.parts||[],k=c[c.length-1];k?.text!==void 0?k.text+=a:c.push({text:a});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let a of u.candidates[0].content.parts)a.functionCall&&o.candidates[0].content?.parts?.push(a);u.usageMetadata&&(o.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw s=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(s)w({provider:m,model:t,input:n,error:s,durationMs:u,streaming:true});else {let a=R({provider:m,model:t,input:n,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:i});if(a){let c=Ve(o.candidates);c.length>0&&G(c,a);}}}}function Ne(e,t){return function(r){let o=e(r);return Ue(o,t)}}function Ue(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="sendMessage"&&typeof s=="function"?ze(s.bind(n),t):r==="sendMessageStream"&&typeof s=="function"?Fe(s.bind(n),t):s}})}function ze(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=Date.now()-o,u=ae(i.response),a=R({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=ue(i.response);c.length>0&&G(c,a);}return i}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Fe(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=se(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}function ie(e){return typeof e=="string"?e:e.contents?e.contents:e}function ae(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function ue(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Ve(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Tt(e,t){return t&&te(t),X().disabled?(l("Tracing disabled, returning unwrapped client"),e):re(e)?(N("gemini"),oe(e)):(x("Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK."),e)}
|
|
2
|
+
var de=Object.defineProperty;var ce=(e,t,n)=>t in e?de(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var le=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var T=(e,t,n)=>ce(e,typeof t!="symbol"?t+"":t,n);var H=le((Ze,he)=>{he.exports={name:"@lelemondev/sdk",version:"0.9.5",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/generative-ai":"^0.24.1","@types/node":"^20.0.0","@vitest/coverage-v8":"^2.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.15",typescript:"^5.9.3",vitest:"^2.0.0"}};});var K=false;function L(e){K=e;}function g(){return K?true:pe("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function l(e,t){g()&&D("debug",e,t);}function P(e,t){g()&&D("info",e,t);}function x(e,t){D("warn",e,t);}function q(e,t,n,r){g()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function I(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function N(e){g()&&console.log(`${p} Wrapped client: provider=${e}`);}function U(e,t){g()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function z(e,t){g()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function F(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function V(e,t,n){g()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function B(e,t){g()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function D(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function pe(e){if(typeof process<"u"&&process.env)return process.env[e]}var fe=10,ge=1e3,me=1e4,M=class{constructor(t){T(this,"config");T(this,"queue",[]);T(this,"flushPromise",null);T(this,"flushTimer",null);this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??fe,flushIntervalMs:t.flushIntervalMs??ge,requestTimeoutMs:t.requestTimeoutMs??me};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();U(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),z(t.length,Date.now()-n);}catch(r){F(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,s=new AbortController,i=r?JSON.stringify(r):void 0;V(t,o,i?.length??0);let d=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),u=Date.now();try{let a=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:s.signal});if(clearTimeout(d),B(a.status,Date.now()-u),!a.ok){let k=await a.text().catch(()=>"Unknown error");throw new Error(`HTTP ${a.status}: ${k}`)}let c=await a.text();return c?JSON.parse(c):{}}catch(a){throw clearTimeout(d),a instanceof Error&&a.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):a}}};var Ce="@lelemondev/sdk",ye="nodejs";function we(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function be(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function Te(){try{if(typeof A<"u")return H().version??"unknown"}catch{}return "unknown"}var y=null;function Y(e){if(!y){let n=we(),r=be();y={"telemetry.sdk.name":Ce,"telemetry.sdk.version":Te(),"telemetry.sdk.language":ye},n&&(y["process.runtime.name"]=n.name,y["process.runtime.version"]=n.version),r&&(y["os.type"]=r);}let t={...y};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var $={},h=null,_=null,J="https://api.lelemon.dev";function Se(e={}){$=e,e.debug&&L(true),_=Y(e.service),P("Initializing SDK",{endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??false,telemetry:_}),h=Q(e),h.isEnabled()?P("SDK initialized - tracing enabled"):l("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function X(){return $}function E(){return _}function ke(){return C().isEnabled()}function C(){return h||(h=Q($)),h}async function xe(){h&&await h.flush();}function Q(e){let t=e.apiKey??Ie("LELEMON_API_KEY");return !t&&!e.disabled&&x("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new M({apiKey:t??"",endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Ie(e){if(typeof process<"u"&&process.env)return process.env[e]}var ee={};function te(e){ee=e,l("Global context updated",e);}function S(){return ee}function R(e){try{let t=C();if(!t.isEnabled()){l("Transport disabled, skipping trace capture");return}let n=S(),r=f(),o=b(),s=E(),i={provider:e.provider,model:e.model,input:j(e.input),rawResponse:e.rawResponse?v(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags,spanType:e.spanType,name:e.name};return q(e.provider,e.model,e.durationMs,e.status),t.enqueue(i),o}catch(t){I(e.provider,t instanceof Error?t:new Error(String(t)));return}}function w(e){try{let t=C();if(!t.isEnabled()){l("Transport disabled, skipping error capture");return}let n=S(),r=f(),o=E(),s={provider:e.provider,model:e.model,input:j(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:b(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:n.tags};q(e.provider,e.model,e.durationMs,"error"),l("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(s);}catch(t){I(e.provider,t instanceof Error?t:new Error(String(t)));}}function O(e){try{let t=C();if(!t.isEnabled()){l("Transport disabled, skipping span capture");return}let n=S(),r=f(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,i=E(),d={...n.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete d._traceId,delete d._parentSpanId;let u={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:j(e.input),output:v(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:n.sessionId,userId:n.userId,traceId:o??r?.traceId,spanId:b(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:d,tags:n.tags};l(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(u);}catch(t){I("unknown",t instanceof Error?t:new Error(String(t)));}}var Z=1e5,Me=["api_key","apikey","password","secret","authorization"],Ee=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Re=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"];function Ge(e){let t=e.toLowerCase();return Re.includes(t)?false:!!(Me.some(n=>t.includes(n))||Ee.some(n=>t.includes(n)))}function j(e){return v(e,0)}function v(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string")return e.length>Z?e.slice(0,Z)+"...[truncated]":e;if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>v(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))Ge(r)?n[r]="[REDACTED]":n[r]=v(o,t+1);return n}return String(e)}var ne=new AsyncLocalStorage;function b(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function f(){return ne.getStore()}function G(e,t){let n=f();if(n)for(let r of e)n.pendingToolCalls.set(r,t),l(`Registered tool call ${r} \u2192 LLM span ${t}`);}function qe(e){let t=f();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function De(e){let t=f();t&&t.pendingToolCalls.delete(e);}async function _e(e,t){let n=typeof e=="string"?{name:e}:e,r=f(),o=r?.traceId??b(),s=b(),i={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,pendingToolCalls:new Map};return ne.run(i,async()=>{let d,u;try{return d=await t(),d}catch(a){throw u=a instanceof Error?a:new Error(String(a)),a}finally{$e(i,u?void 0:d,u);}})}function $e(e,t,n){let r=C();if(!r.isEnabled()){l("Transport disabled, skipping root span");return}let o=S(),s=Date.now()-e.startTime,i=n?null:t,d={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:i,inputTokens:0,outputTokens:0,durationMs:s,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:o.sessionId,userId:o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};l(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(d);}function Oe(e){let t=f();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=qe(e.toolCallId);O({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n}}),e.toolCallId&&De(e.toolCallId);}var m="gemini";function re(e){if(!e||typeof e!="object")return false;let t=e.constructor?.name;if(t==="GoogleGenerativeAI"||t==="GoogleGenAI")return true;let n=e;return !!(typeof n.getGenerativeModel=="function"||n.models&&typeof n.models.generate=="function")}function oe(e){let t=e;return new Proxy(t,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="getGenerativeModel"&&typeof s=="function"?je(s.bind(n)):s}})}function je(e){return function(n){let r=e(n);return Ae(r,n.model)}}function Ae(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="generateContent"&&typeof s=="function"?Ke(s.bind(n),t):r==="generateContentStream"&&typeof s=="function"?Le(s.bind(n),t):r==="startChat"&&typeof s=="function"?Ne(s.bind(n),t):s}})}function Ke(e,t){return async function(r){let o=Date.now(),s=ie(r);try{let i=await e(r),d=Date.now()-o,u=ae(i.response),a=R({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=ue(i.response);c.length>0&&G(c,a);}return i}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Le(e,t){return async function(r){let o=Date.now(),s=ie(r);try{let i=await e(r),d=se(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}async function*se(e,t,n,r){let o={candidates:[{content:{parts:[]}}]},s=null,i,d=false;try{for await(let u of e){try{let a=u.text();if(a){d||(d=!0,i=Date.now()-r);let c=o.candidates[0].content?.parts||[],k=c[c.length-1];k?.text!==void 0?k.text+=a:c.push({text:a});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let a of u.candidates[0].content.parts)a.functionCall&&o.candidates[0].content?.parts?.push(a);u.usageMetadata&&(o.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw s=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(s)w({provider:m,model:t,input:n,error:s,durationMs:u,streaming:true});else {let a=R({provider:m,model:t,input:n,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:i});if(a){let c=Ve(o.candidates);c.length>0&&G(c,a);}}}}function Ne(e,t){return function(r){let o=e(r);return Ue(o,t)}}function Ue(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="sendMessage"&&typeof s=="function"?ze(s.bind(n),t):r==="sendMessageStream"&&typeof s=="function"?Fe(s.bind(n),t):s}})}function ze(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=Date.now()-o,u=ae(i.response),a=R({provider:m,model:t,input:s,rawResponse:u,durationMs:d,status:"success",streaming:!1});if(a){let c=ue(i.response);c.length>0&&G(c,a);}return i}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:false}),i}}}function Fe(e,t){return async function(r){let o=Date.now(),s=r;try{let i=await e(r),d=se(i.stream,t,s,o);return {...i,stream:d}}catch(i){throw w({provider:m,model:t,input:s,error:i instanceof Error?i:new Error(String(i)),durationMs:Date.now()-o,streaming:true}),i}}}function ie(e){return typeof e=="string"?e:e.contents?e.contents:e}function ae(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function ue(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Ve(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Tt(e,t){return t&&te(t),X().disabled?(l("Tracing disabled, returning unwrapped client"),e):re(e)?(N("gemini"),oe(e)):(x("Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK."),e)}
|
|
3
3
|
export{O as captureSpan,xe as flush,f as getTraceContext,Se as init,ke as isEnabled,Tt as observe,Oe as span,_e as trace};//# sourceMappingURL=gemini.mjs.map
|
|
4
4
|
//# sourceMappingURL=gemini.mjs.map
|