-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
index.ts
343 lines (320 loc) Β· 9.62 KB
/
index.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import { type ClientOptions, OpenAIClient } from "@langchain/openai";
import { StructuredTool } from "@langchain/core/tools";
import { Runnable, RunnableConfig } from "@langchain/core/runnables";
import { formatToOpenAIAssistantTool } from "@langchain/openai";
import { sleep } from "../../util/time.js";
import type {
OpenAIAssistantFinish,
OpenAIAssistantAction,
OpenAIToolType,
} from "./schema.js";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ThreadMessage = any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type RequiredActionFunctionToolCall = any;
type ExtractRunOutput<AsAgent extends boolean | undefined> =
AsAgent extends true
? OpenAIAssistantFinish | OpenAIAssistantAction[]
: ThreadMessage[] | RequiredActionFunctionToolCall[];
export type OpenAIAssistantRunnableInput<
AsAgent extends boolean | undefined = undefined
> = {
client?: OpenAIClient;
clientOptions?: ClientOptions;
assistantId: string;
pollIntervalMs?: number;
asAgent?: AsAgent;
};
export class OpenAIAssistantRunnable<
AsAgent extends boolean | undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
RunInput extends Record<string, any> = Record<string, any>
> extends Runnable<RunInput, ExtractRunOutput<AsAgent>> {
lc_namespace = ["langchain", "experimental", "openai_assistant"];
private client: OpenAIClient;
assistantId: string;
pollIntervalMs = 1000;
asAgent?: AsAgent;
constructor(fields: OpenAIAssistantRunnableInput<AsAgent>) {
super(fields);
this.client = fields.client ?? new OpenAIClient(fields?.clientOptions);
this.assistantId = fields.assistantId;
this.asAgent = fields.asAgent ?? this.asAgent;
}
static async createAssistant<AsAgent extends boolean>({
model,
name,
instructions,
tools,
client,
clientOptions,
asAgent,
pollIntervalMs,
fileIds,
}: Omit<OpenAIAssistantRunnableInput<AsAgent>, "assistantId"> & {
model: string;
name?: string;
instructions?: string;
tools?: OpenAIToolType | Array<StructuredTool>;
fileIds?: string[];
}) {
const formattedTools =
tools?.map((tool) => {
// eslint-disable-next-line no-instanceof/no-instanceof
if (tool instanceof StructuredTool) {
return formatToOpenAIAssistantTool(tool);
}
return tool;
}) ?? [];
const oaiClient = client ?? new OpenAIClient(clientOptions);
const assistant = await oaiClient.beta.assistants.create({
name,
instructions,
tools: formattedTools,
model,
file_ids: fileIds,
});
return new this({
client: oaiClient,
assistantId: assistant.id,
asAgent,
pollIntervalMs,
});
}
async invoke(
input: RunInput,
_options?: RunnableConfig
): Promise<ExtractRunOutput<AsAgent>> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let run: any;
if (this.asAgent && input.steps && input.steps.length > 0) {
const parsedStepsInput = await this._parseStepsInput(input);
run = await this.client.beta.threads.runs.submitToolOutputs(
parsedStepsInput.threadId,
parsedStepsInput.runId,
{
tool_outputs: parsedStepsInput.toolOutputs,
}
);
} else if (!("threadId" in input)) {
const thread = {
messages: [
{
role: "user",
content: input.content,
file_ids: input.fileIds,
metadata: input.messagesMetadata,
},
],
metadata: input.threadMetadata,
};
run = await this._createThreadAndRun({
...input,
thread,
});
} else if (!("runId" in input)) {
await this.client.beta.threads.messages.create(input.threadId, {
content: input.content,
role: "user",
file_ids: input.file_ids,
metadata: input.messagesMetadata,
});
run = await this._createRun(input);
} else {
// Submitting tool outputs to an existing run, outside the AgentExecutor
// framework.
run = await this.client.beta.threads.runs.submitToolOutputs(
input.threadId,
input.runId,
{
tool_outputs: input.toolOutputs,
}
);
}
return this._getResponse(run.id, run.thread_id);
}
/**
* Delete an assistant.
*
* @link {https://platform.openai.com/docs/api-reference/assistants/deleteAssistant}
* @returns {Promise<AssistantDeleted>}
*/
public async deleteAssistant() {
return await this.client.beta.assistants.del(this.assistantId);
}
/**
* Retrieves an assistant.
*
* @link {https://platform.openai.com/docs/api-reference/assistants/getAssistant}
* @returns {Promise<OpenAIClient.Beta.Assistants.Assistant>}
*/
public async getAssistant() {
return await this.client.beta.assistants.retrieve(this.assistantId);
}
/**
* Modifies an assistant.
*
* @link {https://platform.openai.com/docs/api-reference/assistants/modifyAssistant}
* @returns {Promise<OpenAIClient.Beta.Assistants.Assistant>}
*/
public async modifyAssistant<AsAgent extends boolean>({
model,
name,
instructions,
fileIds,
}: Omit<OpenAIAssistantRunnableInput<AsAgent>, "assistantId" | "tools"> & {
model?: string;
name?: string;
instructions?: string;
fileIds?: string[];
}) {
return await this.client.beta.assistants.update(this.assistantId, {
name,
instructions,
model,
file_ids: fileIds,
});
}
private async _parseStepsInput(input: RunInput): Promise<RunInput> {
const {
action: { runId, threadId },
} = input.steps[input.steps.length - 1];
const run = await this._waitForRun(runId, threadId);
const toolCalls = run.required_action?.submit_tool_outputs.tool_calls;
if (!toolCalls) {
return input;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const toolOutputs = toolCalls.flatMap((toolCall: any) => {
const matchedAction = (
input.steps as {
action: OpenAIAssistantAction;
observation: string;
}[]
).find((step) => step.action.toolCallId === toolCall.id);
return matchedAction
? [
{
output: matchedAction.observation,
tool_call_id: matchedAction.action.toolCallId,
},
]
: [];
});
return { toolOutputs, runId, threadId } as unknown as RunInput;
}
private async _createRun({
instructions,
model,
tools,
metadata,
threadId,
}: RunInput) {
const run = this.client.beta.threads.runs.create(threadId, {
assistant_id: this.assistantId,
instructions,
model,
tools,
metadata,
});
return run;
}
private async _createThreadAndRun(input: RunInput) {
const params: Record<string, unknown> = [
"instructions",
"model",
"tools",
"run_metadata",
]
.filter((key) => key in input)
.reduce((obj, key) => {
const newObj = obj;
newObj[key] = input[key];
return newObj;
}, {} as Record<string, unknown>);
const run = this.client.beta.threads.createAndRun({
...params,
thread: input.thread,
assistant_id: this.assistantId,
});
return run;
}
private async _waitForRun(runId: string, threadId: string) {
let inProgress = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let run = {} as any;
while (inProgress) {
run = await this.client.beta.threads.runs.retrieve(threadId, runId);
inProgress = ["in_progress", "queued"].includes(run.status);
if (inProgress) {
await sleep(this.pollIntervalMs);
}
}
return run;
}
private async _getResponse(
runId: string,
threadId: string
): Promise<ExtractRunOutput<AsAgent>>;
private async _getResponse(
runId: string,
threadId: string
): Promise<
| OpenAIAssistantFinish
| OpenAIAssistantAction[]
| ThreadMessage[]
| RequiredActionFunctionToolCall[]
> {
const run = await this._waitForRun(runId, threadId);
if (run.status === "completed") {
const messages = await this.client.beta.threads.messages.list(threadId, {
order: "desc",
});
const newMessages = messages.data.filter((msg) => msg.run_id === runId);
if (!this.asAgent) {
return newMessages;
}
const answer = newMessages.flatMap((msg) => msg.content);
if (answer.every((item) => item.type === "text")) {
const answerString = answer
.map((item) => item.type === "text" && item.text.value)
.join("\n");
return {
returnValues: {
output: answerString,
runId,
threadId,
},
log: "",
runId,
threadId,
};
}
} else if (run.status === "requires_action") {
if (!this.asAgent) {
return run.required_action?.submit_tool_outputs.tool_calls ?? [];
}
const actions: OpenAIAssistantAction[] = [];
run.required_action?.submit_tool_outputs.tool_calls.forEach(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(item: any) => {
const functionCall = item.function;
const args = JSON.parse(functionCall.arguments);
actions.push({
tool: functionCall.name,
toolInput: args,
toolCallId: item.id,
log: "",
runId,
threadId,
});
}
);
return actions;
}
const runInfo = JSON.stringify(run, null, 2);
throw new Error(
`Unexpected run status ${run.status}.\nFull run info:\n\n${runInfo}`
);
}
}