@copilotkit/runtime 1.3.16-mme-improve-langsmith.0 → 1.4.0-pre-1-4-0.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 +6 -3
- package/dist/{chunk-QJB3CIHI.mjs → chunk-3SXVSM2J.mjs} +2 -2
- package/dist/{chunk-YGFQK4XG.mjs → chunk-5DFP5VJV.mjs} +2 -2
- package/dist/{chunk-TD3UMHBH.mjs → chunk-5LEQEQFA.mjs} +689 -151
- package/dist/chunk-5LEQEQFA.mjs.map +1 -0
- package/dist/{chunk-MYZHUCL6.mjs → chunk-B74M7FXG.mjs} +1 -1
- package/dist/chunk-B74M7FXG.mjs.map +1 -0
- package/dist/{chunk-KCW3B5UA.mjs → chunk-KDT43TMW.mjs} +37 -10
- package/dist/chunk-KDT43TMW.mjs.map +1 -0
- package/dist/{chunk-E75MOZGE.mjs → chunk-SBNW3ABC.mjs} +2 -2
- package/dist/{chunk-UHFZPBA5.mjs → chunk-VGYN7TGZ.mjs} +5 -10
- package/dist/chunk-VGYN7TGZ.mjs.map +1 -0
- package/dist/{copilot-runtime-df3527ad.d.ts → copilot-runtime-68acb673.d.ts} +29 -7
- package/dist/graphql/types/converted/index.d.ts +1 -1
- package/dist/graphql/types/converted/index.js.map +1 -1
- package/dist/graphql/types/converted/index.mjs +1 -1
- package/dist/{groq-adapter-b122e71f.d.ts → groq-adapter-c30654bd.d.ts} +4 -2
- package/dist/{index-cff31380.d.ts → index-439dfa2a.d.ts} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +765 -205
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13 -9
- package/dist/index.mjs.map +1 -1
- package/dist/{langserve-a14a6849.d.ts → langserve-0d844922.d.ts} +1 -1
- package/dist/lib/index.d.ts +4 -4
- package/dist/lib/index.js +765 -205
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +13 -9
- package/dist/lib/integrations/index.d.ts +4 -4
- package/dist/lib/integrations/index.js +3 -1
- package/dist/lib/integrations/index.js.map +1 -1
- package/dist/lib/integrations/index.mjs +5 -5
- package/dist/lib/integrations/nest/index.d.ts +3 -3
- package/dist/lib/integrations/nest/index.js +3 -1
- package/dist/lib/integrations/nest/index.js.map +1 -1
- package/dist/lib/integrations/nest/index.mjs +3 -3
- package/dist/lib/integrations/node-express/index.d.ts +3 -3
- package/dist/lib/integrations/node-express/index.js +3 -1
- package/dist/lib/integrations/node-express/index.js.map +1 -1
- package/dist/lib/integrations/node-express/index.mjs +3 -3
- package/dist/lib/integrations/node-http/index.d.ts +3 -3
- package/dist/lib/integrations/node-http/index.js +3 -1
- package/dist/lib/integrations/node-http/index.js.map +1 -1
- package/dist/lib/integrations/node-http/index.mjs +2 -2
- package/dist/service-adapters/index.d.ts +4 -4
- package/dist/service-adapters/index.js +4 -9
- package/dist/service-adapters/index.js.map +1 -1
- package/dist/service-adapters/index.mjs +1 -1
- package/package.json +6 -4
- package/src/agents/langgraph/event-source.ts +62 -94
- package/src/agents/langgraph/events.ts +26 -17
- package/src/graphql/types/converted/index.ts +5 -1
- package/src/lib/runtime/copilot-runtime.ts +58 -11
- package/src/lib/runtime/remote-action-constructors.ts +284 -0
- package/src/lib/runtime/remote-actions.ts +65 -159
- package/src/lib/runtime/remote-lg-cloud-action.ts +624 -0
- package/src/service-adapters/google/google-genai-adapter.ts +2 -2
- package/src/service-adapters/langchain/langchain-adapter.ts +5 -4
- package/dist/chunk-KCW3B5UA.mjs.map +0 -1
- package/dist/chunk-MYZHUCL6.mjs.map +0 -1
- package/dist/chunk-TD3UMHBH.mjs.map +0 -1
- package/dist/chunk-UHFZPBA5.mjs.map +0 -1
- /package/dist/{chunk-QJB3CIHI.mjs.map → chunk-3SXVSM2J.mjs.map} +0 -0
- /package/dist/{chunk-YGFQK4XG.mjs.map → chunk-5DFP5VJV.mjs.map} +0 -0
- /package/dist/{chunk-E75MOZGE.mjs.map → chunk-SBNW3ABC.mjs.map} +0 -0
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
import { Client } from "@langchain/langgraph-sdk";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { parse as parsePartialJson } from "partial-json";
|
|
4
|
+
import { Logger } from "pino";
|
|
5
|
+
import { ActionInput } from "../../graphql/inputs/action.input";
|
|
6
|
+
import { LangGraphCloudAgent, LangGraphCloudEndpoint } from "./remote-actions";
|
|
7
|
+
import { CopilotRequestContextProperties } from "../integrations";
|
|
8
|
+
import { Message, MessageType } from "../../graphql/types/converted";
|
|
9
|
+
import { MessageRole } from "../../graphql/types/enums";
|
|
10
|
+
|
|
11
|
+
type State = Record<string, any>;
|
|
12
|
+
|
|
13
|
+
type ExecutionAction = Pick<ActionInput, "name" | "description"> & { parameters: string };
|
|
14
|
+
|
|
15
|
+
interface ExecutionArgs extends Omit<LangGraphCloudEndpoint, "agents"> {
|
|
16
|
+
agent: LangGraphCloudAgent;
|
|
17
|
+
threadId: string;
|
|
18
|
+
nodeName: string;
|
|
19
|
+
messages: Message[];
|
|
20
|
+
state: State;
|
|
21
|
+
properties: CopilotRequestContextProperties;
|
|
22
|
+
actions: ExecutionAction[];
|
|
23
|
+
logger: Logger;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The following types are our own definition to the messages accepted by LangGraph cloud, enhanced with some of our extra data.
|
|
27
|
+
interface ToolCall {
|
|
28
|
+
id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
args: Record<string, unknown>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type BaseLangGraphCloudMessage = Omit<
|
|
34
|
+
Message,
|
|
35
|
+
| "isResultMessage"
|
|
36
|
+
| "isTextMessage"
|
|
37
|
+
| "isActionExecutionMessage"
|
|
38
|
+
| "isAgentStateMessage"
|
|
39
|
+
| "type"
|
|
40
|
+
| "createdAt"
|
|
41
|
+
> & {
|
|
42
|
+
content: string;
|
|
43
|
+
role: MessageRole;
|
|
44
|
+
additional_kwargs?: Record<string, unknown>;
|
|
45
|
+
type: MessageType;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
interface LangGraphCloudResultMessage extends BaseLangGraphCloudMessage {
|
|
49
|
+
tool_call_id: string;
|
|
50
|
+
name: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface LangGraphCloudActionExecutionMessage extends BaseLangGraphCloudMessage {
|
|
54
|
+
tool_calls: ToolCall[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type LangGraphCloudMessage =
|
|
58
|
+
| LangGraphCloudActionExecutionMessage
|
|
59
|
+
| LangGraphCloudResultMessage
|
|
60
|
+
| BaseLangGraphCloudMessage;
|
|
61
|
+
|
|
62
|
+
export async function execute(args: ExecutionArgs): Promise<ReadableStream<Uint8Array>> {
|
|
63
|
+
return new ReadableStream({
|
|
64
|
+
async start(controller) {
|
|
65
|
+
try {
|
|
66
|
+
await streamEvents(controller, args);
|
|
67
|
+
controller.close();
|
|
68
|
+
} catch (err) {}
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function streamEvents(controller: ReadableStreamDefaultController, args: ExecutionArgs) {
|
|
74
|
+
const {
|
|
75
|
+
deploymentUrl,
|
|
76
|
+
langsmithApiKey,
|
|
77
|
+
threadId: agrsInitialThreadId,
|
|
78
|
+
agent,
|
|
79
|
+
nodeName: initialNodeName,
|
|
80
|
+
state: initialState,
|
|
81
|
+
messages,
|
|
82
|
+
actions,
|
|
83
|
+
logger,
|
|
84
|
+
} = args;
|
|
85
|
+
|
|
86
|
+
let nodeName = initialNodeName;
|
|
87
|
+
let state = initialState;
|
|
88
|
+
const { name, assistantId: initialAssistantId } = agent;
|
|
89
|
+
|
|
90
|
+
// TODO: deploymentUrl is not required in local development
|
|
91
|
+
const client = new Client({ apiUrl: deploymentUrl, apiKey: langsmithApiKey });
|
|
92
|
+
let initialThreadId = agrsInitialThreadId;
|
|
93
|
+
const wasInitiatedWithExistingThread = !!initialThreadId;
|
|
94
|
+
if (initialThreadId && initialThreadId.startsWith("ck-")) {
|
|
95
|
+
initialThreadId = initialThreadId.substring(3);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const assistants = await client.assistants.search();
|
|
99
|
+
const retrievedAssistant = assistants.find((a) => a.name === name);
|
|
100
|
+
const threadId = initialThreadId ?? randomUUID();
|
|
101
|
+
if (initialThreadId === threadId) {
|
|
102
|
+
await client.threads.get(threadId);
|
|
103
|
+
} else {
|
|
104
|
+
await client.threads.create({ threadId: threadId });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
let agentState = { values: {} };
|
|
108
|
+
if (wasInitiatedWithExistingThread) {
|
|
109
|
+
agentState = await client.threads.getState(threadId);
|
|
110
|
+
}
|
|
111
|
+
const agentStateValues = agentState.values as State;
|
|
112
|
+
state.messages = agentStateValues.messages;
|
|
113
|
+
const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
|
|
114
|
+
state = langGraphDefaultMergeState(state, formatMessages(messages), actions, name);
|
|
115
|
+
|
|
116
|
+
if (mode === "continue") {
|
|
117
|
+
await client.threads.updateState(threadId, { values: state, asNode: nodeName });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const assistantId = initialAssistantId ?? retrievedAssistant?.assistant_id;
|
|
121
|
+
if (!assistantId) {
|
|
122
|
+
console.error(`
|
|
123
|
+
No agent found for the agent name specified in CopilotKit provider
|
|
124
|
+
Please check your available agents or provide an agent ID in the LangGraph Cloud endpoint definition.\n
|
|
125
|
+
|
|
126
|
+
These are the available agents: [${assistants.map((a) => `${a.name} (ID: ${a.assistant_id})`).join(", ")}]
|
|
127
|
+
`);
|
|
128
|
+
throw new Error("No agent id found");
|
|
129
|
+
}
|
|
130
|
+
const graphInfo = await client.assistants.getGraph(assistantId);
|
|
131
|
+
const streamInput = mode === "start" ? state : null;
|
|
132
|
+
|
|
133
|
+
let streamingStateExtractor = new StreamingStateExtractor([]);
|
|
134
|
+
let prevNodeName = null;
|
|
135
|
+
let emitIntermediateStateUntilEnd = null;
|
|
136
|
+
let shouldExit = null;
|
|
137
|
+
let externalRunId = null;
|
|
138
|
+
|
|
139
|
+
const streamResponse = client.runs.stream(threadId, assistantId, {
|
|
140
|
+
input: streamInput,
|
|
141
|
+
streamMode: ["events", "values"],
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const emit = (message: string) => controller.enqueue(new TextEncoder().encode(message));
|
|
145
|
+
|
|
146
|
+
let latestStateValues = {};
|
|
147
|
+
|
|
148
|
+
for await (const chunk of streamResponse) {
|
|
149
|
+
if (!["events", "values", "error"].includes(chunk.event)) continue;
|
|
150
|
+
|
|
151
|
+
if (chunk.event === "error") {
|
|
152
|
+
logger.error(chunk, `Error event thrown: ${chunk.data.message}`);
|
|
153
|
+
throw new Error(`Error event thrown: ${chunk.data.message}`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (chunk.event === "values") {
|
|
157
|
+
latestStateValues = chunk.data;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const event = chunk.data;
|
|
162
|
+
const currentNodeName = event.name;
|
|
163
|
+
const eventType = event.event;
|
|
164
|
+
const runId = event.metadata.run_id;
|
|
165
|
+
externalRunId = runId;
|
|
166
|
+
const metadata = event.metadata;
|
|
167
|
+
|
|
168
|
+
shouldExit = shouldExit != null ? shouldExit : metadata["copilotkit:exit"];
|
|
169
|
+
const emitIntermediateState = metadata["copilotkit:emit-intermediate-state"];
|
|
170
|
+
const forceEmitIntermediateState = metadata["copilotkit:force-emit-intermediate-state"];
|
|
171
|
+
const manuallyEmitMessage = metadata["copilotkit:manually-emit-messages"];
|
|
172
|
+
const manuallyEmitToolCall = metadata["copilotkit:manually-emit-tool-calls"];
|
|
173
|
+
// we only want to update the node name under certain conditions
|
|
174
|
+
// since we don't need any internal node names to be sent to the frontend
|
|
175
|
+
if (graphInfo["nodes"].some((node) => node.id === currentNodeName)) {
|
|
176
|
+
nodeName = currentNodeName;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (!nodeName) {
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (forceEmitIntermediateState) {
|
|
184
|
+
if (eventType === "on_chain_end") {
|
|
185
|
+
state = event.data.output;
|
|
186
|
+
emit(
|
|
187
|
+
getStateSyncEvent({
|
|
188
|
+
threadId,
|
|
189
|
+
runId,
|
|
190
|
+
agentName: agent.name,
|
|
191
|
+
nodeName,
|
|
192
|
+
state: event.data.output,
|
|
193
|
+
running: true,
|
|
194
|
+
active: true,
|
|
195
|
+
}),
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (manuallyEmitMessage) {
|
|
202
|
+
if (eventType === "on_chain_end") {
|
|
203
|
+
state = event.data.output;
|
|
204
|
+
emit(
|
|
205
|
+
JSON.stringify({
|
|
206
|
+
event: "on_copilotkit_emit_message",
|
|
207
|
+
message: event.data.output,
|
|
208
|
+
messageId: randomUUID(),
|
|
209
|
+
role: MessageRole.assistant,
|
|
210
|
+
}) + "\n",
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (manuallyEmitToolCall) {
|
|
217
|
+
if (eventType === "on_chain_end") {
|
|
218
|
+
state = event.data.output;
|
|
219
|
+
emit(
|
|
220
|
+
JSON.stringify({
|
|
221
|
+
event: "on_copilotkit_emit_tool_call",
|
|
222
|
+
name: event.data.output.name,
|
|
223
|
+
args: event.data.output.args,
|
|
224
|
+
id: event.data.output.id,
|
|
225
|
+
}) + "\n",
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (emitIntermediateState && emitIntermediateStateUntilEnd == null) {
|
|
232
|
+
emitIntermediateStateUntilEnd = nodeName;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (emitIntermediateState && eventType === "on_chat_model_start") {
|
|
236
|
+
// reset the streaming state extractor
|
|
237
|
+
streamingStateExtractor = new StreamingStateExtractor(emitIntermediateState);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
let updatedState = latestStateValues;
|
|
241
|
+
|
|
242
|
+
if (emitIntermediateState && eventType === "on_chat_model_stream") {
|
|
243
|
+
streamingStateExtractor.bufferToolCalls(event);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (emitIntermediateStateUntilEnd !== null) {
|
|
247
|
+
updatedState = {
|
|
248
|
+
...updatedState,
|
|
249
|
+
...streamingStateExtractor.extractState(),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (
|
|
254
|
+
!emitIntermediateState &&
|
|
255
|
+
currentNodeName === emitIntermediateStateUntilEnd &&
|
|
256
|
+
eventType === "on_chain_end"
|
|
257
|
+
) {
|
|
258
|
+
// stop emitting function call state
|
|
259
|
+
emitIntermediateStateUntilEnd = null;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const exitingNode = nodeName === currentNodeName && eventType === "on_chain_end";
|
|
263
|
+
|
|
264
|
+
if (
|
|
265
|
+
JSON.stringify(updatedState) !== JSON.stringify(state) ||
|
|
266
|
+
prevNodeName != nodeName ||
|
|
267
|
+
exitingNode
|
|
268
|
+
) {
|
|
269
|
+
state = updatedState;
|
|
270
|
+
prevNodeName = nodeName;
|
|
271
|
+
emit(
|
|
272
|
+
getStateSyncEvent({
|
|
273
|
+
threadId,
|
|
274
|
+
runId,
|
|
275
|
+
agentName: agent.name,
|
|
276
|
+
nodeName,
|
|
277
|
+
state,
|
|
278
|
+
running: true,
|
|
279
|
+
active: !exitingNode,
|
|
280
|
+
}),
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
emit(JSON.stringify(event) + "\n");
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
state = await client.threads.getState(threadId);
|
|
288
|
+
const isEndNode = state.next.length === 0;
|
|
289
|
+
nodeName = Object.keys(state.metadata.writes)[0];
|
|
290
|
+
|
|
291
|
+
emit(
|
|
292
|
+
getStateSyncEvent({
|
|
293
|
+
threadId,
|
|
294
|
+
runId: externalRunId,
|
|
295
|
+
agentName: agent.name,
|
|
296
|
+
nodeName: isEndNode ? "__end__" : nodeName,
|
|
297
|
+
state: state.values,
|
|
298
|
+
running: !shouldExit,
|
|
299
|
+
active: false,
|
|
300
|
+
}),
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
return Promise.resolve();
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function getStateSyncEvent({
|
|
307
|
+
threadId,
|
|
308
|
+
runId,
|
|
309
|
+
agentName,
|
|
310
|
+
nodeName,
|
|
311
|
+
state,
|
|
312
|
+
running,
|
|
313
|
+
active,
|
|
314
|
+
}: {
|
|
315
|
+
threadId: string;
|
|
316
|
+
runId: string;
|
|
317
|
+
agentName: string;
|
|
318
|
+
nodeName: string;
|
|
319
|
+
state: State;
|
|
320
|
+
running: boolean;
|
|
321
|
+
active: boolean;
|
|
322
|
+
}): string {
|
|
323
|
+
const stateWithoutMessages = Object.keys(state).reduce((acc, key) => {
|
|
324
|
+
if (key !== "messages") {
|
|
325
|
+
acc[key] = state[key];
|
|
326
|
+
}
|
|
327
|
+
return acc;
|
|
328
|
+
}, {} as State);
|
|
329
|
+
|
|
330
|
+
return (
|
|
331
|
+
JSON.stringify({
|
|
332
|
+
event: "on_copilotkit_state_sync",
|
|
333
|
+
thread_id: threadId,
|
|
334
|
+
run_id: runId,
|
|
335
|
+
agent_name: agentName,
|
|
336
|
+
node_name: nodeName,
|
|
337
|
+
active: active,
|
|
338
|
+
state: stateWithoutMessages,
|
|
339
|
+
running: running,
|
|
340
|
+
role: "assistant",
|
|
341
|
+
}) + "\n"
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
class StreamingStateExtractor {
|
|
346
|
+
private emitIntermediateState: { [key: string]: any }[];
|
|
347
|
+
private toolCallBuffer: { [key: string]: string };
|
|
348
|
+
private currentToolCall: string | null;
|
|
349
|
+
private previouslyParsableState: { [key: string]: any };
|
|
350
|
+
|
|
351
|
+
constructor(emitIntermediateState: { [key: string]: any }[]) {
|
|
352
|
+
this.emitIntermediateState = emitIntermediateState;
|
|
353
|
+
this.toolCallBuffer = {};
|
|
354
|
+
this.currentToolCall = null;
|
|
355
|
+
this.previouslyParsableState = {};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
bufferToolCalls(event: {
|
|
359
|
+
data: { chunk: { tool_call_chunks: { name: string | null; args: string }[] } };
|
|
360
|
+
}) {
|
|
361
|
+
if (event.data.chunk.tool_call_chunks.length > 0) {
|
|
362
|
+
const chunk = event.data.chunk.tool_call_chunks[0];
|
|
363
|
+
|
|
364
|
+
if (chunk.name !== null) {
|
|
365
|
+
this.currentToolCall = chunk.name;
|
|
366
|
+
this.toolCallBuffer[this.currentToolCall] = chunk.args;
|
|
367
|
+
} else if (this.currentToolCall !== null) {
|
|
368
|
+
this.toolCallBuffer[this.currentToolCall] += chunk.args;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
getEmitStateConfig(currentToolName: string): [string | null, string | null] {
|
|
374
|
+
for (const config of this.emitIntermediateState) {
|
|
375
|
+
const stateKey = config["state_key"];
|
|
376
|
+
const tool = config["tool"];
|
|
377
|
+
const toolArgument = config["tool_argument"];
|
|
378
|
+
|
|
379
|
+
if (currentToolName === tool) {
|
|
380
|
+
return [toolArgument, stateKey];
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return [null, null];
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
extractState(): State {
|
|
387
|
+
const state: State = {};
|
|
388
|
+
|
|
389
|
+
for (const [key, value] of Object.entries(this.toolCallBuffer)) {
|
|
390
|
+
const [argumentName, stateKey] = this.getEmitStateConfig(key);
|
|
391
|
+
|
|
392
|
+
if (stateKey === null) {
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
let parsedValue;
|
|
397
|
+
try {
|
|
398
|
+
parsedValue = parsePartialJson(value);
|
|
399
|
+
} catch (error) {
|
|
400
|
+
if (key in this.previouslyParsableState) {
|
|
401
|
+
parsedValue = this.previouslyParsableState[key];
|
|
402
|
+
} else {
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
this.previouslyParsableState[key] = parsedValue;
|
|
408
|
+
|
|
409
|
+
if (!argumentName) {
|
|
410
|
+
state[stateKey] = parsedValue;
|
|
411
|
+
} else {
|
|
412
|
+
state[stateKey] = parsedValue[argumentName];
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return state;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// Start of Selection
|
|
421
|
+
function langGraphDefaultMergeState(
|
|
422
|
+
state: State,
|
|
423
|
+
messages: LangGraphCloudMessage[],
|
|
424
|
+
actions: ExecutionAction[],
|
|
425
|
+
agentName: string,
|
|
426
|
+
): State {
|
|
427
|
+
if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
|
|
428
|
+
// remove system message
|
|
429
|
+
messages = messages.slice(1);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// merge with existing messages
|
|
433
|
+
const mergedMessages: LangGraphCloudMessage[] = state.messages || [];
|
|
434
|
+
const existingMessageIds = new Set(mergedMessages.map((message) => message.id));
|
|
435
|
+
const existingToolCallResults = new Set<string>();
|
|
436
|
+
|
|
437
|
+
for (const message of mergedMessages) {
|
|
438
|
+
if ("tool_call_id" in message) {
|
|
439
|
+
existingToolCallResults.add(message.tool_call_id);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
for (const message of messages) {
|
|
444
|
+
// filter tool calls to activate the agent itself
|
|
445
|
+
if (
|
|
446
|
+
"tool_calls" in message &&
|
|
447
|
+
message.tool_calls.length > 0 &&
|
|
448
|
+
message.tool_calls[0].name === agentName
|
|
449
|
+
) {
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// filter results from activating the agent
|
|
454
|
+
if ("name" in message && message.name === agentName) {
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
if (!existingMessageIds.has(message.id)) {
|
|
459
|
+
// skip duplicate tool call results
|
|
460
|
+
if ("tool_call_id" in message && existingToolCallResults.has(message.tool_call_id)) {
|
|
461
|
+
console.warn("Warning: Duplicate tool call result, skipping:", message.tool_call_id);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
mergedMessages.push(message);
|
|
466
|
+
} else {
|
|
467
|
+
// Replace the message with the existing one
|
|
468
|
+
for (let i = 0; i < mergedMessages.length; i++) {
|
|
469
|
+
if (mergedMessages[i].id === message.id) {
|
|
470
|
+
if ("tool_calls" in message) {
|
|
471
|
+
if (
|
|
472
|
+
("tool_calls" in mergedMessages[i] || "additional_kwargs" in mergedMessages[i]) &&
|
|
473
|
+
mergedMessages[i].content
|
|
474
|
+
) {
|
|
475
|
+
message.tool_calls = mergedMessages[i]["tool_calls"];
|
|
476
|
+
message.additional_kwargs = mergedMessages[i].additional_kwargs;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
mergedMessages[i] = message;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// fix wrong tool call ids
|
|
486
|
+
for (let i = 0; i < mergedMessages.length - 1; i++) {
|
|
487
|
+
const currentMessage = mergedMessages[i];
|
|
488
|
+
const nextMessage = mergedMessages[i + 1];
|
|
489
|
+
|
|
490
|
+
if (
|
|
491
|
+
"tool_calls" in currentMessage &&
|
|
492
|
+
currentMessage.tool_calls.length > 0 &&
|
|
493
|
+
"tool_call_id" in nextMessage
|
|
494
|
+
) {
|
|
495
|
+
nextMessage.tool_call_id = currentMessage.tool_calls[0].id;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// try to auto-correct and log alignment issues
|
|
500
|
+
const correctedMessages: LangGraphCloudMessage[] = [];
|
|
501
|
+
|
|
502
|
+
for (let i = 0; i < mergedMessages.length; i++) {
|
|
503
|
+
const currentMessage = mergedMessages[i];
|
|
504
|
+
const nextMessage = mergedMessages[i + 1] || null;
|
|
505
|
+
const prevMessage = mergedMessages[i - 1] || null;
|
|
506
|
+
|
|
507
|
+
if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0) {
|
|
508
|
+
if (!nextMessage) {
|
|
509
|
+
console.warn(
|
|
510
|
+
"No next message to auto-correct tool call, skipping:",
|
|
511
|
+
currentMessage.tool_calls[0].id,
|
|
512
|
+
);
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
if (
|
|
517
|
+
!("tool_call_id" in nextMessage) ||
|
|
518
|
+
nextMessage.tool_call_id !== currentMessage.tool_calls[0].id
|
|
519
|
+
) {
|
|
520
|
+
const toolMessage = mergedMessages.find(
|
|
521
|
+
(m) => "tool_call_id" in m && m.tool_call_id === currentMessage.tool_calls[0].id,
|
|
522
|
+
);
|
|
523
|
+
|
|
524
|
+
if (toolMessage) {
|
|
525
|
+
console.warn(
|
|
526
|
+
"Auto-corrected tool call alignment issue:",
|
|
527
|
+
currentMessage.tool_calls[0].id,
|
|
528
|
+
);
|
|
529
|
+
correctedMessages.push(currentMessage, toolMessage);
|
|
530
|
+
continue;
|
|
531
|
+
} else {
|
|
532
|
+
console.warn(
|
|
533
|
+
"No corresponding tool call result found for tool call, skipping:",
|
|
534
|
+
currentMessage.tool_calls[0].id,
|
|
535
|
+
);
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
correctedMessages.push(currentMessage);
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
if ("tool_call_id" in currentMessage) {
|
|
545
|
+
if (!prevMessage || !("tool_calls" in prevMessage)) {
|
|
546
|
+
console.warn("No previous tool call, skipping tool call result:", currentMessage.id);
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (prevMessage.tool_calls && prevMessage.tool_calls[0].id !== currentMessage.tool_call_id) {
|
|
551
|
+
console.warn("Tool call id is incorrect, skipping tool call result:", currentMessage.id);
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
correctedMessages.push(currentMessage);
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
correctedMessages.push(currentMessage);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
return deepMerge(state, {
|
|
563
|
+
messages: correctedMessages,
|
|
564
|
+
copilotkit: {
|
|
565
|
+
actions,
|
|
566
|
+
},
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function deepMerge(obj1: State, obj2: State) {
|
|
571
|
+
let result = { ...obj1 };
|
|
572
|
+
for (let key in obj2) {
|
|
573
|
+
if (typeof obj2[key] === "object" && !Array.isArray(obj2[key])) {
|
|
574
|
+
if (obj1[key]) {
|
|
575
|
+
result[key] = deepMerge(obj1[key], obj2[key]);
|
|
576
|
+
} else {
|
|
577
|
+
result[key] = { ...obj2[key] };
|
|
578
|
+
}
|
|
579
|
+
} else {
|
|
580
|
+
result[key] = obj2[key];
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return result;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function formatMessages(messages: Message[]): LangGraphCloudMessage[] {
|
|
587
|
+
return messages.map((message) => {
|
|
588
|
+
if (message.isTextMessage() && message.role === "assistant") {
|
|
589
|
+
return message;
|
|
590
|
+
}
|
|
591
|
+
if (message.isTextMessage() && message.role === "system") {
|
|
592
|
+
return message;
|
|
593
|
+
}
|
|
594
|
+
if (message.isTextMessage() && message.role === "user") {
|
|
595
|
+
return message;
|
|
596
|
+
}
|
|
597
|
+
if (message.isActionExecutionMessage()) {
|
|
598
|
+
const toolCall: ToolCall = {
|
|
599
|
+
name: message.name,
|
|
600
|
+
args: message.arguments,
|
|
601
|
+
id: message.id,
|
|
602
|
+
};
|
|
603
|
+
return {
|
|
604
|
+
type: message.type,
|
|
605
|
+
content: "",
|
|
606
|
+
tool_calls: [toolCall],
|
|
607
|
+
role: MessageRole.assistant,
|
|
608
|
+
id: message.id,
|
|
609
|
+
} satisfies LangGraphCloudActionExecutionMessage;
|
|
610
|
+
}
|
|
611
|
+
if (message.isResultMessage()) {
|
|
612
|
+
return {
|
|
613
|
+
type: message.type,
|
|
614
|
+
content: message.result,
|
|
615
|
+
id: message.id,
|
|
616
|
+
tool_call_id: message.actionExecutionId,
|
|
617
|
+
name: message.actionName,
|
|
618
|
+
role: MessageRole.assistant,
|
|
619
|
+
} satisfies LangGraphCloudResultMessage;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
throw new Error(`Unknown message type ${message.type}`);
|
|
623
|
+
});
|
|
624
|
+
}
|
|
@@ -29,12 +29,12 @@ interface GoogleGenerativeAIAdapterOptions {
|
|
|
29
29
|
export class GoogleGenerativeAIAdapter extends LangChainAdapter {
|
|
30
30
|
constructor(options?: GoogleGenerativeAIAdapterOptions) {
|
|
31
31
|
super({
|
|
32
|
-
chainFn: async ({ messages, tools
|
|
32
|
+
chainFn: async ({ messages, tools }) => {
|
|
33
33
|
const model = new ChatGoogle({
|
|
34
34
|
modelName: options?.model ?? "gemini-1.5-pro",
|
|
35
35
|
apiVersion: "v1beta",
|
|
36
36
|
}).bindTools(tools);
|
|
37
|
-
return model.stream(messages
|
|
37
|
+
return model.stream(messages);
|
|
38
38
|
},
|
|
39
39
|
});
|
|
40
40
|
}
|
|
@@ -16,7 +16,9 @@
|
|
|
16
16
|
*
|
|
17
17
|
* const serviceAdapter = new LangChainAdapter({
|
|
18
18
|
* chainFn: async ({ messages, tools }) => {
|
|
19
|
-
* return model.stream(messages
|
|
19
|
+
* return model.bindTools(tools).stream(messages);
|
|
20
|
+
* // or optionally enable strict mode
|
|
21
|
+
* // return model.bindTools(tools, { strict: true }).stream(messages);
|
|
20
22
|
* }
|
|
21
23
|
* });
|
|
22
24
|
*
|
|
@@ -70,8 +72,7 @@ export class LangChainAdapter implements CopilotServiceAdapter {
|
|
|
70
72
|
async process(
|
|
71
73
|
request: CopilotRuntimeChatCompletionRequest,
|
|
72
74
|
): Promise<CopilotRuntimeChatCompletionResponse> {
|
|
73
|
-
const { eventSource, model, actions, messages, runId } = request;
|
|
74
|
-
const threadId = request.threadId ?? randomId();
|
|
75
|
+
const { eventSource, model, actions, messages, threadId, runId } = request;
|
|
75
76
|
const result = await this.options.chainFn({
|
|
76
77
|
messages: messages.map(convertMessageToLangChainMessage),
|
|
77
78
|
tools: actions.map(convertActionInputToLangChainTool),
|
|
@@ -88,7 +89,7 @@ export class LangChainAdapter implements CopilotServiceAdapter {
|
|
|
88
89
|
});
|
|
89
90
|
|
|
90
91
|
return {
|
|
91
|
-
threadId,
|
|
92
|
+
threadId: threadId || randomId(),
|
|
92
93
|
};
|
|
93
94
|
}
|
|
94
95
|
}
|