-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
tracer_langchain_v1.ts
268 lines (244 loc) Β· 7.5 KB
/
tracer_langchain_v1.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import type { ChainValues } from "../utils/types.js";
import { type BaseMessage, getBufferString } from "../messages/index.js";
import type { LLMResult } from "../outputs.js";
import { getEnvironmentVariable } from "../utils/env.js";
import { BaseTracer, type RunType, type Run } from "./base.js";
export interface BaseRunV1 {
uuid: string;
parent_uuid?: string;
start_time: number;
end_time?: number;
execution_order: number;
child_execution_order: number;
serialized: { name: string };
session_id: number;
error?: string;
type: RunType;
}
export interface LLMRun extends BaseRunV1 {
prompts: string[];
response?: LLMResult;
}
export interface ChainRun extends BaseRunV1 {
inputs: ChainValues;
outputs?: ChainValues;
child_llm_runs: LLMRun[];
child_chain_runs: ChainRun[];
child_tool_runs: ToolRun[];
}
export interface ToolRun extends BaseRunV1 {
tool_input: string;
output?: string;
action: string;
child_llm_runs: LLMRun[];
child_chain_runs: ChainRun[];
child_tool_runs: ToolRun[];
}
export interface BaseTracerSession {
start_time: number;
name?: string;
}
export type TracerSessionCreate = BaseTracerSession;
export interface TracerSessionV1 extends BaseTracerSession {
id: number;
}
/** @deprecated Use LangChainTracer instead. */
export class LangChainTracerV1 extends BaseTracer {
name = "langchain_tracer";
protected endpoint =
getEnvironmentVariable("LANGCHAIN_ENDPOINT") || "http://localhost:1984";
protected headers: Record<string, string> = {
"Content-Type": "application/json",
};
protected session: TracerSessionV1;
constructor() {
super();
const apiKey = getEnvironmentVariable("LANGCHAIN_API_KEY");
if (apiKey) {
this.headers["x-api-key"] = apiKey;
}
}
async newSession(sessionName?: string): Promise<TracerSessionV1> {
const sessionCreate: TracerSessionCreate = {
start_time: Date.now(),
name: sessionName,
};
const session = await this.persistSession(sessionCreate);
this.session = session;
return session;
}
async loadSession(sessionName: string): Promise<TracerSessionV1> {
const endpoint = `${this.endpoint}/sessions?name=${sessionName}`;
return this._handleSessionResponse(endpoint);
}
async loadDefaultSession(): Promise<TracerSessionV1> {
const endpoint = `${this.endpoint}/sessions?name=default`;
return this._handleSessionResponse(endpoint);
}
protected async convertV2RunToRun(
run: Run
): Promise<LLMRun | ChainRun | ToolRun> {
const session = this.session ?? (await this.loadDefaultSession());
const serialized = run.serialized as { name: string };
let runResult: LLMRun | ChainRun | ToolRun;
if (run.run_type === "llm") {
const prompts: string[] = run.inputs.prompts
? run.inputs.prompts
: (run.inputs.messages as BaseMessage[][]).map((x) =>
getBufferString(x)
);
const llmRun: LLMRun = {
uuid: run.id,
start_time: run.start_time,
end_time: run.end_time,
execution_order: run.execution_order,
child_execution_order: run.child_execution_order,
serialized,
type: run.run_type,
session_id: session.id,
prompts,
response: run.outputs as LLMResult,
};
runResult = llmRun;
} else if (run.run_type === "chain") {
const child_runs = await Promise.all(
run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))
);
const chainRun: ChainRun = {
uuid: run.id,
start_time: run.start_time,
end_time: run.end_time,
execution_order: run.execution_order,
child_execution_order: run.child_execution_order,
serialized,
type: run.run_type,
session_id: session.id,
inputs: run.inputs,
outputs: run.outputs,
child_llm_runs: child_runs.filter(
(child_run) => child_run.type === "llm"
) as LLMRun[],
child_chain_runs: child_runs.filter(
(child_run) => child_run.type === "chain"
) as ChainRun[],
child_tool_runs: child_runs.filter(
(child_run) => child_run.type === "tool"
) as ToolRun[],
};
runResult = chainRun;
} else if (run.run_type === "tool") {
const child_runs = await Promise.all(
run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))
);
const toolRun: ToolRun = {
uuid: run.id,
start_time: run.start_time,
end_time: run.end_time,
execution_order: run.execution_order,
child_execution_order: run.child_execution_order,
serialized,
type: run.run_type,
session_id: session.id,
tool_input: run.inputs.input,
output: run.outputs?.output,
action: JSON.stringify(serialized),
child_llm_runs: child_runs.filter(
(child_run) => child_run.type === "llm"
) as LLMRun[],
child_chain_runs: child_runs.filter(
(child_run) => child_run.type === "chain"
) as ChainRun[],
child_tool_runs: child_runs.filter(
(child_run) => child_run.type === "tool"
) as ToolRun[],
};
runResult = toolRun;
} else {
throw new Error(`Unknown run type: ${run.run_type}`);
}
return runResult;
}
protected async persistRun(
run: Run | LLMRun | ChainRun | ToolRun
): Promise<void> {
let endpoint;
let v1Run: LLMRun | ChainRun | ToolRun;
if ((run as Run).run_type !== undefined) {
v1Run = await this.convertV2RunToRun(run as Run);
} else {
v1Run = run as LLMRun | ChainRun | ToolRun;
}
if (v1Run.type === "llm") {
endpoint = `${this.endpoint}/llm-runs`;
} else if (v1Run.type === "chain") {
endpoint = `${this.endpoint}/chain-runs`;
} else {
endpoint = `${this.endpoint}/tool-runs`;
}
const response = await fetch(endpoint, {
method: "POST",
headers: this.headers,
body: JSON.stringify(v1Run),
});
if (!response.ok) {
console.error(
`Failed to persist run: ${response.status} ${response.statusText}`
);
}
}
protected async persistSession(
sessionCreate: BaseTracerSession
): Promise<TracerSessionV1> {
const endpoint = `${this.endpoint}/sessions`;
const response = await fetch(endpoint, {
method: "POST",
headers: this.headers,
body: JSON.stringify(sessionCreate),
});
if (!response.ok) {
console.error(
`Failed to persist session: ${response.status} ${response.statusText}, using default session.`
);
return {
id: 1,
...sessionCreate,
};
}
return {
id: (await response.json()).id,
...sessionCreate,
};
}
protected async _handleSessionResponse(
endpoint: string
): Promise<TracerSessionV1> {
const response = await fetch(endpoint, {
method: "GET",
headers: this.headers,
});
let tracerSession: TracerSessionV1;
if (!response.ok) {
console.error(
`Failed to load session: ${response.status} ${response.statusText}`
);
tracerSession = {
id: 1,
start_time: Date.now(),
};
this.session = tracerSession;
return tracerSession;
}
const resp = (await response.json()) as TracerSessionV1[];
if (resp.length === 0) {
tracerSession = {
id: 1,
start_time: Date.now(),
};
this.session = tracerSession;
return tracerSession;
}
[tracerSession] = resp;
this.session = tracerSession;
return tracerSession;
}
}