openlayer 0.16.1 → 0.16.3

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.
Files changed (134) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/_shims/bun-runtime.js +1 -2
  3. package/_shims/bun-runtime.js.map +1 -1
  4. package/_shims/node-runtime.js +18 -9
  5. package/_shims/node-runtime.js.map +1 -1
  6. package/_shims/node-runtime.mjs.map +1 -1
  7. package/_shims/registry.js +2 -2
  8. package/_shims/registry.js.map +1 -1
  9. package/_shims/registry.mjs.map +1 -1
  10. package/_shims/web-runtime.js +1 -2
  11. package/_shims/web-runtime.js.map +1 -1
  12. package/_shims/web-runtime.mjs.map +1 -1
  13. package/core.d.ts +2 -4
  14. package/core.d.ts.map +1 -1
  15. package/core.js +6 -6
  16. package/core.js.map +1 -1
  17. package/core.mjs +1 -1
  18. package/core.mjs.map +1 -1
  19. package/error.js.map +1 -1
  20. package/error.mjs.map +1 -1
  21. package/index.js +17 -7
  22. package/index.js.map +1 -1
  23. package/index.mjs.map +1 -1
  24. package/internal/qs/stringify.js +1 -2
  25. package/internal/qs/stringify.js.map +1 -1
  26. package/internal/qs/stringify.mjs.map +1 -1
  27. package/internal/qs/utils.js +9 -9
  28. package/internal/qs/utils.js.map +1 -1
  29. package/internal/qs/utils.mjs.map +1 -1
  30. package/lib/core/cli.d.ts.map +1 -1
  31. package/lib/core/cli.js +17 -8
  32. package/lib/core/cli.js.map +1 -1
  33. package/lib/core/cli.mjs +0 -1
  34. package/lib/core/cli.mjs.map +1 -1
  35. package/lib/core/openai-monitor.d.ts.map +1 -1
  36. package/lib/core/openai-monitor.js +1 -1
  37. package/lib/core/openai-monitor.js.map +1 -1
  38. package/lib/core/openai-monitor.mjs +1 -1
  39. package/lib/core/openai-monitor.mjs.map +1 -1
  40. package/lib/integrations/bedrockAgentTracer.js +49 -50
  41. package/lib/integrations/bedrockAgentTracer.js.map +1 -1
  42. package/lib/integrations/bedrockAgentTracer.mjs +48 -48
  43. package/lib/integrations/bedrockAgentTracer.mjs.map +1 -1
  44. package/lib/integrations/index.d.ts +5 -0
  45. package/lib/integrations/index.d.ts.map +1 -0
  46. package/lib/integrations/index.js +21 -0
  47. package/lib/integrations/index.js.map +1 -0
  48. package/lib/integrations/index.mjs +5 -0
  49. package/lib/integrations/index.mjs.map +1 -0
  50. package/lib/integrations/langchainCallback.d.ts +83 -27
  51. package/lib/integrations/langchainCallback.d.ts.map +1 -1
  52. package/lib/integrations/langchainCallback.js +597 -88
  53. package/lib/integrations/langchainCallback.js.map +1 -1
  54. package/lib/integrations/langchainCallback.mjs +599 -87
  55. package/lib/integrations/langchainCallback.mjs.map +1 -1
  56. package/lib/integrations/openAiTracer.js +1 -2
  57. package/lib/integrations/openAiTracer.js.map +1 -1
  58. package/lib/integrations/openAiTracer.mjs.map +1 -1
  59. package/lib/integrations/tracedTool.d.ts +66 -0
  60. package/lib/integrations/tracedTool.d.ts.map +1 -0
  61. package/lib/integrations/tracedTool.js +186 -0
  62. package/lib/integrations/tracedTool.js.map +1 -0
  63. package/lib/integrations/tracedTool.mjs +149 -0
  64. package/lib/integrations/tracedTool.mjs.map +1 -0
  65. package/lib/tracing/steps.d.ts +120 -1
  66. package/lib/tracing/steps.d.ts.map +1 -1
  67. package/lib/tracing/steps.js +128 -4
  68. package/lib/tracing/steps.js.map +1 -1
  69. package/lib/tracing/steps.mjs +119 -1
  70. package/lib/tracing/steps.mjs.map +1 -1
  71. package/lib/tracing/tracer.d.ts +69 -1
  72. package/lib/tracing/tracer.d.ts.map +1 -1
  73. package/lib/tracing/tracer.js +92 -18
  74. package/lib/tracing/tracer.js.map +1 -1
  75. package/lib/tracing/tracer.mjs +78 -10
  76. package/lib/tracing/tracer.mjs.map +1 -1
  77. package/package.json +3 -1
  78. package/resources/commits/commits.js +17 -7
  79. package/resources/commits/commits.js.map +1 -1
  80. package/resources/commits/test-results.js.map +1 -1
  81. package/resources/commits/test-results.mjs.map +1 -1
  82. package/resources/inference-pipelines/inference-pipelines.js +17 -7
  83. package/resources/inference-pipelines/inference-pipelines.js.map +1 -1
  84. package/resources/inference-pipelines/inference-pipelines.mjs.map +1 -1
  85. package/resources/inference-pipelines/test-results.js.map +1 -1
  86. package/resources/inference-pipelines/test-results.mjs.map +1 -1
  87. package/resources/projects/commits.js.map +1 -1
  88. package/resources/projects/commits.mjs.map +1 -1
  89. package/resources/projects/inference-pipelines.js.map +1 -1
  90. package/resources/projects/inference-pipelines.mjs.map +1 -1
  91. package/resources/projects/projects.js +17 -7
  92. package/resources/projects/projects.js.map +1 -1
  93. package/resources/projects/projects.mjs.map +1 -1
  94. package/resources/projects/tests.js.map +1 -1
  95. package/resources/projects/tests.mjs.map +1 -1
  96. package/resources/storage/storage.js +17 -7
  97. package/resources/storage/storage.js.map +1 -1
  98. package/shims/node.d.ts +0 -4
  99. package/shims/node.d.ts.map +1 -1
  100. package/shims/node.js +0 -25
  101. package/shims/node.js.map +1 -1
  102. package/shims/node.mjs +0 -1
  103. package/shims/node.mjs.map +1 -1
  104. package/shims/web.js +0 -25
  105. package/shims/web.js.map +1 -1
  106. package/shims/web.mjs +0 -1
  107. package/shims/web.mjs.map +1 -1
  108. package/src/core.ts +1 -1
  109. package/src/lib/core/cli.ts +0 -1
  110. package/src/lib/core/openai-monitor.ts +1 -1
  111. package/src/lib/integrations/index.ts +4 -0
  112. package/src/lib/integrations/langchainCallback.ts +802 -88
  113. package/src/lib/integrations/tracedTool.ts +175 -0
  114. package/src/lib/tracing/index.d.ts +10 -0
  115. package/src/lib/tracing/steps.ts +218 -5
  116. package/src/lib/tracing/tracer.ts +153 -9
  117. package/src/uploads.ts +3 -2
  118. package/src/version.ts +1 -1
  119. package/uploads.d.ts +2 -2
  120. package/uploads.d.ts.map +1 -1
  121. package/uploads.js +3 -4
  122. package/uploads.js.map +1 -1
  123. package/uploads.mjs +1 -2
  124. package/uploads.mjs.map +1 -1
  125. package/version.d.ts +1 -1
  126. package/version.js +1 -1
  127. package/version.mjs +1 -1
  128. package/lib/tracing/enums.d.ts +0 -5
  129. package/lib/tracing/enums.d.ts.map +0 -1
  130. package/lib/tracing/enums.js +0 -9
  131. package/lib/tracing/enums.js.map +0 -1
  132. package/lib/tracing/enums.mjs +0 -6
  133. package/lib/tracing/enums.mjs.map +0 -1
  134. package/src/lib/tracing/enums.ts +0 -4
