@copilotkit/runtime 1.5.1-next.3 → 1.5.1-next.4

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 (82) hide show
  1. package/CHANGELOG.md +10 -2
  2. package/package.json +2 -2
  3. package/__snapshots__/schema/schema.graphql +0 -263
  4. package/dist/chunk-44O2JGUY.mjs +0 -12
  5. package/dist/chunk-44O2JGUY.mjs.map +0 -1
  6. package/dist/chunk-B74M7FXG.mjs +0 -65
  7. package/dist/chunk-B74M7FXG.mjs.map +0 -1
  8. package/dist/chunk-D2WLFQS6.mjs +0 -43
  9. package/dist/chunk-D2WLFQS6.mjs.map +0 -1
  10. package/dist/chunk-DFOKBSIS.mjs +0 -1
  11. package/dist/chunk-DFOKBSIS.mjs.map +0 -1
  12. package/dist/chunk-M4QD67S3.mjs +0 -80
  13. package/dist/chunk-M4QD67S3.mjs.map +0 -1
  14. package/dist/chunk-OKQVDDJ2.mjs +0 -1173
  15. package/dist/chunk-OKQVDDJ2.mjs.map +0 -1
  16. package/dist/chunk-U3AYI5XZ.mjs +0 -25
  17. package/dist/chunk-U3AYI5XZ.mjs.map +0 -1
  18. package/dist/chunk-U3V2BCGI.mjs +0 -152
  19. package/dist/chunk-U3V2BCGI.mjs.map +0 -1
  20. package/dist/chunk-U75F2RAQ.mjs +0 -25
  21. package/dist/chunk-U75F2RAQ.mjs.map +0 -1
  22. package/dist/chunk-ZSWCEADS.mjs +0 -3147
  23. package/dist/chunk-ZSWCEADS.mjs.map +0 -1
  24. package/dist/copilot-runtime-12e7ac40.d.ts +0 -189
  25. package/dist/graphql/types/base/index.d.ts +0 -6
  26. package/dist/graphql/types/base/index.js +0 -63
  27. package/dist/graphql/types/base/index.js.map +0 -1
  28. package/dist/graphql/types/base/index.mjs +0 -8
  29. package/dist/graphql/types/base/index.mjs.map +0 -1
  30. package/dist/graphql/types/converted/index.d.ts +0 -2
  31. package/dist/graphql/types/converted/index.js +0 -123
  32. package/dist/graphql/types/converted/index.js.map +0 -1
  33. package/dist/graphql/types/converted/index.mjs +0 -17
  34. package/dist/graphql/types/converted/index.mjs.map +0 -1
  35. package/dist/groq-adapter-24abe931.d.ts +0 -281
  36. package/dist/index-10b1c870.d.ts +0 -88
  37. package/dist/index.d.ts +0 -23
  38. package/dist/index.js +0 -4667
  39. package/dist/index.js.map +0 -1
  40. package/dist/index.mjs +0 -72
  41. package/dist/index.mjs.map +0 -1
  42. package/dist/langserve-f021ab9c.d.ts +0 -136
  43. package/dist/lib/cloud/index.d.ts +0 -6
  44. package/dist/lib/cloud/index.js +0 -18
  45. package/dist/lib/cloud/index.js.map +0 -1
  46. package/dist/lib/cloud/index.mjs +0 -1
  47. package/dist/lib/cloud/index.mjs.map +0 -1
  48. package/dist/lib/index.d.ts +0 -20
  49. package/dist/lib/index.js +0 -4392
  50. package/dist/lib/index.js.map +0 -1
  51. package/dist/lib/index.mjs +0 -58
  52. package/dist/lib/index.mjs.map +0 -1
  53. package/dist/lib/integrations/index.d.ts +0 -33
  54. package/dist/lib/integrations/index.js +0 -2043
  55. package/dist/lib/integrations/index.js.map +0 -1
  56. package/dist/lib/integrations/index.mjs +0 -34
  57. package/dist/lib/integrations/index.mjs.map +0 -1
  58. package/dist/lib/integrations/nest/index.d.ts +0 -14
  59. package/dist/lib/integrations/nest/index.js +0 -1952
  60. package/dist/lib/integrations/nest/index.js.map +0 -1
  61. package/dist/lib/integrations/nest/index.mjs +0 -13
  62. package/dist/lib/integrations/nest/index.mjs.map +0 -1
  63. package/dist/lib/integrations/node-express/index.d.ts +0 -14
  64. package/dist/lib/integrations/node-express/index.js +0 -1952
  65. package/dist/lib/integrations/node-express/index.js.map +0 -1
  66. package/dist/lib/integrations/node-express/index.mjs +0 -13
  67. package/dist/lib/integrations/node-express/index.mjs.map +0 -1
  68. package/dist/lib/integrations/node-http/index.d.ts +0 -14
  69. package/dist/lib/integrations/node-http/index.js +0 -1938
  70. package/dist/lib/integrations/node-http/index.js.map +0 -1
  71. package/dist/lib/integrations/node-http/index.mjs +0 -12
  72. package/dist/lib/integrations/node-http/index.mjs.map +0 -1
  73. package/dist/service-adapters/index.d.ts +0 -53
  74. package/dist/service-adapters/index.js +0 -1211
  75. package/dist/service-adapters/index.js.map +0 -1
  76. package/dist/service-adapters/index.mjs +0 -22
  77. package/dist/service-adapters/index.mjs.map +0 -1
  78. package/dist/utils/index.d.ts +0 -49
  79. package/dist/utils/index.js +0 -174
  80. package/dist/utils/index.js.map +0 -1
  81. package/dist/utils/index.mjs +0 -12
  82. package/dist/utils/index.mjs.map +0 -1
