openlayer 0.16.2 → 0.17.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/CHANGELOG.md +39 -0
- package/_shims/bun-runtime.js +1 -2
- package/_shims/bun-runtime.js.map +1 -1
- package/_shims/node-runtime.js +18 -9
- package/_shims/node-runtime.js.map +1 -1
- package/_shims/node-runtime.mjs.map +1 -1
- package/_shims/registry.js +2 -2
- package/_shims/registry.js.map +1 -1
- package/_shims/registry.mjs.map +1 -1
- package/_shims/web-runtime.js +1 -2
- package/_shims/web-runtime.js.map +1 -1
- package/_shims/web-runtime.mjs.map +1 -1
- package/core.d.ts +2 -4
- package/core.d.ts.map +1 -1
- package/core.js +9 -9
- package/core.js.map +1 -1
- package/core.mjs +4 -4
- package/core.mjs.map +1 -1
- package/error.js.map +1 -1
- package/error.mjs.map +1 -1
- package/index.js +17 -7
- package/index.js.map +1 -1
- package/index.mjs.map +1 -1
- package/internal/qs/stringify.js +1 -2
- package/internal/qs/stringify.js.map +1 -1
- package/internal/qs/stringify.mjs.map +1 -1
- package/internal/qs/utils.js +9 -9
- package/internal/qs/utils.js.map +1 -1
- package/internal/qs/utils.mjs.map +1 -1
- package/lib/core/cli.js +17 -7
- package/lib/core/cli.js.map +1 -1
- package/lib/core/cli.mjs.map +1 -1
- package/lib/core/openai-monitor.d.ts.map +1 -1
- package/lib/core/openai-monitor.js +1 -1
- package/lib/core/openai-monitor.js.map +1 -1
- package/lib/core/openai-monitor.mjs +1 -1
- package/lib/core/openai-monitor.mjs.map +1 -1
- package/lib/integrations/bedrockAgentTracer.js +49 -50
- package/lib/integrations/bedrockAgentTracer.js.map +1 -1
- package/lib/integrations/bedrockAgentTracer.mjs +48 -48
- package/lib/integrations/bedrockAgentTracer.mjs.map +1 -1
- package/lib/integrations/index.d.ts +5 -0
- package/lib/integrations/index.d.ts.map +1 -0
- package/lib/integrations/index.js +21 -0
- package/lib/integrations/index.js.map +1 -0
- package/lib/integrations/index.mjs +5 -0
- package/lib/integrations/index.mjs.map +1 -0
- package/lib/integrations/langchainCallback.d.ts +83 -27
- package/lib/integrations/langchainCallback.d.ts.map +1 -1
- package/lib/integrations/langchainCallback.js +597 -88
- package/lib/integrations/langchainCallback.js.map +1 -1
- package/lib/integrations/langchainCallback.mjs +599 -87
- package/lib/integrations/langchainCallback.mjs.map +1 -1
- package/lib/integrations/openAiTracer.js +1 -2
- package/lib/integrations/openAiTracer.js.map +1 -1
- package/lib/integrations/openAiTracer.mjs.map +1 -1
- package/lib/integrations/tracedTool.d.ts +66 -0
- package/lib/integrations/tracedTool.d.ts.map +1 -0
- package/lib/integrations/tracedTool.js +186 -0
- package/lib/integrations/tracedTool.js.map +1 -0
- package/lib/integrations/tracedTool.mjs +149 -0
- package/lib/integrations/tracedTool.mjs.map +1 -0
- package/lib/tracing/steps.d.ts +120 -1
- package/lib/tracing/steps.d.ts.map +1 -1
- package/lib/tracing/steps.js +128 -4
- package/lib/tracing/steps.js.map +1 -1
- package/lib/tracing/steps.mjs +119 -1
- package/lib/tracing/steps.mjs.map +1 -1
- package/lib/tracing/tracer.d.ts +69 -1
- package/lib/tracing/tracer.d.ts.map +1 -1
- package/lib/tracing/tracer.js +92 -18
- package/lib/tracing/tracer.js.map +1 -1
- package/lib/tracing/tracer.mjs +78 -10
- package/lib/tracing/tracer.mjs.map +1 -1
- package/package.json +3 -1
- package/resources/commits/commits.js +17 -7
- package/resources/commits/commits.js.map +1 -1
- package/resources/commits/test-results.js.map +1 -1
- package/resources/commits/test-results.mjs.map +1 -1
- package/resources/inference-pipelines/data.d.ts +8 -0
- package/resources/inference-pipelines/data.d.ts.map +1 -1
- package/resources/inference-pipelines/inference-pipelines.js +17 -7
- package/resources/inference-pipelines/inference-pipelines.js.map +1 -1
- package/resources/inference-pipelines/inference-pipelines.mjs.map +1 -1
- package/resources/inference-pipelines/test-results.js.map +1 -1
- package/resources/inference-pipelines/test-results.mjs.map +1 -1
- package/resources/projects/commits.js.map +1 -1
- package/resources/projects/commits.mjs.map +1 -1
- package/resources/projects/inference-pipelines.js.map +1 -1
- package/resources/projects/inference-pipelines.mjs.map +1 -1
- package/resources/projects/projects.js +17 -7
- package/resources/projects/projects.js.map +1 -1
- package/resources/projects/projects.mjs.map +1 -1
- package/resources/projects/tests.js.map +1 -1
- package/resources/projects/tests.mjs.map +1 -1
- package/resources/storage/storage.js +17 -7
- package/resources/storage/storage.js.map +1 -1
- package/shims/node.d.ts +0 -4
- package/shims/node.d.ts.map +1 -1
- package/shims/node.js +0 -25
- package/shims/node.js.map +1 -1
- package/shims/node.mjs +0 -1
- package/shims/node.mjs.map +1 -1
- package/shims/web.js +0 -25
- package/shims/web.js.map +1 -1
- package/shims/web.mjs +0 -1
- package/shims/web.mjs.map +1 -1
- package/src/core.ts +4 -4
- package/src/lib/core/openai-monitor.ts +1 -1
- package/src/lib/integrations/index.ts +4 -0
- package/src/lib/integrations/langchainCallback.ts +802 -88
- package/src/lib/integrations/tracedTool.ts +175 -0
- package/src/lib/tracing/index.d.ts +10 -0
- package/src/lib/tracing/steps.ts +218 -5
- package/src/lib/tracing/tracer.ts +153 -9
- package/src/resources/inference-pipelines/data.ts +10 -0
- package/src/uploads.ts +3 -2
- package/src/version.ts +1 -1
- package/uploads.d.ts +2 -2
- package/uploads.d.ts.map +1 -1
- package/uploads.js +3 -4
- package/uploads.js.map +1 -1
- package/uploads.mjs +1 -2
- package/uploads.mjs.map +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
- package/lib/tracing/enums.d.ts +0 -5
- package/lib/tracing/enums.d.ts.map +0 -1
- package/lib/tracing/enums.js +0 -9
- package/lib/tracing/enums.js.map +0 -1
- package/lib/tracing/enums.mjs +0 -6
- package/lib/tracing/enums.mjs.map +0 -1
- 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
|
|
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(
|
|
51
|
+
constructor(params) {
|
|
18
52
|
super();
|
|
19
53
|
this.name = 'OpenlayerHandler';
|
|
20
|
-
this.
|
|
21
|
-
this.
|
|
22
|
-
this.
|
|
23
|
-
this.
|
|
24
|
-
this.
|
|
25
|
-
this.
|
|
26
|
-
this.
|
|
27
|
-
this.
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
54
|
-
|
|
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
|
-
|
|
57
|
-
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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
|