@@ -1,113 +1,625 @@
1
1
  import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
2
- import { AIMessage, SystemMessage } from '@langchain/core/messages';
3
- import performanceNow from 'performance-now';
4
- import { addChatCompletionStepToTrace } from "../tracing/tracer.mjs";
2
+ import { AIMessage, AIMessageChunk, BaseMessage, ChatMessage, FunctionMessage, HumanMessage, SystemMessage, ToolMessage, } from '@langchain/core/messages';
3
+ import { addChatCompletionStepToTrace, addChainStepToTrace, addAgentStepToTrace, addToolStepToTrace, addRetrieverStepToTrace, } from "../tracing/tracer.mjs";
5
4
  const LANGCHAIN_TO_OPENLAYER_PROVIDER_MAP = {
6
5
  openai: 'OpenAI',
7
6
  'openai-chat': 'OpenAI',
8
7
  'chat-ollama': 'Ollama',
9
8
  vertexai: 'Google',
9
+ anthropic: 'Anthropic',
10
+ 'azure-openai': 'Azure OpenAI',
11
+ cohere: 'Cohere',
12
+ huggingface: 'Hugging Face',
10
13
  };
11
14
  const PROVIDER_TO_STEP_NAME = {
12
15
  OpenAI: 'OpenAI Chat Completion',
13
16
  Ollama: 'Ollama Chat Completion',
14
17
  Google: 'Google Vertex AI Chat Completion',
18
+ Anthropic: 'Anthropic Chat Completion',
19
+ 'Azure OpenAI': 'Azure OpenAI Chat Completion',
20
+ Cohere: 'Cohere Chat Completion',
21
+ 'Hugging Face': 'Hugging Face Chat Completion',
15
22
  };