@@ -1,1211 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/service-adapters/index.ts
31
- var service_adapters_exports = {};
32
- __export(service_adapters_exports, {
33
- AnthropicAdapter: () => AnthropicAdapter,
34
- GoogleGenerativeAIAdapter: () => GoogleGenerativeAIAdapter,
35
- GroqAdapter: () => GroqAdapter,
36
- LangChainAdapter: () => LangChainAdapter,
37
- OpenAIAdapter: () => OpenAIAdapter,
38
- OpenAIAssistantAdapter: () => OpenAIAssistantAdapter,
39
- RemoteChain: () => RemoteChain,
40
- UnifyAdapter: () => UnifyAdapter
41
- });
42
- module.exports = __toCommonJS(service_adapters_exports);
43
-
44
- // src/service-adapters/langchain/langserve.ts
45
- var import_remote = require("langchain/runnables/remote");
46
- var RemoteChain = class {
47
- name;
48
- description;
49
- chainUrl;
50
- parameters;
51
- parameterType;
52
- constructor(options) {
53
- this.name = options.name;
54
- this.description = options.description;
55
- this.chainUrl = options.chainUrl;
56
- this.parameters = options.parameters;
57
- this.parameterType = options.parameterType || "multi";
58
- }
59
- async toAction() {
60
- if (!this.parameters) {
61
- await this.inferLangServeParameters();
62
- }
63
- return {
64
- name: this.name,
65
- description: this.description,
66
- parameters: this.parameters,
67
- handler: async (args) => {
68
- const runnable = new import_remote.RemoteRunnable({
69
- url: this.chainUrl
70
- });
71
- let input;
72
- if (this.parameterType === "single") {
73
- input = args[Object.keys(args)[0]];
74
- } else {
75
- input = args;
76
- }
77
- return await runnable.invoke(input);
78
- }
79
- };
80
- }
81
- async inferLangServeParameters() {
82
- const supportedTypes = [
83
- "string",
84
- "number",
85
- "boolean"
86
- ];
87
- let schemaUrl = this.chainUrl.replace(/\/+$/, "") + "/input_schema";
88
- let schema = await fetch(schemaUrl).then((res) => res.json()).catch(() => {
89
- throw new Error("Failed to fetch langserve schema at " + schemaUrl);
90
- });
91
- if (supportedTypes.includes(schema.type)) {
92
- this.parameterType = "single";
93
- this.parameters = [
94
- {
95
- name: "input",
96
- type: schema.type,
97
- description: "The input to the chain"
98
- }
99
- ];
100
- } else if (schema.type === "object") {
101
- this.parameterType = "multi";
102
- this.parameters = Object.keys(schema.properties).map((key) => {
103
- var _a;
104
- let property = schema.properties[key];
105
- if (!supportedTypes.includes(property.type)) {
106
- throw new Error("Unsupported schema type");
107
- }
108
- return {
109
- name: key,
110
- type: property.type,
111
- description: property.description || "",
112
- required: ((_a = schema.required) == null ? void 0 : _a.includes(key)) || false
113
- };
114
- });
115
- } else {
116
- throw new Error("Unsupported schema type");
117
- }
118
- }
119
- };
120
- __name(RemoteChain, "RemoteChain");
121
-
122
- // src/service-adapters/openai/openai-adapter.ts
123
- var import_openai = __toESM(require("openai"));
124
-
125
- // src/service-adapters/openai/utils.ts
126
- function limitMessagesToTokenCount(messages, tools, model, maxTokens) {
127
- maxTokens || (maxTokens = maxTokensForOpenAIModel(model));
128
- const result = [];
129
- const toolsNumTokens = countToolsTokens(model, tools);
130
- if (toolsNumTokens > maxTokens) {
131
- throw new Error(`Too many tokens in function definitions: ${toolsNumTokens} > ${maxTokens}`);
132
- }
133
- maxTokens -= toolsNumTokens;
134
- for (const message of messages) {
135
- if (message.role === "system") {
136
- const numTokens = countMessageTokens(model, message);
137
- maxTokens -= numTokens;
138
- if (maxTokens < 0) {
139
- throw new Error("Not enough tokens for system message.");
140
- }
141
- }
142
- }
143
- let cutoff = false;
144
- const reversedMessages = [
145
- ...messages
146
- ].reverse();
147
- for (const message of reversedMessages) {
148
- if (message.role === "system") {
149
- result.unshift(message);
150
- continue;
151
- } else if (cutoff) {
152
- continue;
153
- }
154
- let numTokens = countMessageTokens(model, message);
155
- if (maxTokens < numTokens) {
156
- cutoff = true;
157
- continue;
158
- }
159
- result.unshift(message);
160
- maxTokens -= numTokens;
161
- }
162
- return result;
163
- }
164
- __name(limitMessagesToTokenCount, "limitMessagesToTokenCount");
165
- function maxTokensForOpenAIModel(model) {
166
- return maxTokensByModel[model] || DEFAULT_MAX_TOKENS;
167
- }
168
- __name(maxTokensForOpenAIModel, "maxTokensForOpenAIModel");
169
- var DEFAULT_MAX_TOKENS = 128e3;
170
- var maxTokensByModel = {
171
- // GPT-4
172
- "gpt-4o": 128e3,
173
- "gpt-4o-2024-05-13": 128e3,
174
- "gpt-4-turbo": 128e3,
175
- "gpt-4-turbo-2024-04-09": 128e3,
176
- "gpt-4-0125-preview": 128e3,
177
- "gpt-4-turbo-preview": 128e3,
178
- "gpt-4-1106-preview": 128e3,
179
- "gpt-4-vision-preview": 128e3,
180
- "gpt-4-1106-vision-preview": 128e3,
181
- "gpt-4-32k": 32768,
182
- "gpt-4-32k-0613": 32768,
183
- "gpt-4-32k-0314": 32768,
184
- "gpt-4": 8192,
185
- "gpt-4-0613": 8192,
186
- "gpt-4-0314": 8192,
187
- // GPT-3.5
188
- "gpt-3.5-turbo-0125": 16385,
189
- "gpt-3.5-turbo": 16385,
190
- "gpt-3.5-turbo-1106": 16385,
191
- "gpt-3.5-turbo-instruct": 4096,
192
- "gpt-3.5-turbo-16k": 16385,
193
- "gpt-3.5-turbo-0613": 4096,
194
- "gpt-3.5-turbo-16k-0613": 16385,
195
- "gpt-3.5-turbo-0301": 4097
196
- };
197
- function countToolsTokens(model, tools) {
198
- if (tools.length === 0) {
199
- return 0;
200
- }
201
- const json = JSON.stringify(tools);
202
- return countTokens(model, json);
203
- }
204
- __name(countToolsTokens, "countToolsTokens");
205
- function countMessageTokens(model, message) {
206
- return countTokens(model, message.content || "");
207
- }
208
- __name(countMessageTokens, "countMessageTokens");
209
- function countTokens(model, text) {
210
- return text.length / 3;
211
- }
212
- __name(countTokens, "countTokens");
213
- function convertActionInputToOpenAITool(action) {
214
- return {
215
- type: "function",
216
- function: {
217
- name: action.name,
218
- description: action.description,
219
- parameters: JSON.parse(action.jsonSchema)
220
- }
221
- };
222
- }
223
- __name(convertActionInputToOpenAITool, "convertActionInputToOpenAITool");
224
- function convertMessageToOpenAIMessage(message) {
225
- if (message.isTextMessage()) {
226
- return {
227
- role: message.role,
228
- content: message.content
229
- };
230
- } else if (message.isActionExecutionMessage()) {
231
- return {
232
- role: "assistant",
233
- tool_calls: [
234
- {
235
- id: message.id,
236
- type: "function",
237
- function: {
238
- name: message.name,
239
- arguments: JSON.stringify(message.arguments)
240
- }
241
- }
242
- ]
243
- };
244
- } else if (message.isResultMessage()) {
245
- return {
246
- role: "tool",
247
- content: message.result,
248
- tool_call_id: message.actionExecutionId
249
- };
250
- }
251
- }
252
- __name(convertMessageToOpenAIMessage, "convertMessageToOpenAIMessage");
253
- function convertSystemMessageToAssistantAPI(message) {
254
- return {
255
- ...message,
256
- ...message.role === "system" && {
257
- role: "assistant",
258
- content: "THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: " + message.content
259
- }
260
- };
261
- }
262
- __name(convertSystemMessageToAssistantAPI, "convertSystemMessageToAssistantAPI");
263
-
264
- // src/service-adapters/openai/openai-adapter.ts
265
- var import_shared = require("@copilotkit/shared");
266
- var DEFAULT_MODEL = "gpt-4o";
267
- var OpenAIAdapter = class {
268
- model = DEFAULT_MODEL;
269
- disableParallelToolCalls = false;
270
- _openai;
271
- get openai() {
272
- return this._openai;
273
- }
274
- constructor(params) {
275
- this._openai = (params == null ? void 0 : params.openai) || new import_openai.default({});
276
- if (params == null ? void 0 : params.model) {
277
- this.model = params.model;
278
- }
279
- this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
280
- }
281
- async process(request) {
282
- const { threadId, model = this.model, messages, actions, eventSource, forwardedParameters } = request;
283
- const tools = actions.map(convertActionInputToOpenAITool);
284
- let openaiMessages = messages.map(convertMessageToOpenAIMessage);
285
- openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
286
- let toolChoice = forwardedParameters == null ? void 0 : forwardedParameters.toolChoice;
287
- if ((forwardedParameters == null ? void 0 : forwardedParameters.toolChoice) === "function") {
288
- toolChoice = {
289
- type: "function",
290
- function: {
291
- name: forwardedParameters.toolChoiceFunctionName
292
- }
293
- };
294
- }
295
- const stream = this.openai.beta.chat.completions.stream({
296
- model,
297
- stream: true,
298
- messages: openaiMessages,
299
- ...tools.length > 0 && {
300
- tools
301
- },
302
- ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
303
- max_tokens: forwardedParameters.maxTokens
304
- },
305
- ...(forwardedParameters == null ? void 0 : forwardedParameters.stop) && {
306
- stop: forwardedParameters.stop
307
- },
308
- ...toolChoice && {
309
- tool_choice: toolChoice
310
- },
311
- ...this.disableParallelToolCalls && {
312
- parallel_tool_calls: false
313
- }
314
- });
315
- eventSource.stream(async (eventStream$) => {
316
- var _a, _b;
317
- let mode = null;
318
- for await (const chunk of stream) {
319
- if (chunk.choices.length === 0) {
320
- continue;
321
- }
322
- const toolCall = (_a = chunk.choices[0].delta.tool_calls) == null ? void 0 : _a[0];
323
- const content = chunk.choices[0].delta.content;
324
- if (mode === "message" && (toolCall == null ? void 0 : toolCall.id)) {
325
- mode = null;
326
- eventStream$.sendTextMessageEnd();
327
- } else if (mode === "function" && (toolCall === void 0 || (toolCall == null ? void 0 : toolCall.id))) {
328
- mode = null;
329
- eventStream$.sendActionExecutionEnd();
330
- }
331
- if (mode === null) {
332
- if (toolCall == null ? void 0 : toolCall.id) {
333
- mode = "function";
334
- eventStream$.sendActionExecutionStart(toolCall.id, toolCall.function.name);
335
- } else if (content) {
336
- mode = "message";
337
- eventStream$.sendTextMessageStart(chunk.id);
338
- }
339
- }
340
- if (mode === "message" && content) {
341
- eventStream$.sendTextMessageContent(content);
342
- } else if (mode === "function" && ((_b = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _b.arguments)) {
343
- eventStream$.sendActionExecutionArgs(toolCall.function.arguments);
344
- }
345
- }
346
- if (mode === "message") {
347
- eventStream$.sendTextMessageEnd();
348
- } else if (mode === "function") {
349
- eventStream$.sendActionExecutionEnd();
350
- }
351
- eventStream$.complete();
352
- });
353
- return {
354
- threadId: threadId || (0, import_shared.randomId)()
355
- };
356
- }
357
- };
358
- __name(OpenAIAdapter, "OpenAIAdapter");
359
-
360
- // src/service-adapters/langchain/utils.ts
361
- var import_messages = require("@langchain/core/messages");
362
- var import_tools = require("@langchain/core/tools");
363
- var import_shared2 = require("@copilotkit/shared");
364
- function convertMessageToLangChainMessage(message) {
365
- if (message.isTextMessage()) {
366
- if (message.role == "user") {
367
- return new import_messages.HumanMessage(message.content);
368
- } else if (message.role == "assistant") {
369
- return new import_messages.AIMessage(message.content);
370
- } else if (message.role === "system") {
371
- return new import_messages.SystemMessage(message.content);
372
- }
373
- } else if (message.isActionExecutionMessage()) {
374
- return new import_messages.AIMessage({
375
- content: "",
376
- tool_calls: [
377
- {
378
- id: message.id,
379
- args: message.arguments,
380
- name: message.name
381
- }
382
- ]
383
- });
384
- } else if (message.isResultMessage()) {
385
- return new import_messages.ToolMessage({
386
- content: message.result,
387
- tool_call_id: message.actionExecutionId
388
- });
389
- }
390
- }
391
- __name(convertMessageToLangChainMessage, "convertMessageToLangChainMessage");
392
- function convertActionInputToLangChainTool(actionInput) {
393
- return new import_tools.DynamicStructuredTool({
394
- name: actionInput.name,
395
- description: actionInput.description,
396
- schema: (0, import_shared2.convertJsonSchemaToZodSchema)(JSON.parse(actionInput.jsonSchema), true),
397
- func: async () => {
398
- return "";
399
- }
400
- });
401
- }
402
- __name(convertActionInputToLangChainTool, "convertActionInputToLangChainTool");
403
- function isAIMessage(message) {
404
- return Object.prototype.toString.call(message) === "[object AIMessage]";
405
- }
406
- __name(isAIMessage, "isAIMessage");
407
- function isAIMessageChunk(message) {
408
- return Object.prototype.toString.call(message) === "[object AIMessageChunk]";
409
- }
410
- __name(isAIMessageChunk, "isAIMessageChunk");
411
- function isBaseMessageChunk(message) {
412
- return Object.prototype.toString.call(message) === "[object BaseMessageChunk]";
413
- }
414
- __name(isBaseMessageChunk, "isBaseMessageChunk");
415
- function maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution) {
416
- if (actionExecution) {
417
- eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, "Sending a message");
418
- }
419
- }
420
- __name(maybeSendActionExecutionResultIsMessage, "maybeSendActionExecutionResultIsMessage");
421
- async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
422
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
423
- if (typeof result === "string") {
424
- if (!actionExecution) {
425
- eventStream$.sendTextMessage((0, import_shared2.randomId)(), result);
426
- } else {
427
- eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);
428
- }
429
- } else if (isAIMessage(result)) {
430
- maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
431
- if (result.content) {
432
- eventStream$.sendTextMessage((0, import_shared2.randomId)(), result.content);
433
- }
434
- for (const toolCall of result.tool_calls) {
435
- eventStream$.sendActionExecution(toolCall.id || (0, import_shared2.randomId)(), toolCall.name, JSON.stringify(toolCall.args));
436
- }
437
- } else if (isBaseMessageChunk(result)) {
438
- maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
439
- if ((_a = result.lc_kwargs) == null ? void 0 : _a.content) {
440
- eventStream$.sendTextMessage((0, import_shared2.randomId)(), result.content);
441
- }
442
- if ((_b = result.lc_kwargs) == null ? void 0 : _b.tool_calls) {
443
- for (const toolCall of (_c = result.lc_kwargs) == null ? void 0 : _c.tool_calls) {
444
- eventStream$.sendActionExecution(toolCall.id || (0, import_shared2.randomId)(), toolCall.name, JSON.stringify(toolCall.args));
445
- }
446
- }
447
- } else if (result && "getReader" in result) {
448
- maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
449
- let reader = result.getReader();
450
- let mode = null;
451
- const toolCallDetails = {
452
- name: null,
453
- id: null,
454
- index: null,
455
- prevIndex: null
456
- };
457
- while (true) {
458
- try {
459
- const { done, value } = await reader.read();
460
- let toolCallName = void 0;
461
- let toolCallId = void 0;
462
- let toolCallArgs = void 0;
463
- let hasToolCall = false;
464
- let content = value == null ? void 0 : value.content;
465
- if (isAIMessageChunk(value)) {
466
- let chunk = (_d = value.tool_call_chunks) == null ? void 0 : _d[0];
467
- toolCallArgs = chunk == null ? void 0 : chunk.args;
468
- hasToolCall = chunk != void 0;
469
- if (chunk == null ? void 0 : chunk.name)
470
- toolCallDetails.name = chunk.name;
471
- if ((chunk == null ? void 0 : chunk.index) != null) {
472
- toolCallDetails.index = chunk.index;
473
- if (toolCallDetails.prevIndex == null)
474
- toolCallDetails.prevIndex = chunk.index;
475
- }
476
- if (chunk == null ? void 0 : chunk.id)
477
- toolCallDetails.id = chunk.index != null ? `${chunk.id}-idx-${chunk.index}` : chunk.id;
478
- toolCallName = toolCallDetails.name;
479
- toolCallId = toolCallDetails.id;
480
- } else if (isBaseMessageChunk(value)) {
481
- let chunk = (_f = (_e = value.additional_kwargs) == null ? void 0 : _e.tool_calls) == null ? void 0 : _f[0];
482
- toolCallName = (_g = chunk == null ? void 0 : chunk.function) == null ? void 0 : _g.name;
483
- toolCallId = chunk == null ? void 0 : chunk.id;
484
- toolCallArgs = (_h = chunk == null ? void 0 : chunk.function) == null ? void 0 : _h.arguments;
485
- hasToolCall = (chunk == null ? void 0 : chunk.function) != void 0;
486
- }
487
- if (mode === "message" && (toolCallId || done)) {
488
- mode = null;
489
- eventStream$.sendTextMessageEnd();
490
- } else if (mode === "function" && (!hasToolCall || done)) {
491
- mode = null;
492
- eventStream$.sendActionExecutionEnd();
493
- }
494
- if (done) {
495
- break;
496
- }
497
- if (mode === null) {
498
- if (hasToolCall && toolCallId && toolCallName) {
499
- mode = "function";
500
- eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
501
- } else if (content) {
502
- mode = "message";
503
- eventStream$.sendTextMessageStart((0, import_shared2.randomId)());
504
- }
505
- }
506
- if (mode === "message" && content) {
507
- eventStream$.sendTextMessageContent(Array.isArray(content) ? ((_i = content[0]) == null ? void 0 : _i.text) ?? "" : content);
508
- } else if (mode === "function" && toolCallArgs) {
509
- if (toolCallDetails.index !== toolCallDetails.prevIndex) {
510
- eventStream$.sendActionExecutionEnd();
511
- eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
512
- toolCallDetails.prevIndex = toolCallDetails.index;
513
- }
514
- eventStream$.sendActionExecutionArgs(toolCallArgs);
515
- }
516
- } catch (error) {
517
- console.error("Error reading from stream", error);
518
- break;
519
- }
520
- }
521
- } else if (actionExecution) {
522
- eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, encodeResult(result));
523
- } else {
524
- throw new Error("Invalid return type from LangChain function.");
525
- }
526
- eventStream$.complete();
527
- }
528
- __name(streamLangChainResponse, "streamLangChainResponse");
529
- function encodeResult(result) {
530
- if (result === void 0) {
531
- return "";
532
- } else if (typeof result === "string") {
533
- return result;
534
- } else {
535
- return JSON.stringify(result);
536
- }
537
- }
538
- __name(encodeResult, "encodeResult");
539
-
540
- // src/service-adapters/langchain/langchain-adapter.ts
541
- var import_shared3 = require("@copilotkit/shared");
542
- var import_promises = require("@langchain/core/callbacks/promises");
543
- var LangChainAdapter = class {
544
- options;
545
- /**
546
- * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.
547
- */
548
- constructor(options) {
549
- this.options = options;
550
- }
551
- async process(request) {
552
- try {
553
- const { eventSource, model, actions, messages, runId } = request;
554
- const threadId = request.threadId ?? (0, import_shared3.randomId)();
555
- const result = await this.options.chainFn({
556
- messages: messages.map(convertMessageToLangChainMessage),
557
- tools: actions.map(convertActionInputToLangChainTool),
558
- model,
559
- threadId,
560
- runId
561
- });
562
- eventSource.stream(async (eventStream$) => {
563
- await streamLangChainResponse({
564
- result,
565
- eventStream$
566
- });
567
- });
568
- return {
569
- threadId
570
- };
571
- } finally {
572
- await (0, import_promises.awaitAllCallbacks)();
573
- }
574
- }
575
- };
576
- __name(LangChainAdapter, "LangChainAdapter");
577
-
578
- // src/service-adapters/google/google-genai-adapter.ts
579
- var import_google_gauth = require("@langchain/google-gauth");
580
- var GoogleGenerativeAIAdapter = class extends LangChainAdapter {
581
- constructor(options) {
582
- super({
583
- chainFn: async ({ messages, tools, threadId }) => {
584
- const model = new import_google_gauth.ChatGoogle({
585
- modelName: (options == null ? void 0 : options.model) ?? "gemini-1.5-pro",
586
- apiVersion: "v1beta"
587
- }).bindTools(tools);
588
- return model.stream(messages, {
589
- metadata: {
590
- conversation_id: threadId
591
- }
592
- });
593
- }
594
- });
595
- }
596
- };
597
- __name(GoogleGenerativeAIAdapter, "GoogleGenerativeAIAdapter");
598
-
599
- // src/service-adapters/openai/openai-assistant-adapter.ts
600
- var import_openai2 = __toESM(require("openai"));
601
- var OpenAIAssistantAdapter = class {
602
- openai;
603
- codeInterpreterEnabled;
604
- assistantId;
605
- fileSearchEnabled;
606
- disableParallelToolCalls;
607
- constructor(params) {
608
- this.openai = params.openai || new import_openai2.default({});
609
- this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;
610
- this.fileSearchEnabled = params.fileSearchEnabled === false || true;
611
- this.assistantId = params.assistantId;
612
- this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
613
- }
614
- async process(request) {
615
- const { messages, actions, eventSource, runId, forwardedParameters } = request;
616
- let threadId = request.threadId || (await this.openai.beta.threads.create()).id;
617
- const lastMessage = messages.at(-1);
618
- let nextRunId = void 0;
619
- if (lastMessage.isResultMessage() && runId) {
620
- nextRunId = await this.submitToolOutputs(threadId, runId, messages, eventSource);
621
- } else if (lastMessage.isTextMessage()) {
622
- nextRunId = await this.submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters);
623
- } else {
624
- throw new Error("No actionable message found in the messages");
625
- }
626
- return {
627
- threadId,
628
- runId: nextRunId
629
- };
630
- }
631
- async submitToolOutputs(threadId, runId, messages, eventSource) {
632
- let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);
633
- if (!run.required_action) {
634
- throw new Error("No tool outputs required");
635
- }
636
- const toolCallsIds = run.required_action.submit_tool_outputs.tool_calls.map((toolCall) => toolCall.id);
637
- const resultMessages = messages.filter((message) => message.isResultMessage() && toolCallsIds.includes(message.actionExecutionId));
638
- if (toolCallsIds.length != resultMessages.length) {
639
- throw new Error("Number of function results does not match the number of tool calls");
640
- }
641
- const toolOutputs = resultMessages.map((message) => {
642
- return {
643
- tool_call_id: message.actionExecutionId,
644
- output: message.result
645
- };
646
- });
647
- const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {
648
- tool_outputs: toolOutputs,
649
- ...this.disableParallelToolCalls && {
650
- parallel_tool_calls: false
651
- }
652
- });
653
- await this.streamResponse(stream, eventSource);
654
- return runId;
655
- }
656
- async submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters) {
657
- messages = [
658
- ...messages
659
- ];
660
- const instructionsMessage = messages.shift();
661
- const instructions = instructionsMessage.isTextMessage() ? instructionsMessage.content : "";
662
- const userMessage = messages.map(convertMessageToOpenAIMessage).map(convertSystemMessageToAssistantAPI).at(-1);
663
- if (userMessage.role !== "user") {
664
- throw new Error("No user message found");
665
- }
666
- await this.openai.beta.threads.messages.create(threadId, {
667
- role: "user",
668
- content: userMessage.content
669
- });
670
- const openaiTools = actions.map(convertActionInputToOpenAITool);
671
- const tools = [
672
- ...openaiTools,
673
- ...this.codeInterpreterEnabled ? [
674
- {
675
- type: "code_interpreter"
676
- }
677
- ] : [],
678
- ...this.fileSearchEnabled ? [
679
- {
680
- type: "file_search"
681
- }
682
- ] : []
683
- ];
684
- let stream = this.openai.beta.threads.runs.stream(threadId, {
685
- assistant_id: this.assistantId,
686
- instructions,
687
- tools,
688
- ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
689
- max_completion_tokens: forwardedParameters.maxTokens
690
- },
691
- ...this.disableParallelToolCalls && {
692
- parallel_tool_calls: false
693
- }
694
- });
695
- await this.streamResponse(stream, eventSource);
696
- return getRunIdFromStream(stream);
697
- }
698
- async streamResponse(stream, eventSource) {
699
- eventSource.stream(async (eventStream$) => {
700
- var _a, _b, _c, _d, _e, _f;
701
- let inFunctionCall = false;
702
- for await (const chunk of stream) {
703
- switch (chunk.event) {
704
- case "thread.message.created":
705
- if (inFunctionCall) {
706
- eventStream$.sendActionExecutionEnd();
707
- }
708
- eventStream$.sendTextMessageStart(chunk.data.id);
709
- break;
710
- case "thread.message.delta":
711
- if (((_a = chunk.data.delta.content) == null ? void 0 : _a[0].type) === "text") {
712
- eventStream$.sendTextMessageContent((_b = chunk.data.delta.content) == null ? void 0 : _b[0].text.value);
713
- }
714
- break;
715
- case "thread.message.completed":
716
- eventStream$.sendTextMessageEnd();
717
- break;
718
- case "thread.run.step.delta":
719
- let toolCallId;
720
- let toolCallName;
721
- let toolCallArgs;
722
- if (chunk.data.delta.step_details.type === "tool_calls" && ((_c = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _c[0].type) === "function") {
723
- toolCallId = (_d = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _d[0].id;
724
- toolCallName = (_e = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _e[0].function.name;
725
- toolCallArgs = (_f = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _f[0].function.arguments;
726
- }
727
- if (toolCallName && toolCallId) {
728
- if (inFunctionCall) {
729
- eventStream$.sendActionExecutionEnd();
730
- }
731
- inFunctionCall = true;
732
- eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
733
- } else if (toolCallArgs) {
734
- eventStream$.sendActionExecutionArgs(toolCallArgs);
735
- }
736
- break;
737
- }
738
- }
739
- if (inFunctionCall) {
740
- eventStream$.sendActionExecutionEnd();
741
- }
742
- eventStream$.complete();
743
- });
744
- }
745
- };
746
- __name(OpenAIAssistantAdapter, "OpenAIAssistantAdapter");
747
- function getRunIdFromStream(stream) {
748
- return new Promise((resolve, reject) => {
749
- let runIdGetter = /* @__PURE__ */ __name((event) => {
750
- if (event.event === "thread.run.created") {
751
- const runId = event.data.id;
752
- stream.off("event", runIdGetter);
753
- resolve(runId);
754
- }
755
- }, "runIdGetter");
756
- stream.on("event", runIdGetter);
757
- });
758
- }
759
- __name(getRunIdFromStream, "getRunIdFromStream");
760
-
761
- // src/service-adapters/unify/unify-adapter.ts
762
- var import_openai3 = __toESM(require("openai"));
763
- var import_shared4 = require("@copilotkit/shared");
764
- var UnifyAdapter = class {
765
- apiKey;
766
- model;
767
- start;
768
- constructor(options) {
769
- if (options == null ? void 0 : options.apiKey) {
770
- this.apiKey = options.apiKey;
771
- } else {
772
- this.apiKey = "UNIFY_API_KEY";
773
- }
774
- this.model = options == null ? void 0 : options.model;
775
- this.start = true;
776
- }
777
- async process(request) {
778
- const tools = request.actions.map(convertActionInputToOpenAITool);
779
- const openai = new import_openai3.default({
780
- apiKey: this.apiKey,
781
- baseURL: "https://api.unify.ai/v0/"
782
- });
783
- const messages = request.messages.map(convertMessageToOpenAIMessage);
784
- const stream = await openai.chat.completions.create({
785
- model: this.model,
786
- messages,
787
- stream: true,
788
- ...tools.length > 0 && {
789
- tools
790
- }
791
- });
792
- let model = null;
793
- request.eventSource.stream(async (eventStream$) => {
794
- var _a, _b;
795
- let mode = null;
796
- for await (const chunk of stream) {
797
- if (this.start) {
798
- model = chunk.model;
799
- eventStream$.sendTextMessageStart((0, import_shared4.randomId)());
800
- eventStream$.sendTextMessageContent(`Model used: ${model}
801
- `);
802
- eventStream$.sendTextMessageEnd();
803
- this.start = false;
804
- }
805
- const toolCall = (_a = chunk.choices[0].delta.tool_calls) == null ? void 0 : _a[0];
806
- const content = chunk.choices[0].delta.content;
807
- if (mode === "message" && (toolCall == null ? void 0 : toolCall.id)) {
808
- mode = null;
809
- eventStream$.sendTextMessageEnd();
810
- } else if (mode === "function" && (toolCall === void 0 || (toolCall == null ? void 0 : toolCall.id))) {
811
- mode = null;
812
- eventStream$.sendActionExecutionEnd();
813
- }
814
- if (mode === null) {
815
- if (toolCall == null ? void 0 : toolCall.id) {
816
- mode = "function";
817
- eventStream$.sendActionExecutionStart(toolCall.id, toolCall.function.name);
818
- } else if (content) {
819
- mode = "message";
820
- eventStream$.sendTextMessageStart(chunk.id);
821
- }
822
- }
823
- if (mode === "message" && content) {
824
- eventStream$.sendTextMessageContent(content);
825
- } else if (mode === "function" && ((_b = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _b.arguments)) {
826
- eventStream$.sendActionExecutionArgs(toolCall.function.arguments);
827
- }
828
- }
829
- if (mode === "message") {
830
- eventStream$.sendTextMessageEnd();
831
- } else if (mode === "function") {
832
- eventStream$.sendActionExecutionEnd();
833
- }
834
- eventStream$.complete();
835
- });
836
- return {
837
- threadId: request.threadId || (0, import_shared4.randomId)()
838
- };
839
- }
840
- };
841
- __name(UnifyAdapter, "UnifyAdapter");
842
-
843
- // src/service-adapters/groq/groq-adapter.ts
844
- var import_groq_sdk = require("groq-sdk");
845
- var import_shared5 = require("@copilotkit/shared");
846
- var DEFAULT_MODEL2 = "llama3-groq-70b-8192-tool-use-preview";
847
- var GroqAdapter = class {
848
- model = DEFAULT_MODEL2;
849
- disableParallelToolCalls = false;
850
- _groq;
851
- get groq() {
852
- return this._groq;
853
- }
854
- constructor(params) {
855
- this._groq = (params == null ? void 0 : params.groq) || new import_groq_sdk.Groq({});
856
- if (params == null ? void 0 : params.model) {
857
- this.model = params.model;
858
- }
859
- this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
860
- }
861
- async process(request) {
862
- const { threadId, model = this.model, messages, actions, eventSource, forwardedParameters } = request;
863
- const tools = actions.map(convertActionInputToOpenAITool);
864
- let openaiMessages = messages.map(convertMessageToOpenAIMessage);
865
- openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
866
- let toolChoice = forwardedParameters == null ? void 0 : forwardedParameters.toolChoice;
867
- if ((forwardedParameters == null ? void 0 : forwardedParameters.toolChoice) === "function") {
868
- toolChoice = {
869
- type: "function",
870
- function: {
871
- name: forwardedParameters.toolChoiceFunctionName
872
- }
873
- };
874
- }
875
- const stream = await this.groq.chat.completions.create({
876
- model,
877
- stream: true,
878
- messages: openaiMessages,
879
- ...tools.length > 0 && {
880
- tools
881
- },
882
- ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
883
- max_tokens: forwardedParameters.maxTokens
884
- },
885
- ...(forwardedParameters == null ? void 0 : forwardedParameters.stop) && {
886
- stop: forwardedParameters.stop
887
- },
888
- ...toolChoice && {
889
- tool_choice: toolChoice
890
- },
891
- ...this.disableParallelToolCalls && {
892
- parallel_tool_calls: false
893
- }
894
- });
895
- eventSource.stream(async (eventStream$) => {
896
- var _a, _b;
897
- let mode = null;
898
- for await (const chunk of stream) {
899
- const toolCall = (_a = chunk.choices[0].delta.tool_calls) == null ? void 0 : _a[0];
900
- const content = chunk.choices[0].delta.content;
901
- if (mode === "message" && (toolCall == null ? void 0 : toolCall.id)) {
902
- mode = null;
903
- eventStream$.sendTextMessageEnd();
904
- } else if (mode === "function" && (toolCall === void 0 || (toolCall == null ? void 0 : toolCall.id))) {
905
- mode = null;
906
- eventStream$.sendActionExecutionEnd();
907
- }
908
- if (mode === null) {
909
- if (toolCall == null ? void 0 : toolCall.id) {
910
- mode = "function";
911
- eventStream$.sendActionExecutionStart(toolCall.id, toolCall.function.name);
912
- } else if (content) {
913
- mode = "message";
914
- eventStream$.sendTextMessageStart(chunk.id);
915
- }
916
- }
917
- if (mode === "message" && content) {
918
- eventStream$.sendTextMessageContent(content);
919
- } else if (mode === "function" && ((_b = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _b.arguments)) {
920
- eventStream$.sendActionExecutionArgs(toolCall.function.arguments);
921
- }
922
- }
923
- if (mode === "message") {
924
- eventStream$.sendTextMessageEnd();
925
- } else if (mode === "function") {
926
- eventStream$.sendActionExecutionEnd();
927
- }
928
- eventStream$.complete();
929
- });
930
- return {
931
- threadId: threadId || (0, import_shared5.randomId)()
932
- };
933
- }
934
- };
935
- __name(GroqAdapter, "GroqAdapter");
936
-
937
- // src/service-adapters/anthropic/anthropic-adapter.ts
938
- var import_sdk = __toESM(require("@anthropic-ai/sdk"));
939
-
940
- // src/service-adapters/anthropic/utils.ts
941
- function limitMessagesToTokenCount2(messages, tools, model, maxTokens) {
942
- maxTokens || (maxTokens = MAX_TOKENS);
943
- const result = [];
944
- const toolsNumTokens = countToolsTokens2(model, tools);
945
- if (toolsNumTokens > maxTokens) {
946
- throw new Error(`Too many tokens in function definitions: ${toolsNumTokens} > ${maxTokens}`);
947
- }
948
- maxTokens -= toolsNumTokens;
949
- for (const message of messages) {
950
- if (message.role === "system") {
951
- const numTokens = countMessageTokens2(model, message);
952
- maxTokens -= numTokens;
953
- if (maxTokens < 0) {
954
- throw new Error("Not enough tokens for system message.");
955
- }
956
- }
957
- }
958
- let cutoff = false;
959
- const reversedMessages = [
960
- ...messages
961
- ].reverse();
962
- for (const message of reversedMessages) {
963
- if (message.role === "system") {
964
- result.unshift(message);
965
- continue;
966
- } else if (cutoff) {
967
- continue;
968
- }
969
- let numTokens = countMessageTokens2(model, message);
970
- if (maxTokens < numTokens) {
971
- cutoff = true;
972
- continue;
973
- }
974
- result.unshift(message);
975
- maxTokens -= numTokens;
976
- }
977
- return result;
978
- }
979
- __name(limitMessagesToTokenCount2, "limitMessagesToTokenCount");
980
- var MAX_TOKENS = 128e3;
981
- function countToolsTokens2(model, tools) {
982
- if (tools.length === 0) {
983
- return 0;
984
- }
985
- const json = JSON.stringify(tools);
986
- return countTokens2(model, json);
987
- }
988
- __name(countToolsTokens2, "countToolsTokens");
989
- function countMessageTokens2(model, message) {
990
- return countTokens2(model, JSON.stringify(message.content) || "");
991
- }
992
- __name(countMessageTokens2, "countMessageTokens");
993
- function countTokens2(model, text) {
994
- return text.length / 3;
995
- }
996
- __name(countTokens2, "countTokens");
997
- function convertActionInputToAnthropicTool(action) {
998
- return {
999
- name: action.name,
1000
- description: action.description,
1001
- input_schema: JSON.parse(action.jsonSchema)
1002
- };
1003
- }
1004
- __name(convertActionInputToAnthropicTool, "convertActionInputToAnthropicTool");
1005
- function convertMessageToAnthropicMessage(message) {
1006
- if (message.isTextMessage()) {
1007
- if (message.role === "system") {
1008
- return {
1009
- role: "assistant",
1010
- content: [
1011
- {
1012
- type: "text",
1013
- text: "THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: " + message.content
1014
- }
1015
- ]
1016
- };
1017
- } else {
1018
- return {
1019
- role: message.role === "user" ? "user" : "assistant",
1020
- content: [
1021
- {
1022
- type: "text",
1023
- text: message.content
1024
- }
1025
- ]
1026
- };
1027
- }
1028
- } else if (message.isActionExecutionMessage()) {
1029
- return {
1030
- role: "assistant",
1031
- content: [
1032
- {
1033
- id: message.id,
1034
- type: "tool_use",
1035
- input: message.arguments,
1036
- name: message.name
1037
- }
1038
- ]
1039
- };
1040
- } else if (message.isResultMessage()) {
1041
- return {
1042
- role: "user",
1043
- content: [
1044
- {
1045
- type: "tool_result",
1046
- content: message.result,
1047
- tool_use_id: message.actionExecutionId
1048
- }
1049
- ]
1050
- };
1051
- }
1052
- }
1053
- __name(convertMessageToAnthropicMessage, "convertMessageToAnthropicMessage");
1054
- function groupAnthropicMessagesByRole(messageParams) {
1055
- return messageParams.reduce((acc, message) => {
1056
- const lastGroup = acc[acc.length - 1];
1057
- if (lastGroup && lastGroup.role === message.role) {
1058
- lastGroup.content = lastGroup.content.concat(message.content);
1059
- } else {
1060
- acc.push({
1061
- role: message.role,
1062
- content: [
1063
- ...message.content
1064
- ]
1065
- });
1066
- }
1067
- return acc;
1068
- }, []);
1069
- }
1070
- __name(groupAnthropicMessagesByRole, "groupAnthropicMessagesByRole");
1071
-
1072
- // src/service-adapters/anthropic/anthropic-adapter.ts
1073
- var import_shared6 = require("@copilotkit/shared");
1074
- var DEFAULT_MODEL3 = "claude-3-sonnet-20240229";
1075
- var AnthropicAdapter = class {
1076
- model = DEFAULT_MODEL3;
1077
- _anthropic;
1078
- get anthropic() {
1079
- return this._anthropic;
1080
- }
1081
- constructor(params) {
1082
- this._anthropic = (params == null ? void 0 : params.anthropic) || new import_sdk.default({});
1083
- if (params == null ? void 0 : params.model) {
1084
- this.model = params.model;
1085
- }
1086
- }
1087
- async process(request) {
1088
- const { threadId, model = this.model, messages: rawMessages, actions, eventSource, forwardedParameters } = request;
1089
- const tools = actions.map(convertActionInputToAnthropicTool);
1090
- const messages = [
1091
- ...rawMessages
1092
- ];
1093
- const instructionsMessage = messages.shift();
1094
- const instructions = instructionsMessage.isTextMessage() ? instructionsMessage.content : "";
1095
- let anthropicMessages = messages.map(convertMessageToAnthropicMessage);
1096
- anthropicMessages = limitMessagesToTokenCount2(anthropicMessages, tools, model);
1097
- anthropicMessages = groupAnthropicMessagesByRole(anthropicMessages);
1098
- let toolChoice = forwardedParameters == null ? void 0 : forwardedParameters.toolChoice;
1099
- if ((forwardedParameters == null ? void 0 : forwardedParameters.toolChoice) === "function") {
1100
- toolChoice = {
1101
- type: "tool",
1102
- name: forwardedParameters.toolChoiceFunctionName
1103
- };
1104
- }
1105
- const stream = this.anthropic.messages.create({
1106
- system: instructions,
1107
- model: this.model,
1108
- messages: anthropicMessages,
1109
- max_tokens: (forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) || 1024,
1110
- ...tools.length > 0 && {
1111
- tools
1112
- },
1113
- ...toolChoice && {
1114
- tool_choice: toolChoice
1115
- },
1116
- stream: true
1117
- });
1118
- eventSource.stream(async (eventStream$) => {
1119
- let mode = null;
1120
- let didOutputText = false;
1121
- let currentMessageId = (0, import_shared6.randomId)();
1122
- let currentToolCallId = (0, import_shared6.randomId)();
1123
- let filterThinkingTextBuffer = new FilterThinkingTextBuffer();
1124
- for await (const chunk of await stream) {
1125
- if (chunk.type === "message_start") {
1126
- currentMessageId = chunk.message.id;
1127
- } else if (chunk.type === "content_block_start") {
1128
- if (chunk.content_block.type === "text") {
1129
- didOutputText = false;
1130
- filterThinkingTextBuffer.reset();
1131
- mode = "message";
1132
- } else if (chunk.content_block.type === "tool_use") {
1133
- currentToolCallId = chunk.content_block.id;
1134
- eventStream$.sendActionExecutionStart(currentToolCallId, chunk.content_block.name);
1135
- mode = "function";
1136
- }
1137
- } else if (chunk.type === "content_block_delta") {
1138
- if (chunk.delta.type === "text_delta") {
1139
- const text = filterThinkingTextBuffer.onTextChunk(chunk.delta.text);
1140
- if (text.length > 0) {
1141
- if (!didOutputText) {
1142
- eventStream$.sendTextMessageStart(currentMessageId);
1143
- didOutputText = true;
1144
- }
1145
- eventStream$.sendTextMessageContent(text);
1146
- }
1147
- } else if (chunk.delta.type === "input_json_delta") {
1148
- eventStream$.sendActionExecutionArgs(chunk.delta.partial_json);
1149
- }
1150
- } else if (chunk.type === "content_block_stop") {
1151
- if (mode === "message") {
1152
- if (didOutputText) {
1153
- eventStream$.sendTextMessageEnd();
1154
- }
1155
- } else if (mode === "function") {
1156
- eventStream$.sendActionExecutionEnd();
1157
- }
1158
- }
1159
- }
1160
- eventStream$.complete();
1161
- });
1162
- return {
1163
- threadId: threadId || (0, import_shared6.randomId)()
1164
- };
1165
- }
1166
- };
1167
- __name(AnthropicAdapter, "AnthropicAdapter");
1168
- var THINKING_TAG = "<thinking>";
1169
- var THINKING_TAG_END = "</thinking>";
1170
- var FilterThinkingTextBuffer = /* @__PURE__ */ __name(class FilterThinkingTextBuffer2 {
1171
- buffer;
1172
- didFilterThinkingTag = false;
1173
- constructor() {
1174
- this.buffer = "";
1175
- }
1176
- onTextChunk(text) {
1177
- this.buffer += text;
1178
- if (this.didFilterThinkingTag) {
1179
- return text;
1180
- }
1181
- const potentialTag = this.buffer.slice(0, THINKING_TAG.length);
1182
- if (THINKING_TAG.startsWith(potentialTag)) {
1183
- if (this.buffer.includes(THINKING_TAG_END)) {
1184
- const end = this.buffer.indexOf(THINKING_TAG_END);
1185
- const filteredText = this.buffer.slice(end + THINKING_TAG_END.length);
1186
- this.buffer = filteredText;
1187
- this.didFilterThinkingTag = true;
1188
- return filteredText;
1189
- } else {
1190
- return "";
1191
- }
1192
- }
1193
- return text;
1194
- }
1195
- reset() {
1196
- this.buffer = "";
1197
- this.didFilterThinkingTag = false;
1198
- }
1199
- }, "FilterThinkingTextBuffer");
1200
- // Annotate the CommonJS export names for ESM import in node:
1201
- 0 && (module.exports = {
1202
- AnthropicAdapter,
1203
- GoogleGenerativeAIAdapter,
1204
- GroqAdapter,
1205
- LangChainAdapter,
1206
- OpenAIAdapter,
1207
- OpenAIAssistantAdapter,
1208
- RemoteChain,
1209
- UnifyAdapter
1210
- });
1211
- //# sourceMappingURL=index.js.map