@librechat/agents 1.8.8 → 1.8.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/enum.cjs +1 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +8 -1
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/llm.cjs +117 -0
- package/dist/cjs/llm/anthropic/llm.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +277 -0
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +135 -0
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -0
- package/dist/cjs/llm/providers.cjs +5 -4
- package/dist/cjs/llm/providers.cjs.map +1 -1
- package/dist/cjs/llm/text.cjs +58 -0
- package/dist/cjs/llm/text.cjs.map +1 -0
- package/dist/cjs/main.cjs +3 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages.cjs +4 -4
- package/dist/cjs/messages.cjs.map +1 -1
- package/dist/cjs/stream.cjs +63 -48
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +20 -5
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/utils/misc.cjs +49 -0
- package/dist/cjs/utils/misc.cjs.map +1 -0
- package/dist/esm/common/enum.mjs +1 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +8 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/llm/anthropic/llm.mjs +115 -0
- package/dist/esm/llm/anthropic/llm.mjs.map +1 -0
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +274 -0
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -0
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +133 -0
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -0
- package/dist/esm/llm/providers.mjs +5 -4
- package/dist/esm/llm/providers.mjs.map +1 -1
- package/dist/esm/llm/text.mjs +56 -0
- package/dist/esm/llm/text.mjs.map +1 -0
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages.mjs +4 -4
- package/dist/esm/messages.mjs.map +1 -1
- package/dist/esm/stream.mjs +63 -49
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +22 -7
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/utils/misc.mjs +47 -0
- package/dist/esm/utils/misc.mjs.map +1 -0
- package/dist/types/common/enum.d.ts +2 -1
- package/dist/types/llm/anthropic/types.d.ts +4 -0
- package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -1
- package/dist/types/llm/text.d.ts +6 -6
- package/dist/types/stream.d.ts +2 -0
- package/dist/types/types/llm.d.ts +6 -1
- package/dist/types/utils/index.d.ts +1 -0
- package/dist/types/utils/misc.d.ts +6 -0
- package/package.json +7 -6
- package/src/common/enum.ts +1 -0
- package/src/events.ts +9 -1
- package/src/llm/anthropic/llm.ts +1 -1
- package/src/llm/anthropic/types.ts +7 -1
- package/src/llm/anthropic/utils/message_inputs.ts +86 -8
- package/src/llm/providers.ts +6 -4
- package/src/llm/text.ts +30 -45
- package/src/messages.ts +4 -4
- package/src/scripts/args.ts +1 -1
- package/src/scripts/code_exec.ts +4 -0
- package/src/scripts/simple.ts +4 -0
- package/src/stream.ts +68 -50
- package/src/tools/ToolNode.ts +25 -9
- package/src/types/llm.ts +6 -1
- package/src/utils/index.ts +1 -0
- package/src/utils/llmConfig.ts +6 -0
- package/src/utils/misc.ts +45 -0
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var messages = require('@langchain/core/messages');
|
|
4
|
+
|
|
5
|
+
function _makeMessageChunkFromAnthropicEvent(data, fields) {
|
|
6
|
+
if (data.type === 'message_start') {
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
8
|
+
const { content, usage, ...additionalKwargs } = data.message;
|
|
9
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
10
|
+
const filteredAdditionalKwargs = {};
|
|
11
|
+
for (const [key, value] of Object.entries(additionalKwargs)) {
|
|
12
|
+
if (value !== undefined && value !== null) {
|
|
13
|
+
filteredAdditionalKwargs[key] = value;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const usageMetadata = {
|
|
17
|
+
input_tokens: usage.input_tokens,
|
|
18
|
+
output_tokens: usage.output_tokens,
|
|
19
|
+
total_tokens: usage.input_tokens + usage.output_tokens,
|
|
20
|
+
};
|
|
21
|
+
return {
|
|
22
|
+
chunk: new messages.AIMessageChunk({
|
|
23
|
+
content: fields.coerceContentToString ? '' : [],
|
|
24
|
+
additional_kwargs: filteredAdditionalKwargs,
|
|
25
|
+
usage_metadata: fields.streamUsage ? usageMetadata : undefined,
|
|
26
|
+
id: data.message.id,
|
|
27
|
+
}),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
else if (data.type === 'message_delta') {
|
|
31
|
+
const usageMetadata = {
|
|
32
|
+
input_tokens: 0,
|
|
33
|
+
output_tokens: data.usage.output_tokens,
|
|
34
|
+
total_tokens: data.usage.output_tokens,
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
chunk: new messages.AIMessageChunk({
|
|
38
|
+
content: fields.coerceContentToString ? '' : [],
|
|
39
|
+
additional_kwargs: { ...data.delta },
|
|
40
|
+
usage_metadata: fields.streamUsage ? usageMetadata : undefined,
|
|
41
|
+
}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
else if (data.type === 'content_block_start' &&
|
|
45
|
+
data.content_block.type === 'tool_use') {
|
|
46
|
+
const toolCallContentBlock = data.content_block;
|
|
47
|
+
return {
|
|
48
|
+
chunk: new messages.AIMessageChunk({
|
|
49
|
+
content: fields.coerceContentToString
|
|
50
|
+
? ''
|
|
51
|
+
: [
|
|
52
|
+
{
|
|
53
|
+
index: data.index,
|
|
54
|
+
...data.content_block,
|
|
55
|
+
input: '',
|
|
56
|
+
},
|
|
57
|
+
],
|
|
58
|
+
additional_kwargs: {},
|
|
59
|
+
tool_call_chunks: [
|
|
60
|
+
{
|
|
61
|
+
id: toolCallContentBlock.id,
|
|
62
|
+
index: data.index,
|
|
63
|
+
name: toolCallContentBlock.name,
|
|
64
|
+
args: '',
|
|
65
|
+
},
|
|
66
|
+
],
|
|
67
|
+
}),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
else if (data.type === 'content_block_delta' &&
|
|
71
|
+
data.delta.type === 'text_delta') {
|
|
72
|
+
const content = data.delta.text;
|
|
73
|
+
if (content !== undefined) {
|
|
74
|
+
return {
|
|
75
|
+
chunk: new messages.AIMessageChunk({
|
|
76
|
+
content: fields.coerceContentToString
|
|
77
|
+
? content
|
|
78
|
+
: [
|
|
79
|
+
{
|
|
80
|
+
index: data.index,
|
|
81
|
+
...data.delta,
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
additional_kwargs: {},
|
|
85
|
+
}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
else if (data.type === 'content_block_delta' &&
|
|
90
|
+
data.delta.type === 'input_json_delta') {
|
|
91
|
+
return {
|
|
92
|
+
chunk: new messages.AIMessageChunk({
|
|
93
|
+
content: fields.coerceContentToString
|
|
94
|
+
? ''
|
|
95
|
+
: [
|
|
96
|
+
{
|
|
97
|
+
index: data.index,
|
|
98
|
+
input: data.delta.partial_json,
|
|
99
|
+
type: data.delta.type,
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
additional_kwargs: {},
|
|
103
|
+
tool_call_chunks: [
|
|
104
|
+
{
|
|
105
|
+
index: data.index,
|
|
106
|
+
args: data.delta.partial_json,
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
}),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
else if (data.type === 'content_block_start' &&
|
|
113
|
+
data.content_block.type === 'text') {
|
|
114
|
+
const content = data.content_block.text;
|
|
115
|
+
if (content !== undefined) {
|
|
116
|
+
return {
|
|
117
|
+
chunk: new messages.AIMessageChunk({
|
|
118
|
+
content: fields.coerceContentToString
|
|
119
|
+
? content
|
|
120
|
+
: [
|
|
121
|
+
{
|
|
122
|
+
index: data.index,
|
|
123
|
+
...data.content_block,
|
|
124
|
+
},
|
|
125
|
+
],
|
|
126
|
+
additional_kwargs: {},
|
|
127
|
+
}),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
exports._makeMessageChunkFromAnthropicEvent = _makeMessageChunkFromAnthropicEvent;
|
|
135
|
+
//# sourceMappingURL=message_outputs.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message_outputs.cjs","sources":["../../../../../src/llm/anthropic/utils/message_outputs.ts"],"sourcesContent":["/**\n * This util file contains functions for converting Anthropic messages to LangChain messages.\n */\nimport Anthropic from '@anthropic-ai/sdk';\nimport {\n AIMessage,\n UsageMetadata,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport { ChatGeneration } from '@langchain/core/outputs';\nimport { AnthropicMessageResponse } from '../types.js';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extractToolCalls(content: Record<string, any>[]): ToolCall[] {\n const toolCalls: ToolCall[] = [];\n for (const block of content) {\n if (block.type === 'tool_use') {\n toolCalls.push({\n name: block.name,\n args: block.input,\n id: block.id,\n type: 'tool_call',\n });\n }\n }\n return toolCalls;\n}\n\nexport function _makeMessageChunkFromAnthropicEvent(\n data: Anthropic.Messages.RawMessageStreamEvent,\n fields: {\n streamUsage: boolean;\n coerceContentToString: boolean;\n }\n): {\n chunk: AIMessageChunk;\n} | null {\n if (data.type === 'message_start') {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { content, usage, ...additionalKwargs } = data.message;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredAdditionalKwargs: Record<string, any> = {};\n for (const [key, value] of Object.entries(additionalKwargs)) {\n if (value !== undefined && value !== null) {\n filteredAdditionalKwargs[key] = value;\n }\n }\n const usageMetadata: UsageMetadata = {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n total_tokens: usage.input_tokens + usage.output_tokens,\n };\n return {\n chunk: new AIMessageChunk({\n content: fields.coerceContentToString ? '' : [],\n additional_kwargs: filteredAdditionalKwargs,\n usage_metadata: fields.streamUsage ? usageMetadata : undefined,\n id: data.message.id,\n }),\n };\n } else if (data.type === 'message_delta') {\n const usageMetadata: UsageMetadata = {\n input_tokens: 0,\n output_tokens: data.usage.output_tokens,\n total_tokens: data.usage.output_tokens,\n };\n return {\n chunk: new AIMessageChunk({\n content: fields.coerceContentToString ? '' : [],\n additional_kwargs: { ...data.delta },\n usage_metadata: fields.streamUsage ? usageMetadata : undefined,\n }),\n };\n } else if (\n data.type === 'content_block_start' &&\n data.content_block.type === 'tool_use'\n ) {\n const toolCallContentBlock =\n data.content_block as Anthropic.Messages.ToolUseBlock;\n return {\n chunk: new AIMessageChunk({\n content: fields.coerceContentToString\n ? ''\n : [\n {\n index: data.index,\n ...data.content_block,\n input: '',\n },\n ],\n additional_kwargs: {},\n tool_call_chunks: [\n {\n id: toolCallContentBlock.id,\n index: data.index,\n name: toolCallContentBlock.name,\n args: '',\n },\n ],\n }),\n };\n } else if (\n data.type === 'content_block_delta' &&\n data.delta.type === 'text_delta'\n ) {\n const content = data.delta.text;\n if (content !== undefined) {\n return {\n chunk: new AIMessageChunk({\n content: fields.coerceContentToString\n ? content\n : [\n {\n index: data.index,\n ...data.delta,\n },\n ],\n additional_kwargs: {},\n }),\n };\n }\n } else if (\n data.type === 'content_block_delta' &&\n data.delta.type === 'input_json_delta'\n ) {\n return {\n chunk: new AIMessageChunk({\n content: fields.coerceContentToString\n ? ''\n : [\n {\n index: data.index,\n input: data.delta.partial_json,\n type: data.delta.type,\n },\n ],\n additional_kwargs: {},\n tool_call_chunks: [\n {\n index: data.index,\n args: data.delta.partial_json,\n },\n ],\n }),\n };\n } else if (\n data.type === 'content_block_start' &&\n data.content_block.type === 'text'\n ) {\n const content = data.content_block.text;\n if (content !== undefined) {\n return {\n chunk: new AIMessageChunk({\n content: fields.coerceContentToString\n ? content\n : [\n {\n index: data.index,\n ...data.content_block,\n },\n ],\n additional_kwargs: {},\n }),\n };\n }\n }\n\n return null;\n}\n\nexport function anthropicResponseToChatMessages(\n messages: AnthropicMessageResponse[],\n additionalKwargs: Record<string, unknown>\n): ChatGeneration[] {\n const usage: Record<string, number> | null | undefined =\n additionalKwargs.usage as Record<string, number> | null | undefined;\n const usageMetadata =\n usage != null\n ? {\n input_tokens: usage.input_tokens ?? 0,\n output_tokens: usage.output_tokens ?? 0,\n total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),\n }\n : undefined;\n if (messages.length === 1 && messages[0].type === 'text') {\n return [\n {\n text: messages[0].text,\n message: new AIMessage({\n content: messages[0].text,\n additional_kwargs: additionalKwargs,\n usage_metadata: usageMetadata,\n response_metadata: additionalKwargs,\n id: additionalKwargs.id as string,\n }),\n },\n ];\n } else {\n const toolCalls = extractToolCalls(messages);\n const generations: ChatGeneration[] = [\n {\n text: '',\n message: new AIMessage({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n content: messages as any,\n additional_kwargs: additionalKwargs,\n tool_calls: toolCalls,\n usage_metadata: usageMetadata,\n response_metadata: additionalKwargs,\n id: additionalKwargs.id as string,\n }),\n },\n ];\n return generations;\n }\n}"],"names":["AIMessageChunk"],"mappings":";;;;AA6BgB,SAAA,mCAAmC,CACjD,IAA8C,EAC9C,MAGC,EAAA;AAID,IAAA,IAAI,IAAI,CAAC,IAAI,KAAK,eAA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CAAC;SACH;KACF;AAED,IAAA,OAAO,IAAI,CAAC;AACd;;;;"}
|
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
var openai = require('@langchain/openai');
|
|
4
4
|
var ollama = require('@langchain/ollama');
|
|
5
5
|
var aws = require('@langchain/aws');
|
|
6
|
-
var anthropic = require('@langchain/anthropic');
|
|
7
6
|
var mistralai = require('@langchain/mistralai');
|
|
8
7
|
var googleVertexai = require('@langchain/google-vertexai');
|
|
8
|
+
var googleGenai = require('@langchain/google-genai');
|
|
9
9
|
var web = require('@langchain/community/chat_models/bedrock/web');
|
|
10
10
|
var _enum = require('../common/enum.cjs');
|
|
11
|
+
var llm = require('./anthropic/llm.cjs');
|
|
11
12
|
|
|
12
13
|
// src/llm/providers.ts
|
|
13
|
-
// import { CustomAnthropic } from '@/llm/anthropic/llm';
|
|
14
14
|
const llmProviders = {
|
|
15
15
|
[_enum.Providers.OPENAI]: openai.ChatOpenAI,
|
|
16
16
|
[_enum.Providers.OLLAMA]: ollama.ChatOllama,
|
|
@@ -18,8 +18,9 @@ const llmProviders = {
|
|
|
18
18
|
[_enum.Providers.BEDROCK_LEGACY]: web.BedrockChat,
|
|
19
19
|
[_enum.Providers.MISTRALAI]: mistralai.ChatMistralAI,
|
|
20
20
|
[_enum.Providers.BEDROCK]: aws.ChatBedrockConverse,
|
|
21
|
-
|
|
22
|
-
[
|
|
21
|
+
[_enum.Providers.ANTHROPIC]: llm.CustomAnthropic,
|
|
22
|
+
// [Providers.ANTHROPIC]: ChatAnthropic,
|
|
23
|
+
[_enum.Providers.GOOGLE]: googleGenai.ChatGoogleGenerativeAI,
|
|
23
24
|
};
|
|
24
25
|
const manualToolStreamProviders = new Set([_enum.Providers.ANTHROPIC, _enum.Providers.BEDROCK, _enum.Providers.OLLAMA]);
|
|
25
26
|
const getChatModelClass = (provider) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.cjs","sources":["../../../src/llm/providers.ts"],"sourcesContent":["// src/llm/providers.ts\nimport { ChatOpenAI } from '@langchain/openai';\nimport { ChatOllama } from '@langchain/ollama';\nimport { ChatBedrockConverse } from '@langchain/aws';\
|
|
1
|
+
{"version":3,"file":"providers.cjs","sources":["../../../src/llm/providers.ts"],"sourcesContent":["// src/llm/providers.ts\nimport { ChatOpenAI } from '@langchain/openai';\nimport { ChatOllama } from '@langchain/ollama';\nimport { ChatBedrockConverse } from '@langchain/aws';\n// import { ChatAnthropic } from '@langchain/anthropic';\nimport { ChatMistralAI } from '@langchain/mistralai';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { BedrockChat } from '@langchain/community/chat_models/bedrock/web';\nimport type { ChatModelConstructorMap, ProviderOptionsMap, ChatModelMap } from '@/types';\nimport { Providers } from '@/common';\nimport { CustomAnthropic } from '@/llm/anthropic/llm';\n\nexport const llmProviders: Partial<ChatModelConstructorMap> = {\n [Providers.OPENAI]: ChatOpenAI,\n [Providers.OLLAMA]: ChatOllama,\n [Providers.VERTEXAI]: ChatVertexAI,\n [Providers.BEDROCK_LEGACY]: BedrockChat,\n [Providers.MISTRALAI]: ChatMistralAI,\n [Providers.BEDROCK]: ChatBedrockConverse,\n [Providers.ANTHROPIC]: CustomAnthropic,\n // [Providers.ANTHROPIC]: ChatAnthropic,\n [Providers.GOOGLE]: ChatGoogleGenerativeAI,\n};\n\nexport const manualToolStreamProviders = new Set<Providers | string>([Providers.ANTHROPIC, Providers.BEDROCK, Providers.OLLAMA]);\n\nexport const getChatModelClass = <P extends Providers>(\n provider: P\n): new (config: ProviderOptionsMap[P]) => ChatModelMap[P] => {\n const ChatModelClass = llmProviders[provider];\n if (!ChatModelClass) {\n throw new Error(`Unsupported LLM provider: ${provider}`);\n }\n\n return ChatModelClass;\n};"],"names":["Providers","ChatOpenAI","ChatOllama","ChatVertexAI","BedrockChat","ChatMistralAI","ChatBedrockConverse","CustomAnthropic","ChatGoogleGenerativeAI"],"mappings":";;;;;;;;;;;;AAAA;AAaa,MAAA,YAAY,GAAqC;AAC5D,IAAA,CAACA,eAAS,CAAC,MAAM,GAAGC,iBAAU;AAC9B,IAAA,CAACD,eAAS,CAAC,MAAM,GAAGE,iBAAU;AAC9B,IAAA,CAACF,eAAS,CAAC,QAAQ,GAAGG,2BAAY;AAClC,IAAA,CAACH,eAAS,CAAC,cAAc,GAAGI,eAAW;AACvC,IAAA,CAACJ,eAAS,CAAC,SAAS,GAAGK,uBAAa;AACpC,IAAA,CAACL,eAAS,CAAC,OAAO,GAAGM,uBAAmB;AACxC,IAAA,CAACN,eAAS,CAAC,SAAS,GAAGO,mBAAe;;AAEtC,IAAA,CAACP,eAAS,CAAC,MAAM,GAAGQ,kCAAsB;EAC1C;MAEW,yBAAyB,GAAG,IAAI,GAAG,CAAqB,CAACR,eAAS,CAAC,SAAS,EAAEA,eAAS,CAAC,OAAO,EAAEA,eAAS,CAAC,MAAM,CAAC,EAAE;AAEpH,MAAA,iBAAiB,GAAG,CAC/B,QAAW,KAC+C;AAC1D,IAAA,MAAM,cAAc,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC9C,IAAI,CAAC,cAAc,EAAE;AACnB,QAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,QAAQ,CAAA,CAAE,CAAC,CAAC;KAC1D;AAED,IAAA,OAAO,cAAc,CAAC;AACxB;;;;;;"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
class TextStream {
|
|
4
|
+
text;
|
|
5
|
+
currentIndex;
|
|
6
|
+
minChunkSize;
|
|
7
|
+
maxChunkSize;
|
|
8
|
+
delay;
|
|
9
|
+
firstWordChunk;
|
|
10
|
+
constructor(text, options = {}) {
|
|
11
|
+
this.text = text;
|
|
12
|
+
this.currentIndex = 0;
|
|
13
|
+
this.minChunkSize = options.minChunkSize ?? 4;
|
|
14
|
+
this.maxChunkSize = options.maxChunkSize ?? 8;
|
|
15
|
+
this.delay = options.delay ?? 20;
|
|
16
|
+
this.firstWordChunk = options.firstWordChunk ?? true;
|
|
17
|
+
}
|
|
18
|
+
randomInt(min, max) {
|
|
19
|
+
return Math.floor(Math.random() * (max - min)) + min;
|
|
20
|
+
}
|
|
21
|
+
static BOUNDARIES = new Set([' ', '.', ',', '!', '?', ';', ':']);
|
|
22
|
+
findFirstWordBoundary(text, minSize) {
|
|
23
|
+
if (minSize >= text.length)
|
|
24
|
+
return text.length;
|
|
25
|
+
// Ensure we meet the minimum size first
|
|
26
|
+
let pos = minSize;
|
|
27
|
+
// Look forward until we find a boundary
|
|
28
|
+
while (pos < text.length) {
|
|
29
|
+
if (TextStream.BOUNDARIES.has(text[pos])) {
|
|
30
|
+
return pos + 1; // Include the boundary character
|
|
31
|
+
}
|
|
32
|
+
pos++;
|
|
33
|
+
}
|
|
34
|
+
return text.length; // If no boundary found, return entire remaining text
|
|
35
|
+
}
|
|
36
|
+
async *generateText(progressCallback) {
|
|
37
|
+
const { delay, minChunkSize, maxChunkSize } = this;
|
|
38
|
+
while (this.currentIndex < this.text.length) {
|
|
39
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
40
|
+
const remainingText = this.text.slice(this.currentIndex);
|
|
41
|
+
let chunkSize;
|
|
42
|
+
if (this.firstWordChunk) {
|
|
43
|
+
chunkSize = this.findFirstWordBoundary(remainingText, minChunkSize);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
const remainingChars = remainingText.length;
|
|
47
|
+
chunkSize = Math.min(this.randomInt(minChunkSize, maxChunkSize + 1), remainingChars);
|
|
48
|
+
}
|
|
49
|
+
const chunk = this.text.slice(this.currentIndex, this.currentIndex + chunkSize);
|
|
50
|
+
progressCallback?.(chunk);
|
|
51
|
+
yield chunk;
|
|
52
|
+
this.currentIndex += chunkSize;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
exports.TextStream = TextStream;
|
|
58
|
+
//# sourceMappingURL=text.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"text.cjs","sources":["../../../src/llm/text.ts"],"sourcesContent":["/* eslint-disable no-console */\nexport interface TextStreamOptions {\n minChunkSize?: number;\n maxChunkSize?: number;\n delay?: number;\n firstWordChunk?: boolean;\n}\n\nexport type ProgressCallback = (chunk: string) => void;\nexport type PostChunkCallback = (chunk: string) => void;\n\nexport class TextStream {\n private text: string;\n private currentIndex: number;\n private minChunkSize: number;\n private maxChunkSize: number;\n private delay: number;\n private firstWordChunk: boolean;\n\n constructor(text: string, options: TextStreamOptions = {}) {\n this.text = text;\n this.currentIndex = 0;\n this.minChunkSize = options.minChunkSize ?? 4;\n this.maxChunkSize = options.maxChunkSize ?? 8;\n this.delay = options.delay ?? 20;\n this.firstWordChunk = options.firstWordChunk ?? true;\n }\n\n private randomInt(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min)) + min;\n }\n\n private static readonly BOUNDARIES = new Set([' ', '.', ',', '!', '?', ';', ':']);\n\n private findFirstWordBoundary(text: string, minSize: number): number {\n if (minSize >= text.length) return text.length;\n\n // Ensure we meet the minimum size first\n let pos = minSize;\n\n // Look forward until we find a boundary\n while (pos < text.length) {\n if (TextStream.BOUNDARIES.has(text[pos])) {\n return pos + 1; // Include the boundary character\n }\n pos++;\n }\n\n return text.length; // If no boundary found, return entire remaining text\n }\n\n async *generateText(progressCallback?: ProgressCallback): AsyncGenerator<string, void, unknown> {\n const { delay, minChunkSize, maxChunkSize } = this;\n\n while (this.currentIndex < this.text.length) {\n await new Promise(resolve => setTimeout(resolve, delay));\n\n const remainingText = this.text.slice(this.currentIndex);\n let chunkSize: number;\n\n if (this.firstWordChunk) {\n chunkSize = this.findFirstWordBoundary(remainingText, minChunkSize);\n } else {\n const remainingChars = remainingText.length;\n chunkSize = Math.min(this.randomInt(minChunkSize, maxChunkSize + 1), remainingChars);\n }\n\n const chunk = this.text.slice(this.currentIndex, this.currentIndex + chunkSize);\n progressCallback?.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 +8,7 @@ var Graph = require('./graphs/Graph.cjs');
|
|
|
8
8
|
var CodeExecutor = require('./tools/CodeExecutor.cjs');
|
|
9
9
|
var _enum = require('./common/enum.cjs');
|
|
10
10
|
var graph = require('./utils/graph.cjs');
|
|
11
|
+
var misc = require('./utils/misc.cjs');
|
|
11
12
|
var run$1 = require('./utils/run.cjs');
|
|
12
13
|
|
|
13
14
|
|
|
@@ -15,6 +16,7 @@ var run$1 = require('./utils/run.cjs');
|
|
|
15
16
|
exports.Run = run.Run;
|
|
16
17
|
exports.ChatModelStreamHandler = stream.ChatModelStreamHandler;
|
|
17
18
|
exports.createContentAggregator = stream.createContentAggregator;
|
|
19
|
+
exports.handleToolCalls = stream.handleToolCalls;
|
|
18
20
|
exports.HandlerRegistry = events.HandlerRegistry;
|
|
19
21
|
exports.LLMStreamHandler = events.LLMStreamHandler;
|
|
20
22
|
exports.ModelEndHandler = events.ModelEndHandler;
|
|
@@ -80,6 +82,7 @@ Object.defineProperty(exports, "ToolCallTypes", {
|
|
|
80
82
|
});
|
|
81
83
|
exports.joinKeys = graph.joinKeys;
|
|
82
84
|
exports.resetIfNotEmpty = graph.resetIfNotEmpty;
|
|
85
|
+
exports.unescapeObject = misc.unescapeObject;
|
|
83
86
|
exports.RunnableCallable = run$1.RunnableCallable;
|
|
84
87
|
exports.sleep = run$1.sleep;
|
|
85
88
|
//# sourceMappingURL=main.cjs.map
|
package/dist/cjs/main.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/cjs/messages.cjs
CHANGED
|
@@ -23,7 +23,7 @@ User: ${userMessage[1]}
|
|
|
23
23
|
}
|
|
24
24
|
const modifyContent = (messageType, content) => {
|
|
25
25
|
return content.map(item => {
|
|
26
|
-
if (item && typeof item === 'object' && 'type' in item && item.type) {
|
|
26
|
+
if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {
|
|
27
27
|
let newType = item.type;
|
|
28
28
|
if (newType.endsWith('_delta')) {
|
|
29
29
|
newType = newType.replace('_delta', '');
|
|
@@ -63,10 +63,10 @@ function formatAnthropicMessage(message) {
|
|
|
63
63
|
formattedContent = message.content.reduce((acc, item) => {
|
|
64
64
|
if (typeof item === 'object' && item !== null) {
|
|
65
65
|
const extendedItem = item;
|
|
66
|
-
if (extendedItem.type === 'text' && extendedItem.text) {
|
|
66
|
+
if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {
|
|
67
67
|
acc.push({ type: 'text', text: extendedItem.text });
|
|
68
68
|
}
|
|
69
|
-
else if (extendedItem.type === 'tool_use' && extendedItem.id) {
|
|
69
|
+
else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {
|
|
70
70
|
const toolCall = toolCallMap.get(extendedItem.id);
|
|
71
71
|
if (toolCall) {
|
|
72
72
|
acc.push({
|
|
@@ -77,7 +77,7 @@ function formatAnthropicMessage(message) {
|
|
|
77
77
|
});
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
|
-
else if ('input' in extendedItem && extendedItem.input) {
|
|
80
|
+
else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {
|
|
81
81
|
try {
|
|
82
82
|
const parsedInput = JSON.parse(extendedItem.input);
|
|
83
83
|
const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.cjs","sources":["../../src/messages.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst modifyContent = (messageType: string, content: t.ExtendedMessageContent[]): t.ExtendedMessageContent[] => {\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n const allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\nexport function modifyDeltaProperties(obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent(messageType, obj.content);\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent(messageType, obj.lc_kwargs.content);\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch (e) {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatOpenAIArtifactContent(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}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AAC,CAAC;AACZ;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"messages.cjs","sources":["../../src/messages.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst modifyContent = (messageType: string, content: t.ExtendedMessageContent[]): t.ExtendedMessageContent[] => {\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n const allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\nexport function modifyDeltaProperties(obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent(messageType, obj.content);\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent(messageType, obj.lc_kwargs.content);\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch (e) {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatOpenAIArtifactContent(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}"],"names":["HumanMessage","AIMessage","messages","ToolMessage","AIMessageChunk"],"mappings":";;;;AAAA;AAKM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,EAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG,CAAA;QACV,WAAW,CAAC,CAAC,CAAC,CAAA;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO,CAAA;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO,CAAA;CACvB,CAAC;AAEA,IAAA,OAAO,IAAIA,qBAAY,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,aAAa,GAAG,CAAC,WAAmB,EAAE,OAAmC,KAAgC;AAC7G,IAAA,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,IAAG;QACxB,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE;AACxF,YAAA,IAAI,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC;AACxB,YAAA,IAAI,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;gBAC9B,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;aACzC;YACD,MAAM,YAAY,GAAG,CAAC,WAAW,EAAE,MAAM,EAAE,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AG,CAAC,EAAE;AAChC,QAAAD,UAAQ,CAAC,IAAI,CAAC,IAAIF,qBAAY,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC;KACjE;AACH,CAAC;AAEe,SAAA,aAAa,CAAI,KAAU,EAAE,SAAgC,EAAA;AAC3E,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC,CAAC;SACV;KACF;IACD,OAAO,CAAC,CAAC,CAAC;AACZ;;;;;;;;;;"}
|
package/dist/cjs/stream.cjs
CHANGED
|
@@ -27,6 +27,67 @@ const getMessageId = (stepKey, graph, returnExistingId = false) => {
|
|
|
27
27
|
graph.messageIdsByStepKey.set(stepKey, message_id);
|
|
28
28
|
return message_id;
|
|
29
29
|
};
|
|
30
|
+
const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
31
|
+
if (!graph || !metadata) {
|
|
32
|
+
console.warn(`Graph or metadata not found in ${event} event`);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (!toolCalls) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (toolCalls.length === 0) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const tool_calls = [];
|
|
42
|
+
const tool_call_ids = [];
|
|
43
|
+
for (const tool_call of toolCalls) {
|
|
44
|
+
const toolCallId = tool_call.id ?? `toolu_${nanoid.nanoid()}`;
|
|
45
|
+
tool_call.id = toolCallId;
|
|
46
|
+
if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
tool_calls.push(tool_call);
|
|
50
|
+
tool_call_ids.push(toolCallId);
|
|
51
|
+
}
|
|
52
|
+
const stepKey = graph.getStepKey(metadata);
|
|
53
|
+
let prevStepId = '';
|
|
54
|
+
let prevRunStep;
|
|
55
|
+
try {
|
|
56
|
+
prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
57
|
+
prevRunStep = graph.getRunStep(prevStepId);
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
// no previous step
|
|
61
|
+
}
|
|
62
|
+
const dispatchToolCallIds = (lastMessageStepId) => {
|
|
63
|
+
graph.dispatchMessageDelta(lastMessageStepId, {
|
|
64
|
+
content: [{
|
|
65
|
+
type: 'text',
|
|
66
|
+
text: '',
|
|
67
|
+
tool_call_ids,
|
|
68
|
+
}],
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
/* If the previous step exists and is a message creation */
|
|
72
|
+
if (prevStepId && prevRunStep && prevRunStep.type === _enum.StepTypes.MESSAGE_CREATION) {
|
|
73
|
+
dispatchToolCallIds(prevStepId);
|
|
74
|
+
/* If the previous step doesn't exist or is not a message creation */
|
|
75
|
+
}
|
|
76
|
+
else if (!prevRunStep || prevRunStep.type !== _enum.StepTypes.MESSAGE_CREATION) {
|
|
77
|
+
const messageId = getMessageId(stepKey, graph, true) ?? '';
|
|
78
|
+
const stepId = graph.dispatchRunStep(stepKey, {
|
|
79
|
+
type: _enum.StepTypes.MESSAGE_CREATION,
|
|
80
|
+
message_creation: {
|
|
81
|
+
message_id: messageId,
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
dispatchToolCallIds(stepId);
|
|
85
|
+
}
|
|
86
|
+
graph.dispatchRunStep(stepKey, {
|
|
87
|
+
type: _enum.StepTypes.TOOL_CALLS,
|
|
88
|
+
tool_calls,
|
|
89
|
+
});
|
|
90
|
+
};
|
|
30
91
|
class ChatModelStreamHandler {
|
|
31
92
|
handle(event, data, metadata, graph) {
|
|
32
93
|
if (!graph) {
|
|
@@ -45,54 +106,7 @@ class ChatModelStreamHandler {
|
|
|
45
106
|
const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;
|
|
46
107
|
if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {
|
|
47
108
|
hasToolCalls = true;
|
|
48
|
-
|
|
49
|
-
const tool_call_ids = [];
|
|
50
|
-
for (const tool_call of chunk.tool_calls) {
|
|
51
|
-
const toolCallId = tool_call.id ?? '';
|
|
52
|
-
if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {
|
|
53
|
-
continue;
|
|
54
|
-
}
|
|
55
|
-
tool_calls.push(tool_call);
|
|
56
|
-
tool_call_ids.push(toolCallId);
|
|
57
|
-
}
|
|
58
|
-
const stepKey = graph.getStepKey(metadata);
|
|
59
|
-
let prevStepId = '';
|
|
60
|
-
let prevRunStep;
|
|
61
|
-
try {
|
|
62
|
-
prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
63
|
-
prevRunStep = graph.getRunStep(prevStepId);
|
|
64
|
-
}
|
|
65
|
-
catch (e) {
|
|
66
|
-
// no previous step
|
|
67
|
-
}
|
|
68
|
-
const dispatchToolCallIds = (lastMessageStepId) => {
|
|
69
|
-
graph.dispatchMessageDelta(lastMessageStepId, {
|
|
70
|
-
content: [{
|
|
71
|
-
type: 'text',
|
|
72
|
-
text: '',
|
|
73
|
-
tool_call_ids,
|
|
74
|
-
}],
|
|
75
|
-
});
|
|
76
|
-
};
|
|
77
|
-
/* If the previous step exists and is a message creation */
|
|
78
|
-
if (prevStepId && prevRunStep && prevRunStep.type === _enum.StepTypes.MESSAGE_CREATION) {
|
|
79
|
-
dispatchToolCallIds(prevStepId);
|
|
80
|
-
/* If the previous step doesn't exist or is not a message creation */
|
|
81
|
-
}
|
|
82
|
-
else if (!prevRunStep || prevRunStep.type !== _enum.StepTypes.MESSAGE_CREATION) {
|
|
83
|
-
const messageId = getMessageId(stepKey, graph, true) ?? '';
|
|
84
|
-
const stepId = graph.dispatchRunStep(stepKey, {
|
|
85
|
-
type: _enum.StepTypes.MESSAGE_CREATION,
|
|
86
|
-
message_creation: {
|
|
87
|
-
message_id: messageId,
|
|
88
|
-
},
|
|
89
|
-
});
|
|
90
|
-
dispatchToolCallIds(stepId);
|
|
91
|
-
}
|
|
92
|
-
graph.dispatchRunStep(stepKey, {
|
|
93
|
-
type: _enum.StepTypes.TOOL_CALLS,
|
|
94
|
-
tool_calls,
|
|
95
|
-
});
|
|
109
|
+
handleToolCalls(chunk.tool_calls, metadata, graph);
|
|
96
110
|
}
|
|
97
111
|
const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;
|
|
98
112
|
const isEmptyChunk = isEmptyContent && !hasToolCallChunks;
|
|
@@ -310,4 +324,5 @@ function createContentAggregator() {
|
|
|
310
324
|
|
|
311
325
|
exports.ChatModelStreamHandler = ChatModelStreamHandler;
|
|
312
326
|
exports.createContentAggregator = createContentAggregator;
|
|
327
|
+
exports.handleToolCalls = handleToolCalls;
|
|
313
328
|
//# sourceMappingURL=stream.cjs.map
|