23
+ const LANGSMITH_HIDDEN_TAG = 'langsmith:hidden';
24
+ /**
25
+ * Comprehensive LangChain callback handler for Openlayer tracing.
26
+ *
27
+ * Supports all LangChain components:
28
+ * - LLMs and Chat Models (with streaming support)
29
+ * - Chains
30
+ * - Agents and Tools
31
+ * - Retrievers
32
+ * - Error handling and hierarchical tracking
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * import { OpenlayerHandler } from 'openlayer/lib/integrations/langchainCallback';
37
+ *
38
+ * const handler = new OpenlayerHandler({
39
+ * userId: 'user-123',
40
+ * sessionId: 'session-456',
41
+ * tags: ['production'],
42
+ * version: '1.0.0'
43
+ * });
44
+ *
45
+ * const model = new ChatOpenAI({
46
+ * callbacks: [handler]
47
+ * });
48
+ * ```
49
+ */
16
50
  export class OpenlayerHandler extends BaseCallbackHandler {
17
- constructor(kwargs = {}) {
51
+ constructor(params) {
18
52
  super();
19
53
  this.name = 'OpenlayerHandler';
20
- this.startTime = null;
21
- this.endTime = null;
22
- this.prompt = null;
23
- this.latency = 0;
24
- this.model = null;
25
- this.modelParameters = null;
26
- this.promptTokens = 0;
27
- this.completionTokens = 0;
28
- this.totalTokens = 0;
29
- this.output = '';
30
- this.metadata = kwargs;
54
+ this.completionStartTimes = {};
55
+ this.promptToParentRunMap = new Map();
56
+ this.runMap = new Map();
57
+ this.sessionId = params?.sessionId;
58
+ this.userId = params?.userId;
59
+ this.tags = params?.tags ?? [];
60
+ this.traceMetadata = params?.traceMetadata;
61
+ this.version = params?.version;
62
+ }
63
+ // ============================================================================
64
+ // LLM Handlers
65
+ // ============================================================================
66
+ async handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, _fields) {
67
+ try {
68
+ // Track first token timing for streaming
69
+ if (runId && !(runId in this.completionStartTimes)) {
70
+ console.debug(`LLM first streaming token: ${runId}`);
71
+ this.completionStartTimes[runId] = new Date();
72
+ }
73
+ }
74
+ catch (e) {
75
+ console.debug(e instanceof Error ? e.message : String(e));
76
+ }
77
+ }
78
+ async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {
79
+ try {
80
+ console.debug(`LLM start with ID: ${runId}`);
81
+ this.handleGenerationStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name);
82
+ }
83
+ catch (e) {
84
+ console.debug(e instanceof Error ? e.message : String(e));
85
+ }
31
86
  }
32
87
  async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
