@lelemon-ai/trace 0.0.0-stage → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1183 -2
- package/dist/anthropic.d.mts +25 -0
- package/dist/anthropic.d.ts +25 -0
- package/dist/anthropic.js +4 -0
- package/dist/anthropic.mjs +4 -0
- package/dist/bedrock.d.mts +25 -0
- package/dist/bedrock.d.ts +25 -0
- package/dist/bedrock.js +4 -0
- package/dist/bedrock.mjs +4 -0
- package/dist/capture-CC6pIfa4.d.mts +354 -0
- package/dist/capture-CC6pIfa4.d.ts +354 -0
- package/dist/express-BrfMWEVl.d.mts +67 -0
- package/dist/express-BrfMWEVl.d.ts +67 -0
- package/dist/express.d.mts +1 -0
- package/dist/express.d.ts +1 -0
- package/dist/express.js +3 -0
- package/dist/express.mjs +3 -0
- package/dist/gemini.d.mts +28 -0
- package/dist/gemini.d.ts +28 -0
- package/dist/gemini.js +4 -0
- package/dist/gemini.mjs +4 -0
- package/dist/google-genai.d.mts +31 -0
- package/dist/google-genai.d.ts +31 -0
- package/dist/google-genai.js +4 -0
- package/dist/google-genai.mjs +4 -0
- package/dist/hono-MTDbviM5.d.mts +80 -0
- package/dist/hono-MTDbviM5.d.ts +80 -0
- package/dist/hono.d.mts +1 -0
- package/dist/hono.d.ts +1 -0
- package/dist/hono.js +3 -0
- package/dist/hono.mjs +3 -0
- package/dist/index.d.mts +40 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +4 -0
- package/dist/integrations.d.mts +4 -0
- package/dist/integrations.d.ts +4 -0
- package/dist/integrations.js +3 -0
- package/dist/integrations.mjs +3 -0
- package/dist/lambda-Drx54kXf.d.mts +79 -0
- package/dist/lambda-Drx54kXf.d.ts +79 -0
- package/dist/lambda.d.mts +1 -0
- package/dist/lambda.d.ts +1 -0
- package/dist/lambda.js +3 -0
- package/dist/lambda.mjs +3 -0
- package/dist/next-DONwf0f5.d.mts +100 -0
- package/dist/next-DONwf0f5.d.ts +100 -0
- package/dist/next.d.mts +1 -0
- package/dist/next.d.ts +1 -0
- package/dist/next.js +3 -0
- package/dist/next.mjs +3 -0
- package/dist/openai.d.mts +25 -0
- package/dist/openai.d.ts +25 -0
- package/dist/openai.js +4 -0
- package/dist/openai.mjs +4 -0
- package/dist/openrouter.d.mts +33 -0
- package/dist/openrouter.d.ts +33 -0
- package/dist/openrouter.js +4 -0
- package/dist/openrouter.mjs +4 -0
- package/package.json +173 -4
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express Integration
|
|
3
|
+
*
|
|
4
|
+
* Middleware that automatically flushes traces when response finishes.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* import express from 'express';
|
|
8
|
+
* import { createMiddleware } from '@lelemon-ai/trace/express';
|
|
9
|
+
*
|
|
10
|
+
* const app = express();
|
|
11
|
+
* app.use(createMiddleware());
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Minimal Express request type (avoids requiring express as dependency)
|
|
15
|
+
*/
|
|
16
|
+
interface ExpressRequest {
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Minimal Express response type (avoids requiring express as dependency)
|
|
21
|
+
*/
|
|
22
|
+
interface ExpressResponse {
|
|
23
|
+
on(event: 'finish' | 'close' | 'error', listener: () => void): this;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Express next function type
|
|
28
|
+
*/
|
|
29
|
+
type ExpressNextFunction = (error?: unknown) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Express middleware function type
|
|
32
|
+
*
|
|
33
|
+
* @param req - Express request object
|
|
34
|
+
* @param res - Express response object
|
|
35
|
+
* @param next - Next function to pass control
|
|
36
|
+
*/
|
|
37
|
+
type ExpressMiddleware = (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void;
|
|
38
|
+
/**
|
|
39
|
+
* Create Express middleware for automatic trace flushing
|
|
40
|
+
*
|
|
41
|
+
* Flushes traces when the response finishes (after res.send/res.json).
|
|
42
|
+
* This is fire-and-forget and doesn't block the response.
|
|
43
|
+
*
|
|
44
|
+
* @returns Express middleware function
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* // Global middleware
|
|
48
|
+
* app.use(createMiddleware());
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* // Per-route middleware
|
|
52
|
+
* app.post('/chat', createMiddleware(), async (req, res) => {
|
|
53
|
+
* res.json({ ok: true });
|
|
54
|
+
* });
|
|
55
|
+
*/
|
|
56
|
+
declare function createMiddleware(): ExpressMiddleware;
|
|
57
|
+
|
|
58
|
+
type express_ExpressMiddleware = ExpressMiddleware;
|
|
59
|
+
type express_ExpressNextFunction = ExpressNextFunction;
|
|
60
|
+
type express_ExpressRequest = ExpressRequest;
|
|
61
|
+
type express_ExpressResponse = ExpressResponse;
|
|
62
|
+
declare const express_createMiddleware: typeof createMiddleware;
|
|
63
|
+
declare namespace express {
|
|
64
|
+
export { type express_ExpressMiddleware as ExpressMiddleware, type express_ExpressNextFunction as ExpressNextFunction, type express_ExpressRequest as ExpressRequest, type express_ExpressResponse as ExpressResponse, express_createMiddleware as createMiddleware };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export { type ExpressRequest as E, type ExpressResponse as a, type ExpressNextFunction as b, type ExpressMiddleware as c, createMiddleware as d, express as e };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express Integration
|
|
3
|
+
*
|
|
4
|
+
* Middleware that automatically flushes traces when response finishes.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* import express from 'express';
|
|
8
|
+
* import { createMiddleware } from '@lelemon-ai/trace/express';
|
|
9
|
+
*
|
|
10
|
+
* const app = express();
|
|
11
|
+
* app.use(createMiddleware());
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Minimal Express request type (avoids requiring express as dependency)
|
|
15
|
+
*/
|
|
16
|
+
interface ExpressRequest {
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Minimal Express response type (avoids requiring express as dependency)
|
|
21
|
+
*/
|
|
22
|
+
interface ExpressResponse {
|
|
23
|
+
on(event: 'finish' | 'close' | 'error', listener: () => void): this;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Express next function type
|
|
28
|
+
*/
|
|
29
|
+
type ExpressNextFunction = (error?: unknown) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Express middleware function type
|
|
32
|
+
*
|
|
33
|
+
* @param req - Express request object
|
|
34
|
+
* @param res - Express response object
|
|
35
|
+
* @param next - Next function to pass control
|
|
36
|
+
*/
|
|
37
|
+
type ExpressMiddleware = (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void;
|
|
38
|
+
/**
|
|
39
|
+
* Create Express middleware for automatic trace flushing
|
|
40
|
+
*
|
|
41
|
+
* Flushes traces when the response finishes (after res.send/res.json).
|
|
42
|
+
* This is fire-and-forget and doesn't block the response.
|
|
43
|
+
*
|
|
44
|
+
* @returns Express middleware function
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* // Global middleware
|
|
48
|
+
* app.use(createMiddleware());
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* // Per-route middleware
|
|
52
|
+
* app.post('/chat', createMiddleware(), async (req, res) => {
|
|
53
|
+
* res.json({ ok: true });
|
|
54
|
+
* });
|
|
55
|
+
*/
|
|
56
|
+
declare function createMiddleware(): ExpressMiddleware;
|
|
57
|
+
|
|
58
|
+
type express_ExpressMiddleware = ExpressMiddleware;
|
|
59
|
+
type express_ExpressNextFunction = ExpressNextFunction;
|
|
60
|
+
type express_ExpressRequest = ExpressRequest;
|
|
61
|
+
type express_ExpressResponse = ExpressResponse;
|
|
62
|
+
declare const express_createMiddleware: typeof createMiddleware;
|
|
63
|
+
declare namespace express {
|
|
64
|
+
export { type express_ExpressMiddleware as ExpressMiddleware, type express_ExpressNextFunction as ExpressNextFunction, type express_ExpressRequest as ExpressRequest, type express_ExpressResponse as ExpressResponse, express_createMiddleware as createMiddleware };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export { type ExpressRequest as E, type ExpressResponse as a, type ExpressNextFunction as b, type ExpressMiddleware as c, createMiddleware as d, express as e };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { c as ExpressMiddleware, b as ExpressNextFunction, E as ExpressRequest, a as ExpressResponse, d as createMiddleware } from './express-BrfMWEVl.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { c as ExpressMiddleware, b as ExpressNextFunction, E as ExpressRequest, a as ExpressResponse, d as createMiddleware } from './express-BrfMWEVl.js';
|
package/dist/express.js
ADDED
package/dist/express.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.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-CC6pIfa4.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Google Gemini Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/gemini';
|
|
10
|
+
* import { GoogleGenerativeAI } from '@google/generative-ai';
|
|
11
|
+
*
|
|
12
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
13
|
+
* const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
|
|
14
|
+
* const model = observe(genAI.getGenerativeModel({ model: 'gemini-pro' }));
|
|
15
|
+
*
|
|
16
|
+
* await model.generateContent('Hello!');
|
|
17
|
+
* await flush();
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Wrap a Gemini model with automatic tracing
|
|
23
|
+
*
|
|
24
|
+
* Supports both @google/generative-ai (old) and @google/genai (new) SDKs.
|
|
25
|
+
*/
|
|
26
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
27
|
+
|
|
28
|
+
export { ObserveOptions, observe };
|
package/dist/gemini.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.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-CC6pIfa4.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Google Gemini Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/gemini';
|
|
10
|
+
* import { GoogleGenerativeAI } from '@google/generative-ai';
|
|
11
|
+
*
|
|
12
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
13
|
+
* const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
|
|
14
|
+
* const model = observe(genAI.getGenerativeModel({ model: 'gemini-pro' }));
|
|
15
|
+
*
|
|
16
|
+
* await model.generateContent('Hello!');
|
|
17
|
+
* await flush();
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Wrap a Gemini model with automatic tracing
|
|
23
|
+
*
|
|
24
|
+
* Supports both @google/generative-ai (old) and @google/genai (new) SDKs.
|
|
25
|
+
*/
|
|
26
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
27
|
+
|
|
28
|
+
export { ObserveOptions, observe };
|
package/dist/gemini.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var async_hooks=require('async_hooks');/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var U=(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 we=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Z=we((St,ke)=>{ke.exports={name:"@lelemon-ai/trace",version:"0.12.0",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/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/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"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.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"],"google-genai":["./dist/google-genai.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:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var z=false;function F(e){z=e;}function h(){return z?true:be("LELEMON_DEBUG")==="true"}var g="[Lelemon]";function p(e,t){h()&&A("debug",e,t);}function D(e,t){h()&&A("info",e,t);}function E(e,t){A("warn",e,t);}function _(e,t,n,r){h()&&console.log(`${g} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function x(e,t){console.error(`${g} Failed to capture trace: provider=${e} error=${t.message}`);}function q(e){h()&&console.log(`${g} Wrapped client: provider=${e}`);}function V(e,t){h()&&console.log(`${g} Sending batch: count=${e} endpoint=${t}`);}function B(e,t){h()&&console.log(`${g} Batch sent successfully: count=${e} duration=${t}ms`);}function H(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${g} Batch send failed: count=${e} error=${n}`);}function W(e,t,n){h()&&console.log(`${g} Request: ${e} ${t} (${n} bytes)`);}function Y(e,t){h()&&console.log(`${g} Response: status=${e} duration=${t}ms`);}function A(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${g} ${t}`,n):r(`${g} ${t}`);}function be(e){if(typeof process<"u"&&process.env)return process.env[e]}var Se=10,ve=1e3,Te=1e4,G=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(t){this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??Se,flushIntervalMs:t.flushIntervalMs??ve,requestTimeoutMs:t.requestTimeoutMs??Te};}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();V(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),B(t.length,Date.now()-n);}catch(r){H(t.length,r);}}async request(t,n,r){let s=`${this.config.endpoint}${n}`,i=new AbortController,a=r?JSON.stringify(r):void 0;W(t,s,a?.length??0);let o=setTimeout(()=>{i.abort();},this.config.requestTimeoutMs),l=Date.now();try{let u=await fetch(s,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:i.signal});if(clearTimeout(o),Y(u.status,Date.now()-l),!u.ok){let c=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${c}`)}let d=await u.text();return d?JSON.parse(d):{}}catch(u){throw clearTimeout(o),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var Ie="@lelemon-ai/trace",Me="nodejs";function Re(){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 Ee(){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 xe(){try{if(typeof U<"u")return Z().version??"unknown"}catch{}return "unknown"}var k=null;function J(e){if(!k){let n=Re(),r=Ee();k={"telemetry.sdk.name":Ie,"telemetry.sdk.version":xe(),"telemetry.sdk.language":Me},n&&(k["process.runtime.name"]=n.name,k["process.runtime.version"]=n.version),r&&(k["os.type"]=r);}let t={...k};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var j={},v=null,$=null,Q="https://api.lelemon.dev";function Pe(e={}){j=e,e.debug&&F(true),$=J(e.service),D("Initializing SDK",{endpoint:e.endpoint??Q,debug:e.debug??false,disabled:e.disabled??false,telemetry:$}),v=ee(e),v.isEnabled()?D("SDK initialized - tracing enabled"):p("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function P(){return j}function O(){return $}function Oe(){return T().isEnabled()}function T(){return v||(v=ee(j)),v}async function De(){v&&await v.flush();}function ee(e){let t=e.apiKey??_e("LELEMON_API_KEY");return !t&&!e.disabled&&E("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new G({apiKey:t??"",endpoint:e.endpoint??Q,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function _e(e){if(typeof process<"u"&&process.env)return process.env[e]}function y(e){try{let t=T();if(!t.isEnabled()){p("Transport disabled, skipping trace capture");return}let n=e.context??{},r=m(),s=I(),i=O(),a={provider:e.provider,model:e.model,input:K(e.input),rawResponse:e.rawResponse?R(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:s,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...i?{_telemetry:i}:{}},tags:n.tags??r?.tags,spanType:e.spanType,name:e.name};return _(e.provider,e.model,e.durationMs,e.status),t.enqueue(a),s}catch(t){x(e.provider,t instanceof Error?t:new Error(String(t)));return}}function f(e){try{let t=T();if(!t.isEnabled()){p("Transport disabled, skipping error capture");return}let n=e.context??{},r=m(),s=O(),i={provider:e.provider,model:e.model,input:K(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:I(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags??r?.tags};_(e.provider,e.model,e.durationMs,"error"),p("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(i);}catch(t){x(e.provider,t instanceof Error?t:new Error(String(t)));}}function N(e){try{let t=T();if(!t.isEnabled()){p("Transport disabled, skipping span capture");return}let n=e.context??{},r=m(),s=e.metadata?._traceId,i=e.metadata?._parentSpanId,a=O(),o={...n.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete o._traceId,delete o._parentSpanId;let l={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:K(e.input),output:R(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:s??r?.traceId,spanId:I(),parentSpanId:i??r?.currentSpanId,toolCallId:e.toolCallId,metadata:o,tags:n.tags??r?.tags};p(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(l);}catch(t){x("unknown",t instanceof Error?t:new Error(String(t)));}}var te=1e5,qe=["api_key","apikey","password","secret","authorization"],Ae=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],$e=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],ne={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function re(){return P().redaction??{}}function je(e){let t=e.toLowerCase();return $e.includes(t)?false:!!(qe.some(r=>t.includes(r))||Ae.some(r=>t.includes(r))||(re().keys??[]).some(r=>t.includes(r.toLowerCase())))}function Ne(e){let t=re(),n=e;for(let r of t.patterns??[])r.lastIndex=0,n=n.replace(r,"[REDACTED]");return t.emails&&(n=n.replace(ne.emails,"[EMAIL]")),t.phones&&(n=n.replace(ne.phones,"[PHONE]")),n}function K(e){return R(e,0)}function R(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let n=Ne(e);return n.length>te&&(n=n.slice(0,te)+"...[truncated]"),n}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>R(n,t+1));if(typeof e=="object"){let n={};for(let[r,s]of Object.entries(e))je(r)?n[r]="[REDACTED]":n[r]=R(s,t+1);return n}return String(e)}var L=Symbol.for("@lelemondev/sdk:traceStorage");function Le(){let e=globalThis;return e[L]||(e[L]=new async_hooks.AsyncLocalStorage),e[L]}var se=Le();function I(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function m(){return se.getStore()}function w(e,t){let n=m();if(n)for(let r of e)n.pendingToolCalls.set(r,t),p(`Registered tool call ${r} \u2192 LLM span ${t}`);}function Ue(e){let t=m();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function ze(e){let t=m();t&&t.pendingToolCalls.delete(e);}async function Fe(e,t){let n=typeof e=="string"?{name:e}:e,r=m(),s=r?.traceId??I(),i=I(),a={traceId:s,rootSpanId:i,currentSpanId:i,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,outputKey:n.outputKey,outputTransform:n.outputTransform,sessionId:n.sessionId,userId:n.userId,style:n.style,pendingToolCalls:new Map};return se.run(a,async()=>{let o,l;try{return o=await t(),o}catch(u){throw l=u instanceof Error?u:new Error(String(u)),u}finally{He(a,l?void 0:o,l);}})}var Ve=["text","content","message","output","response","result","answer"];function Be(e,t,n){if(n)try{return n(e)}catch{return e}if(t===false)return e;if(typeof t=="string"&&e&&typeof e=="object"){let s=e;return t in s?s[t]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let s of Ve)if(s in r&&typeof r[s]=="string")return r[s];return e}function He(e,t,n){let r=T();if(!r.isEnabled()){p("Transport disabled, skipping root span");return}let s=Date.now()-e.startTime,i=n?null:Be(t,e.outputKey,e.outputTransform),a={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:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};p(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(a);}function We(e){let t=m();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=Ue(e.toolCallId);N({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.style?{_style:e.style}:{}}}),e.toolCallId&&ze(e.toolCallId);}var b="gemini";function oe(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GoogleGenAI")return true;let n=e;return !!(n.models&&typeof n.models=="object"&&typeof n.models.generateContent=="function"&&n.chats&&typeof n.chats=="object")}function ae(e,t){let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="models"&&a&&typeof a=="object"?Ye(a,t):s==="chats"&&a&&typeof a=="object"?Je(a,t):a}})}function Ye(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="generateContent"&&typeof i=="function"?Ze(i.bind(n),t):r==="generateContentStream"&&typeof i=="function"?Xe(i.bind(n),t):i}})}function Ze(e,t){return async function(r){let s=Date.now(),i=r.model,a=ue(r);try{let o=await e(r),l=Date.now()-s,u=de(o),d=y({provider:b,model:i,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:t});if(d){let c=ce(o);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:b,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:false,context:t}),o}}}function Xe(e,t){return async function(r){let s=Date.now(),i=r.model,a=ue(r);try{let o=await e(r);return ie(o,i,a,s,t)}catch(o){throw f({provider:b,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:true,context:t}),o}}}async function*ie(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){let d=u.text;if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],M=c[c.length-1];M?.text!==void 0?M.text+=d:c.push({text:d});}if(u.candidates?.[0]?.content?.parts)for(let c of u.candidates[0].content.parts)c.functionCall&&i.candidates[0].content?.parts?.push(c);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:b,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=y({provider:b,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=rt(i.candidates);c.length>0&&w(c,d);}}}}function Je(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="create"&&typeof i=="function"?Qe(i.bind(n),t):i}})}function Qe(e,t){return function(r){let s=e(r);return et(s,r.model,t)}}function et(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?tt(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?nt(a.bind(r),t,n):a}})}function tt(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s),l=Date.now()-i,u=de(o),d=y({provider:b,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=ce(o);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function nt(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s);return ie(o,t,a,i,n)}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function ue(e){return e.contents}function de(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata,modelVersion:e.modelVersion}}function ce(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function rt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}var S="gemini";function le(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let n=e;return typeof n.generateContent=="function"&&typeof n.generateContentStream=="function"&&typeof n.model=="string"}function pe(e){return !e||typeof e!="object"?false:!!(e.constructor?.name==="GoogleGenerativeAI"||typeof e.getGenerativeModel=="function"||le(e))}function fe(e,t){if(le(e)){let r=e;return ge(r,r.model,t)}let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="getGenerativeModel"&&typeof a=="function"?ot(a.bind(r),t):a}})}function ot(e,t){return function(r){let s=e(r);return ge(s,r.model,t)}}function ge(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="generateContent"&&typeof a=="function"?at(a.bind(r),t,n):s==="generateContentStream"&&typeof a=="function"?it(a.bind(r),t,n):s==="startChat"&&typeof a=="function"?ut(a.bind(r),t,n):a}})}function at(e,t,n){return async function(s){let i=Date.now(),a=Ce(s);try{let o=await e(s),l=Date.now()-i,u=he(o.response),d=y({provider:S,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=ye(o.response);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function it(e,t,n){return async function(s){let i=Date.now(),a=Ce(s);try{let o=await e(s),l=me(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}async function*me(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){try{let d=u.text();if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],M=c[c.length-1];M?.text!==void 0?M.text+=d:c.push({text:d});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let d of u.candidates[0].content.parts)d.functionCall&&i.candidates[0].content?.parts?.push(d);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:S,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=y({provider:S,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=pt(i.candidates);c.length>0&&w(c,d);}}}}function ut(e,t,n){return function(s){let i=e(s);return dt(i,t,n)}}function dt(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?ct(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?lt(a.bind(r),t,n):a}})}function ct(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=Date.now()-i,u=he(o.response),d=y({provider:S,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=ye(o.response);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function lt(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=me(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function Ce(e){return typeof e=="string"?e:e.contents?e.contents:e}function he(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function ye(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function pt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function Yt(e,t){return P().disabled?(p("Tracing disabled, returning unwrapped client"),e):oe(e)?(q("gemini"),ae(e,t)):pe(e)?(q("gemini"),fe(e,t)):(E("Client is not a Gemini model. Use @lelemon-ai/trace/gemini with Google Generative AI or Google GenAI SDK."),e)}
|
|
3
|
+
exports.captureSpan=N;exports.flush=De;exports.getTraceContext=m;exports.init=Pe;exports.isEnabled=Oe;exports.observe=Yt;exports.span=We;exports.trace=Fe;//# sourceMappingURL=gemini.js.map
|
|
4
|
+
//# sourceMappingURL=gemini.js.map
|
package/dist/gemini.mjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {AsyncLocalStorage}from'async_hooks';/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var L=(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 ye=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Y=ye((yt,Te)=>{Te.exports={name:"@lelemon-ai/trace",version:"0.12.0",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/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/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"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.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"],"google-genai":["./dist/google-genai.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:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var U=false;function z(e){U=e;}function C(){return U?true:we("LELEMON_DEBUG")==="true"}var g="[Lelemon]";function p(e,t){C()&&q("debug",e,t);}function O(e,t){C()&&q("info",e,t);}function R(e,t){q("warn",e,t);}function D(e,t,n,r){C()&&console.log(`${g} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function E(e,t){console.error(`${g} Failed to capture trace: provider=${e} error=${t.message}`);}function _(e){C()&&console.log(`${g} Wrapped client: provider=${e}`);}function F(e,t){C()&&console.log(`${g} Sending batch: count=${e} endpoint=${t}`);}function V(e,t){C()&&console.log(`${g} Batch sent successfully: count=${e} duration=${t}ms`);}function B(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${g} Batch send failed: count=${e} error=${n}`);}function H(e,t,n){C()&&console.log(`${g} Request: ${e} ${t} (${n} bytes)`);}function W(e,t){C()&&console.log(`${g} Response: status=${e} duration=${t}ms`);}function q(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${g} ${t}`,n):r(`${g} ${t}`);}function we(e){if(typeof process<"u"&&process.env)return process.env[e]}var be=10,Se=1e3,ve=1e4,x=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(t){this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??be,flushIntervalMs:t.flushIntervalMs??Se,requestTimeoutMs:t.requestTimeoutMs??ve};}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();F(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),V(t.length,Date.now()-n);}catch(r){B(t.length,r);}}async request(t,n,r){let s=`${this.config.endpoint}${n}`,i=new AbortController,a=r?JSON.stringify(r):void 0;H(t,s,a?.length??0);let o=setTimeout(()=>{i.abort();},this.config.requestTimeoutMs),l=Date.now();try{let u=await fetch(s,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:i.signal});if(clearTimeout(o),W(u.status,Date.now()-l),!u.ok){let c=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${c}`)}let d=await u.text();return d?JSON.parse(d):{}}catch(u){throw clearTimeout(o),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var ke="@lelemon-ai/trace",Ie="nodejs";function Me(){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 Re(){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 Ee(){try{if(typeof L<"u")return Y().version??"unknown"}catch{}return "unknown"}var T=null;function X(e){if(!T){let n=Me(),r=Re();T={"telemetry.sdk.name":ke,"telemetry.sdk.version":Ee(),"telemetry.sdk.language":Ie},n&&(T["process.runtime.name"]=n.name,T["process.runtime.version"]=n.version),r&&(T["os.type"]=r);}let t={...T};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var $={},S=null,A=null,J="https://api.lelemon.dev";function Ge(e={}){$=e,e.debug&&z(true),A=X(e.service),O("Initializing SDK",{endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??false,telemetry:A}),S=Q(e),S.isEnabled()?O("SDK initialized - tracing enabled"):p("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function G(){return $}function P(){return A}function Pe(){return v().isEnabled()}function v(){return S||(S=Q($)),S}async function Oe(){S&&await S.flush();}function Q(e){let t=e.apiKey??De("LELEMON_API_KEY");return !t&&!e.disabled&&R("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new x({apiKey:t??"",endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function De(e){if(typeof process<"u"&&process.env)return process.env[e]}function h(e){try{let t=v();if(!t.isEnabled()){p("Transport disabled, skipping trace capture");return}let n=e.context??{},r=m(),s=k(),i=P(),a={provider:e.provider,model:e.model,input:N(e.input),rawResponse:e.rawResponse?M(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:s,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...i?{_telemetry:i}:{}},tags:n.tags??r?.tags,spanType:e.spanType,name:e.name};return D(e.provider,e.model,e.durationMs,e.status),t.enqueue(a),s}catch(t){E(e.provider,t instanceof Error?t:new Error(String(t)));return}}function f(e){try{let t=v();if(!t.isEnabled()){p("Transport disabled, skipping error capture");return}let n=e.context??{},r=m(),s=P(),i={provider:e.provider,model:e.model,input:N(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:k(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags??r?.tags};D(e.provider,e.model,e.durationMs,"error"),p("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(i);}catch(t){E(e.provider,t instanceof Error?t:new Error(String(t)));}}function j(e){try{let t=v();if(!t.isEnabled()){p("Transport disabled, skipping span capture");return}let n=e.context??{},r=m(),s=e.metadata?._traceId,i=e.metadata?._parentSpanId,a=P(),o={...n.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete o._traceId,delete o._parentSpanId;let l={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:N(e.input),output:M(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:s??r?.traceId,spanId:k(),parentSpanId:i??r?.currentSpanId,toolCallId:e.toolCallId,metadata:o,tags:n.tags??r?.tags};p(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(l);}catch(t){E("unknown",t instanceof Error?t:new Error(String(t)));}}var ee=1e5,_e=["api_key","apikey","password","secret","authorization"],qe=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Ae=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],te={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function ne(){return G().redaction??{}}function $e(e){let t=e.toLowerCase();return Ae.includes(t)?false:!!(_e.some(r=>t.includes(r))||qe.some(r=>t.includes(r))||(ne().keys??[]).some(r=>t.includes(r.toLowerCase())))}function je(e){let t=ne(),n=e;for(let r of t.patterns??[])r.lastIndex=0,n=n.replace(r,"[REDACTED]");return t.emails&&(n=n.replace(te.emails,"[EMAIL]")),t.phones&&(n=n.replace(te.phones,"[PHONE]")),n}function N(e){return M(e,0)}function M(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let n=je(e);return n.length>ee&&(n=n.slice(0,ee)+"...[truncated]"),n}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>M(n,t+1));if(typeof e=="object"){let n={};for(let[r,s]of Object.entries(e))$e(r)?n[r]="[REDACTED]":n[r]=M(s,t+1);return n}return String(e)}var K=Symbol.for("@lelemondev/sdk:traceStorage");function Ke(){let e=globalThis;return e[K]||(e[K]=new AsyncLocalStorage),e[K]}var re=Ke();function k(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function m(){return re.getStore()}function y(e,t){let n=m();if(n)for(let r of e)n.pendingToolCalls.set(r,t),p(`Registered tool call ${r} \u2192 LLM span ${t}`);}function Le(e){let t=m();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function Ue(e){let t=m();t&&t.pendingToolCalls.delete(e);}async function ze(e,t){let n=typeof e=="string"?{name:e}:e,r=m(),s=r?.traceId??k(),i=k(),a={traceId:s,rootSpanId:i,currentSpanId:i,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,outputKey:n.outputKey,outputTransform:n.outputTransform,sessionId:n.sessionId,userId:n.userId,style:n.style,pendingToolCalls:new Map};return re.run(a,async()=>{let o,l;try{return o=await t(),o}catch(u){throw l=u instanceof Error?u:new Error(String(u)),u}finally{Be(a,l?void 0:o,l);}})}var Fe=["text","content","message","output","response","result","answer"];function Ve(e,t,n){if(n)try{return n(e)}catch{return e}if(t===false)return e;if(typeof t=="string"&&e&&typeof e=="object"){let s=e;return t in s?s[t]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let s of Fe)if(s in r&&typeof r[s]=="string")return r[s];return e}function Be(e,t,n){let r=v();if(!r.isEnabled()){p("Transport disabled, skipping root span");return}let s=Date.now()-e.startTime,i=n?null:Ve(t,e.outputKey,e.outputTransform),a={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:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};p(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(a);}function He(e){let t=m();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=Le(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.style?{_style:e.style}:{}}}),e.toolCallId&&Ue(e.toolCallId);}var w="gemini";function se(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GoogleGenAI")return true;let n=e;return !!(n.models&&typeof n.models=="object"&&typeof n.models.generateContent=="function"&&n.chats&&typeof n.chats=="object")}function oe(e,t){let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="models"&&a&&typeof a=="object"?We(a,t):s==="chats"&&a&&typeof a=="object"?Xe(a,t):a}})}function We(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="generateContent"&&typeof i=="function"?Ye(i.bind(n),t):r==="generateContentStream"&&typeof i=="function"?Ze(i.bind(n),t):i}})}function Ye(e,t){return async function(r){let s=Date.now(),i=r.model,a=ie(r);try{let o=await e(r),l=Date.now()-s,u=ue(o),d=h({provider:w,model:i,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:t});if(d){let c=de(o);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:w,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:false,context:t}),o}}}function Ze(e,t){return async function(r){let s=Date.now(),i=r.model,a=ie(r);try{let o=await e(r);return ae(o,i,a,s,t)}catch(o){throw f({provider:w,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:true,context:t}),o}}}async function*ae(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){let d=u.text;if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],I=c[c.length-1];I?.text!==void 0?I.text+=d:c.push({text:d});}if(u.candidates?.[0]?.content?.parts)for(let c of u.candidates[0].content.parts)c.functionCall&&i.candidates[0].content?.parts?.push(c);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:w,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=h({provider:w,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=nt(i.candidates);c.length>0&&y(c,d);}}}}function Xe(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="create"&&typeof i=="function"?Je(i.bind(n),t):i}})}function Je(e,t){return function(r){let s=e(r);return Qe(s,r.model,t)}}function Qe(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?et(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?tt(a.bind(r),t,n):a}})}function et(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s),l=Date.now()-i,u=ue(o),d=h({provider:w,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=de(o);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:w,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function tt(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s);return ae(o,t,a,i,n)}catch(o){throw f({provider:w,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function ie(e){return e.contents}function ue(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata,modelVersion:e.modelVersion}}function de(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function nt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}var b="gemini";function ce(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let n=e;return typeof n.generateContent=="function"&&typeof n.generateContentStream=="function"&&typeof n.model=="string"}function le(e){return !e||typeof e!="object"?false:!!(e.constructor?.name==="GoogleGenerativeAI"||typeof e.getGenerativeModel=="function"||ce(e))}function pe(e,t){if(ce(e)){let r=e;return fe(r,r.model,t)}let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="getGenerativeModel"&&typeof a=="function"?st(a.bind(r),t):a}})}function st(e,t){return function(r){let s=e(r);return fe(s,r.model,t)}}function fe(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="generateContent"&&typeof a=="function"?ot(a.bind(r),t,n):s==="generateContentStream"&&typeof a=="function"?at(a.bind(r),t,n):s==="startChat"&&typeof a=="function"?it(a.bind(r),t,n):a}})}function ot(e,t,n){return async function(s){let i=Date.now(),a=me(s);try{let o=await e(s),l=Date.now()-i,u=Ce(o.response),d=h({provider:b,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=he(o.response);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function at(e,t,n){return async function(s){let i=Date.now(),a=me(s);try{let o=await e(s),l=ge(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}async function*ge(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){try{let d=u.text();if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],I=c[c.length-1];I?.text!==void 0?I.text+=d:c.push({text:d});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let d of u.candidates[0].content.parts)d.functionCall&&i.candidates[0].content?.parts?.push(d);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:b,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=h({provider:b,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=lt(i.candidates);c.length>0&&y(c,d);}}}}function it(e,t,n){return function(s){let i=e(s);return ut(i,t,n)}}function ut(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?dt(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?ct(a.bind(r),t,n):a}})}function dt(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=Date.now()-i,u=Ce(o.response),d=h({provider:b,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=he(o.response);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function ct(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=ge(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function me(e){return typeof e=="string"?e:e.contents?e.contents:e}function Ce(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function he(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function lt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function Kt(e,t){return G().disabled?(p("Tracing disabled, returning unwrapped client"),e):se(e)?(_("gemini"),oe(e,t)):le(e)?(_("gemini"),pe(e,t)):(R("Client is not a Gemini model. Use @lelemon-ai/trace/gemini with Google Generative AI or Google GenAI SDK."),e)}
|
|
3
|
+
export{j as captureSpan,Oe as flush,m as getTraceContext,Ge as init,Pe as isEnabled,Kt as observe,He as span,ze as trace};//# sourceMappingURL=gemini.mjs.map
|
|
4
|
+
//# sourceMappingURL=gemini.mjs.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.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-CC6pIfa4.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Google GenAI Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/google-genai';
|
|
10
|
+
* import { GoogleGenAI } from '@google/genai';
|
|
11
|
+
*
|
|
12
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
13
|
+
* const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
|
|
14
|
+
* const client = observe(ai);
|
|
15
|
+
*
|
|
16
|
+
* const response = await client.models.generateContent({
|
|
17
|
+
* model: 'gemini-pro',
|
|
18
|
+
* contents: 'Hello!',
|
|
19
|
+
* });
|
|
20
|
+
* await flush();
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Wrap a Google GenAI client with automatic tracing
|
|
26
|
+
*
|
|
27
|
+
* Supports both @google/genai (new) and @google/generative-ai (old) SDKs.
|
|
28
|
+
*/
|
|
29
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
30
|
+
|
|
31
|
+
export { ObserveOptions, observe };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { O as ObserveOptions } from './capture-CC6pIfa4.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-CC6pIfa4.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Google GenAI Provider Entry Point
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { init, observe, flush } from '@lelemon-ai/trace/google-genai';
|
|
10
|
+
* import { GoogleGenAI } from '@google/genai';
|
|
11
|
+
*
|
|
12
|
+
* init({ apiKey: process.env.LELEMON_API_KEY });
|
|
13
|
+
* const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
|
|
14
|
+
* const client = observe(ai);
|
|
15
|
+
*
|
|
16
|
+
* const response = await client.models.generateContent({
|
|
17
|
+
* model: 'gemini-pro',
|
|
18
|
+
* contents: 'Hello!',
|
|
19
|
+
* });
|
|
20
|
+
* await flush();
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Wrap a Google GenAI client with automatic tracing
|
|
26
|
+
*
|
|
27
|
+
* Supports both @google/genai (new) and @google/generative-ai (old) SDKs.
|
|
28
|
+
*/
|
|
29
|
+
declare function observe<T>(client: T, options?: ObserveOptions): T;
|
|
30
|
+
|
|
31
|
+
export { ObserveOptions, observe };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var async_hooks=require('async_hooks');/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var U=(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 we=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Z=we((St,ke)=>{ke.exports={name:"@lelemon-ai/trace",version:"0.12.0",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/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/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"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.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"],"google-genai":["./dist/google-genai.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:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var z=false;function F(e){z=e;}function h(){return z?true:be("LELEMON_DEBUG")==="true"}var g="[Lelemon]";function p(e,t){h()&&A("debug",e,t);}function D(e,t){h()&&A("info",e,t);}function E(e,t){A("warn",e,t);}function _(e,t,n,r){h()&&console.log(`${g} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function x(e,t){console.error(`${g} Failed to capture trace: provider=${e} error=${t.message}`);}function q(e){h()&&console.log(`${g} Wrapped client: provider=${e}`);}function V(e,t){h()&&console.log(`${g} Sending batch: count=${e} endpoint=${t}`);}function B(e,t){h()&&console.log(`${g} Batch sent successfully: count=${e} duration=${t}ms`);}function H(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${g} Batch send failed: count=${e} error=${n}`);}function W(e,t,n){h()&&console.log(`${g} Request: ${e} ${t} (${n} bytes)`);}function Y(e,t){h()&&console.log(`${g} Response: status=${e} duration=${t}ms`);}function A(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${g} ${t}`,n):r(`${g} ${t}`);}function be(e){if(typeof process<"u"&&process.env)return process.env[e]}var Se=10,ve=1e3,Te=1e4,G=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(t){this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??Se,flushIntervalMs:t.flushIntervalMs??ve,requestTimeoutMs:t.requestTimeoutMs??Te};}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();V(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),B(t.length,Date.now()-n);}catch(r){H(t.length,r);}}async request(t,n,r){let s=`${this.config.endpoint}${n}`,i=new AbortController,a=r?JSON.stringify(r):void 0;W(t,s,a?.length??0);let o=setTimeout(()=>{i.abort();},this.config.requestTimeoutMs),l=Date.now();try{let u=await fetch(s,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:i.signal});if(clearTimeout(o),Y(u.status,Date.now()-l),!u.ok){let c=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${c}`)}let d=await u.text();return d?JSON.parse(d):{}}catch(u){throw clearTimeout(o),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var Ie="@lelemon-ai/trace",Me="nodejs";function Re(){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 Ee(){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 xe(){try{if(typeof U<"u")return Z().version??"unknown"}catch{}return "unknown"}var k=null;function J(e){if(!k){let n=Re(),r=Ee();k={"telemetry.sdk.name":Ie,"telemetry.sdk.version":xe(),"telemetry.sdk.language":Me},n&&(k["process.runtime.name"]=n.name,k["process.runtime.version"]=n.version),r&&(k["os.type"]=r);}let t={...k};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var j={},v=null,$=null,Q="https://api.lelemon.dev";function Pe(e={}){j=e,e.debug&&F(true),$=J(e.service),D("Initializing SDK",{endpoint:e.endpoint??Q,debug:e.debug??false,disabled:e.disabled??false,telemetry:$}),v=ee(e),v.isEnabled()?D("SDK initialized - tracing enabled"):p("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function P(){return j}function O(){return $}function Oe(){return T().isEnabled()}function T(){return v||(v=ee(j)),v}async function De(){v&&await v.flush();}function ee(e){let t=e.apiKey??_e("LELEMON_API_KEY");return !t&&!e.disabled&&E("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new G({apiKey:t??"",endpoint:e.endpoint??Q,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function _e(e){if(typeof process<"u"&&process.env)return process.env[e]}function y(e){try{let t=T();if(!t.isEnabled()){p("Transport disabled, skipping trace capture");return}let n=e.context??{},r=m(),s=I(),i=O(),a={provider:e.provider,model:e.model,input:K(e.input),rawResponse:e.rawResponse?R(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:s,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...i?{_telemetry:i}:{}},tags:n.tags??r?.tags,spanType:e.spanType,name:e.name};return _(e.provider,e.model,e.durationMs,e.status),t.enqueue(a),s}catch(t){x(e.provider,t instanceof Error?t:new Error(String(t)));return}}function f(e){try{let t=T();if(!t.isEnabled()){p("Transport disabled, skipping error capture");return}let n=e.context??{},r=m(),s=O(),i={provider:e.provider,model:e.model,input:K(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:I(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags??r?.tags};_(e.provider,e.model,e.durationMs,"error"),p("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(i);}catch(t){x(e.provider,t instanceof Error?t:new Error(String(t)));}}function N(e){try{let t=T();if(!t.isEnabled()){p("Transport disabled, skipping span capture");return}let n=e.context??{},r=m(),s=e.metadata?._traceId,i=e.metadata?._parentSpanId,a=O(),o={...n.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete o._traceId,delete o._parentSpanId;let l={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:K(e.input),output:R(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:s??r?.traceId,spanId:I(),parentSpanId:i??r?.currentSpanId,toolCallId:e.toolCallId,metadata:o,tags:n.tags??r?.tags};p(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(l);}catch(t){x("unknown",t instanceof Error?t:new Error(String(t)));}}var te=1e5,qe=["api_key","apikey","password","secret","authorization"],Ae=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],$e=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],ne={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function re(){return P().redaction??{}}function je(e){let t=e.toLowerCase();return $e.includes(t)?false:!!(qe.some(r=>t.includes(r))||Ae.some(r=>t.includes(r))||(re().keys??[]).some(r=>t.includes(r.toLowerCase())))}function Ne(e){let t=re(),n=e;for(let r of t.patterns??[])r.lastIndex=0,n=n.replace(r,"[REDACTED]");return t.emails&&(n=n.replace(ne.emails,"[EMAIL]")),t.phones&&(n=n.replace(ne.phones,"[PHONE]")),n}function K(e){return R(e,0)}function R(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let n=Ne(e);return n.length>te&&(n=n.slice(0,te)+"...[truncated]"),n}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>R(n,t+1));if(typeof e=="object"){let n={};for(let[r,s]of Object.entries(e))je(r)?n[r]="[REDACTED]":n[r]=R(s,t+1);return n}return String(e)}var L=Symbol.for("@lelemondev/sdk:traceStorage");function Le(){let e=globalThis;return e[L]||(e[L]=new async_hooks.AsyncLocalStorage),e[L]}var se=Le();function I(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function m(){return se.getStore()}function w(e,t){let n=m();if(n)for(let r of e)n.pendingToolCalls.set(r,t),p(`Registered tool call ${r} \u2192 LLM span ${t}`);}function Ue(e){let t=m();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function ze(e){let t=m();t&&t.pendingToolCalls.delete(e);}async function Fe(e,t){let n=typeof e=="string"?{name:e}:e,r=m(),s=r?.traceId??I(),i=I(),a={traceId:s,rootSpanId:i,currentSpanId:i,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,outputKey:n.outputKey,outputTransform:n.outputTransform,sessionId:n.sessionId,userId:n.userId,style:n.style,pendingToolCalls:new Map};return se.run(a,async()=>{let o,l;try{return o=await t(),o}catch(u){throw l=u instanceof Error?u:new Error(String(u)),u}finally{He(a,l?void 0:o,l);}})}var Ve=["text","content","message","output","response","result","answer"];function Be(e,t,n){if(n)try{return n(e)}catch{return e}if(t===false)return e;if(typeof t=="string"&&e&&typeof e=="object"){let s=e;return t in s?s[t]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let s of Ve)if(s in r&&typeof r[s]=="string")return r[s];return e}function He(e,t,n){let r=T();if(!r.isEnabled()){p("Transport disabled, skipping root span");return}let s=Date.now()-e.startTime,i=n?null:Be(t,e.outputKey,e.outputTransform),a={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:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};p(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(a);}function We(e){let t=m();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=Ue(e.toolCallId);N({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.style?{_style:e.style}:{}}}),e.toolCallId&&ze(e.toolCallId);}var b="gemini";function oe(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GoogleGenAI")return true;let n=e;return !!(n.models&&typeof n.models=="object"&&typeof n.models.generateContent=="function"&&n.chats&&typeof n.chats=="object")}function ae(e,t){let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="models"&&a&&typeof a=="object"?Ye(a,t):s==="chats"&&a&&typeof a=="object"?Je(a,t):a}})}function Ye(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="generateContent"&&typeof i=="function"?Ze(i.bind(n),t):r==="generateContentStream"&&typeof i=="function"?Xe(i.bind(n),t):i}})}function Ze(e,t){return async function(r){let s=Date.now(),i=r.model,a=ue(r);try{let o=await e(r),l=Date.now()-s,u=de(o),d=y({provider:b,model:i,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:t});if(d){let c=ce(o);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:b,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:false,context:t}),o}}}function Xe(e,t){return async function(r){let s=Date.now(),i=r.model,a=ue(r);try{let o=await e(r);return ie(o,i,a,s,t)}catch(o){throw f({provider:b,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:true,context:t}),o}}}async function*ie(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){let d=u.text;if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],M=c[c.length-1];M?.text!==void 0?M.text+=d:c.push({text:d});}if(u.candidates?.[0]?.content?.parts)for(let c of u.candidates[0].content.parts)c.functionCall&&i.candidates[0].content?.parts?.push(c);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:b,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=y({provider:b,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=rt(i.candidates);c.length>0&&w(c,d);}}}}function Je(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="create"&&typeof i=="function"?Qe(i.bind(n),t):i}})}function Qe(e,t){return function(r){let s=e(r);return et(s,r.model,t)}}function et(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?tt(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?nt(a.bind(r),t,n):a}})}function tt(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s),l=Date.now()-i,u=de(o),d=y({provider:b,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=ce(o);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function nt(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s);return ie(o,t,a,i,n)}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function ue(e){return e.contents}function de(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata,modelVersion:e.modelVersion}}function ce(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function rt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}var S="gemini";function le(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let n=e;return typeof n.generateContent=="function"&&typeof n.generateContentStream=="function"&&typeof n.model=="string"}function pe(e){return !e||typeof e!="object"?false:!!(e.constructor?.name==="GoogleGenerativeAI"||typeof e.getGenerativeModel=="function"||le(e))}function fe(e,t){if(le(e)){let r=e;return ge(r,r.model,t)}let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="getGenerativeModel"&&typeof a=="function"?ot(a.bind(r),t):a}})}function ot(e,t){return function(r){let s=e(r);return ge(s,r.model,t)}}function ge(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="generateContent"&&typeof a=="function"?at(a.bind(r),t,n):s==="generateContentStream"&&typeof a=="function"?it(a.bind(r),t,n):s==="startChat"&&typeof a=="function"?ut(a.bind(r),t,n):a}})}function at(e,t,n){return async function(s){let i=Date.now(),a=Ce(s);try{let o=await e(s),l=Date.now()-i,u=he(o.response),d=y({provider:S,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=ye(o.response);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function it(e,t,n){return async function(s){let i=Date.now(),a=Ce(s);try{let o=await e(s),l=me(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}async function*me(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){try{let d=u.text();if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],M=c[c.length-1];M?.text!==void 0?M.text+=d:c.push({text:d});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let d of u.candidates[0].content.parts)d.functionCall&&i.candidates[0].content?.parts?.push(d);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:S,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=y({provider:S,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=pt(i.candidates);c.length>0&&w(c,d);}}}}function ut(e,t,n){return function(s){let i=e(s);return dt(i,t,n)}}function dt(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?ct(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?lt(a.bind(r),t,n):a}})}function ct(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=Date.now()-i,u=he(o.response),d=y({provider:S,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=ye(o.response);c.length>0&&w(c,d);}return o}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function lt(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=me(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:S,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function Ce(e){return typeof e=="string"?e:e.contents?e.contents:e}function he(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function ye(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function pt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function Yt(e,t){return P().disabled?(p("Tracing disabled, returning unwrapped client"),e):oe(e)?(q("gemini"),ae(e,t)):pe(e)?(q("gemini"),fe(e,t)):(E("Client is not a Google GenAI or Gemini model. Use @lelemon-ai/trace/google-genai with Google GenAI or Google Generative AI SDK."),e)}
|
|
3
|
+
exports.captureSpan=N;exports.flush=De;exports.getTraceContext=m;exports.init=Pe;exports.isEnabled=Oe;exports.observe=Yt;exports.span=We;exports.trace=Fe;//# sourceMappingURL=google-genai.js.map
|
|
4
|
+
//# sourceMappingURL=google-genai.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {AsyncLocalStorage}from'async_hooks';/* @lelemon-ai/trace - LLM Observability */
|
|
2
|
+
var L=(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 ye=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Y=ye((yt,Te)=>{Te.exports={name:"@lelemon-ai/trace",version:"0.12.0",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/Lelemon-studio/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/Lelemon-studio/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"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.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"],"google-genai":["./dist/google-genai.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:{"@anthropic-ai/sdk":"^0.82.0","@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.18",typescript:"^6.0.0",vite:"^6.0.0",vitest:"^4.0.0"}};});var U=false;function z(e){U=e;}function C(){return U?true:we("LELEMON_DEBUG")==="true"}var g="[Lelemon]";function p(e,t){C()&&q("debug",e,t);}function O(e,t){C()&&q("info",e,t);}function R(e,t){q("warn",e,t);}function D(e,t,n,r){C()&&console.log(`${g} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function E(e,t){console.error(`${g} Failed to capture trace: provider=${e} error=${t.message}`);}function _(e){C()&&console.log(`${g} Wrapped client: provider=${e}`);}function F(e,t){C()&&console.log(`${g} Sending batch: count=${e} endpoint=${t}`);}function V(e,t){C()&&console.log(`${g} Batch sent successfully: count=${e} duration=${t}ms`);}function B(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${g} Batch send failed: count=${e} error=${n}`);}function H(e,t,n){C()&&console.log(`${g} Request: ${e} ${t} (${n} bytes)`);}function W(e,t){C()&&console.log(`${g} Response: status=${e} duration=${t}ms`);}function q(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${g} ${t}`,n):r(`${g} ${t}`);}function we(e){if(typeof process<"u"&&process.env)return process.env[e]}var be=10,Se=1e3,ve=1e4,x=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(t){this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??be,flushIntervalMs:t.flushIntervalMs??Se,requestTimeoutMs:t.requestTimeoutMs??ve};}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();F(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),V(t.length,Date.now()-n);}catch(r){B(t.length,r);}}async request(t,n,r){let s=`${this.config.endpoint}${n}`,i=new AbortController,a=r?JSON.stringify(r):void 0;H(t,s,a?.length??0);let o=setTimeout(()=>{i.abort();},this.config.requestTimeoutMs),l=Date.now();try{let u=await fetch(s,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:i.signal});if(clearTimeout(o),W(u.status,Date.now()-l),!u.ok){let c=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${c}`)}let d=await u.text();return d?JSON.parse(d):{}}catch(u){throw clearTimeout(o),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var ke="@lelemon-ai/trace",Ie="nodejs";function Me(){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 Re(){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 Ee(){try{if(typeof L<"u")return Y().version??"unknown"}catch{}return "unknown"}var T=null;function X(e){if(!T){let n=Me(),r=Re();T={"telemetry.sdk.name":ke,"telemetry.sdk.version":Ee(),"telemetry.sdk.language":Ie},n&&(T["process.runtime.name"]=n.name,T["process.runtime.version"]=n.version),r&&(T["os.type"]=r);}let t={...T};return e?.name&&(t["service.name"]=e.name),e?.version&&(t["service.version"]=e.version),e?.environment&&(t["deployment.environment"]=e.environment),t}var $={},S=null,A=null,J="https://api.lelemon.dev";function Ge(e={}){$=e,e.debug&&z(true),A=X(e.service),O("Initializing SDK",{endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??false,telemetry:A}),S=Q(e),S.isEnabled()?O("SDK initialized - tracing enabled"):p("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function G(){return $}function P(){return A}function Pe(){return v().isEnabled()}function v(){return S||(S=Q($)),S}async function Oe(){S&&await S.flush();}function Q(e){let t=e.apiKey??De("LELEMON_API_KEY");return !t&&!e.disabled&&R("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new x({apiKey:t??"",endpoint:e.endpoint??J,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function De(e){if(typeof process<"u"&&process.env)return process.env[e]}function h(e){try{let t=v();if(!t.isEnabled()){p("Transport disabled, skipping trace capture");return}let n=e.context??{},r=m(),s=k(),i=P(),a={provider:e.provider,model:e.model,input:N(e.input),rawResponse:e.rawResponse?M(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:s,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...i?{_telemetry:i}:{}},tags:n.tags??r?.tags,spanType:e.spanType,name:e.name};return D(e.provider,e.model,e.durationMs,e.status),t.enqueue(a),s}catch(t){E(e.provider,t instanceof Error?t:new Error(String(t)));return}}function f(e){try{let t=v();if(!t.isEnabled()){p("Transport disabled, skipping error capture");return}let n=e.context??{},r=m(),s=P(),i={provider:e.provider,model:e.model,input:N(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:r?.traceId,spanId:k(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:n.tags??r?.tags};D(e.provider,e.model,e.durationMs,"error"),p("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(i);}catch(t){E(e.provider,t instanceof Error?t:new Error(String(t)));}}function j(e){try{let t=v();if(!t.isEnabled()){p("Transport disabled, skipping span capture");return}let n=e.context??{},r=m(),s=e.metadata?._traceId,i=e.metadata?._parentSpanId,a=P(),o={...n.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete o._traceId,delete o._parentSpanId;let l={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:N(e.input),output:M(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??n.sessionId,userId:r?.userId??n.userId,traceId:s??r?.traceId,spanId:k(),parentSpanId:i??r?.currentSpanId,toolCallId:e.toolCallId,metadata:o,tags:n.tags??r?.tags};p(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(l);}catch(t){E("unknown",t instanceof Error?t:new Error(String(t)));}}var ee=1e5,_e=["api_key","apikey","password","secret","authorization"],qe=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Ae=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],te={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function ne(){return G().redaction??{}}function $e(e){let t=e.toLowerCase();return Ae.includes(t)?false:!!(_e.some(r=>t.includes(r))||qe.some(r=>t.includes(r))||(ne().keys??[]).some(r=>t.includes(r.toLowerCase())))}function je(e){let t=ne(),n=e;for(let r of t.patterns??[])r.lastIndex=0,n=n.replace(r,"[REDACTED]");return t.emails&&(n=n.replace(te.emails,"[EMAIL]")),t.phones&&(n=n.replace(te.phones,"[PHONE]")),n}function N(e){return M(e,0)}function M(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let n=je(e);return n.length>ee&&(n=n.slice(0,ee)+"...[truncated]"),n}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>M(n,t+1));if(typeof e=="object"){let n={};for(let[r,s]of Object.entries(e))$e(r)?n[r]="[REDACTED]":n[r]=M(s,t+1);return n}return String(e)}var K=Symbol.for("@lelemondev/sdk:traceStorage");function Ke(){let e=globalThis;return e[K]||(e[K]=new AsyncLocalStorage),e[K]}var re=Ke();function k(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function m(){return re.getStore()}function y(e,t){let n=m();if(n)for(let r of e)n.pendingToolCalls.set(r,t),p(`Registered tool call ${r} \u2192 LLM span ${t}`);}function Le(e){let t=m();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function Ue(e){let t=m();t&&t.pendingToolCalls.delete(e);}async function ze(e,t){let n=typeof e=="string"?{name:e}:e,r=m(),s=r?.traceId??k(),i=k(),a={traceId:s,rootSpanId:i,currentSpanId:i,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,outputKey:n.outputKey,outputTransform:n.outputTransform,sessionId:n.sessionId,userId:n.userId,style:n.style,pendingToolCalls:new Map};return re.run(a,async()=>{let o,l;try{return o=await t(),o}catch(u){throw l=u instanceof Error?u:new Error(String(u)),u}finally{Be(a,l?void 0:o,l);}})}var Fe=["text","content","message","output","response","result","answer"];function Ve(e,t,n){if(n)try{return n(e)}catch{return e}if(t===false)return e;if(typeof t=="string"&&e&&typeof e=="object"){let s=e;return t in s?s[t]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let s of Fe)if(s in r&&typeof r[s]=="string")return r[s];return e}function Be(e,t,n){let r=v();if(!r.isEnabled()){p("Transport disabled, skipping root span");return}let s=Date.now()-e.startTime,i=n?null:Ve(t,e.outputKey,e.outputTransform),a={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:e.sessionId,userId:e.userId,metadata:{...e.metadata,...e.style?{_style:e.style}:{}},tags:e.tags};p(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(a);}function He(e){let t=m();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=Le(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.style?{_style:e.style}:{}}}),e.toolCallId&&Ue(e.toolCallId);}var w="gemini";function se(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GoogleGenAI")return true;let n=e;return !!(n.models&&typeof n.models=="object"&&typeof n.models.generateContent=="function"&&n.chats&&typeof n.chats=="object")}function oe(e,t){let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="models"&&a&&typeof a=="object"?We(a,t):s==="chats"&&a&&typeof a=="object"?Xe(a,t):a}})}function We(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="generateContent"&&typeof i=="function"?Ye(i.bind(n),t):r==="generateContentStream"&&typeof i=="function"?Ze(i.bind(n),t):i}})}function Ye(e,t){return async function(r){let s=Date.now(),i=r.model,a=ie(r);try{let o=await e(r),l=Date.now()-s,u=ue(o),d=h({provider:w,model:i,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:t});if(d){let c=de(o);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:w,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:false,context:t}),o}}}function Ze(e,t){return async function(r){let s=Date.now(),i=r.model,a=ie(r);try{let o=await e(r);return ae(o,i,a,s,t)}catch(o){throw f({provider:w,model:i,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-s,streaming:true,context:t}),o}}}async function*ae(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){let d=u.text;if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],I=c[c.length-1];I?.text!==void 0?I.text+=d:c.push({text:d});}if(u.candidates?.[0]?.content?.parts)for(let c of u.candidates[0].content.parts)c.functionCall&&i.candidates[0].content?.parts?.push(c);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:w,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=h({provider:w,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=nt(i.candidates);c.length>0&&y(c,d);}}}}function Xe(e,t){return new Proxy(e,{get(n,r,s){let i=Reflect.get(n,r,s);return r==="create"&&typeof i=="function"?Je(i.bind(n),t):i}})}function Je(e,t){return function(r){let s=e(r);return Qe(s,r.model,t)}}function Qe(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?et(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?tt(a.bind(r),t,n):a}})}function et(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s),l=Date.now()-i,u=ue(o),d=h({provider:w,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=de(o);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:w,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function tt(e,t,n){return async function(s){let i=Date.now(),a=s.message;try{let o=await e(s);return ae(o,t,a,i,n)}catch(o){throw f({provider:w,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function ie(e){return e.contents}function ue(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata,modelVersion:e.modelVersion}}function de(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function nt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}var b="gemini";function ce(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let n=e;return typeof n.generateContent=="function"&&typeof n.generateContentStream=="function"&&typeof n.model=="string"}function le(e){return !e||typeof e!="object"?false:!!(e.constructor?.name==="GoogleGenerativeAI"||typeof e.getGenerativeModel=="function"||ce(e))}function pe(e,t){if(ce(e)){let r=e;return fe(r,r.model,t)}let n=e;return new Proxy(n,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="getGenerativeModel"&&typeof a=="function"?st(a.bind(r),t):a}})}function st(e,t){return function(r){let s=e(r);return fe(s,r.model,t)}}function fe(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="generateContent"&&typeof a=="function"?ot(a.bind(r),t,n):s==="generateContentStream"&&typeof a=="function"?at(a.bind(r),t,n):s==="startChat"&&typeof a=="function"?it(a.bind(r),t,n):a}})}function ot(e,t,n){return async function(s){let i=Date.now(),a=me(s);try{let o=await e(s),l=Date.now()-i,u=Ce(o.response),d=h({provider:b,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=he(o.response);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function at(e,t,n){return async function(s){let i=Date.now(),a=me(s);try{let o=await e(s),l=ge(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}async function*ge(e,t,n,r,s){let i={candidates:[{content:{parts:[]}}]},a=null,o,l=false;try{for await(let u of e){try{let d=u.text();if(d){l||(l=!0,o=Date.now()-r);let c=i.candidates[0].content?.parts||[],I=c[c.length-1];I?.text!==void 0?I.text+=d:c.push({text:d});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let d of u.candidates[0].content.parts)d.functionCall&&i.candidates[0].content?.parts?.push(d);u.usageMetadata&&(i.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(i.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)f({provider:b,model:t,input:n,error:a,durationMs:u,streaming:true,context:s});else {let d=h({provider:b,model:t,input:n,rawResponse:i,durationMs:u,status:"success",streaming:true,firstTokenMs:o,context:s});if(d){let c=lt(i.candidates);c.length>0&&y(c,d);}}}}function it(e,t,n){return function(s){let i=e(s);return ut(i,t,n)}}function ut(e,t,n){return new Proxy(e,{get(r,s,i){let a=Reflect.get(r,s,i);return s==="sendMessage"&&typeof a=="function"?dt(a.bind(r),t,n):s==="sendMessageStream"&&typeof a=="function"?ct(a.bind(r),t,n):a}})}function dt(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=Date.now()-i,u=Ce(o.response),d=h({provider:b,model:t,input:a,rawResponse:u,durationMs:l,status:"success",streaming:!1,context:n});if(d){let c=he(o.response);c.length>0&&y(c,d);}return o}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:false,context:n}),o}}}function ct(e,t,n){return async function(s){let i=Date.now(),a=s;try{let o=await e(s),l=ge(o.stream,t,a,i,n);return {...o,stream:l}}catch(o){throw f({provider:b,model:t,input:a,error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-i,streaming:true,context:n}),o}}}function me(e){return typeof e=="string"?e:e.contents?e.contents:e}function Ce(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function he(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function lt(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,s)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${s}`);}),t}function Kt(e,t){return G().disabled?(p("Tracing disabled, returning unwrapped client"),e):se(e)?(_("gemini"),oe(e,t)):le(e)?(_("gemini"),pe(e,t)):(R("Client is not a Google GenAI or Gemini model. Use @lelemon-ai/trace/google-genai with Google GenAI or Google Generative AI SDK."),e)}
|
|
3
|
+
export{j as captureSpan,Oe as flush,m as getTraceContext,Ge as init,Pe as isEnabled,Kt as observe,He as span,ze as trace};//# sourceMappingURL=google-genai.mjs.map
|
|
4
|
+
//# sourceMappingURL=google-genai.mjs.map
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hono Integration
|
|
3
|
+
*
|
|
4
|
+
* Middleware for Hono framework (Cloudflare Workers, Deno, Bun, Node.js).
|
|
5
|
+
* Uses executionCtx.waitUntil() when available for non-blocking flush.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* import { Hono } from 'hono';
|
|
9
|
+
* import { createMiddleware } from '@lelemon-ai/trace/hono';
|
|
10
|
+
*
|
|
11
|
+
* const app = new Hono();
|
|
12
|
+
* app.use(createMiddleware());
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Execution context for edge runtimes (Cloudflare Workers, Deno Deploy)
|
|
16
|
+
*/
|
|
17
|
+
interface ExecutionContext {
|
|
18
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
19
|
+
passThroughOnException(): void;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Minimal Hono context type (avoids requiring hono as dependency)
|
|
23
|
+
*/
|
|
24
|
+
interface HonoContext {
|
|
25
|
+
req: {
|
|
26
|
+
raw: Request;
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
};
|
|
29
|
+
res: Response | undefined;
|
|
30
|
+
executionCtx?: ExecutionContext;
|
|
31
|
+
[key: string]: unknown;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Hono next function type
|
|
35
|
+
*/
|
|
36
|
+
type HonoNextFunction = () => Promise<void>;
|
|
37
|
+
/**
|
|
38
|
+
* Hono middleware function type
|
|
39
|
+
*
|
|
40
|
+
* @param c - Hono context object
|
|
41
|
+
* @param next - Next function to continue middleware chain
|
|
42
|
+
*/
|
|
43
|
+
type HonoMiddleware = (c: HonoContext, next: HonoNextFunction) => Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Create Hono middleware for automatic trace flushing
|
|
46
|
+
*
|
|
47
|
+
* On Cloudflare Workers/Deno Deploy: uses executionCtx.waitUntil() for non-blocking flush
|
|
48
|
+
* On Node.js/Bun: flushes after response (fire-and-forget)
|
|
49
|
+
*
|
|
50
|
+
* @returns Hono middleware function
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* import { Hono } from 'hono';
|
|
54
|
+
* import { createMiddleware } from '@lelemon-ai/trace/hono';
|
|
55
|
+
*
|
|
56
|
+
* const app = new Hono();
|
|
57
|
+
*
|
|
58
|
+
* // Global middleware
|
|
59
|
+
* app.use(createMiddleware());
|
|
60
|
+
*
|
|
61
|
+
* app.post('/chat', async (c) => {
|
|
62
|
+
* const openai = observe(new OpenAI());
|
|
63
|
+
* const result = await openai.chat.completions.create({...});
|
|
64
|
+
* return c.json(result);
|
|
65
|
+
* });
|
|
66
|
+
*
|
|
67
|
+
* export default app;
|
|
68
|
+
*/
|
|
69
|
+
declare function createMiddleware(): HonoMiddleware;
|
|
70
|
+
|
|
71
|
+
type hono_ExecutionContext = ExecutionContext;
|
|
72
|
+
type hono_HonoContext = HonoContext;
|
|
73
|
+
type hono_HonoMiddleware = HonoMiddleware;
|
|
74
|
+
type hono_HonoNextFunction = HonoNextFunction;
|
|
75
|
+
declare const hono_createMiddleware: typeof createMiddleware;
|
|
76
|
+
declare namespace hono {
|
|
77
|
+
export { type hono_ExecutionContext as ExecutionContext, type hono_HonoContext as HonoContext, type hono_HonoMiddleware as HonoMiddleware, type hono_HonoNextFunction as HonoNextFunction, hono_createMiddleware as createMiddleware };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export { type ExecutionContext as E, type HonoContext as H, type HonoNextFunction as a, type HonoMiddleware as b, createMiddleware as c, hono as h };
|