@ai.ntellect/core 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.mocharc.json +6 -0
- package/AGENTS.md +50 -0
- package/ARCHITECTURE.md +58 -0
- package/BENCHMARK.md +38 -0
- package/CHANGELOG.md +224 -0
- package/README.md +411 -142
- package/agent/agent-workflow.ts +569 -0
- package/agent/agent.ts +183 -0
- package/agent/base/executor.ts +103 -0
- package/agent/base/index.ts +87 -0
- package/agent/entity-resolver/confidence.ts +54 -0
- package/agent/entity-resolver/entity-index.ts +241 -0
- package/agent/entity-resolver/explore-strategy.ts +82 -0
- package/agent/entity-resolver/index.ts +22 -0
- package/agent/entity-resolver/resolver.ts +193 -0
- package/agent/entity-resolver/scorer.ts +211 -0
- package/agent/entity-resolver/types.ts +98 -0
- package/agent/generic-executor.ts +713 -0
- package/agent/handlers/cognitive-handler.ts +197 -0
- package/agent/handlers/index.ts +1 -0
- package/agent/handoff.ts +58 -0
- package/agent/llm-factory.ts +343 -0
- package/agent/orchestrator.ts +45 -0
- package/agent/prompt-builder.ts +78 -0
- package/agent/registry.ts +64 -0
- package/agent/tools/file-system.ts +471 -0
- package/agent/tools/index.ts +23 -0
- package/agent/tools/logger.ts +105 -0
- package/agent/tools/tool-resolver.ts +104 -0
- package/benchmark/cortexflow-workflow.ts +182 -0
- package/benchmark/langgraph-workflow.ts +201 -0
- package/benchmark/llm-client.ts +76 -0
- package/benchmark/run-benchmark.ts +222 -0
- package/cli-dev.ts +419 -0
- package/dist/agent/agent-workflow.d.ts +41 -0
- package/dist/agent/agent-workflow.d.ts.map +1 -0
- package/dist/agent/agent-workflow.js +560 -0
- package/dist/agent/agent-workflow.js.map +1 -0
- package/dist/agent/agent.d.ts +38 -0
- package/dist/agent/agent.d.ts.map +1 -0
- package/dist/agent/agent.js +149 -0
- package/dist/agent/agent.js.map +1 -0
- package/dist/agent/base/executor.d.ts +51 -0
- package/dist/agent/base/executor.d.ts.map +1 -0
- package/dist/agent/base/executor.js +69 -0
- package/dist/agent/base/executor.js.map +1 -0
- package/dist/agent/base/index.d.ts +30 -0
- package/dist/agent/base/index.d.ts.map +1 -0
- package/dist/agent/base/index.js +88 -0
- package/dist/agent/base/index.js.map +1 -0
- package/dist/agent/entity-resolver/confidence.d.ts +4 -0
- package/dist/agent/entity-resolver/confidence.d.ts.map +1 -0
- package/dist/agent/entity-resolver/confidence.js +47 -0
- package/dist/agent/entity-resolver/confidence.js.map +1 -0
- package/dist/agent/entity-resolver/entity-index.d.ts +40 -0
- package/dist/agent/entity-resolver/entity-index.d.ts.map +1 -0
- package/dist/agent/entity-resolver/entity-index.js +244 -0
- package/dist/agent/entity-resolver/entity-index.js.map +1 -0
- package/dist/agent/entity-resolver/explore-strategy.d.ts +13 -0
- package/dist/agent/entity-resolver/explore-strategy.d.ts.map +1 -0
- package/dist/agent/entity-resolver/explore-strategy.js +109 -0
- package/dist/agent/entity-resolver/explore-strategy.js.map +1 -0
- package/dist/agent/entity-resolver/index.d.ts +8 -0
- package/dist/agent/entity-resolver/index.d.ts.map +1 -0
- package/dist/agent/entity-resolver/index.js +16 -0
- package/dist/agent/entity-resolver/index.js.map +1 -0
- package/dist/agent/entity-resolver/resolver.d.ts +18 -0
- package/dist/agent/entity-resolver/resolver.d.ts.map +1 -0
- package/dist/agent/entity-resolver/resolver.js +158 -0
- package/dist/agent/entity-resolver/resolver.js.map +1 -0
- package/dist/agent/entity-resolver/scorer.d.ts +3 -0
- package/dist/agent/entity-resolver/scorer.d.ts.map +1 -0
- package/dist/agent/entity-resolver/scorer.js +182 -0
- package/dist/agent/entity-resolver/scorer.js.map +1 -0
- package/dist/agent/entity-resolver/types.d.ts +89 -0
- package/dist/agent/entity-resolver/types.d.ts.map +1 -0
- package/dist/agent/entity-resolver/types.js +3 -0
- package/dist/agent/entity-resolver/types.js.map +1 -0
- package/dist/agent/generic-executor.d.ts +68 -0
- package/dist/agent/generic-executor.d.ts.map +1 -0
- package/dist/agent/generic-executor.js +620 -0
- package/dist/agent/generic-executor.js.map +1 -0
- package/dist/agent/handlers/cognitive-handler.d.ts +44 -0
- package/dist/agent/handlers/cognitive-handler.d.ts.map +1 -0
- package/dist/agent/handlers/cognitive-handler.js +172 -0
- package/dist/agent/handlers/cognitive-handler.js.map +1 -0
- package/dist/agent/handlers/index.d.ts +2 -0
- package/dist/agent/handlers/index.d.ts.map +1 -0
- package/dist/agent/handlers/index.js +7 -0
- package/dist/agent/handlers/index.js.map +1 -0
- package/dist/agent/handoff.d.ts +12 -0
- package/dist/agent/handoff.d.ts.map +1 -0
- package/dist/agent/handoff.js +62 -0
- package/dist/agent/handoff.js.map +1 -0
- package/dist/agent/llm-factory.d.ts +19 -0
- package/dist/agent/llm-factory.d.ts.map +1 -0
- package/dist/agent/llm-factory.js +297 -0
- package/dist/agent/llm-factory.js.map +1 -0
- package/dist/agent/orchestrator.d.ts +18 -0
- package/dist/agent/orchestrator.d.ts.map +1 -0
- package/dist/agent/orchestrator.js +44 -0
- package/dist/agent/orchestrator.js.map +1 -0
- package/dist/agent/prompt-builder.d.ts +35 -0
- package/dist/agent/prompt-builder.d.ts.map +1 -0
- package/dist/agent/prompt-builder.js +76 -0
- package/dist/agent/prompt-builder.js.map +1 -0
- package/dist/agent/registry.d.ts +19 -0
- package/dist/agent/registry.d.ts.map +1 -0
- package/dist/agent/registry.js +48 -0
- package/dist/agent/registry.js.map +1 -0
- package/dist/agent/tools/file-system.d.ts +11 -0
- package/dist/agent/tools/file-system.d.ts.map +1 -0
- package/dist/agent/tools/file-system.js +528 -0
- package/dist/agent/tools/file-system.js.map +1 -0
- package/dist/agent/tools/index.d.ts +4 -0
- package/dist/agent/tools/index.d.ts.map +1 -0
- package/dist/agent/tools/index.js +20 -0
- package/dist/agent/tools/index.js.map +1 -0
- package/dist/agent/tools/logger.d.ts +33 -0
- package/dist/agent/tools/logger.d.ts.map +1 -0
- package/dist/agent/tools/logger.js +86 -0
- package/dist/agent/tools/logger.js.map +1 -0
- package/dist/agent/tools/tool-resolver.d.ts +7 -0
- package/dist/agent/tools/tool-resolver.d.ts.map +1 -0
- package/dist/agent/tools/tool-resolver.js +122 -0
- package/dist/agent/tools/tool-resolver.js.map +1 -0
- package/dist/execution/adapters/in-memory-checkpoint.d.ts +11 -0
- package/dist/execution/adapters/in-memory-checkpoint.d.ts.map +1 -0
- package/dist/execution/adapters/in-memory-checkpoint.js +54 -0
- package/dist/execution/adapters/in-memory-checkpoint.js.map +1 -0
- package/dist/execution/compiler.d.ts +8 -0
- package/dist/execution/compiler.d.ts.map +1 -0
- package/dist/execution/compiler.js +50 -0
- package/dist/execution/compiler.js.map +1 -0
- package/dist/execution/controller.d.ts +30 -0
- package/dist/execution/controller.d.ts.map +1 -0
- package/dist/execution/controller.js +80 -0
- package/dist/execution/controller.js.map +1 -0
- package/dist/execution/event-manager.d.ts +29 -0
- package/dist/execution/event-manager.d.ts.map +1 -0
- package/dist/execution/event-manager.js +264 -0
- package/dist/execution/event-manager.js.map +1 -0
- package/dist/execution/index.d.ts +221 -0
- package/dist/execution/index.d.ts.map +1 -0
- package/dist/execution/index.js +638 -0
- package/dist/execution/index.js.map +1 -0
- package/dist/execution/logger.d.ts +46 -0
- package/dist/execution/logger.d.ts.map +1 -0
- package/dist/execution/logger.js +69 -0
- package/dist/execution/logger.js.map +1 -0
- package/dist/execution/node.d.ts +65 -0
- package/dist/execution/node.d.ts.map +1 -0
- package/dist/execution/node.js +250 -0
- package/dist/execution/node.js.map +1 -0
- package/dist/execution/observer.d.ts +38 -0
- package/dist/execution/observer.d.ts.map +1 -0
- package/dist/execution/observer.js +111 -0
- package/dist/execution/observer.js.map +1 -0
- package/dist/execution/planner.d.ts +14 -0
- package/dist/execution/planner.d.ts.map +1 -0
- package/dist/execution/planner.js +43 -0
- package/dist/execution/planner.js.map +1 -0
- package/dist/execution/reducer.d.ts +19 -0
- package/dist/execution/reducer.d.ts.map +1 -0
- package/dist/execution/reducer.js +61 -0
- package/dist/execution/reducer.js.map +1 -0
- package/dist/execution/registry.d.ts +38 -0
- package/dist/execution/registry.d.ts.map +1 -0
- package/dist/execution/registry.js +63 -0
- package/dist/execution/registry.js.map +1 -0
- package/dist/execution/send-api.d.ts +24 -0
- package/dist/execution/send-api.d.ts.map +1 -0
- package/dist/execution/send-api.js +52 -0
- package/dist/execution/send-api.js.map +1 -0
- package/dist/execution/types.parallel.d.ts +61 -0
- package/dist/execution/types.parallel.d.ts.map +1 -0
- package/dist/execution/types.parallel.js +3 -0
- package/dist/execution/types.parallel.js.map +1 -0
- package/dist/execution/visualizer.d.ts +35 -0
- package/dist/execution/visualizer.d.ts.map +1 -0
- package/dist/execution/visualizer.js +131 -0
- package/dist/execution/visualizer.js.map +1 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +78 -0
- package/dist/index.js.map +1 -0
- package/dist/interfaces/index.d.ts +487 -0
- package/dist/interfaces/index.d.ts.map +1 -0
- package/dist/interfaces/index.js +75 -0
- package/dist/interfaces/index.js.map +1 -0
- package/dist/modules/agenda/adapters/node-cron/index.d.ts +17 -0
- package/dist/modules/agenda/adapters/node-cron/index.d.ts.map +1 -0
- package/dist/modules/agenda/adapters/node-cron/index.js +30 -0
- package/dist/modules/agenda/adapters/node-cron/index.js.map +1 -0
- package/dist/modules/agenda/index.d.ts +63 -0
- package/dist/modules/agenda/index.d.ts.map +1 -0
- package/dist/modules/agenda/index.js +141 -0
- package/dist/modules/agenda/index.js.map +1 -0
- package/dist/modules/cli/index.d.ts +13 -0
- package/dist/modules/cli/index.d.ts.map +1 -0
- package/dist/modules/cli/index.js +672 -0
- package/dist/modules/cli/index.js.map +1 -0
- package/dist/modules/embedding/adapters/ai/index.d.ts +29 -0
- package/dist/modules/embedding/adapters/ai/index.d.ts.map +1 -0
- package/dist/modules/embedding/adapters/ai/index.js +58 -0
- package/dist/modules/embedding/adapters/ai/index.js.map +1 -0
- package/dist/modules/embedding/index.d.ts +36 -0
- package/dist/modules/embedding/index.d.ts.map +1 -0
- package/dist/modules/embedding/index.js +60 -0
- package/dist/modules/embedding/index.js.map +1 -0
- package/dist/modules/nlp/engine.d.ts +126 -0
- package/dist/modules/nlp/engine.d.ts.map +1 -0
- package/dist/modules/nlp/engine.js +299 -0
- package/dist/modules/nlp/engine.js.map +1 -0
- package/dist/modules/nlp/index.d.ts +27 -0
- package/dist/modules/nlp/index.d.ts.map +1 -0
- package/dist/modules/nlp/index.js +56 -0
- package/dist/modules/nlp/index.js.map +1 -0
- package/dist/persistence/index.d.ts +12 -0
- package/dist/persistence/index.d.ts.map +1 -0
- package/dist/persistence/index.js +24 -0
- package/dist/persistence/index.js.map +1 -0
- package/dist/persistence/neo4j/driver.d.ts +26 -0
- package/dist/persistence/neo4j/driver.d.ts.map +1 -0
- package/dist/persistence/neo4j/driver.js +64 -0
- package/dist/persistence/neo4j/driver.js.map +1 -0
- package/dist/persistence/neo4j/entity-store.d.ts +15 -0
- package/dist/persistence/neo4j/entity-store.d.ts.map +1 -0
- package/dist/persistence/neo4j/entity-store.js +136 -0
- package/dist/persistence/neo4j/entity-store.js.map +1 -0
- package/dist/persistence/neo4j/execution-tracer.d.ts +19 -0
- package/dist/persistence/neo4j/execution-tracer.d.ts.map +1 -0
- package/dist/persistence/neo4j/execution-tracer.js +166 -0
- package/dist/persistence/neo4j/execution-tracer.js.map +1 -0
- package/dist/persistence/neo4j/memory-adapter.d.ts +35 -0
- package/dist/persistence/neo4j/memory-adapter.d.ts.map +1 -0
- package/dist/persistence/neo4j/memory-adapter.js +252 -0
- package/dist/persistence/neo4j/memory-adapter.js.map +1 -0
- package/dist/persistence/neo4j/petri-checkpoint-adapter.d.ts +22 -0
- package/dist/persistence/neo4j/petri-checkpoint-adapter.d.ts.map +1 -0
- package/dist/persistence/neo4j/petri-checkpoint-adapter.js +141 -0
- package/dist/persistence/neo4j/petri-checkpoint-adapter.js.map +1 -0
- package/dist/pipeline/agent-pipeline.d.ts +99 -0
- package/dist/pipeline/agent-pipeline.d.ts.map +1 -0
- package/dist/pipeline/agent-pipeline.js +356 -0
- package/dist/pipeline/agent-pipeline.js.map +1 -0
- package/dist/routing/checkpoint-adapter.d.ts +30 -0
- package/dist/routing/checkpoint-adapter.d.ts.map +1 -0
- package/dist/routing/checkpoint-adapter.js +83 -0
- package/dist/routing/checkpoint-adapter.js.map +1 -0
- package/dist/routing/documentation-generator.d.ts +47 -0
- package/dist/routing/documentation-generator.d.ts.map +1 -0
- package/dist/routing/documentation-generator.js +320 -0
- package/dist/routing/documentation-generator.js.map +1 -0
- package/dist/routing/index.d.ts +38 -0
- package/dist/routing/index.d.ts.map +1 -0
- package/dist/routing/index.js +375 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/routing/intent-classifier.d.ts +206 -0
- package/dist/routing/intent-classifier.d.ts.map +1 -0
- package/dist/routing/intent-classifier.js +267 -0
- package/dist/routing/intent-classifier.js.map +1 -0
- package/dist/routing/matrix.d.ts +6 -0
- package/dist/routing/matrix.d.ts.map +1 -0
- package/dist/routing/matrix.js +131 -0
- package/dist/routing/matrix.js.map +1 -0
- package/dist/routing/orchestrator.d.ts +87 -0
- package/dist/routing/orchestrator.d.ts.map +1 -0
- package/dist/routing/orchestrator.js +425 -0
- package/dist/routing/orchestrator.js.map +1 -0
- package/dist/routing/postgres-checkpoint-adapter.d.ts +32 -0
- package/dist/routing/postgres-checkpoint-adapter.d.ts.map +1 -0
- package/dist/routing/postgres-checkpoint-adapter.js +167 -0
- package/dist/routing/postgres-checkpoint-adapter.js.map +1 -0
- package/dist/routing/redis-checkpoint-adapter.d.ts +34 -0
- package/dist/routing/redis-checkpoint-adapter.d.ts.map +1 -0
- package/dist/routing/redis-checkpoint-adapter.js +170 -0
- package/dist/routing/redis-checkpoint-adapter.js.map +1 -0
- package/dist/routing/types.d.ts +49 -0
- package/dist/routing/types.d.ts.map +1 -0
- package/dist/routing/types.js +3 -0
- package/dist/routing/types.js.map +1 -0
- package/dist/types/agent.d.ts +289 -0
- package/dist/types/agent.d.ts.map +1 -0
- package/dist/types/agent.js +78 -0
- package/dist/types/agent.js.map +1 -0
- package/dist/types/index.d.ts +343 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +3 -0
- package/dist/types/index.js.map +1 -0
- package/dist/utils/generate-action-schema.d.ts +4 -0
- package/dist/utils/generate-action-schema.d.ts.map +1 -0
- package/dist/utils/generate-action-schema.js +46 -0
- package/dist/utils/generate-action-schema.js.map +1 -0
- package/dist/utils/header-builder.d.ts +12 -0
- package/dist/utils/header-builder.d.ts.map +1 -0
- package/dist/utils/header-builder.js +35 -0
- package/dist/utils/header-builder.js.map +1 -0
- package/dist/utils/logger.d.ts +27 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +45 -0
- package/dist/utils/logger.js.map +1 -0
- package/docs/.gitbook/assets/image (1).png +0 -0
- package/docs/.gitbook/assets/image (2).png +0 -0
- package/docs/.gitbook/assets/image (3).png +0 -0
- package/docs/.gitbook/assets/image (4).png +0 -0
- package/docs/.gitbook/assets/image (5).png +0 -0
- package/docs/.gitbook/assets/image (6).png +0 -0
- package/docs/.gitbook/assets/image.png +0 -0
- package/docs/README.md +57 -0
- package/docs/SUMMARY.md +34 -0
- package/docs/cas-dusages.md +69 -0
- package/docs/cli/README.md +65 -0
- package/docs/concepts-cles.md +50 -0
- package/docs/core/architecture.md +87 -0
- package/docs/core/benchmark.md +59 -0
- package/docs/core/checkpoint.md +72 -0
- package/docs/core/documentation.md +55 -0
- package/docs/core/graphcontroller.md +63 -0
- package/docs/core/graphflow.md +137 -0
- package/docs/core/introduction.md +41 -0
- package/docs/core/les-evenements.md +95 -0
- package/docs/modules/agenda/README.md +63 -0
- package/docs/modules/agenda/interface-iagenda.md +170 -0
- package/docs/modules/agenda/les-adaptateurs/README.md +237 -0
- package/docs/modules/agenda/les-adaptateurs/nodecronadapter.md +91 -0
- package/docs/modules/introduction.md +55 -0
- package/docs/modules/les-adaptateurs.md +52 -0
- package/docs/modules/memoire/README.md +68 -0
- package/docs/modules/memoire/interface-imemory.md +183 -0
- package/docs/modules/memoire/les-adaptateurs/README.md +209 -0
- package/docs/modules/memoire/les-adaptateurs/inmemoryadapter.md +110 -0
- package/docs/modules/memoire/les-adaptateurs/meilisearchadapter.md +147 -0
- package/docs/modules/memoire/les-adaptateurs/redisadapter.md +212 -0
- package/docs/modules/nlp/README.md +44 -0
- package/docs/philosophie.md +51 -0
- package/docs/tutoriels/ajouter-des-conditions.md +150 -0
- package/docs/tutoriels/branching.md +194 -0
- package/docs/tutoriels/checkpoint-usage.md +99 -0
- package/docs/tutoriels/creer-agent-onchain.md +1041 -0
- package/docs/tutoriels/creer-un-agent.md +108 -0
- package/docs/tutoriels/creer-un-graphe-simple.md +92 -0
- package/docs/tutoriels/gerer-les-erreurs.md +124 -0
- package/docs/tutoriels/pour-commencer.md +73 -0
- package/docs/tutoriels/retry.md +166 -0
- package/execution/adapters/in-memory-checkpoint.ts +35 -0
- package/execution/compiler.ts +47 -0
- package/execution/controller.ts +84 -0
- package/execution/event-manager.ts +331 -0
- package/execution/index.ts +800 -0
- package/execution/logger.ts +70 -0
- package/execution/node.ts +315 -0
- package/execution/observer.ts +192 -0
- package/execution/planner.ts +40 -0
- package/execution/reducer.ts +73 -0
- package/execution/registry.ts +86 -0
- package/execution/send-api.ts +58 -0
- package/execution/types.parallel.ts +81 -0
- package/execution/visualizer.ts +158 -0
- package/index.ts +55 -465
- package/interfaces/index.ts +597 -0
- package/modules/agenda/adapters/node-cron/index.ts +25 -0
- package/modules/agenda/index.ts +146 -0
- package/modules/cli/index.ts +580 -0
- package/modules/embedding/adapters/ai/index.ts +42 -0
- package/modules/embedding/index.ts +45 -0
- package/modules/nlp/engine.ts +324 -0
- package/modules/nlp/index.ts +45 -0
- package/package.json +81 -9
- package/persistence/index.ts +27 -0
- package/persistence/neo4j/driver.ts +34 -0
- package/persistence/neo4j/entity-store.ts +141 -0
- package/persistence/neo4j/execution-tracer.ts +194 -0
- package/persistence/neo4j/memory-adapter.ts +281 -0
- package/persistence/neo4j/petri-checkpoint-adapter.ts +153 -0
- package/pipeline/agent-pipeline.ts +426 -0
- package/routing/checkpoint-adapter.ts +79 -0
- package/routing/documentation-generator.ts +358 -0
- package/routing/index.ts +459 -0
- package/routing/intent-classifier.ts +360 -0
- package/routing/matrix.ts +138 -0
- package/routing/orchestrator.ts +498 -0
- package/routing/patterns/data-extraction.json +79 -0
- package/routing/patterns/human-approval.json +64 -0
- package/routing/patterns/rag-search.json +68 -0
- package/routing/postgres-checkpoint-adapter.ts +172 -0
- package/routing/redis-checkpoint-adapter.ts +187 -0
- package/routing/types.ts +59 -0
- package/routing/web-server.ts +260 -0
- package/scripts/generate-petri-docs.ts +70 -0
- package/scripts/get-gmail-token.js +65 -0
- package/scripts/get-gmail-token.ts +65 -0
- package/test/agent/agent.test.ts +92 -0
- package/test/agent/clone.test.ts +143 -0
- package/test/agent/cognitive-handler.test.ts +78 -0
- package/test/agent/entity-store.test.ts +80 -0
- package/test/agent/generic-executor.test.ts +230 -0
- package/test/agent/handoff.test.ts +163 -0
- package/test/agent/llm-factory.test.ts +40 -0
- package/test/agent/orchestrator.test.ts +156 -0
- package/test/agent/registry.test.ts +97 -0
- package/test/agent/tools.test.ts +267 -0
- package/test/execution/checkpoint.test.ts +811 -0
- package/test/execution/controller.test.ts +236 -0
- package/test/execution/event-manager.test.ts +118 -0
- package/test/execution/index.test.ts +690 -0
- package/test/execution/node.test.ts +464 -0
- package/test/execution/observer.test.ts +393 -0
- package/test/execution/parallel.test.ts +135 -0
- package/test/execution/plan-llm-integration.test.ts +290 -0
- package/test/execution/plan-real-onchain.test.ts +226 -0
- package/test/execution/send-api.test.ts +121 -0
- package/test/modules/agenda/node-cron.test.ts +307 -0
- package/test/modules/cli/index.test.ts +125 -0
- package/test/persistence/neo4j-execution-tracer.test.ts +96 -0
- package/test/persistence/neo4j-memory-adapter.test.ts +107 -0
- package/test/persistence/neo4j-petri-checkpoint.test.ts +89 -0
- package/test/pipeline/agent-pipeline.test.ts +118 -0
- package/test/routing/checkpoint-persistence.test.ts +58 -0
- package/test/routing/documentation-generator.test.ts +76 -0
- package/test/routing/integration.test.ts +261 -0
- package/test/routing/intent-classifier.test.ts +102 -0
- package/test/routing/petri.test.ts +156 -0
- package/test/routing/real-llm.test.ts +260 -0
- package/test-petri-features.ts +218 -0
- package/test-pipeline-api.ts +163 -0
- package/tsconfig.json +30 -108
- package/types/agent.ts +296 -0
- package/types/index.ts +387 -0
- package/utils/generate-action-schema.ts +47 -0
- package/utils/header-builder.ts +40 -0
- package/utils/logger.ts +40 -0
- package/package copy.json +0 -21
- package/types.ts +0 -62
- package/utils/executor.ts +0 -42
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { AgentContext } from "../../types/agent";
|
|
3
|
+
import { AgentLogger, LogLevel } from "../tools/logger";
|
|
4
|
+
|
|
5
|
+
const DEFAULT_DYNAMIC_GOAL_PROMPT = `Contexte actuel:
|
|
6
|
+
- Input utilisateur: {input}
|
|
7
|
+
- Actions déjà exécutées: {executedActions}
|
|
8
|
+
- Résultats disponibles: {results}
|
|
9
|
+
- Goal original: {originalGoal}
|
|
10
|
+
|
|
11
|
+
Réponds uniquement avec le format JSON: {"goal": "votre sous-goal en 1-2 phrases"}
|
|
12
|
+
Le sous-goal doit être la prochaine étape à accomplir.`;
|
|
13
|
+
|
|
14
|
+
const DEFAULT_DYNAMIC_NEXT_PROMPT = `Contexte actuel:
|
|
15
|
+
- État actuel: {currentState}
|
|
16
|
+
- Input utilisateur: {input}
|
|
17
|
+
- Goal: {goal}
|
|
18
|
+
- Actions exécutées: {executedActions}
|
|
19
|
+
- Résultats disponibles: {results}
|
|
20
|
+
- Nombre d'itérations: {iteration}
|
|
21
|
+
|
|
22
|
+
Nodes cognitifs disponibles:
|
|
23
|
+
- defineGoal: Déterminer le goal dynamique
|
|
24
|
+
- think: Analyser le contexte et décider des actions
|
|
25
|
+
- execute: Exécuter les outils/actions
|
|
26
|
+
- plan: Planifier les étapes suivantes
|
|
27
|
+
- schedule: Planifier une tâche pour plus tard (utilise le module Agenda)
|
|
28
|
+
- reply: Répondre à l'utilisateur
|
|
29
|
+
- ask: Poser une question clarificatrice
|
|
30
|
+
- end: Terminer le workflow
|
|
31
|
+
|
|
32
|
+
Choisis le prochain node le plus approprié.
|
|
33
|
+
Réponds uniquement: {"next": "nom_du_node", "reason": "explication courte"}`;
|
|
34
|
+
|
|
35
|
+
export const COGNITIVE_NODES = ["defineGoal", "think", "execute", "plan", "schedule", "reply", "ask", "end"];
|
|
36
|
+
|
|
37
|
+
type LLM = {
|
|
38
|
+
generate: (messages: { system: string; user: string }, schema: any) => Promise<{ object: any }>;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export class CognitiveHandler {
|
|
42
|
+
private dynamicGoalEnabled: boolean;
|
|
43
|
+
private dynamicNextEnabled: boolean;
|
|
44
|
+
private goalPromptTemplate: string;
|
|
45
|
+
private nextPromptTemplate: string;
|
|
46
|
+
private currentGoal: string;
|
|
47
|
+
private currentState: string;
|
|
48
|
+
|
|
49
|
+
constructor(
|
|
50
|
+
private llm: LLM,
|
|
51
|
+
private logger: AgentLogger,
|
|
52
|
+
private options: {
|
|
53
|
+
dynamicGoal?: boolean;
|
|
54
|
+
goalPrompt?: string;
|
|
55
|
+
initialGoal?: string;
|
|
56
|
+
dynamicNext?: boolean;
|
|
57
|
+
nextPrompt?: string;
|
|
58
|
+
} = {}
|
|
59
|
+
) {
|
|
60
|
+
this.dynamicGoalEnabled = options.dynamicGoal ?? false;
|
|
61
|
+
this.dynamicNextEnabled = options.dynamicNext ?? false;
|
|
62
|
+
this.goalPromptTemplate = options.goalPrompt ?? DEFAULT_DYNAMIC_GOAL_PROMPT;
|
|
63
|
+
this.nextPromptTemplate = options.nextPrompt ?? DEFAULT_DYNAMIC_NEXT_PROMPT;
|
|
64
|
+
this.currentGoal = options.initialGoal ?? "";
|
|
65
|
+
this.currentState = "defineGoal";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
setGoal(goal: string): void {
|
|
69
|
+
this.currentGoal = goal;
|
|
70
|
+
this.log("info", `Goal adjusted: ${goal}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
getCurrentGoal(): string {
|
|
74
|
+
return this.currentGoal;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
getCurrentState(): string {
|
|
78
|
+
return this.currentState;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
setCurrentState(state: string): void {
|
|
82
|
+
if (COGNITIVE_NODES.includes(state)) {
|
|
83
|
+
this.currentState = state;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
getAvailableNodes(): string[] {
|
|
88
|
+
return COGNITIVE_NODES;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
setEnabled(opts: { dynamicGoal?: boolean; dynamicNext?: boolean }): void {
|
|
92
|
+
if (opts.dynamicGoal !== undefined) this.dynamicGoalEnabled = opts.dynamicGoal;
|
|
93
|
+
if (opts.dynamicNext !== undefined) this.dynamicNextEnabled = opts.dynamicNext;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async computeGoal(context: AgentContext): Promise<string> {
|
|
97
|
+
if (!this.dynamicGoalEnabled) return this.currentGoal;
|
|
98
|
+
|
|
99
|
+
this.log("thinking", "Computing dynamic goal...");
|
|
100
|
+
|
|
101
|
+
const executedTools = context.executedActions.map(a => a.name);
|
|
102
|
+
const results = context.executedActions
|
|
103
|
+
.map(a => `${a.name}: ${JSON.stringify(a.result)}`)
|
|
104
|
+
.join("\n");
|
|
105
|
+
|
|
106
|
+
const prompt = this.goalPromptTemplate
|
|
107
|
+
.replace("{input}", context.input.raw)
|
|
108
|
+
.replace("{executedActions}", executedTools.join(", ") || "Aucune")
|
|
109
|
+
.replace("{results}", results || "Aucun résultat")
|
|
110
|
+
.replace("{originalGoal}", this.currentGoal);
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
const result = await this.llm.generate(
|
|
114
|
+
{
|
|
115
|
+
system: "Tu dois répondre au format JSON exact: {\"goal\": \"votre texte\"}. Sois concis.",
|
|
116
|
+
user: prompt,
|
|
117
|
+
},
|
|
118
|
+
z.object({
|
|
119
|
+
goal: z.string(),
|
|
120
|
+
}).transform(v => ({ goal: v.goal || "Accomplir la tâche" }))
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
const computedGoal = result.object?.goal || this.currentGoal;
|
|
124
|
+
this.currentGoal = computedGoal;
|
|
125
|
+
this.log("info", `Dynamic goal: ${computedGoal}`);
|
|
126
|
+
return computedGoal;
|
|
127
|
+
} catch (error) {
|
|
128
|
+
this.log("warning", `Failed to compute dynamic goal: ${error}, falling back to original`);
|
|
129
|
+
return this.currentGoal;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async computeNext(context: AgentContext, currentState: string, iteration: number): Promise<string> {
|
|
134
|
+
if (!this.dynamicNextEnabled) {
|
|
135
|
+
return this.getDefaultNextState(currentState, context);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
this.log("thinking", `Computing next state from "${currentState}"...`);
|
|
139
|
+
|
|
140
|
+
const executedTools = context.executedActions.map(a => a.name);
|
|
141
|
+
const results = context.executedActions
|
|
142
|
+
.map(a => `${a.name}: ${JSON.stringify(a.result)}`)
|
|
143
|
+
.join("\n");
|
|
144
|
+
|
|
145
|
+
const prompt = this.nextPromptTemplate
|
|
146
|
+
.replace("{currentState}", currentState)
|
|
147
|
+
.replace("{input}", context.input.raw)
|
|
148
|
+
.replace("{goal}", this.currentGoal)
|
|
149
|
+
.replace("{executedActions}", executedTools.join(", ") || "Aucune")
|
|
150
|
+
.replace("{results}", results || "Aucun résultat")
|
|
151
|
+
.replace("{iteration}", String(iteration));
|
|
152
|
+
|
|
153
|
+
try {
|
|
154
|
+
const result = await this.llm.generate(
|
|
155
|
+
{
|
|
156
|
+
system: "Tu es un assistant qui détermine le prochain état cognitif. Réponds uniquement en JSON.",
|
|
157
|
+
user: prompt,
|
|
158
|
+
},
|
|
159
|
+
z.object({
|
|
160
|
+
next: z.string(),
|
|
161
|
+
reason: z.string().optional(),
|
|
162
|
+
}).transform(v => ({
|
|
163
|
+
next: COGNITIVE_NODES.includes(v.next) ? v.next : "think",
|
|
164
|
+
reason: v.reason
|
|
165
|
+
}))
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
const nextState = result.object.next;
|
|
169
|
+
this.currentState = nextState;
|
|
170
|
+
this.log("info", `Next state: ${nextState}${result.object.reason ? ` (${result.object.reason})` : ''}`);
|
|
171
|
+
return nextState;
|
|
172
|
+
} catch (error) {
|
|
173
|
+
this.log("warning", `Failed to compute next state: ${error}, using default`);
|
|
174
|
+
return this.getDefaultNextState(currentState, context);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private getDefaultNextState(currentState: string, context: AgentContext): string {
|
|
179
|
+
switch (currentState) {
|
|
180
|
+
case "defineGoal": return "think";
|
|
181
|
+
case "think": return context.actions && context.actions.length > 0 ? "execute" : "reply";
|
|
182
|
+
case "execute": return context.executedActions && context.executedActions.length > 0 ? "think" : "reply";
|
|
183
|
+
case "plan": return "think";
|
|
184
|
+
case "schedule": return "think";
|
|
185
|
+
case "reply": return "end";
|
|
186
|
+
case "ask": return "think";
|
|
187
|
+
default: return "think";
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private log(type: "info" | "success" | "warning" | "error" | "thinking", message: string) {
|
|
192
|
+
const levelMap: Record<string, LogLevel> = {
|
|
193
|
+
info: "info", success: "info", warning: "warn", error: "error", thinking: "info",
|
|
194
|
+
};
|
|
195
|
+
this.logger.log(levelMap[type], "cognitive", message);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { CognitiveHandler, COGNITIVE_NODES } from "./cognitive-handler";
|
package/agent/handoff.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { GraphFlow } from "../execution/index";
|
|
3
|
+
import { AgentRegistry } from "./registry";
|
|
4
|
+
import { AgentLogger } from "./tools/logger";
|
|
5
|
+
|
|
6
|
+
export function createHandoffTool(registry?: AgentRegistry): GraphFlow<any> {
|
|
7
|
+
return new GraphFlow({
|
|
8
|
+
name: "handoff",
|
|
9
|
+
schema: z.object({
|
|
10
|
+
targetAgent: z.string().describe("Nom de l'agent cible (enregistré dans le registry)"),
|
|
11
|
+
task: z.string().describe("Description de la tâche à déléguer"),
|
|
12
|
+
contextData: z.string().optional().describe("Données de contexte supplémentaires en JSON"),
|
|
13
|
+
}),
|
|
14
|
+
context: { targetAgent: "", task: "", contextData: "" },
|
|
15
|
+
nodes: [
|
|
16
|
+
{
|
|
17
|
+
name: "handoff",
|
|
18
|
+
execute: async (ctx: any) => {
|
|
19
|
+
const { targetAgent, task } = ctx;
|
|
20
|
+
if (!targetAgent) {
|
|
21
|
+
throw new Error("Handoff: targetAgent requis");
|
|
22
|
+
}
|
|
23
|
+
if (registry && !registry.has(targetAgent)) {
|
|
24
|
+
const logger = new AgentLogger();
|
|
25
|
+
logger.warn("handoff", `Agent "${targetAgent}" non trouvé dans le registry, handoff ignoré`);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
ctx._handoff = {
|
|
29
|
+
goto: targetAgent,
|
|
30
|
+
graph: "PARENT",
|
|
31
|
+
update: { handoffTask: task, handoffFrom: ctx._agentName || "unknown" },
|
|
32
|
+
metadata: {
|
|
33
|
+
sourceAgent: ctx._agentName || "unknown",
|
|
34
|
+
handoffTime: Date.now(),
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
},
|
|
38
|
+
next: [],
|
|
39
|
+
},
|
|
40
|
+
],
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createCommand(
|
|
45
|
+
goto: string,
|
|
46
|
+
update?: Record<string, any>,
|
|
47
|
+
metadata?: Record<string, any>
|
|
48
|
+
) {
|
|
49
|
+
return {
|
|
50
|
+
goto,
|
|
51
|
+
update,
|
|
52
|
+
graph: "PARENT" as const,
|
|
53
|
+
metadata: {
|
|
54
|
+
...metadata,
|
|
55
|
+
timestamp: Date.now(),
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { LLMConfig, LLMProvider, PromptInput } from "@/types/agent";
|
|
3
|
+
import { openai } from "@ai-sdk/openai";
|
|
4
|
+
import { generateObject } from "ai";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_GROQ_MODEL = "llama-3.1-8b-instant";
|
|
8
|
+
|
|
9
|
+
const GROQ_FALLBACK_MODELS = [
|
|
10
|
+
"allam-2-7b",
|
|
11
|
+
"groq/compound-mini",
|
|
12
|
+
"groq/compound",
|
|
13
|
+
"qwen/qwen3-32b",
|
|
14
|
+
"llama-3.3-70b-versatile",
|
|
15
|
+
"meta-llama/llama-4-scout-17b-16e-instruct",
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
const DEFAULT_FALLBACK_MODEL = "llama-3.1-8b-instant";
|
|
19
|
+
|
|
20
|
+
interface LLMUsage {
|
|
21
|
+
promptTokens: number;
|
|
22
|
+
completionTokens: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface LLMResult {
|
|
26
|
+
object: any;
|
|
27
|
+
usage?: LLMUsage;
|
|
28
|
+
duration: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface LLMInstance {
|
|
32
|
+
generate: (prompt: string | PromptInput, schema: z.ZodType<any>) => Promise<LLMResult>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function createOpenAICompatibleLLM(
|
|
36
|
+
baseUrl: string,
|
|
37
|
+
apiKey: string,
|
|
38
|
+
model: string,
|
|
39
|
+
providerName: string
|
|
40
|
+
): LLMInstance {
|
|
41
|
+
return {
|
|
42
|
+
generate: async (
|
|
43
|
+
prompt: string | PromptInput,
|
|
44
|
+
schema: z.ZodType<any>
|
|
45
|
+
) => {
|
|
46
|
+
const t0 = performance.now();
|
|
47
|
+
const userPrompt = typeof prompt === "string" ? prompt : prompt.user;
|
|
48
|
+
const systemPrompt = typeof prompt === "string" ? undefined : prompt.system;
|
|
49
|
+
|
|
50
|
+
const response = await fetch(`${baseUrl}/chat/completions`, {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: {
|
|
53
|
+
"Content-Type": "application/json",
|
|
54
|
+
"Authorization": `Bearer ${apiKey}`,
|
|
55
|
+
},
|
|
56
|
+
body: JSON.stringify({
|
|
57
|
+
model: model,
|
|
58
|
+
messages: [
|
|
59
|
+
...(systemPrompt ? [{ role: "system", content: systemPrompt }] : []),
|
|
60
|
+
{ role: "user", content: userPrompt },
|
|
61
|
+
],
|
|
62
|
+
temperature: 0.7,
|
|
63
|
+
max_tokens: 4096,
|
|
64
|
+
response_format: { type: "json_object" },
|
|
65
|
+
}),
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
if (!response.ok) {
|
|
69
|
+
const errorText = await response.text();
|
|
70
|
+
throw new Error(`${providerName} API error (${response.status}): ${errorText}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const data = await response.json();
|
|
74
|
+
const duration = performance.now() - t0;
|
|
75
|
+
const usage: LLMUsage | undefined = data.usage
|
|
76
|
+
? { promptTokens: data.usage.prompt_tokens ?? 0, completionTokens: data.usage.completion_tokens ?? 0 }
|
|
77
|
+
: undefined;
|
|
78
|
+
let content = data.choices?.[0]?.message?.content || "";
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(content);
|
|
82
|
+
const validated = schema.parse(parsed);
|
|
83
|
+
return { object: validated, usage, duration };
|
|
84
|
+
} catch (e: any) {
|
|
85
|
+
console.log(chalk.yellow(`[WARN] ${providerName} JSON parse error: ${e.message}`));
|
|
86
|
+
return { object: { actions: [], response: content.substring(0, 200) }, usage, duration };
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function createLLMWithFallback(
|
|
93
|
+
baseUrl: string,
|
|
94
|
+
apiKey: string,
|
|
95
|
+
primaryModel: string,
|
|
96
|
+
fallbackModels: string[],
|
|
97
|
+
providerName: string
|
|
98
|
+
): LLMInstance {
|
|
99
|
+
const allModels = [primaryModel, ...fallbackModels];
|
|
100
|
+
let currentModelIndex = 0;
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
generate: async (prompt: string | PromptInput, schema: z.ZodType<any>) => {
|
|
104
|
+
let lastError: Error | null = null;
|
|
105
|
+
|
|
106
|
+
for (const model of allModels.slice(currentModelIndex)) {
|
|
107
|
+
try {
|
|
108
|
+
// model trying info suppressed for cleaner CLI
|
|
109
|
+
const llm = createOpenAICompatibleLLM(baseUrl, apiKey, model, providerName);
|
|
110
|
+
const result = await llm.generate(prompt, schema);
|
|
111
|
+
|
|
112
|
+
if (result?.object) {
|
|
113
|
+
currentModelIndex = allModels.indexOf(model);
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
} catch (error: any) {
|
|
117
|
+
lastError = error;
|
|
118
|
+
|
|
119
|
+
const isRateLimit = error.message?.includes("429") ||
|
|
120
|
+
error.message?.includes("rate limit");
|
|
121
|
+
|
|
122
|
+
if (isRateLimit) {
|
|
123
|
+
console.log(chalk.yellow(`[WARN] Rate limit for ${model}, trying fallback...`));
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
console.log(chalk.yellow(`[WARN] ${providerName} error: ${error.message}`));
|
|
128
|
+
|
|
129
|
+
if (error.message?.includes("500") || error.message?.includes("502") || error.message?.includes("503")) {
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
throw lastError || new Error(`All ${providerName} models failed`);
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Factory class for creating Language Model instances based on configuration
|
|
144
|
+
* @class LLMFactory
|
|
145
|
+
*/
|
|
146
|
+
export class LLMFactory {
|
|
147
|
+
/**
|
|
148
|
+
* Creates an LLM instance based on the provided configuration
|
|
149
|
+
* @static
|
|
150
|
+
* @param {LLMConfig} config - Configuration for the LLM
|
|
151
|
+
* @returns {Object} An object with a generate method for interacting with the LLM
|
|
152
|
+
* @throws {Error} When an unsupported provider is specified or custom provider lacks required function
|
|
153
|
+
*/
|
|
154
|
+
static createLLM(config: LLMConfig) {
|
|
155
|
+
switch (config.provider) {
|
|
156
|
+
case "openai":
|
|
157
|
+
return {
|
|
158
|
+
generate: async (
|
|
159
|
+
prompt: string | PromptInput,
|
|
160
|
+
schema: z.ZodType<any>
|
|
161
|
+
) => {
|
|
162
|
+
const t0 = performance.now();
|
|
163
|
+
const result = await generateObject({
|
|
164
|
+
model: openai(config.model),
|
|
165
|
+
temperature: config.temperature ?? 0.7,
|
|
166
|
+
maxTokens: config.maxTokens,
|
|
167
|
+
prompt: typeof prompt === "string" ? prompt : prompt.user,
|
|
168
|
+
system: typeof prompt === "string" ? undefined : prompt.system,
|
|
169
|
+
schema,
|
|
170
|
+
});
|
|
171
|
+
const duration = performance.now() - t0;
|
|
172
|
+
return {
|
|
173
|
+
object: result.object,
|
|
174
|
+
usage: result.usage
|
|
175
|
+
? { promptTokens: result.usage.promptTokens ?? 0, completionTokens: result.usage.completionTokens ?? 0 }
|
|
176
|
+
: undefined,
|
|
177
|
+
duration,
|
|
178
|
+
};
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
case "ollama":
|
|
182
|
+
return {
|
|
183
|
+
generate: async (
|
|
184
|
+
prompt: string | PromptInput,
|
|
185
|
+
schema: z.ZodType<any>
|
|
186
|
+
) => {
|
|
187
|
+
const t0 = performance.now();
|
|
188
|
+
const baseUrl = config.baseUrl || "http://localhost:11434";
|
|
189
|
+
const userPrompt = typeof prompt === "string" ? prompt : prompt.user;
|
|
190
|
+
const systemPrompt = typeof prompt === "string" ? undefined : prompt.system;
|
|
191
|
+
|
|
192
|
+
const response = await fetch(`${baseUrl}/api/chat`, {
|
|
193
|
+
method: "POST",
|
|
194
|
+
headers: { "Content-Type": "application/json" },
|
|
195
|
+
body: JSON.stringify({
|
|
196
|
+
model: config.model,
|
|
197
|
+
messages: [
|
|
198
|
+
...(systemPrompt ? [{ role: "system", content: systemPrompt }] : []),
|
|
199
|
+
{ role: "user", content: userPrompt + "\n\nImportant: Respond ONLY with valid JSON matching the required schema." },
|
|
200
|
+
],
|
|
201
|
+
stream: false,
|
|
202
|
+
}),
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
if (!response.ok) {
|
|
206
|
+
const errorText = await response.text();
|
|
207
|
+
throw new Error(`Ollama API error (${response.status}): ${errorText}`);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const data = await response.json();
|
|
211
|
+
const duration = performance.now() - t0;
|
|
212
|
+
const usage: LLMUsage | undefined = data.usage
|
|
213
|
+
? { promptTokens: data.usage.prompt_eval_count ?? 0, completionTokens: data.usage.eval_count ?? 0 }
|
|
214
|
+
: undefined;
|
|
215
|
+
let content = data.message?.content || "";
|
|
216
|
+
|
|
217
|
+
if (data.message?.thinking) {
|
|
218
|
+
console.log(chalk.cyan('\n[REASONING] ') + data.message.thinking.substring(0, 500) + '...\n');
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
let parsed: any;
|
|
222
|
+
const firstBrace = content.indexOf('{');
|
|
223
|
+
|
|
224
|
+
const errResult = (obj: any) => ({ object: obj, usage, duration });
|
|
225
|
+
|
|
226
|
+
if (firstBrace !== -1) {
|
|
227
|
+
let endBrace = -1;
|
|
228
|
+
let braceCount = 0;
|
|
229
|
+
for (let i = firstBrace; i < content.length; i++) {
|
|
230
|
+
if (content[i] === '{') braceCount++;
|
|
231
|
+
else if (content[i] === '}') {
|
|
232
|
+
braceCount--;
|
|
233
|
+
if (braceCount === 0) {
|
|
234
|
+
endBrace = i;
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (endBrace !== -1) {
|
|
241
|
+
const jsonStr = content.substring(firstBrace, endBrace + 1);
|
|
242
|
+
try {
|
|
243
|
+
parsed = JSON.parse(jsonStr);
|
|
244
|
+
} catch (e: any) {
|
|
245
|
+
console.log(chalk.yellow('[WARN] Truncated JSON, attempting repair...'));
|
|
246
|
+
const repaired = jsonStr.replace(/,(\s*[}\]])/g, '$1').replace(/([}\]])(\s*[,\n])/g, '$1$2');
|
|
247
|
+
try {
|
|
248
|
+
parsed = JSON.parse(repaired);
|
|
249
|
+
} catch {
|
|
250
|
+
console.log(chalk.yellow('[WARN] Repair failed, extracting partial actions...'));
|
|
251
|
+
const actionMatches = jsonStr.matchAll(/"name"\s*:\s*"([^"]+)"/g);
|
|
252
|
+
const actions = [];
|
|
253
|
+
for (const match of actionMatches) {
|
|
254
|
+
actions.push({ name: match[1], parameters: {} });
|
|
255
|
+
}
|
|
256
|
+
if (actions.length > 0) {
|
|
257
|
+
parsed = { actions, response: "Partial response" };
|
|
258
|
+
} else {
|
|
259
|
+
return errResult({ actions: [], response: content.substring(0, 200) });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
} else {
|
|
264
|
+
console.log(chalk.yellow('[WARN] Incomplete JSON, returning empty response'));
|
|
265
|
+
return errResult({ actions: [], response: content.substring(0, 100) });
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
return errResult({ actions: [], response: content.substring(0, 200) });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const validated = schema.parse(parsed);
|
|
272
|
+
return { object: validated, usage, duration };
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
case "groq":
|
|
276
|
+
return createLLMWithFallback(
|
|
277
|
+
"https://api.groq.com/openai/v1",
|
|
278
|
+
config.apiKey || "",
|
|
279
|
+
config.model || DEFAULT_GROQ_MODEL,
|
|
280
|
+
GROQ_FALLBACK_MODELS,
|
|
281
|
+
"Groq"
|
|
282
|
+
);
|
|
283
|
+
case "openrouter":
|
|
284
|
+
return createLLMWithFallback(
|
|
285
|
+
"https://openrouter.ai/api/v1",
|
|
286
|
+
config.apiKey || "",
|
|
287
|
+
config.model || "google/gemini-flash-1.5",
|
|
288
|
+
[],
|
|
289
|
+
"OpenRouter"
|
|
290
|
+
);
|
|
291
|
+
case "google":
|
|
292
|
+
return {
|
|
293
|
+
generate: async (prompt: string | PromptInput, schema: z.ZodType<any>) => {
|
|
294
|
+
const t0 = performance.now();
|
|
295
|
+
const userPrompt = typeof prompt === "string" ? prompt : prompt.user;
|
|
296
|
+
const systemPrompt = typeof prompt === "string" ? undefined : prompt.system;
|
|
297
|
+
const apiKey = config.apiKey || "";
|
|
298
|
+
const model = config.model || "gemini-flash-1.5";
|
|
299
|
+
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
|
|
300
|
+
const body = {
|
|
301
|
+
contents: [{
|
|
302
|
+
parts: [{ text: `${systemPrompt ? `System: ${systemPrompt}\n\n` : ""}${userPrompt}` }]
|
|
303
|
+
}],
|
|
304
|
+
generationConfig: { temperature: 0.7, maxOutputTokens: 4096 }
|
|
305
|
+
};
|
|
306
|
+
const response = await fetch(url, {
|
|
307
|
+
method: "POST",
|
|
308
|
+
headers: { "Content-Type": "application/json" },
|
|
309
|
+
body: JSON.stringify(body)
|
|
310
|
+
});
|
|
311
|
+
if (!response.ok) {
|
|
312
|
+
const errorText = await response.text();
|
|
313
|
+
throw new Error(`Google API error (${response.status}): ${errorText}`);
|
|
314
|
+
}
|
|
315
|
+
const data = await response.json();
|
|
316
|
+
const duration = performance.now() - t0;
|
|
317
|
+
const usage: LLMUsage | undefined = data.usageMetadata
|
|
318
|
+
? {
|
|
319
|
+
promptTokens: data.usageMetadata.promptTokenCount ?? 0,
|
|
320
|
+
completionTokens: data.usageMetadata.candidatesTokenCount ?? 0,
|
|
321
|
+
}
|
|
322
|
+
: undefined;
|
|
323
|
+
const text = data.candidates?.[0]?.content?.parts?.[0]?.text || "";
|
|
324
|
+
try {
|
|
325
|
+
const parsed = JSON.parse(text);
|
|
326
|
+
return { object: schema.parse(parsed), usage, duration };
|
|
327
|
+
} catch {
|
|
328
|
+
return { object: { actions: [], response: text.substring(0, 200) }, usage, duration };
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
case "custom":
|
|
333
|
+
if (!config.customCall) {
|
|
334
|
+
throw new Error("Custom LLM provider requires a customCall function");
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
generate: config.customCall,
|
|
338
|
+
};
|
|
339
|
+
default:
|
|
340
|
+
throw new Error(`Unsupported LLM provider: ${config.provider}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { AgentContext } from "../types/agent";
|
|
2
|
+
import { Agent } from "./agent";
|
|
3
|
+
import { AgentRegistry } from "./registry";
|
|
4
|
+
|
|
5
|
+
export type OrchestratorConfig = {
|
|
6
|
+
mainAgent: Agent;
|
|
7
|
+
registry: AgentRegistry;
|
|
8
|
+
autoHandoff?: boolean;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export class OrchestratorAgent {
|
|
12
|
+
private mainAgent: Agent;
|
|
13
|
+
private registry: AgentRegistry;
|
|
14
|
+
private autoHandoff: boolean;
|
|
15
|
+
|
|
16
|
+
constructor(config: OrchestratorConfig) {
|
|
17
|
+
this.mainAgent = config.mainAgent;
|
|
18
|
+
this.registry = config.registry;
|
|
19
|
+
this.autoHandoff = config.autoHandoff ?? true;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async process(input: string): Promise<AgentContext> {
|
|
23
|
+
const ctx = await this.mainAgent.process(input);
|
|
24
|
+
|
|
25
|
+
const handoff = (ctx as any)._handoff;
|
|
26
|
+
if (handoff && handoff.graph === "PARENT" && this.autoHandoff) {
|
|
27
|
+
const targetName = handoff.goto;
|
|
28
|
+
const target = this.registry.getAgent(targetName);
|
|
29
|
+
if (target) {
|
|
30
|
+
const handoffTask = handoff.update?.handoffTask || input;
|
|
31
|
+
return target.process(handoffTask);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return ctx;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
getMainAgent(): Agent {
|
|
39
|
+
return this.mainAgent;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
getRegistry(): AgentRegistry {
|
|
43
|
+
return this.registry;
|
|
44
|
+
}
|
|
45
|
+
}
|