33
- this.initializeRun(extraParams || {}, metadata || {});
34
- this.prompt = this.langchainMassagesToPrompt(messages);
35
- this.startTime = performanceNow();
36
- }
37
- initializeRun(extraParams, metadata) {
38
- this.modelParameters = extraParams['invocation_params'] || {};
39
- const provider = metadata?.['ls_provider'];
40
- if (provider && LANGCHAIN_TO_OPENLAYER_PROVIDER_MAP[provider]) {
41
- this.provider = LANGCHAIN_TO_OPENLAYER_PROVIDER_MAP[provider];
42
- }
43
- this.model = this.modelParameters?.['model'] || metadata['ls_model_name'] || null;
44
- this.output = '';
45
- }
46
- langchainMassagesToPrompt(messages) {
47
- let prompt = [];
48
- for (const message of messages) {
49
- for (const m of message) {
50
- if (m instanceof AIMessage) {
51
- prompt.push({ role: 'assistant', content: m.content });
88
+ try {
89
+ console.debug(`Chat model start with ID: ${runId}`);
90
+ const prompts = messages.flatMap((message) => message.map((m) => this.extractChatMessageContent(m)));
91
+ this.handleGenerationStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name);
92
+ }
93
+ catch (e) {
94
+ console.debug(e instanceof Error ? e.message : String(e));
95
+ }
96
+ }
97
+ async handleLLMEnd(output, runId, parentRunId) {
98
+ try {
99
+ console.debug(`LLM end with ID: ${runId}`);
100
+ if (output.generations.length === 0) {
101
+ console.debug('No generations found in LLM output');
102
+ return;
103
+ }
104
+ const lastGeneration = output.generations[output.generations.length - 1];
105
+ if (!lastGeneration || lastGeneration.length === 0) {
106
+ console.debug('No responses found in last generation');
107
+ return;
108
+ }
109
+ const lastResponse = lastGeneration[lastGeneration.length - 1];
110
+ const llmUsage = (lastResponse ? this.extractUsageMetadata(lastResponse) : undefined) ||
111
+ output.llmOutput?.['tokenUsage'];
112
+ const modelName = lastResponse ? this.extractModelNameFromMetadata(lastResponse) : undefined;
113
+ const usageDetails = {
114
+ input: llmUsage?.input_tokens ?? llmUsage?.promptTokens,
115
+ output: llmUsage?.output_tokens ?? llmUsage?.completionTokens,
116
+ total: llmUsage?.total_tokens ?? llmUsage?.totalTokens,
117
+ };
118
+ // Handle detailed token usage if available
119
+ if (llmUsage && 'input_token_details' in llmUsage) {
120
+ for (const [key, val] of Object.entries(llmUsage['input_token_details'] ?? {})) {
121
+ usageDetails[`input_${key}`] = val;
122
+ if ('input' in usageDetails && typeof val === 'number') {
123
+ usageDetails['input'] = Math.max(0, usageDetails['input'] - val);
124
+ }
52
125
  }
53
- else if (m instanceof SystemMessage) {
54
- prompt.push({ role: 'system', content: m.content });
126
+ }
127
+ if (llmUsage && 'output_token_details' in llmUsage) {
128
+ for (const [key, val] of Object.entries(llmUsage['output_token_details'] ?? {})) {
129
+ usageDetails[`output_${key}`] = val;
130
+ if ('output' in usageDetails && typeof val === 'number') {
131
+ usageDetails['output'] = Math.max(0, usageDetails['output'] - val);
132
+ }
55
133
  }
56
- else {
57
- prompt.push({ role: 'user', content: m.content });
134
+ }
135
+ // Extract clean output for dashboard display
136
+ const extractedOutput = lastResponse ?
137
+ 'message' in lastResponse && lastResponse['message'] instanceof BaseMessage ?
138
+ lastResponse['message'].content // Just the content, not the full message object
139
+ : lastResponse.text || ''
140
+ : '';
141
+ // Extract raw output (complete response object for debugging/analysis)
142
+ const rawOutput = lastResponse ?
143
+ JSON.stringify({
144
+ generation: lastResponse,
145
+ llmOutput: output.llmOutput,
146
+ fullResponse: output,
147
+ }, null, 2)
148
+ : null;
149
+ this.handleStepEnd({
150
+ runId,
151
+ output: extractedOutput,
152
+ rawOutput,
153
+ ...(modelName && { modelName }),
154
+ usageDetails,
155
+ ...(runId in this.completionStartTimes && { completionStartTime: this.completionStartTimes[runId] }),
156
+ });
157
+ if (runId in this.completionStartTimes) {
158
+ delete this.completionStartTimes[runId];
159
+ }
160
+ }
161
+ catch (e) {
162
+ console.debug(e instanceof Error ? e.message : String(e));
163
+ }
164
+ }
165
+ async handleLLMError(err, runId, parentRunId) {
166
+ try {
167
+ console.debug(`LLM error ${err} with ID: ${runId}`);
168
+ const azureRefusalError = this.parseAzureRefusalError(err);
169
+ this.handleStepEnd({
170
+ runId,
171
+ error: err.toString() + azureRefusalError,
172
+ });
173
+ }
174
+ catch (e) {
175
+ console.debug(e instanceof Error ? e.message : String(e));
176
+ }
177
+ }
178
+ // ============================================================================
179
+ // Chain Handlers
180
+ // ============================================================================
181
+ async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
182
+ try {
183
+ console.debug(`Chain start with ID: ${runId}`);
184
+ const runName = name ?? chain.id.at(-1)?.toString() ?? 'Langchain Chain';
185
+ this.registerOpenlayerPrompt(parentRunId, metadata);
186
+ // Process inputs to handle different formats
187
+ let finalInput = inputs;
188
+ if (typeof inputs === 'object' &&
189
+ 'input' in inputs &&
190
+ Array.isArray(inputs['input']) &&
191
+ inputs['input'].every((m) => m instanceof BaseMessage)) {
192
+ finalInput = inputs['input'].map((m) => this.extractChatMessageContent(m));
193
+ }
194
+ else if (typeof inputs === 'object' && 'content' in inputs && typeof inputs['content'] === 'string') {
195
+ finalInput = inputs['content'];
196
+ }
197
+ const { step, endStep } = addChainStepToTrace({
198
+ name: runName,
199
+ inputs: finalInput,
200
+ metadata: this.joinTagsAndMetaData(tags, metadata) || {},
201
+ });
202
+ this.runMap.set(runId, { step, endStep });
203
+ }
204
+ catch (e) {
205
+ console.debug(e instanceof Error ? e.message : String(e));
206
+ }
207
+ }
208
+ async handleChainEnd(outputs, runId, parentRunId) {
209
+ try {
210
+ console.debug(`Chain end with ID: ${runId}`);
211
+ let finalOutput = outputs;
212
+ if (typeof outputs === 'object' && 'output' in outputs && typeof outputs['output'] === 'string') {
213
+ finalOutput = outputs['output'];
214
+ }
215
+ this.handleStepEnd({
216
+ runId,
217
+ output: finalOutput,
218
+ });
219
+ this.deregisterOpenlayerPrompt(runId);
220
+ }
221
+ catch (e) {
222
+ console.debug(e instanceof Error ? e.message : String(e));
223
+ }
224
+ }
225
+ async handleChainError(err, runId, parentRunId) {
226
+ try {
227
+ console.debug(`Chain error: ${err} with ID: ${runId}`);
228
+ const azureRefusalError = this.parseAzureRefusalError(err);
229
+ this.handleStepEnd({
230
+ runId,
231
+ error: err.toString() + azureRefusalError,
232
+ });
233
+ }
234
+ catch (e) {
235
+ console.debug(e instanceof Error ? e.message : String(e));
236
+ }
237
+ }
238
+ // ============================================================================
239
+ // Agent Handlers
240
+ // ============================================================================
241
+ async handleAgentAction(action, runId, parentRunId) {
242
+ try {
243
+ console.debug(`Agent action ${action.tool} with ID: ${runId}`);
244
+ const { step, endStep } = addAgentStepToTrace({
245
+ name: action.tool,
246
+ inputs: action,
247
+ tool: action.tool,
248
+ action: action,
249
+ });
250
+ this.runMap.set(runId, { step, endStep });
251
+ }
252
+ catch (e) {
253
+ console.debug(e instanceof Error ? e.message : String(e));
254
+ }
255
+ }
256
+ async handleAgentEnd(action, runId, parentRunId) {
257
+ try {
258
+ console.debug(`Agent finish with ID: ${runId}`);
259
+ this.handleStepEnd({
260
+ runId,
261
+ output: action,
262
+ });
263
+ }
264
+ catch (e) {
265
+ console.debug(e instanceof Error ? e.message : String(e));
266
+ }
267
+ }
268
+ // ============================================================================
269
+ // Tool Handlers
270
+ // ============================================================================
271
+ async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) {
272
+ try {
273
+ console.debug(`Tool start with ID: ${runId}`);
274
+ const { step, endStep } = addToolStepToTrace({
275
+ name: name ?? tool.id.at(-1)?.toString() ?? 'Tool execution',
276
+ inputs: input,
277
+ metadata: this.joinTagsAndMetaData(tags, metadata) || {},
278
+ });
279
+ this.runMap.set(runId, { step, endStep });
280
+ }
281
+ catch (e) {
282
+ console.debug(e instanceof Error ? e.message : String(e));
283
+ }
284
+ }
285
+ async handleToolEnd(output, runId, parentRunId) {
286
+ try {
287
+ console.debug(`Tool end with ID: ${runId}`);
288
+ this.handleStepEnd({
289
+ runId,
290
+ output: output,
291
+ });
292
+ }
293
+ catch (e) {
294
+ console.debug(e instanceof Error ? e.message : String(e));
295
+ }
296
+ }
297
+ async handleToolError(err, runId, parentRunId) {
298
+ try {
299
+ console.debug(`Tool error ${err} with ID: ${runId}`);
300
+ this.handleStepEnd({
301
+ runId,
302
+ error: err.toString(),
303
+ });
304
+ }
305
+ catch (e) {
306
+ console.debug(e instanceof Error ? e.message : String(e));
307
+ }
308
+ }
309
+ // ============================================================================
310
+ // Retriever Handlers
311
+ // ============================================================================
312
+ async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
313
+ try {
314
+ console.debug(`Retriever start with ID: ${runId}`);
315
+ const { step, endStep } = addRetrieverStepToTrace({
316
+ name: name ?? retriever.id.at(-1)?.toString() ?? 'Retriever',
317
+ inputs: query,
318
+ metadata: this.joinTagsAndMetaData(tags, metadata) || {},
319
+ });
320
+ this.runMap.set(runId, { step, endStep });
321
+ }
322
+ catch (e) {
323
+ console.debug(e instanceof Error ? e.message : String(e));
324
+ }
325
+ }
326
+ async handleRetrieverEnd(documents, runId, parentRunId) {
327
+ try {
328
+ console.debug(`Retriever end with ID: ${runId}`);
329
+ this.handleStepEnd({
330
+ runId,
331
+ output: documents,
332
+ });
333
+ }
334
+ catch (e) {
335
+ console.debug(e instanceof Error ? e.message : String(e));
336
+ }
337
+ }
338
+ async handleRetrieverError(err, runId, parentRunId) {
339
+ try {
340
+ console.debug(`Retriever error: ${err} with ID: ${runId}`);
341
+ this.handleStepEnd({
342
+ runId,
343
+ error: err.toString(),
344
+ });
345
+ }
346
+ catch (e) {
347
+ console.debug(e instanceof Error ? e.message : String(e));
348
+ }
349
+ }
350
+ // ============================================================================
351
+ // Private Helper Methods
352
+ // ============================================================================
353
+ async handleGenerationStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
354
+ console.debug(`Generation start with ID: ${runId} and parentRunId ${parentRunId}`);
355
+ const runName = name ?? llm.id?.at?.(-1)?.toString() ?? llm.id?.slice?.(-1)?.[0]?.toString() ?? 'Langchain Generation';
356
+ // Extract comprehensive model parameters
357
+ const modelParameters = {};
358
+ const invocationParams = extraParams?.['invocation_params'];
359
+ // Standard parameters
360
+ const standardParams = {
361
+ temperature: invocationParams?.['temperature'],
362
+ max_tokens: invocationParams?.['max_tokens'],
363
+ top_p: invocationParams?.['top_p'],
364
+ top_k: invocationParams?.['top_k'],
365
+ frequency_penalty: invocationParams?.['frequency_penalty'],
366
+ presence_penalty: invocationParams?.['presence_penalty'],
367
+ request_timeout: invocationParams?.['request_timeout'],
368
+ stop: invocationParams?.['stop'],
369
+ seed: invocationParams?.['seed'],
370
+ response_format: invocationParams?.['response_format'],
371
+ tools: invocationParams?.['tools'],
372
+ tool_choice: invocationParams?.['tool_choice'],
373
+ };
374
+ for (const [key, value] of Object.entries(standardParams)) {
375
+ if (value !== undefined && value !== null) {
376
+ modelParameters[key] = value;
377
+ }
378
+ }
379
+ // Add any additional parameters that weren't in the standard list
380
+ if (invocationParams && typeof invocationParams === 'object') {
381
+ for (const [key, value] of Object.entries(invocationParams)) {
382
+ if (!(key in standardParams) && value !== undefined && value !== null) {
383
+ modelParameters[key] = value;
58
384
  }
59
385
  }
60
386
  }
61
- return prompt;
62
- }
63
- async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
64
- this.initializeRun(extraParams || {}, metadata || {});
65
- this.prompt = prompts.map((p) => ({ role: 'user', content: p }));
66
- this.startTime = performanceNow();
67
- }
68
- async handleLLMEnd(output, runId, parentRunId, tags) {
69
- this.endTime = performanceNow();
70
- this.latency = this.endTime - this.startTime;
71
- this.extractTokenInformation(output);
72
- this.extractOutput(output);
73
- this.addToTrace();
74
- }
75
- extractTokenInformation(output) {
76
- if (this.provider === 'OpenAI') {
77
- this.openaiTokenInformation(output);
78
- }
79
- }
80
- openaiTokenInformation(output) {
81
- if (output.llmOutput && 'tokenUsage' in output.llmOutput) {
82
- this.promptTokens = output.llmOutput?.['tokenUsage']?.promptTokens ?? 0;
83
- this.completionTokens = output.llmOutput?.['tokenUsage']?.completionTokens ?? 0;
84
- this.totalTokens = output.llmOutput?.['tokenUsage']?.totalTokens ?? 0;
85
- }
86
- }
87
- extractOutput(output) {
88
- const lastResponse = output?.generations?.at(-1)?.at(-1) ?? undefined;
89
- this.output += lastResponse?.text ?? '';
90
- }
91
- addToTrace() {
92
- let name = 'Chat Completion Model';
93
- if (this.provider && this.provider in PROVIDER_TO_STEP_NAME) {
94
- name = PROVIDER_TO_STEP_NAME[this.provider] ?? 'Chat Completion Model';
95
- }
96
- addChatCompletionStepToTrace({
97
- name: name,
98
- inputs: { prompt: this.prompt },
99
- output: this.output,
100
- latency: this.latency,
101
- tokens: this.totalTokens,
102
- promptTokens: this.promptTokens,
103
- completionTokens: this.completionTokens,
104
- model: this.model,
105
- modelParameters: this.modelParameters,
106
- metadata: this.metadata,
107
- provider: this.provider ?? '',
108
- startTime: this.startTime,
109
- endTime: this.endTime,
387
+ let extractedModelName;
388
+ if (extraParams) {
389
+ const invocationParamsModelName = extraParams['invocation_params']?.model;
390
+ const metadataModelName = metadata && 'ls_model_name' in metadata ? metadata['ls_model_name'] : undefined;
391
+ extractedModelName = invocationParamsModelName ?? metadataModelName;
392
+ }
393
+ // Extract provider with multiple fallbacks
394
+ let provider = metadata?.['ls_provider'];
395
+ // Fallback provider detection if not in metadata
396
+ if (!provider) {
397
+ // Try to detect from model name
398
+ if (extractedModelName) {
399
+ if (extractedModelName.includes('gpt') || extractedModelName.includes('openai')) {
400
+ provider = 'openai';
401
+ }
402
+ else if (extractedModelName.includes('claude')) {
403
+ provider = 'anthropic';
404
+ }
405
+ else if (extractedModelName.includes('gemini') || extractedModelName.includes('google')) {
406
+ provider = 'google';
407
+ }
408
+ else if (extractedModelName.includes('llama') || extractedModelName.includes('meta')) {
409
+ provider = 'meta';
410
+ }
411
+ }
412
+ // Try to detect from LLM class name
413
+ if (!provider && llm.id && Array.isArray(llm.id)) {
414
+ const className = llm.id[0]?.toLowerCase() || '';
415
+ if (className.includes('openai') || className.includes('chatgpt')) {
416
+ provider = 'openai';
417
+ }
418
+ else if (className.includes('anthropic') || className.includes('claude')) {
419
+ provider = 'anthropic';
420
+ }
421
+ else if (className.includes('google') || className.includes('gemini')) {
422
+ provider = 'google';
423
+ }
424
+ }
425
+ }
426
+ const mappedProvider = provider && LANGCHAIN_TO_OPENLAYER_PROVIDER_MAP[provider] ?
427
+ LANGCHAIN_TO_OPENLAYER_PROVIDER_MAP[provider]
428
+ : 'Unknown';
429
+ // Get registered prompt if available
430
+ const registeredPrompt = this.promptToParentRunMap.get(parentRunId ?? 'root');
431
+ if (registeredPrompt && parentRunId) {
432
+ this.deregisterOpenlayerPrompt(parentRunId);
433
+ }
434
+ // Create step but don't end it yet - we'll update it in handleLLMEnd
435
+ const stepName = mappedProvider && PROVIDER_TO_STEP_NAME[mappedProvider] ?
436
+ PROVIDER_TO_STEP_NAME[mappedProvider]
437
+ : runName;
438
+ // For generations, we need to track the start time and other data to use in handleLLMEnd
439
+ const startTime = performance.now();
440
+ // Enhanced metadata collection
441
+ const enhancedMetadata = this.joinTagsAndMetaData(tags, metadata, {
442
+ // LangChain specific metadata
443
+ langchain_provider: provider,
444
+ langchain_model: extractedModelName,
445
+ langchain_run_id: runId,
446
+ langchain_parent_run_id: parentRunId,
447
+ // Invocation details
448
+ invocation_params: invocationParams,
449
+ // Timing
450
+ start_time: new Date().toISOString(),
451
+ // LLM info
452
+ llm_class: llm.id ?
453
+ Array.isArray(llm.id) ?
454
+ llm.id.join('.')
455
+ : llm.id
456
+ : 'unknown',
457
+ // Additional context
458
+ ...(Object.keys(modelParameters).length > 0 && { model_parameters: modelParameters }),
459
+ ...(extraParams && { extra_params: extraParams }),
460
+ });
461
+ this.runMap.set(runId, {
462
+ step: {
463
+ name: stepName,
464
+ inputs: { prompt: messages },
465
+ startTime,
466
+ provider: mappedProvider,
467
+ model: extractedModelName,
468
+ modelParameters,
469
+ metadata: enhancedMetadata,
470
+ prompt: registeredPrompt,
471
+ },
472
+ endStep: () => { }, // Will be replaced in handleLLMEnd
110
473
  });
111
474
  }
475
+ handleStepEnd(params) {
476
+ const { runId, output, rawOutput, error, modelName, usageDetails, completionStartTime } = params;
477
+ const runData = this.runMap.get(runId);
478
+ if (!runData) {
479
+ console.warn('Step not found in runMap. Skipping operation');
480
+ return;
481
+ }
482
+ const { step } = runData;
483
+ // Handle LLM/Generation steps specially
484
+ if (step.provider) {
485
+ const endTime = performance.now();
486
+ const latency = endTime - step.startTime;
487
+ addChatCompletionStepToTrace({
488
+ name: step.name || 'Unknown Generation',
489
+ inputs: step.inputs || {},
490
+ output: output || '',
491
+ latency,
492
+ tokens: usageDetails?.['total'] || null,
493
+ promptTokens: usageDetails?.['input'] || null,
494
+ completionTokens: usageDetails?.['output'] || null,
495
+ model: modelName || step.model || null,
496
+ modelParameters: step.modelParameters || null,
497
+ metadata: error ?
498
+ { ...step.metadata, error, rawOutput: rawOutput || null }
499
+ : { rawOutput: rawOutput || null, ...step.metadata },
500
+ provider: step.provider || 'Unknown',
501
+ });
502
+ }
503
+ else {
504
+ // For other step types, update and end the existing step
505
+ if (step.log) {
506
+ step.log({
507
+ output: output,
508
+ metadata: error ? { ...step.metadata, error } : step.metadata,
509
+ });
510
+ }
511
+ if (runData.endStep) {
512
+ runData.endStep();
513
+ }
514
+ }
515
+ this.runMap.delete(runId);
516
+ }
517
+ registerOpenlayerPrompt(parentRunId, metadata) {
518
+ if (metadata && 'openlayerPrompt' in metadata && parentRunId) {
519
+ this.promptToParentRunMap.set(parentRunId, metadata['openlayerPrompt']);
520
+ }
521
+ }
522
+ deregisterOpenlayerPrompt(runId) {
523
+ this.promptToParentRunMap.delete(runId);
524
+ }
525
+ parseAzureRefusalError(err) {
526
+ let azureRefusalError = '';
527
+ if (typeof err == 'object' && 'error' in err) {
528
+ try {
529
+ azureRefusalError = '\n\nError details:\n' + JSON.stringify(err['error'], null, 2);
530
+ }
531
+ catch { }
532
+ }
533
+ return azureRefusalError;
534
+ }
535
+ joinTagsAndMetaData(tags, metadata1, metadata2) {
536
+ const finalDict = {};
537
+ if (tags && tags.length > 0) {
538
+ finalDict['tags'] = tags;
539
+ }
540
+ if (metadata1) {
541
+ Object.assign(finalDict, metadata1);
542
+ }
543
+ if (metadata2) {
544
+ Object.assign(finalDict, metadata2);
545
+ }
546
+ return this.stripOpenlayerKeysFromMetadata(finalDict);
547
+ }
548
+ stripOpenlayerKeysFromMetadata(metadata) {
549
+ if (!metadata) {
550
+ return;
551
+ }
552
+ const openlayerKeys = ['openlayerPrompt', 'openlayerUserId', 'openlayerSessionId'];
553
+ return Object.fromEntries(Object.entries(metadata).filter(([key, _]) => !openlayerKeys.includes(key)));
554
+ }
555
+ extractUsageMetadata(generation) {
556
+ try {
557
+ const usageMetadata = ('message' in generation &&
558
+ (generation['message'] instanceof AIMessage || generation['message'] instanceof AIMessageChunk)) ?
559
+ generation['message'].usage_metadata
560
+ : undefined;
561
+ return usageMetadata;
562
+ }
563
+ catch (err) {
564
+ console.debug(`Error extracting usage metadata: ${err}`);
565
+ return;
566
+ }
567
+ }
568
+ extractModelNameFromMetadata(generation) {
569
+ try {
570
+ return ('message' in generation &&
571
+ (generation['message'] instanceof AIMessage || generation['message'] instanceof AIMessageChunk)) ?
572
+ generation['message'].response_metadata?.['model_name']
573
+ : undefined;
574
+ }
575
+ catch {
576
+ return undefined;
577
+ }
578
+ }
579
+ extractChatMessageContent(message) {
580
+ let response = undefined;
581
+ if (message instanceof HumanMessage) {
582
+ response = { content: message.content, role: 'user' };
583
+ }
584
+ else if (message instanceof ChatMessage) {
585
+ response = { content: message.content, role: message.role };
586
+ }
587
+ else if (message instanceof AIMessage) {
588
+ response = { content: message.content, role: 'assistant' };
589
+ if ('tool_calls' in message && (message.tool_calls?.length ?? 0) > 0) {
590
+ response['tool_calls'] = message['tool_calls'];
591
+ }
592
+ }
593
+ else if (message instanceof SystemMessage) {
594
+ response = { content: message.content, role: 'system' };
595
+ }
596
+ else if (message instanceof FunctionMessage) {
597
+ response = {
598
+ content: message.content,
599
+ additional_kwargs: message.additional_kwargs,
600
+ role: message.name,
601
+ };
602
+ }
603
+ else if (message instanceof ToolMessage) {
604
+ response = {
605
+ content: message.content,
606
+ additional_kwargs: message.additional_kwargs,
607
+ role: message.name,
608
+ };
609
+ }
610
+ else if (!message.name) {
611
+ response = { content: message.content };
612
+ }
613
+ else {
614
+ response = {
615
+ role: message.name,
616
+ content: message.content,
617
+ };
618
+ }
619
+ if (message.additional_kwargs?.function_call || message.additional_kwargs?.tool_calls) {
620
+ return { ...response, additional_kwargs: message.additional_kwargs };
621
+ }
622
+ return response;
623
+ }
112
624
  }
113
625
  //# sourceMappingURL=langchainCallback.mjs.map