@copilotkit/runtime 1.2.2-feat-runtime-remote-actions.1 → 1.3.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +6 -13
  2. package/dist/{chunk-BPEPG56J.mjs → chunk-47TPNJX7.mjs} +2 -2
  3. package/dist/{chunk-Y5TWOZFD.mjs → chunk-4BZ6WXBB.mjs} +3 -3
  4. package/dist/{chunk-3SKYFYY2.mjs → chunk-IRRAL44O.mjs} +4 -5
  5. package/dist/chunk-IRRAL44O.mjs.map +1 -0
  6. package/dist/{chunk-BJ2LVHWA.mjs → chunk-OF6AN6HF.mjs} +521 -256
  7. package/dist/chunk-OF6AN6HF.mjs.map +1 -0
  8. package/dist/{chunk-UL2OKN2O.mjs → chunk-VWS65V7Y.mjs} +2 -2
  9. package/dist/{chunk-U2EKJP47.mjs → chunk-XCGRXAJU.mjs} +2 -2
  10. package/dist/{copilot-runtime-d427e991.d.ts → copilot-runtime-a1b5f1ce.d.ts} +1 -1
  11. package/dist/{index-079752b9.d.ts → groq-adapter-069ac812.d.ts} +82 -82
  12. package/dist/index.d.ts +7 -5
  13. package/dist/index.js +721 -454
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +10 -6
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/{langserve-d6073a3b.d.ts → langserve-15a1286b.d.ts} +1 -1
  18. package/dist/lib/index.d.ts +4 -4
  19. package/dist/lib/index.js +445 -446
  20. package/dist/lib/index.js.map +1 -1
  21. package/dist/lib/index.mjs +6 -6
  22. package/dist/lib/integrations/index.d.ts +3 -3
  23. package/dist/lib/integrations/index.js +3 -4
  24. package/dist/lib/integrations/index.js.map +1 -1
  25. package/dist/lib/integrations/index.mjs +4 -4
  26. package/dist/lib/integrations/nest/index.d.ts +2 -2
  27. package/dist/lib/integrations/nest/index.js +3 -4
  28. package/dist/lib/integrations/nest/index.js.map +1 -1
  29. package/dist/lib/integrations/nest/index.mjs +2 -2
  30. package/dist/lib/integrations/node-express/index.d.ts +2 -2
  31. package/dist/lib/integrations/node-express/index.js +3 -4
  32. package/dist/lib/integrations/node-express/index.js.map +1 -1
  33. package/dist/lib/integrations/node-express/index.mjs +2 -2
  34. package/dist/lib/integrations/node-http/index.d.ts +2 -2
  35. package/dist/lib/integrations/node-http/index.js +3 -4
  36. package/dist/lib/integrations/node-http/index.js.map +1 -1
  37. package/dist/lib/integrations/node-http/index.mjs +1 -1
  38. package/dist/service-adapters/index.d.ts +47 -3
  39. package/dist/service-adapters/index.js +708 -442
  40. package/dist/service-adapters/index.js.map +1 -1
  41. package/dist/service-adapters/index.mjs +3 -1
  42. package/package.json +6 -7
  43. package/src/index.ts +1 -0
  44. package/src/service-adapters/anthropic/anthropic-adapter.ts +197 -0
  45. package/src/service-adapters/anthropic/utils.ts +144 -0
  46. package/src/service-adapters/index.ts +9 -7
  47. package/dist/chunk-3SKYFYY2.mjs.map +0 -1
  48. package/dist/chunk-BJ2LVHWA.mjs.map +0 -1
  49. /package/dist/{chunk-BPEPG56J.mjs.map → chunk-47TPNJX7.mjs.map} +0 -0
  50. /package/dist/{chunk-Y5TWOZFD.mjs.map → chunk-4BZ6WXBB.mjs.map} +0 -0
  51. /package/dist/{chunk-UL2OKN2O.mjs.map → chunk-VWS65V7Y.mjs.map} +0 -0
  52. /package/dist/{chunk-U2EKJP47.mjs.map → chunk-XCGRXAJU.mjs.map} +0 -0
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/service-adapters/index.ts
31
31
  var service_adapters_exports = {};
