@illuma-ai/agents 1.0.81
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/README.md +485 -0
- package/dist/cjs/agents/AgentContext.cjs +734 -0
- package/dist/cjs/agents/AgentContext.cjs.map +1 -0
- package/dist/cjs/common/enum.cjs +190 -0
- package/dist/cjs/common/enum.cjs.map +1 -0
- package/dist/cjs/events.cjs +172 -0
- package/dist/cjs/events.cjs.map +1 -0
- package/dist/cjs/graphs/Graph.cjs +1615 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -0
- package/dist/cjs/graphs/MultiAgentGraph.cjs +890 -0
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -0
- package/dist/cjs/instrumentation.cjs +21 -0
- package/dist/cjs/instrumentation.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/index.cjs +292 -0
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/types.cjs +50 -0
- package/dist/cjs/llm/anthropic/types.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +630 -0
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +218 -0
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/utils/tools.cjs +29 -0
- package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -0
- package/dist/cjs/llm/bedrock/index.cjs +282 -0
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -0
- package/dist/cjs/llm/fake.cjs +97 -0
- package/dist/cjs/llm/fake.cjs.map +1 -0
- package/dist/cjs/llm/google/index.cjs +216 -0
- package/dist/cjs/llm/google/index.cjs.map +1 -0
- package/dist/cjs/llm/google/utils/common.cjs +647 -0
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -0
- package/dist/cjs/llm/openai/index.cjs +1028 -0
- package/dist/cjs/llm/openai/index.cjs.map +1 -0
- package/dist/cjs/llm/openai/utils/index.cjs +765 -0
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -0
- package/dist/cjs/llm/openrouter/index.cjs +212 -0
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -0
- package/dist/cjs/llm/providers.cjs +43 -0
- package/dist/cjs/llm/providers.cjs.map +1 -0
- package/dist/cjs/llm/text.cjs +69 -0
- package/dist/cjs/llm/text.cjs.map +1 -0
- package/dist/cjs/llm/vertexai/index.cjs +329 -0
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -0
- package/dist/cjs/main.cjs +240 -0
- package/dist/cjs/main.cjs.map +1 -0
- package/dist/cjs/messages/cache.cjs +387 -0
- package/dist/cjs/messages/cache.cjs.map +1 -0
- package/dist/cjs/messages/content.cjs +53 -0
- package/dist/cjs/messages/content.cjs.map +1 -0
- package/dist/cjs/messages/core.cjs +367 -0
- package/dist/cjs/messages/core.cjs.map +1 -0
- package/dist/cjs/messages/format.cjs +761 -0
- package/dist/cjs/messages/format.cjs.map +1 -0
- package/dist/cjs/messages/ids.cjs +23 -0
- package/dist/cjs/messages/ids.cjs.map +1 -0
- package/dist/cjs/messages/prune.cjs +398 -0
- package/dist/cjs/messages/prune.cjs.map +1 -0
- package/dist/cjs/messages/tools.cjs +96 -0
- package/dist/cjs/messages/tools.cjs.map +1 -0
- package/dist/cjs/run.cjs +328 -0
- package/dist/cjs/run.cjs.map +1 -0
- package/dist/cjs/schemas/validate.cjs +324 -0
- package/dist/cjs/schemas/validate.cjs.map +1 -0
- package/dist/cjs/splitStream.cjs +210 -0
- package/dist/cjs/splitStream.cjs.map +1 -0
- package/dist/cjs/stream.cjs +620 -0
- package/dist/cjs/stream.cjs.map +1 -0
- package/dist/cjs/tools/BrowserTools.cjs +248 -0
- package/dist/cjs/tools/BrowserTools.cjs.map +1 -0
- package/dist/cjs/tools/Calculator.cjs +66 -0
- package/dist/cjs/tools/Calculator.cjs.map +1 -0
- package/dist/cjs/tools/CodeExecutor.cjs +234 -0
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +636 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +548 -0
- package/dist/cjs/tools/ToolNode.cjs.map +1 -0
- package/dist/cjs/tools/ToolSearch.cjs +909 -0
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -0
- package/dist/cjs/tools/handlers.cjs +255 -0
- package/dist/cjs/tools/handlers.cjs.map +1 -0
- package/dist/cjs/tools/schema.cjs +31 -0
- package/dist/cjs/tools/schema.cjs.map +1 -0
- package/dist/cjs/tools/search/anthropic.cjs +40 -0
- package/dist/cjs/tools/search/anthropic.cjs.map +1 -0
- package/dist/cjs/tools/search/content.cjs +140 -0
- package/dist/cjs/tools/search/content.cjs.map +1 -0
- package/dist/cjs/tools/search/firecrawl.cjs +179 -0
- package/dist/cjs/tools/search/firecrawl.cjs.map +1 -0
- package/dist/cjs/tools/search/format.cjs +203 -0
- package/dist/cjs/tools/search/format.cjs.map +1 -0
- package/dist/cjs/tools/search/highlights.cjs +245 -0
- package/dist/cjs/tools/search/highlights.cjs.map +1 -0
- package/dist/cjs/tools/search/rerankers.cjs +174 -0
- package/dist/cjs/tools/search/rerankers.cjs.map +1 -0
- package/dist/cjs/tools/search/schema.cjs +117 -0
- package/dist/cjs/tools/search/schema.cjs.map +1 -0
- package/dist/cjs/tools/search/search.cjs +566 -0
- package/dist/cjs/tools/search/search.cjs.map +1 -0
- package/dist/cjs/tools/search/serper-scraper.cjs +132 -0
- package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -0
- package/dist/cjs/tools/search/tool.cjs +456 -0
- package/dist/cjs/tools/search/tool.cjs.map +1 -0
- package/dist/cjs/tools/search/utils.cjs +66 -0
- package/dist/cjs/tools/search/utils.cjs.map +1 -0
- package/dist/cjs/types/graph.cjs +29 -0
- package/dist/cjs/types/graph.cjs.map +1 -0
- package/dist/cjs/utils/contextAnalytics.cjs +66 -0
- package/dist/cjs/utils/contextAnalytics.cjs.map +1 -0
- package/dist/cjs/utils/events.cjs +31 -0
- package/dist/cjs/utils/events.cjs.map +1 -0
- package/dist/cjs/utils/graph.cjs +16 -0
- package/dist/cjs/utils/graph.cjs.map +1 -0
- package/dist/cjs/utils/handlers.cjs +70 -0
- package/dist/cjs/utils/handlers.cjs.map +1 -0
- package/dist/cjs/utils/llm.cjs +27 -0
- package/dist/cjs/utils/llm.cjs.map +1 -0
- package/dist/cjs/utils/misc.cjs +56 -0
- package/dist/cjs/utils/misc.cjs.map +1 -0
- package/dist/cjs/utils/run.cjs +73 -0
- package/dist/cjs/utils/run.cjs.map +1 -0
- package/dist/cjs/utils/schema.cjs +27 -0
- package/dist/cjs/utils/schema.cjs.map +1 -0
- package/dist/cjs/utils/title.cjs +125 -0
- package/dist/cjs/utils/title.cjs.map +1 -0
- package/dist/cjs/utils/tokens.cjs +125 -0
- package/dist/cjs/utils/tokens.cjs.map +1 -0
- package/dist/cjs/utils/toonFormat.cjs +388 -0
- package/dist/cjs/utils/toonFormat.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +732 -0
- package/dist/esm/agents/AgentContext.mjs.map +1 -0
- package/dist/esm/common/enum.mjs +190 -0
- package/dist/esm/common/enum.mjs.map +1 -0
- package/dist/esm/events.mjs +164 -0
- package/dist/esm/events.mjs.map +1 -0
- package/dist/esm/graphs/Graph.mjs +1612 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -0
- package/dist/esm/graphs/MultiAgentGraph.mjs +888 -0
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -0
- package/dist/esm/instrumentation.mjs +19 -0
- package/dist/esm/instrumentation.mjs.map +1 -0
- package/dist/esm/llm/anthropic/index.mjs +290 -0
- package/dist/esm/llm/anthropic/index.mjs.map +1 -0
- package/dist/esm/llm/anthropic/types.mjs +48 -0
- package/dist/esm/llm/anthropic/types.mjs.map +1 -0
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +627 -0
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -0
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +216 -0
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -0
- package/dist/esm/llm/anthropic/utils/tools.mjs +27 -0
- package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -0
- package/dist/esm/llm/bedrock/index.mjs +280 -0
- package/dist/esm/llm/bedrock/index.mjs.map +1 -0
- package/dist/esm/llm/fake.mjs +94 -0
- package/dist/esm/llm/fake.mjs.map +1 -0
- package/dist/esm/llm/google/index.mjs +214 -0
- package/dist/esm/llm/google/index.mjs.map +1 -0
- package/dist/esm/llm/google/utils/common.mjs +638 -0
- package/dist/esm/llm/google/utils/common.mjs.map +1 -0
- package/dist/esm/llm/openai/index.mjs +1018 -0
- package/dist/esm/llm/openai/index.mjs.map +1 -0
- package/dist/esm/llm/openai/utils/index.mjs +759 -0
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -0
- package/dist/esm/llm/openrouter/index.mjs +210 -0
- package/dist/esm/llm/openrouter/index.mjs.map +1 -0
- package/dist/esm/llm/providers.mjs +39 -0
- package/dist/esm/llm/providers.mjs.map +1 -0
- package/dist/esm/llm/text.mjs +67 -0
- package/dist/esm/llm/text.mjs.map +1 -0
- package/dist/esm/llm/vertexai/index.mjs +327 -0
- package/dist/esm/llm/vertexai/index.mjs.map +1 -0
- package/dist/esm/main.mjs +37 -0
- package/dist/esm/main.mjs.map +1 -0
- package/dist/esm/messages/cache.mjs +382 -0
- package/dist/esm/messages/cache.mjs.map +1 -0
- package/dist/esm/messages/content.mjs +51 -0
- package/dist/esm/messages/content.mjs.map +1 -0
- package/dist/esm/messages/core.mjs +359 -0
- package/dist/esm/messages/core.mjs.map +1 -0
- package/dist/esm/messages/format.mjs +752 -0
- package/dist/esm/messages/format.mjs.map +1 -0
- package/dist/esm/messages/ids.mjs +21 -0
- package/dist/esm/messages/ids.mjs.map +1 -0
- package/dist/esm/messages/prune.mjs +393 -0
- package/dist/esm/messages/prune.mjs.map +1 -0
- package/dist/esm/messages/tools.mjs +93 -0
- package/dist/esm/messages/tools.mjs.map +1 -0
- package/dist/esm/run.mjs +325 -0
- package/dist/esm/run.mjs.map +1 -0
- package/dist/esm/schemas/validate.mjs +317 -0
- package/dist/esm/schemas/validate.mjs.map +1 -0
- package/dist/esm/splitStream.mjs +207 -0
- package/dist/esm/splitStream.mjs.map +1 -0
- package/dist/esm/stream.mjs +616 -0
- package/dist/esm/stream.mjs.map +1 -0
- package/dist/esm/tools/BrowserTools.mjs +244 -0
- package/dist/esm/tools/BrowserTools.mjs.map +1 -0
- package/dist/esm/tools/Calculator.mjs +41 -0
- package/dist/esm/tools/Calculator.mjs.map +1 -0
- package/dist/esm/tools/CodeExecutor.mjs +226 -0
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +622 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +545 -0
- package/dist/esm/tools/ToolNode.mjs.map +1 -0
- package/dist/esm/tools/ToolSearch.mjs +870 -0
- package/dist/esm/tools/ToolSearch.mjs.map +1 -0
- package/dist/esm/tools/handlers.mjs +250 -0
- package/dist/esm/tools/handlers.mjs.map +1 -0
- package/dist/esm/tools/schema.mjs +28 -0
- package/dist/esm/tools/schema.mjs.map +1 -0
- package/dist/esm/tools/search/anthropic.mjs +37 -0
- package/dist/esm/tools/search/anthropic.mjs.map +1 -0
- package/dist/esm/tools/search/content.mjs +119 -0
- package/dist/esm/tools/search/content.mjs.map +1 -0
- package/dist/esm/tools/search/firecrawl.mjs +176 -0
- package/dist/esm/tools/search/firecrawl.mjs.map +1 -0
- package/dist/esm/tools/search/format.mjs +201 -0
- package/dist/esm/tools/search/format.mjs.map +1 -0
- package/dist/esm/tools/search/highlights.mjs +243 -0
- package/dist/esm/tools/search/highlights.mjs.map +1 -0
- package/dist/esm/tools/search/rerankers.mjs +168 -0
- package/dist/esm/tools/search/rerankers.mjs.map +1 -0
- package/dist/esm/tools/search/schema.mjs +104 -0
- package/dist/esm/tools/search/schema.mjs.map +1 -0
- package/dist/esm/tools/search/search.mjs +563 -0
- package/dist/esm/tools/search/search.mjs.map +1 -0
- package/dist/esm/tools/search/serper-scraper.mjs +129 -0
- package/dist/esm/tools/search/serper-scraper.mjs.map +1 -0
- package/dist/esm/tools/search/tool.mjs +454 -0
- package/dist/esm/tools/search/tool.mjs.map +1 -0
- package/dist/esm/tools/search/utils.mjs +61 -0
- package/dist/esm/tools/search/utils.mjs.map +1 -0
- package/dist/esm/types/graph.mjs +26 -0
- package/dist/esm/types/graph.mjs.map +1 -0
- package/dist/esm/utils/contextAnalytics.mjs +64 -0
- package/dist/esm/utils/contextAnalytics.mjs.map +1 -0
- package/dist/esm/utils/events.mjs +29 -0
- package/dist/esm/utils/events.mjs.map +1 -0
- package/dist/esm/utils/graph.mjs +13 -0
- package/dist/esm/utils/graph.mjs.map +1 -0
- package/dist/esm/utils/handlers.mjs +68 -0
- package/dist/esm/utils/handlers.mjs.map +1 -0
- package/dist/esm/utils/llm.mjs +24 -0
- package/dist/esm/utils/llm.mjs.map +1 -0
- package/dist/esm/utils/misc.mjs +53 -0
- package/dist/esm/utils/misc.mjs.map +1 -0
- package/dist/esm/utils/run.mjs +70 -0
- package/dist/esm/utils/run.mjs.map +1 -0
- package/dist/esm/utils/schema.mjs +24 -0
- package/dist/esm/utils/schema.mjs.map +1 -0
- package/dist/esm/utils/title.mjs +122 -0
- package/dist/esm/utils/title.mjs.map +1 -0
- package/dist/esm/utils/tokens.mjs +121 -0
- package/dist/esm/utils/tokens.mjs.map +1 -0
- package/dist/esm/utils/toonFormat.mjs +381 -0
- package/dist/esm/utils/toonFormat.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +293 -0
- package/dist/types/common/enum.d.ts +155 -0
- package/dist/types/common/index.d.ts +1 -0
- package/dist/types/events.d.ts +31 -0
- package/dist/types/graphs/Graph.d.ts +216 -0
- package/dist/types/graphs/MultiAgentGraph.d.ts +104 -0
- package/dist/types/graphs/index.d.ts +2 -0
- package/dist/types/index.d.ts +21 -0
- package/dist/types/instrumentation.d.ts +1 -0
- package/dist/types/llm/anthropic/index.d.ts +39 -0
- package/dist/types/llm/anthropic/types.d.ts +37 -0
- package/dist/types/llm/anthropic/utils/message_inputs.d.ts +14 -0
- package/dist/types/llm/anthropic/utils/message_outputs.d.ts +14 -0
- package/dist/types/llm/anthropic/utils/output_parsers.d.ts +22 -0
- package/dist/types/llm/anthropic/utils/tools.d.ts +3 -0
- package/dist/types/llm/bedrock/index.d.ts +141 -0
- package/dist/types/llm/bedrock/types.d.ts +27 -0
- package/dist/types/llm/bedrock/utils/index.d.ts +5 -0
- package/dist/types/llm/bedrock/utils/message_inputs.d.ts +31 -0
- package/dist/types/llm/bedrock/utils/message_outputs.d.ts +33 -0
- package/dist/types/llm/fake.d.ts +31 -0
- package/dist/types/llm/google/index.d.ts +24 -0
- package/dist/types/llm/google/types.d.ts +42 -0
- package/dist/types/llm/google/utils/common.d.ts +34 -0
- package/dist/types/llm/google/utils/tools.d.ts +10 -0
- package/dist/types/llm/google/utils/zod_to_genai_parameters.d.ts +14 -0
- package/dist/types/llm/openai/index.d.ts +127 -0
- package/dist/types/llm/openai/types.d.ts +10 -0
- package/dist/types/llm/openai/utils/index.d.ts +29 -0
- package/dist/types/llm/openrouter/index.d.ts +15 -0
- package/dist/types/llm/providers.d.ts +5 -0
- package/dist/types/llm/text.d.ts +21 -0
- package/dist/types/llm/vertexai/index.d.ts +293 -0
- package/dist/types/messages/cache.d.ts +54 -0
- package/dist/types/messages/content.d.ts +7 -0
- package/dist/types/messages/core.d.ts +14 -0
- package/dist/types/messages/format.d.ts +137 -0
- package/dist/types/messages/ids.d.ts +3 -0
- package/dist/types/messages/index.d.ts +7 -0
- package/dist/types/messages/prune.d.ts +52 -0
- package/dist/types/messages/reducer.d.ts +9 -0
- package/dist/types/messages/tools.d.ts +17 -0
- package/dist/types/mockStream.d.ts +32 -0
- package/dist/types/prompts/collab.d.ts +1 -0
- package/dist/types/prompts/index.d.ts +2 -0
- package/dist/types/prompts/taskmanager.d.ts +41 -0
- package/dist/types/run.d.ts +41 -0
- package/dist/types/schemas/index.d.ts +1 -0
- package/dist/types/schemas/validate.d.ts +59 -0
- package/dist/types/splitStream.d.ts +37 -0
- package/dist/types/stream.d.ts +15 -0
- package/dist/types/test/mockTools.d.ts +28 -0
- package/dist/types/tools/BrowserTools.d.ts +87 -0
- package/dist/types/tools/Calculator.d.ts +34 -0
- package/dist/types/tools/CodeExecutor.d.ts +57 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +138 -0
- package/dist/types/tools/ToolNode.d.ts +51 -0
- package/dist/types/tools/ToolSearch.d.ts +219 -0
- package/dist/types/tools/handlers.d.ts +22 -0
- package/dist/types/tools/schema.d.ts +12 -0
- package/dist/types/tools/search/anthropic.d.ts +16 -0
- package/dist/types/tools/search/content.d.ts +4 -0
- package/dist/types/tools/search/firecrawl.d.ts +54 -0
- package/dist/types/tools/search/format.d.ts +5 -0
- package/dist/types/tools/search/highlights.d.ts +13 -0
- package/dist/types/tools/search/index.d.ts +3 -0
- package/dist/types/tools/search/rerankers.d.ts +38 -0
- package/dist/types/tools/search/schema.d.ts +103 -0
- package/dist/types/tools/search/search.d.ts +8 -0
- package/dist/types/tools/search/serper-scraper.d.ts +59 -0
- package/dist/types/tools/search/test.d.ts +1 -0
- package/dist/types/tools/search/tool.d.ts +3 -0
- package/dist/types/tools/search/types.d.ts +575 -0
- package/dist/types/tools/search/utils.d.ts +10 -0
- package/dist/types/types/graph.d.ts +399 -0
- package/dist/types/types/index.d.ts +5 -0
- package/dist/types/types/llm.d.ts +105 -0
- package/dist/types/types/messages.d.ts +4 -0
- package/dist/types/types/run.d.ts +112 -0
- package/dist/types/types/stream.d.ts +308 -0
- package/dist/types/types/tools.d.ts +296 -0
- package/dist/types/utils/contextAnalytics.d.ts +37 -0
- package/dist/types/utils/events.d.ts +6 -0
- package/dist/types/utils/graph.d.ts +2 -0
- package/dist/types/utils/handlers.d.ts +34 -0
- package/dist/types/utils/index.d.ts +9 -0
- package/dist/types/utils/llm.d.ts +3 -0
- package/dist/types/utils/llmConfig.d.ts +3 -0
- package/dist/types/utils/logging.d.ts +1 -0
- package/dist/types/utils/misc.d.ts +7 -0
- package/dist/types/utils/run.d.ts +27 -0
- package/dist/types/utils/schema.d.ts +8 -0
- package/dist/types/utils/title.d.ts +4 -0
- package/dist/types/utils/tokens.d.ts +28 -0
- package/dist/types/utils/toonFormat.d.ts +111 -0
- package/package.json +190 -0
- package/src/agents/AgentContext.test.ts +458 -0
- package/src/agents/AgentContext.ts +972 -0
- package/src/agents/__tests__/AgentContext.test.ts +805 -0
- package/src/agents/__tests__/resolveStructuredOutputMode.test.ts +137 -0
- package/src/common/enum.ts +203 -0
- package/src/common/index.ts +2 -0
- package/src/events.ts +223 -0
- package/src/graphs/Graph.ts +2228 -0
- package/src/graphs/MultiAgentGraph.ts +1063 -0
- package/src/graphs/__tests__/structured-output.integration.test.ts +809 -0
- package/src/graphs/__tests__/structured-output.test.ts +183 -0
- package/src/graphs/index.ts +2 -0
- package/src/index.ts +34 -0
- package/src/instrumentation.ts +22 -0
- package/src/llm/anthropic/Jacob_Lee_Resume_2023.pdf +0 -0
- package/src/llm/anthropic/index.ts +413 -0
- package/src/llm/anthropic/llm.spec.ts +1442 -0
- package/src/llm/anthropic/types.ts +140 -0
- package/src/llm/anthropic/utils/message_inputs.ts +757 -0
- package/src/llm/anthropic/utils/message_outputs.ts +289 -0
- package/src/llm/anthropic/utils/output_parsers.ts +133 -0
- package/src/llm/anthropic/utils/tools.ts +29 -0
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +495 -0
- package/src/llm/bedrock/index.ts +411 -0
- package/src/llm/bedrock/llm.spec.ts +616 -0
- package/src/llm/bedrock/types.ts +51 -0
- package/src/llm/bedrock/utils/index.ts +18 -0
- package/src/llm/bedrock/utils/message_inputs.ts +563 -0
- package/src/llm/bedrock/utils/message_outputs.ts +310 -0
- package/src/llm/fake.ts +133 -0
- package/src/llm/google/data/gettysburg10.wav +0 -0
- package/src/llm/google/data/hotdog.jpg +0 -0
- package/src/llm/google/index.ts +337 -0
- package/src/llm/google/llm.spec.ts +934 -0
- package/src/llm/google/types.ts +56 -0
- package/src/llm/google/utils/common.ts +873 -0
- package/src/llm/google/utils/tools.ts +160 -0
- package/src/llm/google/utils/zod_to_genai_parameters.ts +86 -0
- package/src/llm/openai/index.ts +1366 -0
- package/src/llm/openai/types.ts +24 -0
- package/src/llm/openai/utils/index.ts +1035 -0
- package/src/llm/openai/utils/isReasoningModel.test.ts +90 -0
- package/src/llm/openrouter/index.ts +291 -0
- package/src/llm/providers.ts +52 -0
- package/src/llm/text.ts +94 -0
- package/src/llm/vertexai/index.ts +359 -0
- package/src/messages/__tests__/tools.test.ts +473 -0
- package/src/messages/cache.test.ts +1261 -0
- package/src/messages/cache.ts +518 -0
- package/src/messages/content.test.ts +362 -0
- package/src/messages/content.ts +63 -0
- package/src/messages/core.ts +473 -0
- package/src/messages/ensureThinkingBlock.test.ts +468 -0
- package/src/messages/format.ts +1029 -0
- package/src/messages/formatAgentMessages.test.ts +1513 -0
- package/src/messages/formatAgentMessages.tools.test.ts +419 -0
- package/src/messages/formatMessage.test.ts +693 -0
- package/src/messages/ids.ts +26 -0
- package/src/messages/index.ts +7 -0
- package/src/messages/labelContentByAgent.test.ts +887 -0
- package/src/messages/prune.ts +568 -0
- package/src/messages/reducer.ts +80 -0
- package/src/messages/shiftIndexTokenCountMap.test.ts +81 -0
- package/src/messages/tools.ts +108 -0
- package/src/mockStream.ts +99 -0
- package/src/prompts/collab.ts +6 -0
- package/src/prompts/index.ts +2 -0
- package/src/prompts/taskmanager.ts +61 -0
- package/src/run.ts +467 -0
- package/src/schemas/index.ts +2 -0
- package/src/schemas/schema-preparation.test.ts +500 -0
- package/src/schemas/validate.test.ts +358 -0
- package/src/schemas/validate.ts +454 -0
- package/src/scripts/abort.ts +157 -0
- package/src/scripts/ant_web_search.ts +158 -0
- package/src/scripts/ant_web_search_edge_case.ts +162 -0
- package/src/scripts/ant_web_search_error_edge_case.ts +148 -0
- package/src/scripts/args.ts +48 -0
- package/src/scripts/caching.ts +132 -0
- package/src/scripts/cli.ts +172 -0
- package/src/scripts/cli2.ts +133 -0
- package/src/scripts/cli3.ts +184 -0
- package/src/scripts/cli4.ts +191 -0
- package/src/scripts/cli5.ts +191 -0
- package/src/scripts/code_exec.ts +213 -0
- package/src/scripts/code_exec_files.ts +236 -0
- package/src/scripts/code_exec_multi_session.ts +241 -0
- package/src/scripts/code_exec_ptc.ts +334 -0
- package/src/scripts/code_exec_session.ts +282 -0
- package/src/scripts/code_exec_simple.ts +147 -0
- package/src/scripts/content.ts +138 -0
- package/src/scripts/empty_input.ts +137 -0
- package/src/scripts/handoff-test.ts +135 -0
- package/src/scripts/image.ts +178 -0
- package/src/scripts/memory.ts +97 -0
- package/src/scripts/multi-agent-chain.ts +331 -0
- package/src/scripts/multi-agent-conditional.ts +221 -0
- package/src/scripts/multi-agent-document-review-chain.ts +197 -0
- package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
- package/src/scripts/multi-agent-parallel-start.ts +265 -0
- package/src/scripts/multi-agent-parallel.ts +394 -0
- package/src/scripts/multi-agent-sequence.ts +217 -0
- package/src/scripts/multi-agent-supervisor.ts +365 -0
- package/src/scripts/multi-agent-test.ts +186 -0
- package/src/scripts/parallel-asymmetric-tools-test.ts +274 -0
- package/src/scripts/parallel-full-metadata-test.ts +240 -0
- package/src/scripts/parallel-tools-test.ts +340 -0
- package/src/scripts/programmatic_exec.ts +396 -0
- package/src/scripts/programmatic_exec_agent.ts +231 -0
- package/src/scripts/search.ts +146 -0
- package/src/scripts/sequential-full-metadata-test.ts +197 -0
- package/src/scripts/simple.ts +225 -0
- package/src/scripts/single-agent-metadata-test.ts +198 -0
- package/src/scripts/stream.ts +140 -0
- package/src/scripts/test-custom-prompt-key.ts +145 -0
- package/src/scripts/test-handoff-input.ts +170 -0
- package/src/scripts/test-handoff-preamble.ts +277 -0
- package/src/scripts/test-multi-agent-list-handoff.ts +417 -0
- package/src/scripts/test-parallel-agent-labeling.ts +325 -0
- package/src/scripts/test-parallel-handoffs.ts +291 -0
- package/src/scripts/test-thinking-handoff-bedrock.ts +153 -0
- package/src/scripts/test-thinking-handoff.ts +155 -0
- package/src/scripts/test-tools-before-handoff.ts +226 -0
- package/src/scripts/test_code_api.ts +361 -0
- package/src/scripts/thinking-bedrock.ts +159 -0
- package/src/scripts/thinking.ts +171 -0
- package/src/scripts/tool_search.ts +162 -0
- package/src/scripts/tools.ts +177 -0
- package/src/specs/agent-handoffs.test.ts +888 -0
- package/src/specs/anthropic.simple.test.ts +387 -0
- package/src/specs/azure.simple.test.ts +364 -0
- package/src/specs/cache.simple.test.ts +396 -0
- package/src/specs/deepseek.simple.test.ts +283 -0
- package/src/specs/emergency-prune.test.ts +407 -0
- package/src/specs/moonshot.simple.test.ts +358 -0
- package/src/specs/openai.simple.test.ts +311 -0
- package/src/specs/openrouter.simple.test.ts +107 -0
- package/src/specs/prune.test.ts +901 -0
- package/src/specs/reasoning.test.ts +201 -0
- package/src/specs/spec.utils.ts +3 -0
- package/src/specs/thinking-handoff.test.ts +620 -0
- package/src/specs/thinking-prune.test.ts +703 -0
- package/src/specs/token-distribution-edge-case.test.ts +316 -0
- package/src/specs/token-memoization.test.ts +32 -0
- package/src/specs/tool-error.test.ts +198 -0
- package/src/splitStream.test.ts +691 -0
- package/src/splitStream.ts +234 -0
- package/src/stream.test.ts +94 -0
- package/src/stream.ts +801 -0
- package/src/test/mockTools.ts +386 -0
- package/src/tools/BrowserTools.ts +393 -0
- package/src/tools/Calculator.test.ts +278 -0
- package/src/tools/Calculator.ts +46 -0
- package/src/tools/CodeExecutor.ts +270 -0
- package/src/tools/ProgrammaticToolCalling.ts +785 -0
- package/src/tools/ToolNode.ts +674 -0
- package/src/tools/ToolSearch.ts +1095 -0
- package/src/tools/__tests__/BrowserTools.test.ts +265 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +319 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +1006 -0
- package/src/tools/__tests__/ToolSearch.integration.test.ts +162 -0
- package/src/tools/__tests__/ToolSearch.test.ts +1003 -0
- package/src/tools/handlers.ts +363 -0
- package/src/tools/schema.ts +37 -0
- package/src/tools/search/anthropic.ts +51 -0
- package/src/tools/search/content.test.ts +173 -0
- package/src/tools/search/content.ts +147 -0
- package/src/tools/search/firecrawl.ts +210 -0
- package/src/tools/search/format.ts +250 -0
- package/src/tools/search/highlights.ts +320 -0
- package/src/tools/search/index.ts +3 -0
- package/src/tools/search/jina-reranker.test.ts +130 -0
- package/src/tools/search/output.md +2775 -0
- package/src/tools/search/rerankers.ts +242 -0
- package/src/tools/search/schema.ts +113 -0
- package/src/tools/search/search.ts +768 -0
- package/src/tools/search/serper-scraper.ts +155 -0
- package/src/tools/search/test.html +884 -0
- package/src/tools/search/test.md +643 -0
- package/src/tools/search/test.ts +159 -0
- package/src/tools/search/tool.ts +657 -0
- package/src/tools/search/types.ts +665 -0
- package/src/tools/search/utils.ts +79 -0
- package/src/types/graph.test.ts +218 -0
- package/src/types/graph.ts +533 -0
- package/src/types/index.ts +6 -0
- package/src/types/llm.ts +140 -0
- package/src/types/messages.ts +4 -0
- package/src/types/run.ts +128 -0
- package/src/types/stream.ts +417 -0
- package/src/types/tools.ts +355 -0
- package/src/utils/contextAnalytics.ts +103 -0
- package/src/utils/events.ts +32 -0
- package/src/utils/graph.ts +11 -0
- package/src/utils/handlers.ts +107 -0
- package/src/utils/index.ts +9 -0
- package/src/utils/llm.ts +26 -0
- package/src/utils/llmConfig.ts +208 -0
- package/src/utils/logging.ts +48 -0
- package/src/utils/misc.ts +57 -0
- package/src/utils/run.ts +106 -0
- package/src/utils/schema.ts +35 -0
- package/src/utils/title.ts +177 -0
- package/src/utils/tokens.ts +142 -0
- package/src/utils/toonFormat.ts +475 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var prompts = require('@langchain/core/prompts');
|
|
4
|
+
var runnables = require('@langchain/core/runnables');
|
|
5
|
+
var _enum = require('../common/enum.cjs');
|
|
6
|
+
|
|
7
|
+
const defaultTitlePrompt = `Analyze this conversation and provide:
|
|
8
|
+
1. The detected language of the conversation
|
|
9
|
+
2. A concise title in the detected language (5 words or less, no punctuation or quotation)
|
|
10
|
+
|
|
11
|
+
{convo}`;
|
|
12
|
+
const titleSchema = {
|
|
13
|
+
type: 'object',
|
|
14
|
+
properties: {
|
|
15
|
+
title: {
|
|
16
|
+
type: 'string',
|
|
17
|
+
description: 'A concise title for the conversation in 5 words or less, without punctuation or quotation',
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
required: ['title'],
|
|
21
|
+
};
|
|
22
|
+
const combinedSchema = {
|
|
23
|
+
type: 'object',
|
|
24
|
+
properties: {
|
|
25
|
+
language: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'The detected language of the conversation',
|
|
28
|
+
},
|
|
29
|
+
title: {
|
|
30
|
+
type: 'string',
|
|
31
|
+
description: 'A concise title for the conversation in 5 words or less, without punctuation or quotation',
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
required: ['language', 'title'],
|
|
35
|
+
};
|
|
36
|
+
const createTitleRunnable = async (model, _titlePrompt) => {
|
|
37
|
+
// Disabled since this works fine
|
|
38
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
39
|
+
/* @ts-ignore */
|
|
40
|
+
const titleLLM = model.withStructuredOutput(titleSchema);
|
|
41
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
42
|
+
/* @ts-ignore */
|
|
43
|
+
const combinedLLM = model.withStructuredOutput(combinedSchema);
|
|
44
|
+
const titlePrompt = prompts.ChatPromptTemplate.fromTemplate(_titlePrompt ?? defaultTitlePrompt).withConfig({ runName: 'TitlePrompt' });
|
|
45
|
+
const titleOnlyInnerChain = runnables.RunnableSequence.from([titlePrompt, titleLLM]);
|
|
46
|
+
const combinedInnerChain = runnables.RunnableSequence.from([titlePrompt, combinedLLM]);
|
|
47
|
+
/** Wrap titleOnlyChain in RunnableLambda to create parent span */
|
|
48
|
+
const titleOnlyChain = new runnables.RunnableLambda({
|
|
49
|
+
func: async (input, config) => {
|
|
50
|
+
const result = await titleOnlyInnerChain.invoke(input, config);
|
|
51
|
+
return result;
|
|
52
|
+
},
|
|
53
|
+
}).withConfig({ runName: 'TitleOnlyChain' });
|
|
54
|
+
/** Wrap combinedChain in RunnableLambda to create parent span */
|
|
55
|
+
const combinedChain = new runnables.RunnableLambda({
|
|
56
|
+
func: async (input, config) => {
|
|
57
|
+
const result = await combinedInnerChain.invoke(input, config);
|
|
58
|
+
return result;
|
|
59
|
+
},
|
|
60
|
+
}).withConfig({ runName: 'TitleLanguageChain' });
|
|
61
|
+
/** Runnable to add default values if needed */
|
|
62
|
+
const addDefaults = new runnables.RunnableLambda({
|
|
63
|
+
func: (result) => ({
|
|
64
|
+
language: result?.language ?? 'English',
|
|
65
|
+
title: result?.title ?? '',
|
|
66
|
+
}),
|
|
67
|
+
}).withConfig({ runName: 'AddDefaults' });
|
|
68
|
+
const combinedChainInner = runnables.RunnableSequence.from([
|
|
69
|
+
combinedChain,
|
|
70
|
+
addDefaults,
|
|
71
|
+
]);
|
|
72
|
+
/** Wrap combinedChainWithDefaults in RunnableLambda to create parent span */
|
|
73
|
+
const combinedChainWithDefaults = new runnables.RunnableLambda({
|
|
74
|
+
func: async (input, config) => {
|
|
75
|
+
return await combinedChainInner.invoke(input, config);
|
|
76
|
+
},
|
|
77
|
+
}).withConfig({ runName: 'CombinedChainWithDefaults' });
|
|
78
|
+
return new runnables.RunnableLambda({
|
|
79
|
+
func: async (input, config) => {
|
|
80
|
+
const invokeInput = { convo: input.convo };
|
|
81
|
+
if (input.skipLanguage) {
|
|
82
|
+
return (await titleOnlyChain.invoke(invokeInput, config));
|
|
83
|
+
}
|
|
84
|
+
return await combinedChainWithDefaults.invoke(invokeInput, config);
|
|
85
|
+
},
|
|
86
|
+
}).withConfig({ runName: 'TitleGenerator' });
|
|
87
|
+
};
|
|
88
|
+
const defaultCompletionPrompt = `Provide a concise, 5-word-or-less title for the conversation, using title case conventions. Only return the title itself.
|
|
89
|
+
|
|
90
|
+
Conversation:
|
|
91
|
+
{convo}`;
|
|
92
|
+
const createCompletionTitleRunnable = async (model, titlePrompt) => {
|
|
93
|
+
const completionPrompt = prompts.ChatPromptTemplate.fromTemplate(titlePrompt ?? defaultCompletionPrompt).withConfig({ runName: 'CompletionTitlePrompt' });
|
|
94
|
+
/** Runnable to extract content from model response */
|
|
95
|
+
const extractContent = new runnables.RunnableLambda({
|
|
96
|
+
func: (response) => {
|
|
97
|
+
let content = '';
|
|
98
|
+
if (typeof response.content === 'string') {
|
|
99
|
+
content = response.content;
|
|
100
|
+
}
|
|
101
|
+
else if (Array.isArray(response.content)) {
|
|
102
|
+
content = response.content
|
|
103
|
+
.filter((part) => part.type === _enum.ContentTypes.TEXT)
|
|
104
|
+
.map((part) => part.text)
|
|
105
|
+
.join('');
|
|
106
|
+
}
|
|
107
|
+
return { title: content.trim() };
|
|
108
|
+
},
|
|
109
|
+
}).withConfig({ runName: 'ExtractTitle' });
|
|
110
|
+
const innerChain = runnables.RunnableSequence.from([
|
|
111
|
+
completionPrompt,
|
|
112
|
+
model,
|
|
113
|
+
extractContent,
|
|
114
|
+
]);
|
|
115
|
+
/** Wrap in RunnableLambda to create a parent span for LangFuse */
|
|
116
|
+
return new runnables.RunnableLambda({
|
|
117
|
+
func: async (input, config) => {
|
|
118
|
+
return await innerChain.invoke(input, config);
|
|
119
|
+
},
|
|
120
|
+
}).withConfig({ runName: 'CompletionTitleChain' });
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
exports.createCompletionTitleRunnable = createCompletionTitleRunnable;
|
|
124
|
+
exports.createTitleRunnable = createTitleRunnable;
|
|
125
|
+
//# sourceMappingURL=title.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"title.cjs","sources":["../../../src/utils/title.ts"],"sourcesContent":["import { ChatPromptTemplate } from '@langchain/core/prompts';\nimport { RunnableLambda, RunnableSequence } from '@langchain/core/runnables';\nimport type { Runnable, RunnableConfig } from '@langchain/core/runnables';\nimport type { AIMessage } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { ContentTypes } from '@/common';\n\nconst defaultTitlePrompt = `Analyze this conversation and provide:\n1. The detected language of the conversation\n2. A concise title in the detected language (5 words or less, no punctuation or quotation)\n\n{convo}`;\n\nconst titleSchema = {\n type: 'object',\n properties: {\n title: {\n type: 'string',\n description:\n 'A concise title for the conversation in 5 words or less, without punctuation or quotation',\n },\n },\n required: ['title'],\n} as const;\n\nconst combinedSchema = {\n type: 'object',\n properties: {\n language: {\n type: 'string',\n description: 'The detected language of the conversation',\n },\n title: {\n type: 'string',\n description:\n 'A concise title for the conversation in 5 words or less, without punctuation or quotation',\n },\n },\n required: ['language', 'title'],\n} as const;\n\nexport const createTitleRunnable = async (\n model: t.ChatModelInstance,\n _titlePrompt?: string\n): Promise<Runnable> => {\n // Disabled since this works fine\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /* @ts-ignore */\n const titleLLM = model.withStructuredOutput(titleSchema);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /* @ts-ignore */\n const combinedLLM = model.withStructuredOutput(combinedSchema);\n\n const titlePrompt = ChatPromptTemplate.fromTemplate(\n _titlePrompt ?? defaultTitlePrompt\n ).withConfig({ runName: 'TitlePrompt' });\n\n const titleOnlyInnerChain = RunnableSequence.from([titlePrompt, titleLLM]);\n const combinedInnerChain = RunnableSequence.from([titlePrompt, combinedLLM]);\n\n /** Wrap titleOnlyChain in RunnableLambda to create parent span */\n const titleOnlyChain = new RunnableLambda({\n func: async (\n input: { convo: string },\n config?: Partial<RunnableConfig>\n ): Promise<{ title: string }> => {\n const result = await titleOnlyInnerChain.invoke(input, config);\n return result as { title: string };\n },\n }).withConfig({ runName: 'TitleOnlyChain' });\n\n /** Wrap combinedChain in RunnableLambda to create parent span */\n const combinedChain = new RunnableLambda({\n func: async (\n input: { convo: string },\n config?: Partial<RunnableConfig>\n ): Promise<{ language: string; title: string }> => {\n const result = await combinedInnerChain.invoke(input, config);\n return result as { language: string; title: string };\n },\n }).withConfig({ runName: 'TitleLanguageChain' });\n\n /** Runnable to add default values if needed */\n const addDefaults = new RunnableLambda({\n func: (\n result: { language: string; title: string } | undefined\n ): { language: string; title: string } => ({\n language: result?.language ?? 'English',\n title: result?.title ?? '',\n }),\n }).withConfig({ runName: 'AddDefaults' });\n\n const combinedChainInner = RunnableSequence.from([\n combinedChain,\n addDefaults,\n ]);\n\n /** Wrap combinedChainWithDefaults in RunnableLambda to create parent span */\n const combinedChainWithDefaults = new RunnableLambda({\n func: async (\n input: { convo: string },\n config?: Partial<RunnableConfig>\n ): Promise<{ language: string; title: string }> => {\n return await combinedChainInner.invoke(input, config);\n },\n }).withConfig({ runName: 'CombinedChainWithDefaults' });\n\n return new RunnableLambda({\n func: async (\n input: {\n convo: string;\n inputText: string;\n skipLanguage: boolean;\n },\n config?: Partial<RunnableConfig>\n ): Promise<{ language: string; title: string } | { title: string }> => {\n const invokeInput = { convo: input.convo };\n\n if (input.skipLanguage) {\n return (await titleOnlyChain.invoke(invokeInput, config)) as {\n title: string;\n };\n }\n\n return await combinedChainWithDefaults.invoke(invokeInput, config);\n },\n }).withConfig({ runName: 'TitleGenerator' });\n};\n\nconst defaultCompletionPrompt = `Provide a concise, 5-word-or-less title for the conversation, using title case conventions. Only return the title itself.\n\nConversation:\n{convo}`;\n\nexport const createCompletionTitleRunnable = async (\n model: t.ChatModelInstance,\n titlePrompt?: string\n): Promise<Runnable> => {\n const completionPrompt = ChatPromptTemplate.fromTemplate(\n titlePrompt ?? defaultCompletionPrompt\n ).withConfig({ runName: 'CompletionTitlePrompt' });\n\n /** Runnable to extract content from model response */\n const extractContent = new RunnableLambda({\n func: (response: AIMessage): { title: string } => {\n let content = '';\n if (typeof response.content === 'string') {\n content = response.content;\n } else if (Array.isArray(response.content)) {\n content = response.content\n .filter(\n (part): part is { type: ContentTypes.TEXT; text: string } =>\n part.type === ContentTypes.TEXT\n )\n .map((part) => part.text)\n .join('');\n }\n return { title: content.trim() };\n },\n }).withConfig({ runName: 'ExtractTitle' });\n\n const innerChain = RunnableSequence.from([\n completionPrompt,\n model,\n extractContent,\n ]);\n\n /** Wrap in RunnableLambda to create a parent span for LangFuse */\n return new RunnableLambda({\n func: async (\n input: { convo: string },\n config?: Partial<RunnableConfig>\n ): Promise<{ title: string }> => {\n return await innerChain.invoke(input, config);\n },\n }).withConfig({ runName: 'CompletionTitleChain' });\n};\n"],"names":["ChatPromptTemplate","RunnableSequence","RunnableLambda","ContentTypes"],"mappings":";;;;;;AAOA,MAAM,kBAAkB,GAAG,CAAA;;;;QAInB;AAER,MAAM,WAAW,GAAG;AAClB,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,KAAK,EAAE;AACL,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EACT,2FAA2F;AAC9F,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,OAAO,CAAC;CACX;AAEV,MAAM,cAAc,GAAG;AACrB,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,QAAQ,EAAE;AACR,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,2CAA2C;AACzD,SAAA;AACD,QAAA,KAAK,EAAE;AACL,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EACT,2FAA2F;AAC9F,SAAA;AACF,KAAA;AACD,IAAA,QAAQ,EAAE,CAAC,U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c,GAAG,IAAIE,wBAAc,CAAC;AACxC,QAAA,IAAI,EAAE,CAAC,QAAmB,KAAuB;YAC/C,IAAI,OAAO,GAAG,EAAE;AAChB,YAAA,IAAI,OAAO,QAAQ,CAAC,OAAO,KAAK,QAAQ,EAAE;AACxC,gBAAA,OAAO,GAAG,QAAQ,CAAC,OAAO;;iBACrB,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;gBAC1C,OAAO,GAAG,QAAQ,CAAC;AAChB,qBAAA,MAAM,CACL,CAAC,IAAI,KACH,IAAI,CAAC,IAAI,KAAKC,kBAAY,CAAC,IAAI;qBAElC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI;qBACvB,IAAI,CAAC,EAAE,CAAC;;YAEb,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,EAAE;SACjC;KACF,CAAC,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1C,IAAA,MAAM,UAAU,GAAGF,0BAAgB,CAAC,IAAI,CAAC;QACvC,gBAAgB;QAChB,KAAK;QACL,cAAc;AACf,KAAA,CAAC;;IAGF,OAAO,IAAIC,wBAAc,CAAC;AACxB,QAAA,IAAI,EAAE,OACJ,KAAwB,EACxB,MAAgC,KACF;YAC9B,OAAO,MAAM,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC;SAC9C;KACF,CAAC,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,sBAAsB,EAAE,CAAC;AACpD;;;;;"}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var jsTiktoken = require('js-tiktoken');
|
|
4
|
+
var _enum = require('../common/enum.cjs');
|
|
5
|
+
|
|
6
|
+
function getTokenCountForMessage(message, getTokenCount) {
|
|
7
|
+
const tokensPerMessage = 3;
|
|
8
|
+
const processValue = (value) => {
|
|
9
|
+
if (Array.isArray(value)) {
|
|
10
|
+
for (const item of value) {
|
|
11
|
+
if (!item ||
|
|
12
|
+
!item.type ||
|
|
13
|
+
item.type === _enum.ContentTypes.ERROR ||
|
|
14
|
+
item.type === _enum.ContentTypes.IMAGE_URL) {
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (item.type === _enum.ContentTypes.TOOL_CALL && item.tool_call != null) {
|
|
18
|
+
const toolName = item.tool_call?.name || '';
|
|
19
|
+
if (toolName != null && toolName && typeof toolName === 'string') {
|
|
20
|
+
numTokens += getTokenCount(toolName);
|
|
21
|
+
}
|
|
22
|
+
const args = item.tool_call?.args || '';
|
|
23
|
+
if (args != null && args && typeof args === 'string') {
|
|
24
|
+
numTokens += getTokenCount(args);
|
|
25
|
+
}
|
|
26
|
+
const output = item.tool_call?.output || '';
|
|
27
|
+
if (output != null && output && typeof output === 'string') {
|
|
28
|
+
numTokens += getTokenCount(output);
|
|
29
|
+
}
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
const nestedValue = item[item.type];
|
|
33
|
+
if (!nestedValue) {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
processValue(nestedValue);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else if (typeof value === 'string') {
|
|
40
|
+
numTokens += getTokenCount(value);
|
|
41
|
+
}
|
|
42
|
+
else if (typeof value === 'number') {
|
|
43
|
+
numTokens += getTokenCount(value.toString());
|
|
44
|
+
}
|
|
45
|
+
else if (typeof value === 'boolean') {
|
|
46
|
+
numTokens += getTokenCount(value.toString());
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
let numTokens = tokensPerMessage;
|
|
50
|
+
processValue(message.content);
|
|
51
|
+
return numTokens;
|
|
52
|
+
}
|
|
53
|
+
let encoderPromise;
|
|
54
|
+
let tokenCounterPromise;
|
|
55
|
+
/**
|
|
56
|
+
* Simple character-based token estimation (~4 chars per token).
|
|
57
|
+
* Used as fallback when tiktoken encoder fails to load.
|
|
58
|
+
*/
|
|
59
|
+
const estimateTokens = (text) => Math.ceil(text.length / 4);
|
|
60
|
+
async function getSharedEncoder() {
|
|
61
|
+
if (encoderPromise) {
|
|
62
|
+
return encoderPromise;
|
|
63
|
+
}
|
|
64
|
+
// Use bundled tokenizer data - no external network calls
|
|
65
|
+
encoderPromise = Promise.resolve().then(() => {
|
|
66
|
+
try {
|
|
67
|
+
return jsTiktoken.getEncoding('o200k_base');
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// Fallback to null - will use character estimation
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
return encoderPromise;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Creates a singleton token counter function that reuses the same encoder instance.
|
|
78
|
+
* Falls back to character-based estimation (~4 chars per token) if encoder fails.
|
|
79
|
+
* This ensures token counting never blocks LLM calls.
|
|
80
|
+
*/
|
|
81
|
+
const createTokenCounter = async () => {
|
|
82
|
+
if (tokenCounterPromise) {
|
|
83
|
+
return tokenCounterPromise;
|
|
84
|
+
}
|
|
85
|
+
tokenCounterPromise = (async () => {
|
|
86
|
+
const enc = await getSharedEncoder();
|
|
87
|
+
const countTokens = enc
|
|
88
|
+
? (text) => enc.encode(text).length
|
|
89
|
+
: estimateTokens;
|
|
90
|
+
return (message) => getTokenCountForMessage(message, countTokens);
|
|
91
|
+
})();
|
|
92
|
+
return tokenCounterPromise;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Utility to manage the token encoder lifecycle explicitly.
|
|
96
|
+
* Useful for applications that need fine-grained control over resource management.
|
|
97
|
+
*/
|
|
98
|
+
const TokenEncoderManager = {
|
|
99
|
+
/**
|
|
100
|
+
* Pre-initializes the encoder. This can be called during app startup
|
|
101
|
+
* to avoid lazy loading delays later.
|
|
102
|
+
*/
|
|
103
|
+
async initialize() {
|
|
104
|
+
await getSharedEncoder();
|
|
105
|
+
},
|
|
106
|
+
/**
|
|
107
|
+
* Clears the cached encoder and token counter.
|
|
108
|
+
* Useful for testing or when you need to force a fresh reload.
|
|
109
|
+
*/
|
|
110
|
+
reset() {
|
|
111
|
+
encoderPromise = undefined;
|
|
112
|
+
tokenCounterPromise = undefined;
|
|
113
|
+
},
|
|
114
|
+
/**
|
|
115
|
+
* Checks if the encoder has been initialized.
|
|
116
|
+
*/
|
|
117
|
+
isInitialized() {
|
|
118
|
+
return encoderPromise !== undefined;
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
exports.TokenEncoderManager = TokenEncoderManager;
|
|
123
|
+
exports.createTokenCounter = createTokenCounter;
|
|
124
|
+
exports.getTokenCountForMessage = getTokenCountForMessage;
|
|
125
|
+
//# sourceMappingURL=tokens.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokens.cjs","sources":["../../../src/utils/tokens.ts"],"sourcesContent":["import { getEncoding, type Tiktoken } from 'js-tiktoken';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { ContentTypes } from '@/common/enum';\n\nexport function getTokenCountForMessage(\n message: BaseMessage,\n getTokenCount: (text: string) => number\n): number {\n const tokensPerMessage = 3;\n\n const processValue = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (\n !item ||\n !item.type ||\n item.type === ContentTypes.ERROR ||\n item.type === ContentTypes.IMAGE_URL\n ) {\n continue;\n }\n\n if (item.type === ContentTypes.TOOL_CALL && item.tool_call != null) {\n const toolName = item.tool_call?.name || '';\n if (toolName != null && toolName && typeof toolName === 'string') {\n numTokens += getTokenCount(toolName);\n }\n\n const args = item.tool_call?.args || '';\n if (args != null && args && typeof args === 'string') {\n numTokens += getTokenCount(args);\n }\n\n const output = item.tool_call?.output || '';\n if (output != null && output && typeof output === 'string') {\n numTokens += getTokenCount(output);\n }\n continue;\n }\n\n const nestedValue = item[item.type];\n\n if (!nestedValue) {\n continue;\n }\n\n processValue(nestedValue);\n }\n } else if (typeof value === 'string') {\n numTokens += getTokenCount(value);\n } else if (typeof value === 'number') {\n numTokens += getTokenCount(value.toString());\n } else if (typeof value === 'boolean') {\n numTokens += getTokenCount(value.toString());\n }\n };\n\n let numTokens = tokensPerMessage;\n processValue(message.content);\n return numTokens;\n}\n\nlet encoderPromise: Promise<Tiktoken | null> | undefined;\nlet tokenCounterPromise: Promise<(message: BaseMessage) => number> | undefined;\n\n/**\n * Simple character-based token estimation (~4 chars per token).\n * Used as fallback when tiktoken encoder fails to load.\n */\nconst estimateTokens = (text: string): number => Math.ceil(text.length / 4);\n\nasync function getSharedEncoder(): Promise<Tiktoken | null> {\n if (encoderPromise) {\n return encoderPromise;\n }\n // Use bundled tokenizer data - no external network calls\n encoderPromise = Promise.resolve().then(() => {\n try {\n return getEncoding('o200k_base');\n } catch {\n // Fallback to null - will use character estimation\n return null;\n }\n });\n return encoderPromise;\n}\n\n/**\n * Creates a singleton token counter function that reuses the same encoder instance.\n * Falls back to character-based estimation (~4 chars per token) if encoder fails.\n * This ensures token counting never blocks LLM calls.\n */\nexport const createTokenCounter = async (): Promise<\n (message: BaseMessage) => number\n> => {\n if (tokenCounterPromise) {\n return tokenCounterPromise;\n }\n\n tokenCounterPromise = (async (): Promise<\n (message: BaseMessage) => number\n > => {\n const enc = await getSharedEncoder();\n const countTokens = enc\n ? (text: string): number => enc.encode(text).length\n : estimateTokens;\n return (message: BaseMessage): number =>\n getTokenCountForMessage(message, countTokens);\n })();\n\n return tokenCounterPromise;\n};\n\n/**\n * Utility to manage the token encoder lifecycle explicitly.\n * Useful for applications that need fine-grained control over resource management.\n */\nexport const TokenEncoderManager = {\n /**\n * Pre-initializes the encoder. This can be called during app startup\n * to avoid lazy loading delays later.\n */\n async initialize(): Promise<void> {\n await getSharedEncoder();\n },\n\n /**\n * Clears the cached encoder and token counter.\n * Useful for testing or when you need to force a fresh reload.\n */\n reset(): void {\n encoderPromise = undefined;\n tokenCounterPromise = undefined;\n },\n\n /**\n * Checks if the encoder has been initialized.\n */\n isInitial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ACpC,MAAM,WAAW,GAAG;AAClB,cAAE,CAAC,IAAY,KAAa,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;cAC3C,cAAc;QAClB,OAAO,CAAC,OAAoB,KAC1B,uBAAuB,CAAC,OAAO,EAAE,WAAW,CAAC;KAChD,GAAG;AAEJ,IAAA,OAAO,mBAAmB;AAC5B;AAEA;;;AAGG;AACU,MAAA,mBAAmB,GAAG;AACjC;;;AAGG;AACH,IAAA,MAAM,UAAU,GAAA;QACd,MAAM,gBAAgB,EAAE;KACzB;AAED;;;AAGG;IACH,KAAK,GAAA;QACH,cAAc,GAAG,SAAS;QAC1B,mBAAmB,GAAG,SAAS;KAChC;AAED;;AAEG;IACH,aAAa,GAAA;QACX,OAAO,cAAc,KAAK,SAAS;KACpC;;;;;;;"}
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* TOON Format Utility
|
|
5
|
+
*
|
|
6
|
+
* Provides JSON to TOON conversion for token-efficient encoding.
|
|
7
|
+
* TOON format can reduce token count by 30-60% for JSON data.
|
|
8
|
+
*
|
|
9
|
+
* Uses the official @toon-format/toon library when available.
|
|
10
|
+
*/
|
|
11
|
+
// Dynamic import holder for the TOON library (ESM)
|
|
12
|
+
let toonEncode = null;
|
|
13
|
+
let toonLoadAttempted = false;
|
|
14
|
+
let toonLoadPromise = null;
|
|
15
|
+
/**
|
|
16
|
+
* Lazily loads the TOON library
|
|
17
|
+
* Tries both ESM dynamic import and CommonJS require for compatibility
|
|
18
|
+
*/
|
|
19
|
+
async function loadToonLibrary() {
|
|
20
|
+
if (toonLoadAttempted)
|
|
21
|
+
return toonEncode !== null;
|
|
22
|
+
toonLoadAttempted = true;
|
|
23
|
+
// Try ESM dynamic import first
|
|
24
|
+
try {
|
|
25
|
+
const mod = await import('@toon-format/toon');
|
|
26
|
+
toonEncode = mod.encode;
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// ESM import failed, try CommonJS require
|
|
31
|
+
try {
|
|
32
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
33
|
+
const mod = require('@toon-format/toon');
|
|
34
|
+
toonEncode = mod.encode;
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// Library not available - that's OK, we'll return original content
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Ensures the TOON library is loaded. Call this before using jsonToToon in tests.
|
|
45
|
+
*/
|
|
46
|
+
async function ensureToonLoaded() {
|
|
47
|
+
if (!toonLoadPromise) {
|
|
48
|
+
toonLoadPromise = loadToonLibrary();
|
|
49
|
+
}
|
|
50
|
+
return toonLoadPromise;
|
|
51
|
+
}
|
|
52
|
+
// Start loading immediately
|
|
53
|
+
ensureToonLoaded();
|
|
54
|
+
/**
|
|
55
|
+
* Check if a string appears to be in TOON format.
|
|
56
|
+
* TOON format characteristics:
|
|
57
|
+
* - Uses key: value syntax (like YAML)
|
|
58
|
+
* - Uses array notation like [3] or {fields}
|
|
59
|
+
* - Does NOT start with { or [
|
|
60
|
+
* - Often has patterns like "name[N]:" or "name{fields}:"
|
|
61
|
+
*
|
|
62
|
+
* @param str - String to check
|
|
63
|
+
* @returns true if string appears to be TOON format
|
|
64
|
+
*/
|
|
65
|
+
function isToonFormat(str) {
|
|
66
|
+
if (typeof str !== 'string' || str.length === 0)
|
|
67
|
+
return false;
|
|
68
|
+
const trimmed = str.trim();
|
|
69
|
+
// TOON doesn't start with JSON brackets
|
|
70
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('['))
|
|
71
|
+
return false;
|
|
72
|
+
// Check for TOON-specific patterns:
|
|
73
|
+
// 1. Key-value with colon (but not URL-like patterns)
|
|
74
|
+
// 2. Array notation like "items[3]:" or "data[10]:"
|
|
75
|
+
// 3. Object schema notation like "items{id,name}:"
|
|
76
|
+
const toonPatterns = [
|
|
77
|
+
/^\w+:$/m, // Simple key: at start of line
|
|
78
|
+
/^\w+\[\d+\]:/m, // Array notation: items[3]:
|
|
79
|
+
/^\w+\{[^}]+\}:/m, // Schema notation: items{id,name}:
|
|
80
|
+
/^\w+\[\d+\]\{[^}]+\}:/m, // Combined: items[3]{id,name}:
|
|
81
|
+
];
|
|
82
|
+
// Must match at least one TOON pattern
|
|
83
|
+
const hasToonPattern = toonPatterns.some((pattern) => pattern.test(trimmed));
|
|
84
|
+
// Additional check: TOON typically has multiple lines with consistent indentation
|
|
85
|
+
const lines = trimmed.split('\n').filter((l) => l.trim());
|
|
86
|
+
const hasMultipleKeyValueLines = lines.filter((l) => /^\s*\w+.*:/.test(l)).length >= 2;
|
|
87
|
+
return hasToonPattern || hasMultipleKeyValueLines;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Extract the first valid JSON object or array from a string.
|
|
91
|
+
* Handles pure JSON or JSON embedded in text (e.g., tool responses).
|
|
92
|
+
*
|
|
93
|
+
* @param str - The string to extract JSON from
|
|
94
|
+
* @returns Object with found status, parsed JSON, and indices
|
|
95
|
+
*/
|
|
96
|
+
function extractFirstJson(str) {
|
|
97
|
+
if (typeof str !== 'string' || str.length === 0) {
|
|
98
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
99
|
+
}
|
|
100
|
+
// Find the first { or [ character
|
|
101
|
+
const objStart = str.indexOf('{');
|
|
102
|
+
const arrStart = str.indexOf('[');
|
|
103
|
+
if (objStart === -1 && arrStart === -1) {
|
|
104
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
105
|
+
}
|
|
106
|
+
let startIndex;
|
|
107
|
+
if (objStart === -1) {
|
|
108
|
+
startIndex = arrStart;
|
|
109
|
+
}
|
|
110
|
+
else if (arrStart === -1) {
|
|
111
|
+
startIndex = objStart;
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
startIndex = Math.min(objStart, arrStart);
|
|
115
|
+
}
|
|
116
|
+
// Find the matching closing bracket using a stack-based approach
|
|
117
|
+
// Properly handle strings to avoid counting brackets inside strings
|
|
118
|
+
let depth = 0;
|
|
119
|
+
let inString = false;
|
|
120
|
+
let escapeNext = false;
|
|
121
|
+
for (let i = startIndex; i < str.length; i++) {
|
|
122
|
+
const char = str[i];
|
|
123
|
+
if (escapeNext) {
|
|
124
|
+
escapeNext = false;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (char === '\\' && inString) {
|
|
128
|
+
escapeNext = true;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (char === '"') {
|
|
132
|
+
inString = !inString;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (inString)
|
|
136
|
+
continue;
|
|
137
|
+
if (char === '{' || char === '[')
|
|
138
|
+
depth++;
|
|
139
|
+
if (char === '}' || char === ']')
|
|
140
|
+
depth--;
|
|
141
|
+
if (depth === 0) {
|
|
142
|
+
// Found matching bracket, try to parse
|
|
143
|
+
const jsonStr = str.substring(startIndex, i + 1);
|
|
144
|
+
try {
|
|
145
|
+
const parsed = JSON.parse(jsonStr);
|
|
146
|
+
return { found: true, parsed, startIndex, endIndex: i };
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// Not valid JSON at this bracket level, continue searching
|
|
150
|
+
// Reset and look for the next JSON start after this position
|
|
151
|
+
const nextResult = extractFirstJson(str.substring(i + 1));
|
|
152
|
+
if (nextResult.found) {
|
|
153
|
+
return {
|
|
154
|
+
found: true,
|
|
155
|
+
parsed: nextResult.parsed,
|
|
156
|
+
startIndex: i + 1 + nextResult.startIndex,
|
|
157
|
+
endIndex: i + 1 + nextResult.endIndex,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Convert JSON content to TOON format for token efficiency.
|
|
168
|
+
* Extracts JSON from string if embedded, converts to TOON.
|
|
169
|
+
* Returns original string if:
|
|
170
|
+
* - Already in TOON format
|
|
171
|
+
* - Not JSON
|
|
172
|
+
* - TOON conversion fails or is larger
|
|
173
|
+
*
|
|
174
|
+
* @param str - The string containing JSON to convert
|
|
175
|
+
* @returns Object with conversion status, result, and reduction percentage
|
|
176
|
+
*/
|
|
177
|
+
function jsonToToon(str) {
|
|
178
|
+
if (!toonEncode || typeof str !== 'string') {
|
|
179
|
+
return {
|
|
180
|
+
converted: false,
|
|
181
|
+
result: str,
|
|
182
|
+
reduction: 0,
|
|
183
|
+
error: !toonEncode ? 'TOON library not loaded' : undefined,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
// Check if already in TOON format - skip conversion
|
|
187
|
+
if (isToonFormat(str)) {
|
|
188
|
+
return { converted: false, result: str, reduction: 0, alreadyToon: true };
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
const { found, parsed, startIndex, endIndex } = extractFirstJson(str);
|
|
192
|
+
if (!found || !parsed) {
|
|
193
|
+
return {
|
|
194
|
+
converted: false,
|
|
195
|
+
result: str,
|
|
196
|
+
reduction: 0,
|
|
197
|
+
error: 'No JSON found in content',
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
// Check if this JSON structure would benefit from TOON
|
|
201
|
+
// Text-heavy content (emails, documents) won't compress well
|
|
202
|
+
if (!isToonBeneficial(parsed)) {
|
|
203
|
+
return {
|
|
204
|
+
converted: false,
|
|
205
|
+
result: str,
|
|
206
|
+
reduction: 0,
|
|
207
|
+
error: 'Content is text-heavy (>70% string values), TOON not beneficial',
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
const toonResult = toonEncode(parsed);
|
|
211
|
+
// Preserve text before and after the JSON block
|
|
212
|
+
const textBefore = str.substring(0, startIndex);
|
|
213
|
+
const textAfter = str.substring(endIndex + 1);
|
|
214
|
+
// Build the full result: textBefore + TOON + textAfter
|
|
215
|
+
const fullResult = textBefore + toonResult + textAfter;
|
|
216
|
+
if (fullResult.length < str.length) {
|
|
217
|
+
const reduction = Math.round(((str.length - fullResult.length) / str.length) * 100);
|
|
218
|
+
return { converted: true, result: fullResult, reduction };
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
// TOON output was larger or same size - not beneficial
|
|
222
|
+
return {
|
|
223
|
+
converted: false,
|
|
224
|
+
result: str,
|
|
225
|
+
reduction: 0,
|
|
226
|
+
error: `TOON output not smaller (${fullResult.length} >= ${str.length})`,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
// TOON encoding or extraction failed - log error for debugging
|
|
232
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
233
|
+
return {
|
|
234
|
+
converted: false,
|
|
235
|
+
result: str,
|
|
236
|
+
reduction: 0,
|
|
237
|
+
error: `TOON conversion error: ${errorMsg}`,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Check if TOON library is loaded and available
|
|
243
|
+
*/
|
|
244
|
+
function isToonAvailable() {
|
|
245
|
+
return toonEncode !== null;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Analyze JSON structure to determine if TOON conversion would be beneficial.
|
|
249
|
+
* Text-heavy content (emails, documents) doesn't compress well with TOON.
|
|
250
|
+
* Structured data (API responses, metadata) compresses much better.
|
|
251
|
+
*
|
|
252
|
+
* @param parsed - Parsed JSON object
|
|
253
|
+
* @returns true if TOON conversion is likely beneficial
|
|
254
|
+
*/
|
|
255
|
+
function isToonBeneficial(parsed) {
|
|
256
|
+
if (!parsed || typeof parsed !== 'object')
|
|
257
|
+
return false;
|
|
258
|
+
const jsonStr = JSON.stringify(parsed);
|
|
259
|
+
const totalLength = jsonStr.length;
|
|
260
|
+
// Count characters in string values (text content)
|
|
261
|
+
let textContentLength = 0;
|
|
262
|
+
function countTextContent(obj) {
|
|
263
|
+
if (typeof obj === 'string') {
|
|
264
|
+
// Count string length (this is text content that TOON can't compress)
|
|
265
|
+
textContentLength += obj.length;
|
|
266
|
+
}
|
|
267
|
+
else if (Array.isArray(obj)) {
|
|
268
|
+
obj.forEach(countTextContent);
|
|
269
|
+
}
|
|
270
|
+
else if (obj && typeof obj === 'object') {
|
|
271
|
+
Object.values(obj).forEach(countTextContent);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
countTextContent(parsed);
|
|
275
|
+
// Calculate ratio of text content to total JSON
|
|
276
|
+
const textRatio = textContentLength / totalLength;
|
|
277
|
+
// If more than 70% is text content, TOON won't help much
|
|
278
|
+
// TOON compresses structure (field names, brackets), not text
|
|
279
|
+
return textRatio < 0.7;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Process tool output: apply TOON conversion if beneficial, then truncate if needed.
|
|
283
|
+
* This is the main entry point for processing any tool output (regular or MCP).
|
|
284
|
+
*
|
|
285
|
+
* Flow:
|
|
286
|
+
* 1. Check if already TOON format → skip conversion
|
|
287
|
+
* 2. Try TOON conversion if content is JSON and large enough
|
|
288
|
+
* 3. Truncate if still exceeds maxLength (with smart break points)
|
|
289
|
+
*
|
|
290
|
+
* @param content - The tool output content
|
|
291
|
+
* @param options - Processing options
|
|
292
|
+
* @returns Processed content and metadata
|
|
293
|
+
*/
|
|
294
|
+
function processToolOutput(content, options = {}) {
|
|
295
|
+
const { maxLength = 100000, enableToon = true, minSizeForToon = 1000, minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial
|
|
296
|
+
} = options;
|
|
297
|
+
const originalLength = content.length;
|
|
298
|
+
const originalTokens = Math.ceil(originalLength / 4);
|
|
299
|
+
let result = content;
|
|
300
|
+
let toonConverted = false;
|
|
301
|
+
let alreadyToon = false;
|
|
302
|
+
let reduction = 0;
|
|
303
|
+
let truncated = false;
|
|
304
|
+
let toonError;
|
|
305
|
+
// Step 1: Check if already TOON format
|
|
306
|
+
if (isToonFormat(content)) {
|
|
307
|
+
alreadyToon = true;
|
|
308
|
+
}
|
|
309
|
+
// Step 2: Apply TOON conversion if enabled and content is large enough
|
|
310
|
+
else if (enableToon && content.length > minSizeForToon) {
|
|
311
|
+
const toonResult = jsonToToon(content);
|
|
312
|
+
if (toonResult.alreadyToon) {
|
|
313
|
+
alreadyToon = true;
|
|
314
|
+
}
|
|
315
|
+
else if (toonResult.converted &&
|
|
316
|
+
toonResult.reduction >= minReductionPercent) {
|
|
317
|
+
result = toonResult.result;
|
|
318
|
+
toonConverted = true;
|
|
319
|
+
reduction = toonResult.reduction;
|
|
320
|
+
}
|
|
321
|
+
else if (toonResult.error) {
|
|
322
|
+
// Track error for debugging
|
|
323
|
+
toonError = toonResult.error;
|
|
324
|
+
}
|
|
325
|
+
else if (toonResult.converted &&
|
|
326
|
+
toonResult.reduction < minReductionPercent) {
|
|
327
|
+
// TOON converted but reduction was too small to be worth it
|
|
328
|
+
toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;
|
|
329
|
+
}
|
|
330
|
+
else if (!toonResult.converted) {
|
|
331
|
+
// Conversion failed without explicit error - investigate
|
|
332
|
+
toonError =
|
|
333
|
+
toonResult.error || 'TOON conversion returned false with no error';
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// Step 3: Truncate if still too long (with smart break points)
|
|
337
|
+
if (result.length > maxLength) {
|
|
338
|
+
let truncatedStr = result.substring(0, maxLength);
|
|
339
|
+
// Try to find a clean break point
|
|
340
|
+
if (toonConverted || alreadyToon) {
|
|
341
|
+
// For TOON format, break at newline for cleaner output
|
|
342
|
+
const lastNewline = truncatedStr.lastIndexOf('\n');
|
|
343
|
+
if (lastNewline > maxLength * 0.7) {
|
|
344
|
+
truncatedStr = truncatedStr.substring(0, lastNewline);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
// For JSON, try to find a clean JSON break point
|
|
349
|
+
const lastCompleteItem = truncatedStr.lastIndexOf('},');
|
|
350
|
+
const lastArrayItem = truncatedStr.lastIndexOf('],');
|
|
351
|
+
const breakPoint = Math.max(lastCompleteItem, lastArrayItem);
|
|
352
|
+
if (breakPoint > maxLength * 0.5) {
|
|
353
|
+
truncatedStr = truncatedStr.substring(0, breakPoint + 1);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
// Build truncation message
|
|
357
|
+
const truncationInfo = toonConverted
|
|
358
|
+
? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +
|
|
359
|
+
`Still exceeds ${maxLength.toLocaleString()} char limit.`
|
|
360
|
+
: `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;
|
|
361
|
+
result =
|
|
362
|
+
truncatedStr +
|
|
363
|
+
`\n\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;
|
|
364
|
+
truncated = true;
|
|
365
|
+
}
|
|
366
|
+
const finalLength = result.length;
|
|
367
|
+
const finalTokens = Math.ceil(finalLength / 4);
|
|
368
|
+
return {
|
|
369
|
+
content: result,
|
|
370
|
+
toonConverted,
|
|
371
|
+
truncated,
|
|
372
|
+
reduction,
|
|
373
|
+
alreadyToon,
|
|
374
|
+
originalLength,
|
|
375
|
+
originalTokens,
|
|
376
|
+
finalLength,
|
|
377
|
+
finalTokens,
|
|
378
|
+
toonError,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
exports.ensureToonLoaded = ensureToonLoaded;
|
|
383
|
+
exports.extractFirstJson = extractFirstJson;
|
|
384
|
+
exports.isToonAvailable = isToonAvailable;
|
|
385
|
+
exports.isToonFormat = isToonFormat;
|
|
386
|
+
exports.jsonToToon = jsonToToon;
|
|
387
|
+
exports.processToolOutput = processToolOutput;
|
|
388
|
+
//# sourceMappingURL=toonFormat.cjs.map
|