illuma-agents 1.0.65 → 1.0.67
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 +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +3 -132
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +47 -4
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +0 -50
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/prompts/collab.cjs +11 -0
- package/dist/cjs/prompts/collab.cjs.map +1 -0
- package/dist/cjs/prompts/taskmanager.cjs +66 -0
- package/dist/cjs/prompts/taskmanager.cjs.map +1 -0
- package/dist/cjs/prompts/taskplanning.cjs +99 -0
- package/dist/cjs/prompts/taskplanning.cjs.map +1 -0
- package/dist/cjs/tools/Calculator.cjs +23 -2
- package/dist/cjs/tools/Calculator.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +19 -1
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/TaskProgress.cjs +172 -0
- package/dist/cjs/tools/TaskProgress.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +2 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/search/schema.cjs +45 -0
- package/dist/cjs/tools/search/schema.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +3 -132
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +8 -3
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +2 -51
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/prompts/collab.mjs +9 -0
- package/dist/esm/prompts/collab.mjs.map +1 -0
- package/dist/esm/prompts/taskmanager.mjs +60 -0
- package/dist/esm/prompts/taskmanager.mjs.map +1 -0
- package/dist/esm/prompts/taskplanning.mjs +94 -0
- package/dist/esm/prompts/taskplanning.mjs.map +1 -0
- package/dist/esm/tools/Calculator.mjs +20 -3
- package/dist/esm/tools/Calculator.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +16 -2
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/TaskProgress.mjs +163 -0
- package/dist/esm/tools/TaskProgress.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +2 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/search/schema.mjs +42 -1
- package/dist/esm/tools/search/schema.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/messages/format.d.ts +0 -9
- package/dist/types/prompts/index.d.ts +1 -0
- package/dist/types/prompts/taskplanning.d.ts +54 -0
- package/dist/types/tools/Calculator.d.ts +26 -0
- package/dist/types/tools/CodeExecutor.d.ts +51 -0
- package/dist/types/tools/TaskProgress.d.ts +142 -0
- package/dist/types/tools/search/index.d.ts +1 -0
- package/dist/types/tools/search/schema.d.ts +69 -0
- package/package.json +1 -1
- package/src/common/enum.ts +2 -0
- package/src/graphs/Graph.ts +5 -160
- package/src/index.ts +4 -0
- package/src/messages/format.ts +0 -60
- package/src/prompts/index.ts +2 -1
- package/src/prompts/taskplanning.ts +96 -0
- package/src/specs/task-progress.test.ts +330 -0
- package/src/tools/Calculator.ts +24 -3
- package/src/tools/CodeExecutor.ts +19 -2
- package/src/tools/TaskProgress.ts +247 -0
- package/src/tools/ToolNode.ts +2 -1
- package/src/tools/search/index.ts +1 -0
- package/src/tools/search/schema.ts +45 -0
- package/src/tools/search/tool.ts +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HumanMessage, AIMessage, SystemMessage, getBufferString,
|
|
1
|
+
import { HumanMessage, AIMessage, SystemMessage, getBufferString, ToolMessage, AIMessageChunk } from '@langchain/core/messages';
|
|
2
2
|
import { Providers, ContentTypes, MessageTypes } from '../common/enum.mjs';
|
|
3
3
|
import { processToolOutput } from '../utils/toonFormat.mjs';
|
|
4
4
|
|
|
@@ -680,55 +680,6 @@ function ensureThinkingBlockInMessages(messages, _provider) {
|
|
|
680
680
|
}
|
|
681
681
|
return result;
|
|
682
682
|
}
|
|
683
|
-
/**
|
|
684
|
-
* Strips thinking blocks from messages for structured output invocation.
|
|
685
|
-
* When switching from thinking-enabled mode to structured output (which requires thinking disabled),
|
|
686
|
-
* we need to remove thinking/reasoning blocks from the conversation to avoid Bedrock errors.
|
|
687
|
-
*
|
|
688
|
-
* @param messages - Array of messages to process
|
|
689
|
-
* @returns The messages array with thinking blocks stripped from AI messages
|
|
690
|
-
*/
|
|
691
|
-
function stripThinkingBlocksFromMessages(messages) {
|
|
692
|
-
return messages.map((msg) => {
|
|
693
|
-
const isAI = msg instanceof AIMessage || msg instanceof AIMessageChunk;
|
|
694
|
-
if (!isAI) {
|
|
695
|
-
return msg;
|
|
696
|
-
}
|
|
697
|
-
const aiMsg = msg;
|
|
698
|
-
const content = aiMsg.content;
|
|
699
|
-
// If content is not an array, nothing to strip
|
|
700
|
-
if (!Array.isArray(content)) {
|
|
701
|
-
return msg;
|
|
702
|
-
}
|
|
703
|
-
// Filter out thinking/reasoning blocks
|
|
704
|
-
const filteredContent = content.filter((c) => {
|
|
705
|
-
if (typeof c !== 'object' || c === null) {
|
|
706
|
-
return true;
|
|
707
|
-
}
|
|
708
|
-
const type = c.type;
|
|
709
|
-
return (type !== ContentTypes.THINKING &&
|
|
710
|
-
type !== ContentTypes.REASONING_CONTENT &&
|
|
711
|
-
type !== ContentTypes.REASONING &&
|
|
712
|
-
type !== 'thinking' &&
|
|
713
|
-
type !== 'redacted_thinking');
|
|
714
|
-
});
|
|
715
|
-
// If no content left after filtering, add a placeholder
|
|
716
|
-
if (filteredContent.length === 0) {
|
|
717
|
-
filteredContent.push({
|
|
718
|
-
type: 'text',
|
|
719
|
-
text: '(previous response)',
|
|
720
|
-
});
|
|
721
|
-
}
|
|
722
|
-
// Create a new AI message with the filtered content
|
|
723
|
-
return new AIMessageChunk({
|
|
724
|
-
content: filteredContent,
|
|
725
|
-
id: aiMsg.id,
|
|
726
|
-
response_metadata: aiMsg.response_metadata,
|
|
727
|
-
usage_metadata: aiMsg.usage_metadata,
|
|
728
|
-
// Don't include tool_calls - we're stripping those for structured output context
|
|
729
|
-
});
|
|
730
|
-
});
|
|
731
|
-
}
|
|
732
683
|
|
|
733
|
-
export { ensureThinkingBlockInMessages, formatAgentMessages, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, labelContentByAgent, shiftIndexTokenCountMap
|
|
684
|
+
export { ensureThinkingBlockInMessages, formatAgentMessages, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, labelContentByAgent, shiftIndexTokenCountMap };
|
|
734
685
|
//# sourceMappingURL=format.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.mjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ExtendedMessageContent,\n MessageContentComplex,\n ReasoningContentText,\n ToolCallContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport { Providers, ContentTypes, MessageTypes } from '@/common';\nimport { processToolOutput } from '@/utils/toonFormat';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | HumanMessage\n | AIMessage\n | SystemMessage => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ content });\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = new AIMessage({\n content: part.text != null ? part.text : '',\n });\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = new AIMessage({ content: '' });\n formattedMessages.push(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n // Apply TOON compression to historical tool outputs for context efficiency\n // processToolOutput handles: JSON→TOON conversion, already-TOON detection (skip), truncation\n const processedOutput =\n output != null ? processToolOutput(output).content : '';\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: processedOutput,\n })\n );\n } else if (part.type === ContentTypes.THINK) {\n hasReasoning = true;\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE\n ) {\n continue;\n } else {\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(new AIMessage({ content: currentContent }));\n }\n\n return formattedMessages;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message.content = [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ];\n }\n if (message.role !== 'assistant') {\n messages.push(\n formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage\n );\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n // If tools set is provided, we need to check if we need to convert tool messages to a string\n if (tools) {\n // First, check if this message contains tool calls\n let hasToolCalls = false;\n let hasInvalidTool = false;\n const toolNames: string[] = [];\n\n const content = message.content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n hasToolCalls = true;\n if (tools.size === 0) {\n hasInvalidTool = true;\n break;\n }\n // Protect against malformed tool call entries\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n hasInvalidTool = true;\n continue;\n }\n const toolName = part.tool_call.name;\n toolNames.push(toolName);\n if (!tools.has(toolName)) {\n hasInvalidTool = true;\n }\n }\n }\n }\n\n // If this message has tool calls and at least one is invalid, we need to convert it\n if (hasToolCalls && hasInvalidTool) {\n // We need to collect all related messages (this message and any subsequent tool messages)\n const toolSequence: BaseMessage[] = [];\n let sequenceEndIndex = i;\n\n // Process the current assistant message to get the AIMessage with tool calls\n const formattedMessages = formatAssistantMessage(message);\n toolSequence.push(...formattedMessages);\n\n // Look ahead for any subsequent assistant messages that might be part of this tool sequence\n let j = i + 1;\n while (j < payload.length && payload[j].role === 'assistant') {\n // Check if this is a continuation of the tool sequence\n let isToolResponse = false;\n const content = payload[j].content;\n if (content != null && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n isToolResponse = true;\n break;\n }\n }\n }\n\n if (isToolResponse) {\n // This is part of the tool sequence, add it\n const nextMessages = formatAssistantMessage(payload[j]);\n toolSequence.push(...nextMessages);\n sequenceEndIndex = j;\n j++;\n } else {\n // This is not part of the tool sequence, stop looking\n break;\n }\n }\n\n // Convert the sequence to a string\n const bufferString = getBufferString(toolSequence);\n messages.push(new AIMessage({ content: bufferString }));\n\n // Skip the messages we've already processed\n i = sequenceEndIndex;\n\n // Update the index mapping for this sequence\n const resultIndices = [messages.length - 1];\n for (let k = i; k >= i && k <= sequenceEndIndex; k++) {\n indexMapping[k] = resultIndices;\n }\n\n continue;\n }\n }\n\n // Process the assistant message using the helper function\n const formattedMessages = formatAssistantMessage(message);\n messages.push(...formattedMessages);\n\n // Update the index mapping for this assistant message\n // Store all indices that were created from this original message\n const endMessageIndex = messages.length;\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n // Update the token count map if it was provided\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount !== undefined) {\n if (resultIndices.length === 1) {\n // Simple 1:1 mapping\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n } else if (resultIndices.length > 1) {\n // If one message was split into multiple, distribute the token count\n // This is a simplification - in reality, you might want a more sophisticated distribution\n const countPerMessage = Math.floor(tokenCount / resultIndices.length);\n resultIndices.forEach((resultIndex, idx) => {\n if (idx === resultIndices.length - 1) {\n // Give any remainder to the last message\n updatedIndexTokenCountMap[resultIndex] =\n tokenCount - countPerMessage * (resultIndices.length - 1);\n } else {\n updatedIndexTokenCountMap[resultIndex] = countPerMessage;\n }\n });\n }\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers\n): BaseMessage[] {\n const result: BaseMessage[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n const isAI = msg instanceof AIMessage || msg instanceof AIMessageChunk;\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let firstContentType: string | undefined;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n const content = aiMsg.content as ExtendedMessageContent[];\n firstContentType = content[0]?.type;\n hasToolUse =\n hasToolUse ||\n content.some((c) => typeof c === 'object' && c.type === 'tool_use');\n }\n\n // If message has tool use but no thinking block, convert to buffer string\n if (\n hasToolUse &&\n firstContentType !== ContentTypes.THINKING &&\n firstContentType !== ContentTypes.REASONING_CONTENT &&\n firstContentType !== ContentTypes.REASONING &&\n firstContentType !== 'redacted_thinking'\n ) {\n // Collect the AI message and any following tool messages\n const toolSequence: BaseMessage[] = [msg];\n let j = i + 1;\n\n // Look ahead for tool messages that belong to this AI message\n // Use getType() instead of instanceof to avoid module mismatch issues\n // where different copies of ToolMessage class might be loaded\n while (\n j < messages.length &&\n messages[j].getType() === MessageTypes.TOOL\n ) {\n toolSequence.push(messages[j]);\n j++;\n }\n\n // Convert the sequence to a buffer string and wrap in a HumanMessage\n // This avoids the thinking block requirement which only applies to AI messages\n const bufferString = getBufferString(toolSequence);\n result.push(\n new HumanMessage({\n content: `[Previous agent context]\\n${bufferString}`,\n })\n );\n\n // Skip the messages we've processed\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n\n/**\n * Strips thinking blocks from messages for structured output invocation.\n * When switching from thinking-enabled mode to structured output (which requires thinking disabled),\n * we need to remove thinking/reasoning blocks from the conversation to avoid Bedrock errors.\n *\n * @param messages - Array of messages to process\n * @returns The messages array with thinking blocks stripped from AI messages\n */\nexport function stripThinkingBlocksFromMessages(\n messages: BaseMessage[]\n): BaseMessage[] {\n return messages.map((msg) => {\n const isAI = msg instanceof AIMessage || msg instanceof AIMessageChunk;\n \n if (!isAI) {\n return msg;\n }\n \n const aiMsg = msg as AIMessage | AIMessageChunk;\n const content = aiMsg.content;\n \n // If content is not an array, nothing to strip\n if (!Array.isArray(content)) {\n return msg;\n }\n \n // Filter out thinking/reasoning blocks\n const filteredContent = content.filter((c) => {\n if (typeof c !== 'object' || c === null) {\n return true;\n }\n const type = (c as ExtendedMessageContent).type;\n return (\n type !== ContentTypes.THINKING &&\n type !== ContentTypes.REASONING_CONTENT &&\n type !== ContentTypes.REASONING &&\n type !== 'thinking' &&\n type !== 'redacted_thinking'\n );\n });\n \n // If no content left after filtering, add a placeholder\n if (filteredContent.length === 0) {\n filteredContent.push({\n type: 'text',\n text: '(previous response)',\n });\n }\n \n // Create a new AI message with the filtered content\n return new AIMessageChunk({\n content: filteredContent,\n id: aiMsg.id,\n response_metadata: aiMsg.response_metadata,\n usage_metadata: aiMsg.usage_metadata,\n // Don't include tool_calls - we're stripping those for structured output context\n });\n });\n}\n"],"names":[],"mappings":";;;;AAAA;AAmCA;;;;;AAKG;AACI,MAAM,kBAAkB,GAAG,CAAC,EACjC,OAAO,EACP,QAAQ,EACR,UAAU,GACS,KAKjB;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE,EAA6B;KACvC;AAED,IAAA,IAAI,QAAQ,KAAK,SAAS,CAAC,SAAS,EAAE;QACpC,MAAM,CAAC,OAAO,GAAG;AACf,YAAA,GAAG,UAAU;YACb,EAAE,IAAI,EAAE,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;SACxB;AAC5B,QAAA,OAAO,MAAM;;IAGf,MAAM,CAAC,OAAO,GAAG;QACf,EAAE,IAAI,EAAE,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;AAClD,QAAA,GAAG,UAAU;KACa;AAE5B,IAAA,OAAO,MAAM;AACf;AA+BA;;;;;AAKG;AACU,MAA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AC3B,YAAA,OAAO,GAAG;;;QAIZ,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;YAC3C,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,EAAE;AACvC,gBAAA,OAAO,IAAI;;AAEb,YAAA,MAAM,IAAI,GAAI,CAA4B,CAAC,IAAI;AAC/C,YAAA,QACE,IAAI,KAAK,YAAY,CAAC,QAAQ;gBAC9B,IAAI,KAAK,YAAY,CAAC,iBAAiB;gBACvC,IAAI,KAAK,YAAY,CAAC,SAAS;AAC/B,gBAAA,IAAI,KAAK,UAAU;gBACnB,IAAI,KAAK,mBAAmB;AAEhC,SAAC,CAAC;;AAGF,QAAA,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE;YAChC,eAAe,CAAC,IAAI,CAAC;AACnB,gBAAA,IAAI,EAAE,MAAM;AACZ,gBAAA,IAAI,EAAE,qBAAqB;AAC5B,aAAA,CAAC;;;QAIJ,OAAO,IAAI,cAAc,CAAC;AACxB,YAAA,OAAO,EAAE,eAAe;YACxB,EAAE,EAAE,KAAK,CAAC,EAAE;YACZ,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;;AAErC,SAAA,CAAC;AACJ,KAAC,CAAC;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"format.mjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ExtendedMessageContent,\n MessageContentComplex,\n ReasoningContentText,\n ToolCallContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport { Providers, ContentTypes, MessageTypes } from '@/common';\nimport { processToolOutput } from '@/utils/toonFormat';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | HumanMessage\n | AIMessage\n | SystemMessage => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ content });\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = new AIMessage({\n content: part.text != null ? part.text : '',\n });\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = new AIMessage({ content: '' });\n formattedMessages.push(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n // Apply TOON compression to historical tool outputs for context efficiency\n // processToolOutput handles: JSON→TOON conversion, already-TOON detection (skip), truncation\n const processedOutput =\n output != null ? processToolOutput(output).content : '';\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: processedOutput,\n })\n );\n } else if (part.type === ContentTypes.THINK) {\n hasReasoning = true;\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE\n ) {\n continue;\n } else {\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(new AIMessage({ content: currentContent }));\n }\n\n return formattedMessages;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message.content = [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ];\n }\n if (message.role !== 'assistant') {\n messages.push(\n formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage\n );\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n // If tools set is provided, we need to check if we need to convert tool messages to a string\n if (tools) {\n // First, check if this message contains tool calls\n let hasToolCalls = false;\n let hasInvalidTool = false;\n const toolNames: string[] = [];\n\n const content = message.content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n hasToolCalls = true;\n if (tools.size === 0) {\n hasInvalidTool = true;\n break;\n }\n // Protect against malformed tool call entries\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n hasInvalidTool = true;\n continue;\n }\n const toolName = part.tool_call.name;\n toolNames.push(toolName);\n if (!tools.has(toolName)) {\n hasInvalidTool = true;\n }\n }\n }\n }\n\n // If this message has tool calls and at least one is invalid, we need to convert it\n if (hasToolCalls && hasInvalidTool) {\n // We need to collect all related messages (this message and any subsequent tool messages)\n const toolSequence: BaseMessage[] = [];\n let sequenceEndIndex = i;\n\n // Process the current assistant message to get the AIMessage with tool calls\n const formattedMessages = formatAssistantMessage(message);\n toolSequence.push(...formattedMessages);\n\n // Look ahead for any subsequent assistant messages that might be part of this tool sequence\n let j = i + 1;\n while (j < payload.length && payload[j].role === 'assistant') {\n // Check if this is a continuation of the tool sequence\n let isToolResponse = false;\n const content = payload[j].content;\n if (content != null && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n isToolResponse = true;\n break;\n }\n }\n }\n\n if (isToolResponse) {\n // This is part of the tool sequence, add it\n const nextMessages = formatAssistantMessage(payload[j]);\n toolSequence.push(...nextMessages);\n sequenceEndIndex = j;\n j++;\n } else {\n // This is not part of the tool sequence, stop looking\n break;\n }\n }\n\n // Convert the sequence to a string\n const bufferString = getBufferString(toolSequence);\n messages.push(new AIMessage({ content: bufferString }));\n\n // Skip the messages we've already processed\n i = sequenceEndIndex;\n\n // Update the index mapping for this sequence\n const resultIndices = [messages.length - 1];\n for (let k = i; k >= i && k <= sequenceEndIndex; k++) {\n indexMapping[k] = resultIndices;\n }\n\n continue;\n }\n }\n\n // Process the assistant message using the helper function\n const formattedMessages = formatAssistantMessage(message);\n messages.push(...formattedMessages);\n\n // Update the index mapping for this assistant message\n // Store all indices that were created from this original message\n const endMessageIndex = messages.length;\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n // Update the token count map if it was provided\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount !== undefined) {\n if (resultIndices.length === 1) {\n // Simple 1:1 mapping\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n } else if (resultIndices.length > 1) {\n // If one message was split into multiple, distribute the token count\n // This is a simplification - in reality, you might want a more sophisticated distribution\n const countPerMessage = Math.floor(tokenCount / resultIndices.length);\n resultIndices.forEach((resultIndex, idx) => {\n if (idx === resultIndices.length - 1) {\n // Give any remainder to the last message\n updatedIndexTokenCountMap[resultIndex] =\n tokenCount - countPerMessage * (resultIndices.length - 1);\n } else {\n updatedIndexTokenCountMap[resultIndex] = countPerMessage;\n }\n });\n }\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers\n): BaseMessage[] {\n const result: BaseMessage[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n const isAI = msg instanceof AIMessage || msg instanceof AIMessageChunk;\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let firstContentType: string | undefined;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n const content = aiMsg.content as ExtendedMessageContent[];\n firstContentType = content[0]?.type;\n hasToolUse =\n hasToolUse ||\n content.some((c) => typeof c === 'object' && c.type === 'tool_use');\n }\n\n // If message has tool use but no thinking block, convert to buffer string\n if (\n hasToolUse &&\n firstContentType !== ContentTypes.THINKING &&\n firstContentType !== ContentTypes.REASONING_CONTENT &&\n firstContentType !== ContentTypes.REASONING &&\n firstContentType !== 'redacted_thinking'\n ) {\n // Collect the AI message and any following tool messages\n const toolSequence: BaseMessage[] = [msg];\n let j = i + 1;\n\n // Look ahead for tool messages that belong to this AI message\n // Use getType() instead of instanceof to avoid module mismatch issues\n // where different copies of ToolMessage class might be loaded\n while (\n j < messages.length &&\n messages[j].getType() === MessageTypes.TOOL\n ) {\n toolSequence.push(messages[j]);\n j++;\n }\n\n // Convert the sequence to a buffer string and wrap in a HumanMessage\n // This avoids the thinking block requirement which only applies to AI messages\n const bufferString = getBufferString(toolSequence);\n result.push(\n new HumanMessage({\n content: `[Previous agent context]\\n${bufferString}`,\n })\n );\n\n // Skip the messages we've processed\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n"],"names":[],"mappings":";;;;AAAA;AAmCA;;;;;AAKG;AACI,MAAM,kBAAkB,GAAG,CAAC,EACjC,OAAO,EACP,QAAQ,EACR,UAAU,GACS,KAKjB;;AA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,CAAC;;aACA;;AAEL,YAAA,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;AAChB,YAAA,CAAC,EAAE;;;AAIP,IAAA,OAAO,MAAM;AACf;;;;"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// src/prompts/collab.ts
|
|
2
|
+
const supervisorPrompt = `You are a supervisor tasked with managing a conversation between the
|
|
3
|
+
following workers: {members}. Given the following user request,
|
|
4
|
+
respond with the worker to act next. Each worker will perform a
|
|
5
|
+
task and respond with their results and status. Multiple workers can work at once, and they can use multiple tools at once. Each worker can run their tools multiple times per task. When finished,
|
|
6
|
+
respond with FINISH.`;
|
|
7
|
+
|
|
8
|
+
export { supervisorPrompt };
|
|
9
|
+
//# sourceMappingURL=collab.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collab.mjs","sources":["../../../src/prompts/collab.ts"],"sourcesContent":["// src/prompts/collab.ts\nexport const supervisorPrompt = `You are a supervisor tasked with managing a conversation between the\nfollowing workers: {members}. Given the following user request,\nrespond with the worker to act next. Each worker will perform a\ntask and respond with their results and status. Multiple workers can work at once, and they can use multiple tools at once. Each worker can run their tools multiple times per task. When finished,\nrespond with FINISH.`;"],"names":[],"mappings":"AAAA;AACa,MAAA,gBAAgB,GAAG,CAAA;;;;;;;;"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const taskManagerPrompt = `You are a Task Manager responsible for efficiently coordinating a team of specialized workers: {members}. Your PRIMARY and SOLE OBJECTIVE is to fulfill the user's specific request as quickly and effectively as possible.
|
|
2
|
+
|
|
3
|
+
CRITICAL GUIDELINES:
|
|
4
|
+
1. The user's request is your CHIEF CONCERN. Every action must directly contribute to fulfilling this request.
|
|
5
|
+
2. Aim to complete the entire task in NO MORE THAN 2-3 TURNS, unless explicitly instructed otherwise.
|
|
6
|
+
3. Eliminate all superfluous activity. Each task must be essential to achieving the user's goal.
|
|
7
|
+
4. Assign no more than 5 tasks per turn, and only if absolutely necessary.
|
|
8
|
+
5. Be concise and direct in your task assignments.
|
|
9
|
+
6. End the process IMMEDIATELY once the user's request is fulfilled by setting 'end' to true and assigning no new tasks.
|
|
10
|
+
|
|
11
|
+
Your responsibilities:
|
|
12
|
+
1. Analyze the user's request and break it down into the minimum necessary subtasks.
|
|
13
|
+
2. Assign these essential tasks to the most appropriate team members based on their skills and tools.
|
|
14
|
+
3. Prioritize tasks to ensure the most efficient path to completion.
|
|
15
|
+
4. Continuously evaluate if the user's request has been fully addressed.
|
|
16
|
+
5. End the process IMMEDIATELY once the user's request is fulfilled.
|
|
17
|
+
|
|
18
|
+
Task Assignment Guidelines:
|
|
19
|
+
- Assign only the most crucial tasks required to meet the user's needs.
|
|
20
|
+
- Multiple tasks can be assigned to the same team member if it improves efficiency.
|
|
21
|
+
- Always specify the tool to use if applicable.
|
|
22
|
+
- Consider task dependencies to minimize the number of turns.
|
|
23
|
+
|
|
24
|
+
After each round:
|
|
25
|
+
- Critically assess if the user's request has been fully addressed.
|
|
26
|
+
- If more work is genuinely needed, assign only the most essential remaining tasks.
|
|
27
|
+
- If the user's request has been fulfilled or can be fulfilled with the results at hand, set 'end' to true and assign no new tasks.
|
|
28
|
+
|
|
29
|
+
REMEMBER: Your success is measured by how quickly and effectively you fulfill the user's request, not by the number of tasks assigned or turns taken. Excessive deliberation or unnecessary tasks are counterproductive. Focus solely on the user's needs and conclude the process as soon as those needs are met.`;
|
|
30
|
+
const assignTasksFunctionDescription = 'Assign the minimum necessary tasks to team members to fulfill the user\'s request as quickly as possible. Assign up to 5 tasks maximum per turn, only if absolutely necessary. Each task must specify the team member, a concise description, and the tool to use if applicable.';
|
|
31
|
+
const assignTasksFunctionParameters = {
|
|
32
|
+
type: 'object',
|
|
33
|
+
properties: {
|
|
34
|
+
tasks: {
|
|
35
|
+
type: 'array',
|
|
36
|
+
items: {
|
|
37
|
+
type: 'object',
|
|
38
|
+
properties: {
|
|
39
|
+
member: { type: 'string', description: 'Name of the team member assigned to the task' },
|
|
40
|
+
description: { type: 'string', description: 'Concise description of the essential task to be performed' },
|
|
41
|
+
tool: { type: 'string', description: 'Specific tool to be used for the task, if applicable' },
|
|
42
|
+
},
|
|
43
|
+
required: ['member', 'description'],
|
|
44
|
+
},
|
|
45
|
+
description: 'List of essential tasks to be assigned, maximum 5 tasks per turn.',
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
required: ['tasks'],
|
|
49
|
+
};
|
|
50
|
+
const endProcessFunctionDescription = 'End the process when the user\'s request has been fulfilled.';
|
|
51
|
+
const endProcessFunctionParameters = {
|
|
52
|
+
type: 'object',
|
|
53
|
+
properties: {
|
|
54
|
+
reason: { type: 'string', description: 'Brief explanation of why the process is ending' },
|
|
55
|
+
},
|
|
56
|
+
required: ['reason'],
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export { assignTasksFunctionDescription, assignTasksFunctionParameters, endProcessFunctionDescription, endProcessFunctionParameters, taskManagerPrompt };
|
|
60
|
+
//# sourceMappingURL=taskmanager.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskmanager.mjs","sources":["../../../src/prompts/taskmanager.ts"],"sourcesContent":["export const taskManagerPrompt = `You are a Task Manager responsible for efficiently coordinating a team of specialized workers: {members}. Your PRIMARY and SOLE OBJECTIVE is to fulfill the user's specific request as quickly and effectively as possible.\n\nCRITICAL GUIDELINES:\n1. The user's request is your CHIEF CONCERN. Every action must directly contribute to fulfilling this request.\n2. Aim to complete the entire task in NO MORE THAN 2-3 TURNS, unless explicitly instructed otherwise.\n3. Eliminate all superfluous activity. Each task must be essential to achieving the user's goal.\n4. Assign no more than 5 tasks per turn, and only if absolutely necessary.\n5. Be concise and direct in your task assignments.\n6. End the process IMMEDIATELY once the user's request is fulfilled by setting 'end' to true and assigning no new tasks.\n\nYour responsibilities:\n1. Analyze the user's request and break it down into the minimum necessary subtasks.\n2. Assign these essential tasks to the most appropriate team members based on their skills and tools.\n3. Prioritize tasks to ensure the most efficient path to completion.\n4. Continuously evaluate if the user's request has been fully addressed.\n5. End the process IMMEDIATELY once the user's request is fulfilled.\n\nTask Assignment Guidelines:\n- Assign only the most crucial tasks required to meet the user's needs.\n- Multiple tasks can be assigned to the same team member if it improves efficiency.\n- Always specify the tool to use if applicable.\n- Consider task dependencies to minimize the number of turns.\n\nAfter each round:\n- Critically assess if the user's request has been fully addressed.\n- If more work is genuinely needed, assign only the most essential remaining tasks.\n- If the user's request has been fulfilled or can be fulfilled with the results at hand, set 'end' to true and assign no new tasks.\n\nREMEMBER: Your success is measured by how quickly and effectively you fulfill the user's request, not by the number of tasks assigned or turns taken. Excessive deliberation or unnecessary tasks are counterproductive. Focus solely on the user's needs and conclude the process as soon as those needs are met.`;\n\nexport const assignTasksFunctionDescription = 'Assign the minimum necessary tasks to team members to fulfill the user\\'s request as quickly as possible. Assign up to 5 tasks maximum per turn, only if absolutely necessary. Each task must specify the team member, a concise description, and the tool to use if applicable.';\n\nexport const assignTasksFunctionParameters = {\n type: 'object',\n properties: {\n tasks: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n member: { type: 'string', description: 'Name of the team member assigned to the task' },\n description: { type: 'string', description: 'Concise description of the essential task to be performed' },\n tool: { type: 'string', description: 'Specific tool to be used for the task, if applicable' },\n },\n required: ['member', 'description'],\n },\n description: 'List of essential tasks to be assigned, maximum 5 tasks per turn.',\n },\n },\n required: ['tasks'],\n};\n\nexport const endProcessFunctionDescription = 'End the process when the user\\'s request has been fulfilled.';\n\nexport const endProcessFunctionParameters = {\n type: 'object',\n properties: {\n reason: { type: 'string', description: 'Brief explanation of why the process is ending' },\n },\n required: ['reason'],\n};\n"],"names":[],"mappings":"AAAa,MAAA,iBAAiB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8B1B,MAAM,8BAA8B,GAAG;AAEjC,MAAA,6BAA6B,GAAG;AAC3C,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,KAAK,EAAE;AACL,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE;AACL,gBAAA,IAAI,EAAE,QAAQ;AACd,gBAAA,UAAU,EAAE;oBACV,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8CAA8C,EAAE;oBACvF,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,2DAA2D,EAAE;oBACzG,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,sDAAsD,EAAE;AAC9F,iBAAA;AACD,gBAAA,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,CAAC;AACpC,aAAA;AACD,YAAA,WAAW,EAAE,mEAAmE;AACjF,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,OAAO,CAAC;;AAGd,MAAM,6BAA6B,GAAG;AAEhC,MAAA,4BAA4B,GAAG;AAC1C,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;QACV,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gDAAgD,EAAE;AAC1F,KAAA;IACD,QAAQ,EAAE,CAAC,QAAQ,CAAC;;;;;"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// src/prompts/taskplanning.ts
|
|
2
|
+
/**
|
|
3
|
+
* System prompt fragment for task planning capabilities.
|
|
4
|
+
*
|
|
5
|
+
* Include this in the agent's system prompt when:
|
|
6
|
+
* - Agent is ephemeral (not a persistent workflow)
|
|
7
|
+
* - Agent handles complex, multi-step research or coding tasks
|
|
8
|
+
* - You want visible progress tracking for the user
|
|
9
|
+
*
|
|
10
|
+
* Do NOT include for:
|
|
11
|
+
* - Simple tool-calling agents
|
|
12
|
+
* - Workflow/builder agents with predefined steps
|
|
13
|
+
* - Agents with fixed execution patterns
|
|
14
|
+
*/
|
|
15
|
+
const taskPlanningPrompt = `## Task Planning & Progress
|
|
16
|
+
|
|
17
|
+
You have access to a \`manage_todo_list\` tool for tracking complex tasks.
|
|
18
|
+
|
|
19
|
+
### When to Use Task Planning
|
|
20
|
+
- **USE** for complex work requiring 3+ steps (research, multi-file changes, analysis)
|
|
21
|
+
- **SKIP** for simple requests (single file edit, quick lookup, conversational responses)
|
|
22
|
+
|
|
23
|
+
### Task Workflow
|
|
24
|
+
1. **Plan First**: Before starting complex work, create a todo list with 3-6 clear, actionable items
|
|
25
|
+
2. **One at a Time**: Mark ONE task as "in-progress" before starting work on it
|
|
26
|
+
3. **Multiple Tool Calls OK**: A single task may require multiple tool calls (searches, reads, writes)
|
|
27
|
+
4. **Complete Immediately**: Mark task "completed" right after finishing, don't batch updates
|
|
28
|
+
5. **Iterate**: Move to next task, repeat until done
|
|
29
|
+
|
|
30
|
+
### Task Best Practices
|
|
31
|
+
- Keep titles short and action-oriented (3-7 words): "Research API options", "Implement auth flow"
|
|
32
|
+
- Group related work into single tasks rather than micro-tasks
|
|
33
|
+
- Update status promptly so user sees real-time progress
|
|
34
|
+
- For simple 1-2 step work, just do it directly without creating todos
|
|
35
|
+
|
|
36
|
+
### Example Task Breakdown
|
|
37
|
+
For "Add user authentication to the app":
|
|
38
|
+
1. Review existing auth code and dependencies
|
|
39
|
+
2. Implement login endpoint
|
|
40
|
+
3. Add session management
|
|
41
|
+
4. Create protected route middleware
|
|
42
|
+
5. Test authentication flow
|
|
43
|
+
|
|
44
|
+
Each task above might involve multiple file reads, code writes, and searches - that's expected.
|
|
45
|
+
`;
|
|
46
|
+
/**
|
|
47
|
+
* Short version of task planning prompt for constrained context
|
|
48
|
+
*/
|
|
49
|
+
const taskPlanningPromptShort = `## Task Tracking
|
|
50
|
+
Use \`manage_todo_list\` for complex multi-step work (3+ steps).
|
|
51
|
+
- Create 3-6 actionable todos before starting
|
|
52
|
+
- Mark one "in-progress" at a time
|
|
53
|
+
- Mark "completed" immediately after finishing
|
|
54
|
+
- Skip for simple 1-2 step tasks
|
|
55
|
+
`;
|
|
56
|
+
/**
|
|
57
|
+
* Function description for structured output agents
|
|
58
|
+
*/
|
|
59
|
+
const manageTodoListFunctionDescription = 'Manage a todo list for tracking progress on complex multi-step tasks. Create todos before starting work, mark in-progress while working, mark completed when done.';
|
|
60
|
+
/**
|
|
61
|
+
* Function parameters schema (for agents using function calling format)
|
|
62
|
+
*/
|
|
63
|
+
const manageTodoListFunctionParameters = {
|
|
64
|
+
type: 'object',
|
|
65
|
+
properties: {
|
|
66
|
+
todoList: {
|
|
67
|
+
type: 'array',
|
|
68
|
+
description: 'Complete array of all todo items (existing and new)',
|
|
69
|
+
items: {
|
|
70
|
+
type: 'object',
|
|
71
|
+
properties: {
|
|
72
|
+
id: {
|
|
73
|
+
type: 'number',
|
|
74
|
+
description: 'Sequential ID starting from 1',
|
|
75
|
+
},
|
|
76
|
+
title: {
|
|
77
|
+
type: 'string',
|
|
78
|
+
description: 'Short action-oriented title (3-7 words)',
|
|
79
|
+
},
|
|
80
|
+
status: {
|
|
81
|
+
type: 'string',
|
|
82
|
+
enum: ['not-started', 'in-progress', 'completed'],
|
|
83
|
+
description: 'Current task status',
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
required: ['id', 'title', 'status'],
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
required: ['todoList'],
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export { manageTodoListFunctionDescription, manageTodoListFunctionParameters, taskPlanningPrompt, taskPlanningPromptShort };
|
|
94
|
+
//# sourceMappingURL=taskplanning.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskplanning.mjs","sources":["../../../src/prompts/taskplanning.ts"],"sourcesContent":["// src/prompts/taskplanning.ts\r\n\r\n/**\r\n * System prompt fragment for task planning capabilities.\r\n *\r\n * Include this in the agent's system prompt when:\r\n * - Agent is ephemeral (not a persistent workflow)\r\n * - Agent handles complex, multi-step research or coding tasks\r\n * - You want visible progress tracking for the user\r\n *\r\n * Do NOT include for:\r\n * - Simple tool-calling agents\r\n * - Workflow/builder agents with predefined steps\r\n * - Agents with fixed execution patterns\r\n */\r\nexport const taskPlanningPrompt = `## Task Planning & Progress\r\n\r\nYou have access to a \\`manage_todo_list\\` tool for tracking complex tasks.\r\n\r\n### When to Use Task Planning\r\n- **USE** for complex work requiring 3+ steps (research, multi-file changes, analysis)\r\n- **SKIP** for simple requests (single file edit, quick lookup, conversational responses)\r\n\r\n### Task Workflow\r\n1. **Plan First**: Before starting complex work, create a todo list with 3-6 clear, actionable items\r\n2. **One at a Time**: Mark ONE task as \"in-progress\" before starting work on it\r\n3. **Multiple Tool Calls OK**: A single task may require multiple tool calls (searches, reads, writes)\r\n4. **Complete Immediately**: Mark task \"completed\" right after finishing, don't batch updates\r\n5. **Iterate**: Move to next task, repeat until done\r\n\r\n### Task Best Practices\r\n- Keep titles short and action-oriented (3-7 words): \"Research API options\", \"Implement auth flow\"\r\n- Group related work into single tasks rather than micro-tasks\r\n- Update status promptly so user sees real-time progress\r\n- For simple 1-2 step work, just do it directly without creating todos\r\n\r\n### Example Task Breakdown\r\nFor \"Add user authentication to the app\":\r\n1. Review existing auth code and dependencies\r\n2. Implement login endpoint\r\n3. Add session management\r\n4. Create protected route middleware\r\n5. Test authentication flow\r\n\r\nEach task above might involve multiple file reads, code writes, and searches - that's expected.\r\n`;\r\n\r\n/**\r\n * Short version of task planning prompt for constrained context\r\n */\r\nexport const taskPlanningPromptShort = `## Task Tracking\r\nUse \\`manage_todo_list\\` for complex multi-step work (3+ steps).\r\n- Create 3-6 actionable todos before starting\r\n- Mark one \"in-progress\" at a time\r\n- Mark \"completed\" immediately after finishing\r\n- Skip for simple 1-2 step tasks\r\n`;\r\n\r\n/**\r\n * Function description for structured output agents\r\n */\r\nexport const manageTodoListFunctionDescription =\r\n 'Manage a todo list for tracking progress on complex multi-step tasks. Create todos before starting work, mark in-progress while working, mark completed when done.';\r\n\r\n/**\r\n * Function parameters schema (for agents using function calling format)\r\n */\r\nexport const manageTodoListFunctionParameters = {\r\n type: 'object',\r\n properties: {\r\n todoList: {\r\n type: 'array',\r\n description: 'Complete array of all todo items (existing and new)',\r\n items: {\r\n type: 'object',\r\n properties: {\r\n id: {\r\n type: 'number',\r\n description: 'Sequential ID starting from 1',\r\n },\r\n title: {\r\n type: 'string',\r\n description: 'Short action-oriented title (3-7 words)',\r\n },\r\n status: {\r\n type: 'string',\r\n enum: ['not-started', 'in-progress', 'completed'],\r\n description: 'Current task status',\r\n },\r\n },\r\n required: ['id', 'title', 'status'],\r\n },\r\n },\r\n },\r\n required: ['todoList'],\r\n};\r\n"],"names":[],"mappings":"AAAA;AAEA;;;;;;;;;;;;AAYG;AACU,MAAA,kBAAkB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgClC;;AAEG;AACU,MAAA,uBAAuB,GAAG,CAAA;;;;;;;AAQvC;;AAEG;AACI,MAAM,iCAAiC,GAC5C;AAEF;;AAEG;AACU,MAAA,gCAAgC,GAAG;AAC9C,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,QAAQ,EAAE;AACR,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,WAAW,EAAE,qDAAqD;AAClE,YAAA,KAAK,EAAE;AACL,gBAAA,IAAI,EAAE,QAAQ;AACd,gBAAA,UAAU,EAAE;AACV,oBAAA,EAAE,EAAE;AACF,wBAAA,IAAI,EAAE,QAAQ;AACd,wBAAA,WAAW,EAAE,+BAA+B;AAC7C,qBAAA;AACD,oBAAA,KAAK,EAAE;AACL,wBAAA,IAAI,EAAE,QAAQ;AACd,wBAAA,WAAW,EAAE,yCAAyC;AACvD,qBAAA;AACD,oBAAA,MAAM,EAAE;AACN,wBAAA,IAAI,EAAE,QAAQ;AACd,wBAAA,IAAI,EAAE,CAAC,aAAa,EAAE,aAAa,EAAE,WAAW,CAAC;AACjD,wBAAA,WAAW,EAAE,qBAAqB;AACnC,qBAAA;AACF,iBAAA;AACD,gBAAA,QAAQ,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC;AACpC,aAAA;AACF,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,UAAU,CAAC;;;;;"}
|
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
import { Tool } from '@langchain/core/tools';
|
|
2
2
|
import * as math from 'mathjs';
|
|
3
3
|
|
|
4
|
+
const CalculatorToolName = 'calculator';
|
|
5
|
+
const CalculatorToolDescription = 'Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.';
|
|
6
|
+
const CalculatorSchema = {
|
|
7
|
+
type: 'object',
|
|
8
|
+
properties: {
|
|
9
|
+
input: {
|
|
10
|
+
type: 'string',
|
|
11
|
+
description: 'A valid mathematical expression to evaluate',
|
|
12
|
+
},
|
|
13
|
+
},
|
|
14
|
+
required: ['input'],
|
|
15
|
+
};
|
|
16
|
+
const CalculatorToolDefinition = {
|
|
17
|
+
name: CalculatorToolName,
|
|
18
|
+
description: CalculatorToolDescription,
|
|
19
|
+
schema: CalculatorSchema,
|
|
20
|
+
};
|
|
4
21
|
class Calculator extends Tool {
|
|
5
22
|
static lc_name() {
|
|
6
23
|
return 'Calculator';
|
|
@@ -8,7 +25,7 @@ class Calculator extends Tool {
|
|
|
8
25
|
get lc_namespace() {
|
|
9
26
|
return [...super.lc_namespace, 'calculator'];
|
|
10
27
|
}
|
|
11
|
-
name =
|
|
28
|
+
name = CalculatorToolName;
|
|
12
29
|
async _call(input) {
|
|
13
30
|
try {
|
|
14
31
|
return math.evaluate(input).toString();
|
|
@@ -17,8 +34,8 @@ class Calculator extends Tool {
|
|
|
17
34
|
return 'I don\'t know how to do that.';
|
|
18
35
|
}
|
|
19
36
|
}
|
|
20
|
-
description =
|
|
37
|
+
description = CalculatorToolDescription;
|
|
21
38
|
}
|
|
22
39
|
|
|
23
|
-
export { Calculator };
|
|
40
|
+
export { Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName };
|
|
24
41
|
//# sourceMappingURL=Calculator.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Calculator.mjs","sources":["../../../src/tools/Calculator.ts"],"sourcesContent":["import { Tool } from '@langchain/core/tools';\nimport * as math from 'mathjs';\n\nexport class Calculator extends Tool {\n static lc_name(): string {\n return 'Calculator';\n }\n\n get lc_namespace(): string[] {\n return [...super.lc_namespace, 'calculator'];\n }\n\n name =
|
|
1
|
+
{"version":3,"file":"Calculator.mjs","sources":["../../../src/tools/Calculator.ts"],"sourcesContent":["import { Tool } from '@langchain/core/tools';\nimport * as math from 'mathjs';\n\nexport const CalculatorToolName = 'calculator';\n\nexport const CalculatorToolDescription =\n 'Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.';\n\nexport const CalculatorSchema = {\n type: 'object',\n properties: {\n input: {\n type: 'string',\n description: 'A valid mathematical expression to evaluate',\n },\n },\n required: ['input'],\n} as const;\n\nexport const CalculatorToolDefinition = {\n name: CalculatorToolName,\n description: CalculatorToolDescription,\n schema: CalculatorSchema,\n} as const;\n\nexport class Calculator extends Tool {\n static lc_name(): string {\n return 'Calculator';\n }\n\n get lc_namespace(): string[] {\n return [...super.lc_namespace, 'calculator'];\n }\n\n name = CalculatorToolName;\n\n async _call(input: string): Promise<string> {\n try {\n return math.evaluate(input).toString();\n } catch {\n return 'I don\\'t know how to do that.';\n }\n }\n\n description = CalculatorToolDescription;\n}\n"],"names":[],"mappings":";;;AAGO,MAAM,kBAAkB,GAAG;AAE3B,MAAM,yBAAyB,GACpC;AAEW,MAAA,gBAAgB,GAAG;AAC9B,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,KAAK,EAAE;AACL,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,6CAA6C;AAC3D,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,OAAO,CAAC;;AAGR,MAAA,wBAAwB,GAAG;AACtC,IAAA,IAAI,EAAE,kBAAkB;AACxB,IAAA,WAAW,EAAE,yBAAyB;AACtC,IAAA,MAAM,EAAE,gBAAgB;;AAGpB,MAAO,UAAW,SAAQ,IAAI,CAAA;AAClC,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,YAAY;;AAGrB,IAAA,IAAI,YAAY,GAAA;QACd,OAAO,CAAC,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,CAAC;;IAG9C,IAAI,GAAG,kBAAkB;IAEzB,MAAM,KAAK,CAAC,KAAa,EAAA;AACvB,QAAA,IAAI;YACF,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE;;AACtC,QAAA,MAAM;AACN,YAAA,OAAO,+BAA+B;;;IAI1C,WAAW,GAAG,yBAAyB;AACxC;;;;"}
|
|
@@ -60,6 +60,20 @@ const CodeExecutionToolSchema = {
|
|
|
60
60
|
};
|
|
61
61
|
const baseEndpoint = getCodeBaseURL();
|
|
62
62
|
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
63
|
+
const CodeExecutionToolDescription = `
|
|
64
|
+
Runs code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
|
|
65
|
+
|
|
66
|
+
Usage:
|
|
67
|
+
- No network access available.
|
|
68
|
+
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
69
|
+
- NEVER use this tool to execute malicious code.
|
|
70
|
+
`.trim();
|
|
71
|
+
const CodeExecutionToolName = Constants.EXECUTE_CODE;
|
|
72
|
+
const CodeExecutionToolDefinition = {
|
|
73
|
+
name: CodeExecutionToolName,
|
|
74
|
+
description: CodeExecutionToolDescription,
|
|
75
|
+
schema: CodeExecutionToolSchema,
|
|
76
|
+
};
|
|
63
77
|
function createCodeExecutionTool(params = {}) {
|
|
64
78
|
const apiKey = params[EnvVar.CODE_API_KEY] ??
|
|
65
79
|
params.apiKey ??
|
|
@@ -201,12 +215,12 @@ Rules:
|
|
|
201
215
|
throw new Error(`Execution error:\n\n${error?.message}`);
|
|
202
216
|
}
|
|
203
217
|
}, {
|
|
204
|
-
name:
|
|
218
|
+
name: CodeExecutionToolName,
|
|
205
219
|
description,
|
|
206
220
|
schema: CodeExecutionToolSchema,
|
|
207
221
|
responseFormat: Constants.CONTENT_AND_ARTIFACT,
|
|
208
222
|
});
|
|
209
223
|
}
|
|
210
224
|
|
|
211
|
-
export { createCodeExecutionTool, getCodeBaseURL, imageExtRegex };
|
|
225
|
+
export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, createCodeExecutionTool, getCodeBaseURL, imageExtRegex };
|
|
212
226
|
//# sourceMappingURL=CodeExecutor.mjs.map
|