32
32
  __export(service_adapters_exports, {
33
+ AnthropicAdapter: () => AnthropicAdapter,
33
34
  GoogleGenerativeAIAdapter: () => GoogleGenerativeAIAdapter,
34
35
  GroqAdapter: () => GroqAdapter,
35
36
  LangChainAdapter: () => LangChainAdapter,
@@ -40,6 +41,84 @@ __export(service_adapters_exports, {
40
41
  });
41
42
  module.exports = __toCommonJS(service_adapters_exports);
42
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
+
43
122
  // src/service-adapters/openai/openai-adapter.ts
44
123
  var import_openai = __toESM(require("openai"));
45
124
 
@@ -329,167 +408,229 @@ var OpenAIAdapter = class {
329
408
  };
330
409
  __name(OpenAIAdapter, "OpenAIAdapter");
331
410
 
332
- // src/service-adapters/openai/openai-assistant-adapter.ts
333
- var import_openai2 = __toESM(require("openai"));
334
- var OpenAIAssistantAdapter = class {
335
- openai;
336
- codeInterpreterEnabled;
337
- assistantId;
338
- fileSearchEnabled;
339
- disableParallelToolCalls;
340
- constructor(params) {
341
- this.openai = params.openai || new import_openai2.default({});
342
- this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;
343
- this.fileSearchEnabled = params.fileSearchEnabled === false || true;
344
- this.assistantId = params.assistantId;
345
- this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
346
- }
347
- async process(request) {
348
- const { messages, actions, eventSource, runId, forwardedParameters } = request;
349
- let threadId = request.threadId || (await this.openai.beta.threads.create()).id;
350
- const lastMessage = messages.at(-1);
351
- let nextRunId = void 0;
352
- if (lastMessage instanceof ResultMessage && runId) {
353
- nextRunId = await this.submitToolOutputs(threadId, runId, messages, eventSource);
354
- } else if (lastMessage instanceof TextMessage) {
355
- nextRunId = await this.submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters);
356
- } else {
357
- throw new Error("No actionable message found in the messages");
358
- }
359
- return {
360
- threadId,
361
- runId: nextRunId
362
- };
363
- }
364
- async submitToolOutputs(threadId, runId, messages, eventSource) {
365
- let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);
366
- if (!run.required_action) {
367
- throw new Error("No tool outputs required");
368
- }
369
- const toolCallsIds = run.required_action.submit_tool_outputs.tool_calls.map((toolCall) => toolCall.id);
370
- const resultMessages = messages.filter((message) => message instanceof ResultMessage && toolCallsIds.includes(message.actionExecutionId));
371
- if (toolCallsIds.length != resultMessages.length) {
372
- throw new Error("Number of function results does not match the number of tool calls");
373
- }
374
- const toolOutputs = resultMessages.map((message) => {
375
- return {
376
- tool_call_id: message.actionExecutionId,
377
- output: message.result
378
- };
379
- });
380
- const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {
381
- tool_outputs: toolOutputs,
382
- ...this.disableParallelToolCalls && {
383
- parallel_tool_calls: false
384
- }
385
- });
386
- await this.streamResponse(stream, eventSource);
387
- return runId;
388
- }
389
- async submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters) {
390
- messages = [
391
- ...messages
392
- ];
393
- const instructionsMessage = messages.shift();
394
- const instructions = instructionsMessage instanceof TextMessage ? instructionsMessage.content : "";
395
- const userMessage = messages.map(convertMessageToOpenAIMessage).map(convertSystemMessageToAssistantAPI).at(-1);
396
- if (userMessage.role !== "user") {
397
- throw new Error("No user message found");
411
+ // src/service-adapters/langchain/utils.ts
412
+ var import_messages = require("@langchain/core/messages");
413
+ var import_tools = require("@langchain/core/tools");
414
+ var import_zod = require("zod");
415
+ var import_shared2 = require("@copilotkit/shared");
416
+ function convertMessageToLangChainMessage(message) {
417
+ if (message instanceof TextMessage) {
418
+ if (message.role == "user") {
419
+ return new import_messages.HumanMessage(message.content);
420
+ } else if (message.role == "assistant") {
421
+ return new import_messages.AIMessage(message.content);
422
+ } else if (message.role === "system") {
423
+ return new import_messages.SystemMessage(message.content);
398
424
  }
399
- await this.openai.beta.threads.messages.create(threadId, {
400
- role: "user",
401
- content: userMessage.content
402
- });
403
- const openaiTools = actions.map(convertActionInputToOpenAITool);
404
- const tools = [
405
- ...openaiTools,
406
- ...this.codeInterpreterEnabled ? [
407
- {
408
- type: "code_interpreter"
409
- }
410
- ] : [],
411
- ...this.fileSearchEnabled ? [
425
+ } else if (message instanceof ActionExecutionMessage) {
426
+ return new import_messages.AIMessage({
427
+ content: "",
428
+ tool_calls: [
412
429
  {
413
- type: "file_search"
430
+ id: message.id,
431
+ args: message.arguments,
432
+ name: message.name
414
433
  }
415
- ] : []
416
- ];
417
- let stream = this.openai.beta.threads.runs.stream(threadId, {
418
- assistant_id: this.assistantId,
419
- instructions,
420
- tools,
421
- ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
422
- max_completion_tokens: forwardedParameters.maxTokens
423
- },
424
- ...this.disableParallelToolCalls && {
425
- parallel_tool_calls: false
426
- }
434
+ ]
427
435
  });
428
- await this.streamResponse(stream, eventSource);
429
- return getRunIdFromStream(stream);
430
- }
431
- async streamResponse(stream, eventSource) {
432
- eventSource.stream(async (eventStream$) => {
433
- var _a, _b, _c, _d, _e, _f;
434
- let inFunctionCall = false;
435
- for await (const chunk of stream) {
436
- switch (chunk.event) {
437
- case "thread.message.created":
438
- if (inFunctionCall) {
439
- eventStream$.sendActionExecutionEnd();
440
- }
441
- eventStream$.sendTextMessageStart(chunk.data.id);
442
- break;
443
- case "thread.message.delta":
444
- if (((_a = chunk.data.delta.content) == null ? void 0 : _a[0].type) === "text") {
445
- eventStream$.sendTextMessageContent((_b = chunk.data.delta.content) == null ? void 0 : _b[0].text.value);
446
- }
447
- break;
448
- case "thread.message.completed":
449
- eventStream$.sendTextMessageEnd();
450
- break;
451
- case "thread.run.step.delta":
452
- let toolCallId;
453
- let toolCallName;
454
- let toolCallArgs;
455
- if (chunk.data.delta.step_details.type === "tool_calls" && ((_c = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _c[0].type) === "function") {
456
- toolCallId = (_d = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _d[0].id;
457
- toolCallName = (_e = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _e[0].function.name;
458
- toolCallArgs = (_f = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _f[0].function.arguments;
459
- }
460
- if (toolCallName && toolCallId) {
461
- if (inFunctionCall) {
462
- eventStream$.sendActionExecutionEnd();
463
- }
464
- inFunctionCall = true;
465
- eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
466
- } else if (toolCallArgs) {
467
- eventStream$.sendActionExecutionArgs(toolCallArgs);
468
- }
469
- break;
470
- }
471
- }
472
- if (inFunctionCall) {
473
- eventStream$.sendActionExecutionEnd();
474
- }
475
- eventStream$.complete();
436
+ } else if (message instanceof ResultMessage) {
437
+ return new import_messages.ToolMessage({
438
+ content: message.result,
439
+ tool_call_id: message.actionExecutionId
476
440
  });
477
441
  }
478
- };
479
- __name(OpenAIAssistantAdapter, "OpenAIAssistantAdapter");
480
- function getRunIdFromStream(stream) {
481
- return new Promise((resolve, reject) => {
482
- let runIdGetter = /* @__PURE__ */ __name((event) => {
483
- if (event.event === "thread.run.created") {
484
- const runId = event.data.id;
485
- stream.off("event", runIdGetter);
486
- resolve(runId);
487
- }
488
- }, "runIdGetter");
489
- stream.on("event", runIdGetter);
490
- });
491
442
  }
492
- __name(getRunIdFromStream, "getRunIdFromStream");
443
+ __name(convertMessageToLangChainMessage, "convertMessageToLangChainMessage");
444
+ function convertJsonSchemaToZodSchema(jsonSchema, required) {
445
+ if (jsonSchema.type === "object") {
446
+ const spec = {};
447
+ for (const [key, value] of Object.entries(jsonSchema.properties)) {
448
+ spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);
449
+ }
450
+ let schema = import_zod.z.object(spec);
451
+ return !required ? schema.optional() : schema;
452
+ } else if (jsonSchema.type === "string") {
453
+ let schema = import_zod.z.string().describe(jsonSchema.description);
454
+ return !required ? schema.optional() : schema;
455
+ } else if (jsonSchema.type === "number") {
456
+ let schema = import_zod.z.number().describe(jsonSchema.description);
457
+ return !required ? schema.optional() : schema;
458
+ } else if (jsonSchema.type === "boolean") {
459
+ let schema = import_zod.z.boolean().describe(jsonSchema.description);
460
+ return !required ? schema.optional() : schema;
461
+ } else if (jsonSchema.type === "array") {
462
+ let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, false);
463
+ let schema = import_zod.z.array(itemSchema);
464
+ return !required ? schema.optional() : schema;
465
+ }
466
+ }
467
+ __name(convertJsonSchemaToZodSchema, "convertJsonSchemaToZodSchema");
468
+ function convertActionInputToLangChainTool(actionInput) {
469
+ return new import_tools.DynamicStructuredTool({
470
+ name: actionInput.name,
471
+ description: actionInput.description,
472
+ schema: convertJsonSchemaToZodSchema(JSON.parse(actionInput.jsonSchema), true),
473
+ func: async () => {
474
+ return "";
475
+ }
476
+ });
477
+ }
478
+ __name(convertActionInputToLangChainTool, "convertActionInputToLangChainTool");
479
+ function getConstructorName(object) {
480
+ if (object && typeof object === "object" && object.constructor && object.constructor.name) {
481
+ return object.constructor.name;
482
+ }
483
+ return "";
484
+ }
485
+ __name(getConstructorName, "getConstructorName");
486
+ function isAIMessage(message) {
487
+ return getConstructorName(message) === "AIMessage";
488
+ }
489
+ __name(isAIMessage, "isAIMessage");
490
+ function isAIMessageChunk(message) {
491
+ return getConstructorName(message) === "AIMessageChunk";
492
+ }
493
+ __name(isAIMessageChunk, "isAIMessageChunk");
494
+ function isBaseMessageChunk(message) {
495
+ return getConstructorName(message) === "BaseMessageChunk";
496
+ }
497
+ __name(isBaseMessageChunk, "isBaseMessageChunk");
498
+ function maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution) {
499
+ if (actionExecution) {
500
+ eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, "Sending a message");
501
+ }
502
+ }
503
+ __name(maybeSendActionExecutionResultIsMessage, "maybeSendActionExecutionResultIsMessage");
504
+ async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
505
+ var _a, _b, _c, _d, _e, _f, _g, _h;
506
+ if (typeof result === "string") {
507
+ if (!actionExecution) {
508
+ eventStream$.sendTextMessage((0, import_shared2.randomId)(), result);
509
+ } else {
510
+ eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);
511
+ }
512
+ } else if (isAIMessage(result)) {
513
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
514
+ if (result.content) {
515
+ eventStream$.sendTextMessage((0, import_shared2.randomId)(), result.content);
516
+ }
517
+ for (const toolCall of result.tool_calls) {
518
+ eventStream$.sendActionExecution(toolCall.id || (0, import_shared2.randomId)(), toolCall.name, JSON.stringify(toolCall.args));
519
+ }
520
+ } else if (isBaseMessageChunk(result)) {
521
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
522
+ if ((_a = result.lc_kwargs) == null ? void 0 : _a.content) {
523
+ eventStream$.sendTextMessage((0, import_shared2.randomId)(), result.content);
524
+ }
525
+ if ((_b = result.lc_kwargs) == null ? void 0 : _b.tool_calls) {
526
+ for (const toolCall of (_c = result.lc_kwargs) == null ? void 0 : _c.tool_calls) {
527
+ eventStream$.sendActionExecution(toolCall.id || (0, import_shared2.randomId)(), toolCall.name, JSON.stringify(toolCall.args));
528
+ }
529
+ }
530
+ } else if (result && "getReader" in result) {
531
+ maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
532
+ let reader = result.getReader();
533
+ let mode = null;
534
+ while (true) {
535
+ try {
536
+ const { done, value } = await reader.read();
537
+ let toolCallName = void 0;
538
+ let toolCallId = void 0;
539
+ let toolCallArgs = void 0;
540
+ let hasToolCall = false;
541
+ let content = value == null ? void 0 : value.content;
542
+ if (isAIMessageChunk(value)) {
543
+ let chunk = (_d = value.tool_call_chunks) == null ? void 0 : _d[0];
544
+ toolCallName = chunk == null ? void 0 : chunk.name;
545
+ toolCallId = chunk == null ? void 0 : chunk.id;
546
+ toolCallArgs = chunk == null ? void 0 : chunk.args;
547
+ hasToolCall = chunk != void 0;
548
+ } else if (isBaseMessageChunk(value)) {
549
+ let chunk = (_f = (_e = value.additional_kwargs) == null ? void 0 : _e.tool_calls) == null ? void 0 : _f[0];
550
+ toolCallName = (_g = chunk == null ? void 0 : chunk.function) == null ? void 0 : _g.name;
551
+ toolCallId = chunk == null ? void 0 : chunk.id;
552
+ toolCallArgs = (_h = chunk == null ? void 0 : chunk.function) == null ? void 0 : _h.arguments;
553
+ hasToolCall = (chunk == null ? void 0 : chunk.function) != void 0;
554
+ }
555
+ if (mode === "message" && (toolCallId || done)) {
556
+ mode = null;
557
+ eventStream$.sendTextMessageEnd();
558
+ } else if (mode === "function" && (!hasToolCall || done)) {
559
+ mode = null;
560
+ eventStream$.sendActionExecutionEnd();
561
+ }
562
+ if (done) {
563
+ break;
564
+ }
565
+ if (mode === null) {
566
+ if (hasToolCall) {
567
+ mode = "function";
568
+ eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
569
+ } else if (content) {
570
+ mode = "message";
571
+ eventStream$.sendTextMessageStart((0, import_shared2.randomId)());
572
+ }
573
+ }
574
+ if (mode === "message" && content) {
575
+ eventStream$.sendTextMessageContent(content);
576
+ } else if (mode === "function" && toolCallArgs) {
577
+ eventStream$.sendActionExecutionArgs(toolCallArgs);
578
+ }
579
+ } catch (error) {
580
+ console.error("Error reading from stream", error);
581
+ break;
582
+ }
583
+ }
584
+ } else if (actionExecution) {
585
+ eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, encodeResult(result));
586
+ } else {
587
+ throw new Error("Invalid return type from LangChain function.");
588
+ }
589
+ eventStream$.complete();
590
+ }
591
+ __name(streamLangChainResponse, "streamLangChainResponse");
592
+ function encodeResult(result) {
593
+ if (result === void 0) {
594
+ return "";
595
+ } else if (typeof result === "string") {
596
+ return result;
597
+ } else {
598
+ return JSON.stringify(result);
599
+ }
600
+ }
601
+ __name(encodeResult, "encodeResult");
602
+
603
+ // src/service-adapters/langchain/langchain-adapter.ts
604
+ var import_shared3 = require("@copilotkit/shared");
605
+ var LangChainAdapter = class {
606
+ options;
607
+ /**
608
+ * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.
609
+ */
610
+ constructor(options) {
611
+ this.options = options;
612
+ }
613
+ async process(request) {
614
+ const { eventSource, model, actions, messages, threadId, runId } = request;
615
+ const result = await this.options.chainFn({
616
+ messages: messages.map(convertMessageToLangChainMessage),
617
+ tools: actions.map(convertActionInputToLangChainTool),
618
+ model,
619
+ threadId,
620
+ runId
621
+ });
622
+ eventSource.stream(async (eventStream$) => {
623
+ await streamLangChainResponse({
624
+ result,
625
+ eventStream$
626
+ });
627
+ });
628
+ return {
629
+ threadId: threadId || (0, import_shared3.randomId)()
630
+ };
631
+ }
632
+ };
633
+ __name(LangChainAdapter, "LangChainAdapter");
493
634
 
494
635
  // src/service-adapters/google/google-genai-adapter.ts
495
636
  var import_generative_ai = require("@google/generative-ai");
@@ -580,7 +721,7 @@ function tryParseJson(str) {
580
721
  __name(tryParseJson, "tryParseJson");
581
722
 
582
723
  // src/service-adapters/google/google-genai-adapter.ts
583
- var import_shared2 = require("@copilotkit/shared");
724
+ var import_shared4 = require("@copilotkit/shared");
584
725
  var GoogleGenerativeAIAdapter = class {
585
726
  model;
586
727
  constructor(options) {
@@ -647,7 +788,7 @@ var GoogleGenerativeAIAdapter = class {
647
788
  }
648
789
  if (!isTextMessage) {
649
790
  isTextMessage = true;
650
- eventStream$.sendTextMessageStart((0, import_shared2.randomId)());
791
+ eventStream$.sendTextMessageStart((0, import_shared4.randomId)());
651
792
  }
652
793
  eventStream$.sendTextMessageContent(chunkText);
653
794
  }
@@ -657,13 +798,13 @@ var GoogleGenerativeAIAdapter = class {
657
798
  let calls = (await result.response).functionCalls();
658
799
  if (calls) {
659
800
  for (let call of calls) {
660
- eventStream$.sendActionExecution((0, import_shared2.randomId)(), call.name, JSON.stringify(replaceNewlinesInObject(call.args)));
801
+ eventStream$.sendActionExecution((0, import_shared4.randomId)(), call.name, JSON.stringify(replaceNewlinesInObject(call.args)));
661
802
  }
662
803
  }
663
804
  eventStream$.complete();
664
805
  });
665
806
  return {
666
- threadId: request.threadId || (0, import_shared2.randomId)()
807
+ threadId: request.threadId || (0, import_shared4.randomId)()
667
808
  };
668
809
  }
669
810
  };
@@ -686,307 +827,167 @@ function replaceNewlinesInObject(obj) {
686
827
  }
687
828
  __name(replaceNewlinesInObject, "replaceNewlinesInObject");
688
829
 
689
- // src/service-adapters/langchain/utils.ts
690
- var import_messages = require("@langchain/core/messages");
691
- var import_tools = require("@langchain/core/tools");
692
- var import_zod = require("zod");
693
- var import_shared3 = require("@copilotkit/shared");
694
- function convertMessageToLangChainMessage(message) {
695
- if (message instanceof TextMessage) {
696
- if (message.role == "user") {
697
- return new import_messages.HumanMessage(message.content);
698
- } else if (message.role == "assistant") {
699
- return new import_messages.AIMessage(message.content);
700
- } else if (message.role === "system") {
701
- return new import_messages.SystemMessage(message.content);
702
- }
703
- } else if (message instanceof ActionExecutionMessage) {
704
- return new import_messages.AIMessage({
705
- content: "",
706
- tool_calls: [
707
- {
708
- id: message.id,
709
- args: message.arguments,
710
- name: message.name
711
- }
712
- ]
713
- });
714
- } else if (message instanceof ResultMessage) {
715
- return new import_messages.ToolMessage({
716
- content: message.result,
717
- tool_call_id: message.actionExecutionId
718
- });
830
+ // src/service-adapters/openai/openai-assistant-adapter.ts
831
+ var import_openai2 = __toESM(require("openai"));
832
+ var OpenAIAssistantAdapter = class {
833
+ openai;
834
+ codeInterpreterEnabled;
835
+ assistantId;
836
+ fileSearchEnabled;
837
+ disableParallelToolCalls;
838
+ constructor(params) {
839
+ this.openai = params.openai || new import_openai2.default({});
840
+ this.codeInterpreterEnabled = params.codeInterpreterEnabled === false || true;
841
+ this.fileSearchEnabled = params.fileSearchEnabled === false || true;
842
+ this.assistantId = params.assistantId;
843
+ this.disableParallelToolCalls = (params == null ? void 0 : params.disableParallelToolCalls) || false;
719
844
  }
720
- }
721
- __name(convertMessageToLangChainMessage, "convertMessageToLangChainMessage");
722
- function convertJsonSchemaToZodSchema(jsonSchema, required) {
723
- if (jsonSchema.type === "object") {
724
- const spec = {};
725
- for (const [key, value] of Object.entries(jsonSchema.properties)) {
726
- spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);
845
+ async process(request) {
846
+ const { messages, actions, eventSource, runId, forwardedParameters } = request;
847
+ let threadId = request.threadId || (await this.openai.beta.threads.create()).id;
848
+ const lastMessage = messages.at(-1);
849
+ let nextRunId = void 0;
850
+ if (lastMessage instanceof ResultMessage && runId) {
851
+ nextRunId = await this.submitToolOutputs(threadId, runId, messages, eventSource);
852
+ } else if (lastMessage instanceof TextMessage) {
853
+ nextRunId = await this.submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters);
854
+ } else {
855
+ throw new Error("No actionable message found in the messages");
727
856
  }
728
- let schema = import_zod.z.object(spec);
729
- return !required ? schema.optional() : schema;
730
- } else if (jsonSchema.type === "string") {
731
- let schema = import_zod.z.string().describe(jsonSchema.description);
732
- return !required ? schema.optional() : schema;
733
- } else if (jsonSchema.type === "number") {
734
- let schema = import_zod.z.number().describe(jsonSchema.description);
735
- return !required ? schema.optional() : schema;
736
- } else if (jsonSchema.type === "boolean") {
737
- let schema = import_zod.z.boolean().describe(jsonSchema.description);
738
- return !required ? schema.optional() : schema;
739
- } else if (jsonSchema.type === "array") {
740
- let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, false);
741
- let schema = import_zod.z.array(itemSchema);
742
- return !required ? schema.optional() : schema;
743
- }
744
- }
745
- __name(convertJsonSchemaToZodSchema, "convertJsonSchemaToZodSchema");
746
- function convertActionInputToLangChainTool(actionInput) {
747
- return new import_tools.DynamicStructuredTool({
748
- name: actionInput.name,
749
- description: actionInput.description,
750
- schema: convertJsonSchemaToZodSchema(JSON.parse(actionInput.jsonSchema), true),
751
- func: async () => {
752
- return "";
753
- }
754
- });
755
- }
756
- __name(convertActionInputToLangChainTool, "convertActionInputToLangChainTool");
757
- function getConstructorName(object) {
758
- if (object && typeof object === "object" && object.constructor && object.constructor.name) {
759
- return object.constructor.name;
760
- }
761
- return "";
762
- }
763
- __name(getConstructorName, "getConstructorName");
764
- function isAIMessage(message) {
765
- return getConstructorName(message) === "AIMessage";
766
- }
767
- __name(isAIMessage, "isAIMessage");
768
- function isAIMessageChunk(message) {
769
- return getConstructorName(message) === "AIMessageChunk";
770
- }
771
- __name(isAIMessageChunk, "isAIMessageChunk");
772
- function isBaseMessageChunk(message) {
773
- return getConstructorName(message) === "BaseMessageChunk";
774
- }
775
- __name(isBaseMessageChunk, "isBaseMessageChunk");
776
- function maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution) {
777
- if (actionExecution) {
778
- eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, "Sending a message");
857
+ return {
858
+ threadId,
859
+ runId: nextRunId
860
+ };
779
861
  }
780
- }
781
- __name(maybeSendActionExecutionResultIsMessage, "maybeSendActionExecutionResultIsMessage");
782
- async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
783
- var _a, _b, _c, _d, _e, _f, _g, _h;
784
- if (typeof result === "string") {
785
- if (!actionExecution) {
786
- eventStream$.sendTextMessage((0, import_shared3.randomId)(), result);
787
- } else {
788
- eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, result);
789
- }
790
- } else if (isAIMessage(result)) {
791
- maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
792
- if (result.content) {
793
- eventStream$.sendTextMessage((0, import_shared3.randomId)(), result.content);
794
- }
795
- for (const toolCall of result.tool_calls) {
796
- eventStream$.sendActionExecution(toolCall.id || (0, import_shared3.randomId)(), toolCall.name, JSON.stringify(toolCall.args));
862
+ async submitToolOutputs(threadId, runId, messages, eventSource) {
863
+ let run = await this.openai.beta.threads.runs.retrieve(threadId, runId);
864
+ if (!run.required_action) {
865
+ throw new Error("No tool outputs required");
797
866
  }
798
- } else if (isBaseMessageChunk(result)) {
799
- maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
800
- if ((_a = result.lc_kwargs) == null ? void 0 : _a.content) {
801
- eventStream$.sendTextMessage((0, import_shared3.randomId)(), result.content);
867
+ const toolCallsIds = run.required_action.submit_tool_outputs.tool_calls.map((toolCall) => toolCall.id);
868
+ const resultMessages = messages.filter((message) => message instanceof ResultMessage && toolCallsIds.includes(message.actionExecutionId));
869
+ if (toolCallsIds.length != resultMessages.length) {
870
+ throw new Error("Number of function results does not match the number of tool calls");
802
871
  }
803
- if ((_b = result.lc_kwargs) == null ? void 0 : _b.tool_calls) {
804
- for (const toolCall of (_c = result.lc_kwargs) == null ? void 0 : _c.tool_calls) {
805
- eventStream$.sendActionExecution(toolCall.id || (0, import_shared3.randomId)(), toolCall.name, JSON.stringify(toolCall.args));
872
+ const toolOutputs = resultMessages.map((message) => {
873
+ return {
874
+ tool_call_id: message.actionExecutionId,
875
+ output: message.result
876
+ };
877
+ });
878
+ const stream = this.openai.beta.threads.runs.submitToolOutputsStream(threadId, runId, {
879
+ tool_outputs: toolOutputs,
880
+ ...this.disableParallelToolCalls && {
881
+ parallel_tool_calls: false
806
882
  }
883
+ });
884
+ await this.streamResponse(stream, eventSource);
885
+ return runId;
886
+ }
887
+ async submitUserMessage(threadId, messages, actions, eventSource, forwardedParameters) {
888
+ messages = [
889
+ ...messages
890
+ ];
891
+ const instructionsMessage = messages.shift();
892
+ const instructions = instructionsMessage instanceof TextMessage ? instructionsMessage.content : "";
893
+ const userMessage = messages.map(convertMessageToOpenAIMessage).map(convertSystemMessageToAssistantAPI).at(-1);
894
+ if (userMessage.role !== "user") {
895
+ throw new Error("No user message found");
807
896
  }
808
- } else if (result && "getReader" in result) {
809
- maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
810
- let reader = result.getReader();
811
- let mode = null;
812
- while (true) {
813
- try {
814
- const { done, value } = await reader.read();
815
- let toolCallName = void 0;
816
- let toolCallId = void 0;
817
- let toolCallArgs = void 0;
818
- let hasToolCall = false;
819
- let content = value == null ? void 0 : value.content;
820
- if (isAIMessageChunk(value)) {
821
- let chunk = (_d = value.tool_call_chunks) == null ? void 0 : _d[0];
822
- toolCallName = chunk == null ? void 0 : chunk.name;
823
- toolCallId = chunk == null ? void 0 : chunk.id;
824
- toolCallArgs = chunk == null ? void 0 : chunk.args;
825
- hasToolCall = chunk != void 0;
826
- } else if (isBaseMessageChunk(value)) {
827
- let chunk = (_f = (_e = value.additional_kwargs) == null ? void 0 : _e.tool_calls) == null ? void 0 : _f[0];
828
- toolCallName = (_g = chunk == null ? void 0 : chunk.function) == null ? void 0 : _g.name;
829
- toolCallId = chunk == null ? void 0 : chunk.id;
830
- toolCallArgs = (_h = chunk == null ? void 0 : chunk.function) == null ? void 0 : _h.arguments;
831
- hasToolCall = (chunk == null ? void 0 : chunk.function) != void 0;
832
- }
833
- if (mode === "message" && (toolCallId || done)) {
834
- mode = null;
835
- eventStream$.sendTextMessageEnd();
836
- } else if (mode === "function" && (!hasToolCall || done)) {
837
- mode = null;
838
- eventStream$.sendActionExecutionEnd();
839
- }
840
- if (done) {
841
- break;
842
- }
843
- if (mode === null) {
844
- if (hasToolCall) {
845
- mode = "function";
846
- eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
847
- } else if (content) {
848
- mode = "message";
849
- eventStream$.sendTextMessageStart((0, import_shared3.randomId)());
850
- }
897
+ await this.openai.beta.threads.messages.create(threadId, {
898
+ role: "user",
899
+ content: userMessage.content
900
+ });
901
+ const openaiTools = actions.map(convertActionInputToOpenAITool);
902
+ const tools = [
903
+ ...openaiTools,
904
+ ...this.codeInterpreterEnabled ? [
905
+ {
906
+ type: "code_interpreter"
851
907
  }
852
- if (mode === "message" && content) {
853
- eventStream$.sendTextMessageContent(content);
854
- } else if (mode === "function" && toolCallArgs) {
855
- eventStream$.sendActionExecutionArgs(toolCallArgs);
908
+ ] : [],
909
+ ...this.fileSearchEnabled ? [
910
+ {
911
+ type: "file_search"
856
912
  }
857
- } catch (error) {
858
- console.error("Error reading from stream", error);
859
- break;
913
+ ] : []
914
+ ];
915
+ let stream = this.openai.beta.threads.runs.stream(threadId, {
916
+ assistant_id: this.assistantId,
917
+ instructions,
918
+ tools,
919
+ ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
920
+ max_completion_tokens: forwardedParameters.maxTokens
921
+ },
922
+ ...this.disableParallelToolCalls && {
923
+ parallel_tool_calls: false
860
924
  }
861
- }
862
- } else if (actionExecution) {
863
- eventStream$.sendActionExecutionResult(actionExecution.id, actionExecution.name, encodeResult(result));
864
- } else {
865
- throw new Error("Invalid return type from LangChain function.");
866
- }
867
- eventStream$.complete();
868
- }
869
- __name(streamLangChainResponse, "streamLangChainResponse");
870
- function encodeResult(result) {
871
- if (result === void 0) {
872
- return "";
873
- } else if (typeof result === "string") {
874
- return result;
875
- } else {
876
- return JSON.stringify(result);
877
- }
878
- }
879
- __name(encodeResult, "encodeResult");
880
-
881
- // src/service-adapters/langchain/langchain-adapter.ts
882
- var import_shared4 = require("@copilotkit/shared");
883
- var LangChainAdapter = class {
884
- options;
885
- /**
886
- * To use LangChain as a backend, provide a handler function to the adapter with your custom LangChain logic.
887
- */
888
- constructor(options) {
889
- this.options = options;
890
- }
891
- async process(request) {
892
- const { eventSource, model, actions, messages, threadId, runId } = request;
893
- const result = await this.options.chainFn({
894
- messages: messages.map(convertMessageToLangChainMessage),
895
- tools: actions.map(convertActionInputToLangChainTool),
896
- model,
897
- threadId,
898
- runId
899
925
  });
900
- eventSource.stream(async (eventStream$) => {
901
- await streamLangChainResponse({
902
- result,
903
- eventStream$
904
- });
905
- });
906
- return {
907
- threadId: threadId || (0, import_shared4.randomId)()
908
- };
909
- }
910
- };
911
- __name(LangChainAdapter, "LangChainAdapter");
912
-
913
- // src/service-adapters/langchain/langserve.ts
914
- var import_remote = require("langchain/runnables/remote");
915
- var RemoteChain = class {
916
- name;
917
- description;
918
- chainUrl;
919
- parameters;
920
- parameterType;
921
- constructor(options) {
922
- this.name = options.name;
923
- this.description = options.description;
924
- this.chainUrl = options.chainUrl;
925
- this.parameters = options.parameters;
926
- this.parameterType = options.parameterType || "multi";
926
+ await this.streamResponse(stream, eventSource);
927
+ return getRunIdFromStream(stream);
927
928
  }
928
- async toAction() {
929
- if (!this.parameters) {
930
- await this.inferLangServeParameters();
931
- }
932
- return {
933
- name: this.name,
934
- description: this.description,
935
- parameters: this.parameters,
936
- handler: async (args) => {
937
- const runnable = new import_remote.RemoteRunnable({
938
- url: this.chainUrl
939
- });
940
- let input;
941
- if (this.parameterType === "single") {
942
- input = args[Object.keys(args)[0]];
943
- } else {
944
- input = args;
929
+ async streamResponse(stream, eventSource) {
930
+ eventSource.stream(async (eventStream$) => {
931
+ var _a, _b, _c, _d, _e, _f;
932
+ let inFunctionCall = false;
933
+ for await (const chunk of stream) {
934
+ switch (chunk.event) {
935
+ case "thread.message.created":
936
+ if (inFunctionCall) {
937
+ eventStream$.sendActionExecutionEnd();
938
+ }
939
+ eventStream$.sendTextMessageStart(chunk.data.id);
940
+ break;
941
+ case "thread.message.delta":
942
+ if (((_a = chunk.data.delta.content) == null ? void 0 : _a[0].type) === "text") {
943
+ eventStream$.sendTextMessageContent((_b = chunk.data.delta.content) == null ? void 0 : _b[0].text.value);
944
+ }
945
+ break;
946
+ case "thread.message.completed":
947
+ eventStream$.sendTextMessageEnd();
948
+ break;
949
+ case "thread.run.step.delta":
950
+ let toolCallId;
951
+ let toolCallName;
952
+ let toolCallArgs;
953
+ if (chunk.data.delta.step_details.type === "tool_calls" && ((_c = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _c[0].type) === "function") {
954
+ toolCallId = (_d = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _d[0].id;
955
+ toolCallName = (_e = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _e[0].function.name;
956
+ toolCallArgs = (_f = chunk.data.delta.step_details.tool_calls) == null ? void 0 : _f[0].function.arguments;
957
+ }
958
+ if (toolCallName && toolCallId) {
959
+ if (inFunctionCall) {
960
+ eventStream$.sendActionExecutionEnd();
961
+ }
962
+ inFunctionCall = true;
963
+ eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
964
+ } else if (toolCallArgs) {
965
+ eventStream$.sendActionExecutionArgs(toolCallArgs);
966
+ }
967
+ break;
945
968
  }
946
- return await runnable.invoke(input);
947
969
  }
948
- };
949
- }
950
- async inferLangServeParameters() {
951
- const supportedTypes = [
952
- "string",
953
- "number",
954
- "boolean"
955
- ];
956
- let schemaUrl = this.chainUrl.replace(/\/+$/, "") + "/input_schema";
957
- let schema = await fetch(schemaUrl).then((res) => res.json()).catch(() => {
958
- throw new Error("Failed to fetch langserve schema at " + schemaUrl);
970
+ if (inFunctionCall) {
971
+ eventStream$.sendActionExecutionEnd();
972
+ }
973
+ eventStream$.complete();
959
974
  });
960
- if (supportedTypes.includes(schema.type)) {
961
- this.parameterType = "single";
962
- this.parameters = [
963
- {
964
- name: "input",
965
- type: schema.type,
966
- description: "The input to the chain"
967
- }
968
- ];
969
- } else if (schema.type === "object") {
970
- this.parameterType = "multi";
971
- this.parameters = Object.keys(schema.properties).map((key) => {
972
- var _a;
973
- let property = schema.properties[key];
974
- if (!supportedTypes.includes(property.type)) {
975
- throw new Error("Unsupported schema type");
976
- }
977
- return {
978
- name: key,
979
- type: property.type,
980
- description: property.description || "",
981
- required: ((_a = schema.required) == null ? void 0 : _a.includes(key)) || false
982
- };
983
- });
984
- } else {
985
- throw new Error("Unsupported schema type");
986
- }
987
975
  }
988
976
  };
989
- __name(RemoteChain, "RemoteChain");
977
+ __name(OpenAIAssistantAdapter, "OpenAIAssistantAdapter");
978
+ function getRunIdFromStream(stream) {
979
+ return new Promise((resolve, reject) => {
980
+ let runIdGetter = /* @__PURE__ */ __name((event) => {
981
+ if (event.event === "thread.run.created") {
982
+ const runId = event.data.id;
983
+ stream.off("event", runIdGetter);
984
+ resolve(runId);
985
+ }
986
+ }, "runIdGetter");
987
+ stream.on("event", runIdGetter);
988
+ });
989
+ }
990
+ __name(getRunIdFromStream, "getRunIdFromStream");
990
991
 
991
992
  // src/service-adapters/unify/unify-adapter.ts
992
993
  var import_openai3 = __toESM(require("openai"));
@@ -1163,8 +1164,273 @@ var GroqAdapter = class {
1163
1164
  }
1164
1165
  };
1165
1166
  __name(GroqAdapter, "GroqAdapter");
1167
+
1168
+ // src/service-adapters/anthropic/anthropic-adapter.ts
1169
+ var import_sdk = __toESM(require("@anthropic-ai/sdk"));
1170
+
1171
+ // src/service-adapters/anthropic/utils.ts
1172
+ function limitMessagesToTokenCount2(messages, tools, model, maxTokens) {
1173
+ maxTokens || (maxTokens = MAX_TOKENS);
1174
+ const result = [];
1175
+ const toolsNumTokens = countToolsTokens2(model, tools);
1176
+ if (toolsNumTokens > maxTokens) {
1177
+ throw new Error(`Too many tokens in function definitions: ${toolsNumTokens} > ${maxTokens}`);
1178
+ }
1179
+ maxTokens -= toolsNumTokens;
1180
+ for (const message of messages) {
1181
+ if (message.role === "system") {
1182
+ const numTokens = countMessageTokens2(model, message);
1183
+ maxTokens -= numTokens;
1184
+ if (maxTokens < 0) {
1185
+ throw new Error("Not enough tokens for system message.");
1186
+ }
1187
+ }
1188
+ }
1189
+ let cutoff = false;
1190
+ const reversedMessages = [
1191
+ ...messages
1192
+ ].reverse();
1193
+ for (const message of reversedMessages) {
1194
+ if (message.role === "system") {
1195
+ result.unshift(message);
1196
+ continue;
1197
+ } else if (cutoff) {
1198
+ continue;
1199
+ }
1200
+ let numTokens = countMessageTokens2(model, message);
1201
+ if (maxTokens < numTokens) {
1202
+ cutoff = true;
1203
+ continue;
1204
+ }
1205
+ result.unshift(message);
1206
+ maxTokens -= numTokens;
1207
+ }
1208
+ return result;
1209
+ }
1210
+ __name(limitMessagesToTokenCount2, "limitMessagesToTokenCount");
1211
+ var MAX_TOKENS = 128e3;
1212
+ function countToolsTokens2(model, tools) {
1213
+ if (tools.length === 0) {
1214
+ return 0;
1215
+ }
1216
+ const json = JSON.stringify(tools);
1217
+ return countTokens2(model, json);
1218
+ }
1219
+ __name(countToolsTokens2, "countToolsTokens");
1220
+ function countMessageTokens2(model, message) {
1221
+ return countTokens2(model, JSON.stringify(message.content) || "");
1222
+ }
1223
+ __name(countMessageTokens2, "countMessageTokens");
1224
+ function countTokens2(model, text) {
1225
+ return text.length / 3;
1226
+ }
1227
+ __name(countTokens2, "countTokens");
1228
+ function convertActionInputToAnthropicTool(action) {
1229
+ return {
1230
+ name: action.name,
1231
+ description: action.description,
1232
+ input_schema: JSON.parse(action.jsonSchema)
1233
+ };
1234
+ }
1235
+ __name(convertActionInputToAnthropicTool, "convertActionInputToAnthropicTool");
1236
+ function convertMessageToAnthropicMessage(message) {
1237
+ if (message instanceof TextMessage) {
1238
+ if (message.role === "system") {
1239
+ return {
1240
+ role: "assistant",
1241
+ content: [
1242
+ {
1243
+ type: "text",
1244
+ text: "THE FOLLOWING MESSAGE IS A SYSTEM MESSAGE: " + message.content
1245
+ }
1246
+ ]
1247
+ };
1248
+ } else {
1249
+ return {
1250
+ role: message.role === "user" ? "user" : "assistant",
1251
+ content: [
1252
+ {
1253
+ type: "text",
1254
+ text: message.content
1255
+ }
1256
+ ]
1257
+ };
1258
+ }
1259
+ } else if (message instanceof ActionExecutionMessage) {
1260
+ return {
1261
+ role: "assistant",
1262
+ content: [
1263
+ {
1264
+ id: message.id,
1265
+ type: "tool_use",
1266
+ input: message.arguments,
1267
+ name: message.name
1268
+ }
1269
+ ]
1270
+ };
1271
+ } else if (message instanceof ResultMessage) {
1272
+ return {
1273
+ role: "user",
1274
+ content: [
1275
+ {
1276
+ type: "tool_result",
1277
+ content: message.result,
1278
+ tool_use_id: message.actionExecutionId
1279
+ }
1280
+ ]
1281
+ };
1282
+ }
1283
+ }
1284
+ __name(convertMessageToAnthropicMessage, "convertMessageToAnthropicMessage");
1285
+ function groupAnthropicMessagesByRole(messageParams) {
1286
+ return messageParams.reduce((acc, message) => {
1287
+ const lastGroup = acc[acc.length - 1];
1288
+ if (lastGroup && lastGroup.role === message.role) {
1289
+ lastGroup.content = lastGroup.content.concat(message.content);
1290
+ } else {
1291
+ acc.push({
1292
+ role: message.role,
1293
+ content: [
1294
+ ...message.content
1295
+ ]
1296
+ });
1297
+ }
1298
+ return acc;
1299
+ }, []);
1300
+ }
1301
+ __name(groupAnthropicMessagesByRole, "groupAnthropicMessagesByRole");
1302
+
1303
+ // src/service-adapters/anthropic/anthropic-adapter.ts
1304
+ var import_shared7 = require("@copilotkit/shared");
1305
+ var DEFAULT_MODEL3 = "claude-3-opus-20240229";
1306
+ var AnthropicAdapter = class {
1307
+ model = DEFAULT_MODEL3;
1308
+ _anthropic;
1309
+ get anthropic() {
1310
+ return this._anthropic;
1311
+ }
1312
+ constructor(params) {
1313
+ this._anthropic = (params == null ? void 0 : params.anthropic) || new import_sdk.default({});
1314
+ if (params == null ? void 0 : params.model) {
1315
+ this.model = params.model;
1316
+ }
1317
+ }
1318
+ async process(request) {
1319
+ const { threadId, model = this.model, messages: rawMessages, actions, eventSource, forwardedParameters } = request;
1320
+ const tools = actions.map(convertActionInputToAnthropicTool);
1321
+ const messages = [
1322
+ ...rawMessages
1323
+ ];
1324
+ const instructionsMessage = messages.shift();
1325
+ const instructions = instructionsMessage instanceof TextMessage ? instructionsMessage.content : "";
1326
+ let anthropicMessages = messages.map(convertMessageToAnthropicMessage);
1327
+ anthropicMessages = limitMessagesToTokenCount2(anthropicMessages, tools, model);
1328
+ anthropicMessages = groupAnthropicMessagesByRole(anthropicMessages);
1329
+ let toolChoice = forwardedParameters == null ? void 0 : forwardedParameters.toolChoice;
1330
+ if ((forwardedParameters == null ? void 0 : forwardedParameters.toolChoice) === "function") {
1331
+ toolChoice = {
1332
+ type: "tool",
1333
+ name: forwardedParameters.toolChoiceFunctionName
1334
+ };
1335
+ }
1336
+ const stream = this.anthropic.messages.create({
1337
+ system: instructions,
1338
+ model: this.model,
1339
+ messages: anthropicMessages,
1340
+ max_tokens: (forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) || 1024,
1341
+ ...tools.length > 0 && {
1342
+ tools
1343
+ },
1344
+ ...toolChoice && {
1345
+ tool_choice: toolChoice
1346
+ },
1347
+ stream: true
1348
+ });
1349
+ eventSource.stream(async (eventStream$) => {
1350
+ let mode = null;
1351
+ let didOutputText = false;
1352
+ let currentMessageId = (0, import_shared7.randomId)();
1353
+ let currentToolCallId = (0, import_shared7.randomId)();
1354
+ let filterThinkingTextBuffer = new FilterThinkingTextBuffer();
1355
+ for await (const chunk of await stream) {
1356
+ if (chunk.type === "message_start") {
1357
+ currentMessageId = chunk.message.id;
1358
+ } else if (chunk.type === "content_block_start") {
1359
+ if (chunk.content_block.type === "text") {
1360
+ didOutputText = false;
1361
+ filterThinkingTextBuffer.reset();
1362
+ mode = "message";
1363
+ } else if (chunk.content_block.type === "tool_use") {
1364
+ currentToolCallId = chunk.content_block.id;
1365
+ eventStream$.sendActionExecutionStart(currentToolCallId, chunk.content_block.name);
1366
+ mode = "function";
1367
+ }
1368
+ } else if (chunk.type === "content_block_delta") {
1369
+ if (chunk.delta.type === "text_delta") {
1370
+ const text = filterThinkingTextBuffer.onTextChunk(chunk.delta.text);
1371
+ if (text.length > 0) {
1372
+ if (!didOutputText) {
1373
+ eventStream$.sendTextMessageStart(currentMessageId);
1374
+ didOutputText = true;
1375
+ }
1376
+ eventStream$.sendTextMessageContent(text);
1377
+ }
1378
+ } else if (chunk.delta.type === "input_json_delta") {
1379
+ eventStream$.sendActionExecutionArgs(chunk.delta.partial_json);
1380
+ }
1381
+ } else if (chunk.type === "content_block_stop") {
1382
+ if (mode === "message") {
1383
+ if (didOutputText) {
1384
+ eventStream$.sendTextMessageEnd();
1385
+ }
1386
+ } else if (mode === "function") {
1387
+ eventStream$.sendActionExecutionEnd();
1388
+ }
1389
+ }
1390
+ }
1391
+ eventStream$.complete();
1392
+ });
1393
+ return {
1394
+ threadId: threadId || (0, import_shared7.randomId)()
1395
+ };
1396
+ }
1397
+ };
1398
+ __name(AnthropicAdapter, "AnthropicAdapter");
1399
+ var THINKING_TAG = "<thinking>";
1400
+ var THINKING_TAG_END = "</thinking>";
1401
+ var FilterThinkingTextBuffer = /* @__PURE__ */ __name(class FilterThinkingTextBuffer2 {
1402
+ buffer;
1403
+ didFilterThinkingTag = false;
1404
+ constructor() {
1405
+ this.buffer = "";
1406
+ }
1407
+ onTextChunk(text) {
1408
+ this.buffer += text;
1409
+ if (this.didFilterThinkingTag) {
1410
+ return text;
1411
+ }
1412
+ const potentialTag = this.buffer.slice(0, THINKING_TAG.length);
1413
+ if (THINKING_TAG.startsWith(potentialTag)) {
1414
+ if (this.buffer.includes(THINKING_TAG_END)) {
1415
+ const end = this.buffer.indexOf(THINKING_TAG_END);
1416
+ const filteredText = this.buffer.slice(end + THINKING_TAG_END.length);
1417
+ this.buffer = filteredText;
1418
+ this.didFilterThinkingTag = true;
1419
+ return filteredText;
1420
+ } else {
1421
+ return "";
1422
+ }
1423
+ }
1424
+ return text;
1425
+ }
1426
+ reset() {
1427
+ this.buffer = "";
1428
+ this.didFilterThinkingTag = false;
1429
+ }
1430
+ }, "FilterThinkingTextBuffer");
1166
1431
  // Annotate the CommonJS export names for ESM import in node:
1167
1432
  0 && (module.exports = {
1433
+ AnthropicAdapter,
1168
1434
  GoogleGenerativeAIAdapter,
1169
1435
  GroqAdapter,
1170
1436
  LangChainAdapter,