agent-swarm-kit 1.1.63 → 1.1.65

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 CHANGED
@@ -5,7 +5,8 @@
5
5
  [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/tripolskypetr/agent-swarm-kit)
6
6
  [![npm](https://img.shields.io/npm/v/agent-swarm-kit.svg?style=flat-square)](https://npmjs.org/package/agent-swarm-kit)
7
7
 
8
- Unleash the power of collaborative AI with `agent-swarm-kit`! This library empowers you to create intelligent, modular agent networks that work together seamlessly—perfect for automating workflows, solving complex problems, or designing next-gen AI systems. With a simple API, robust validation, and flexible architecture, it’s your toolkit for building smarter solutions, faster.
8
+ Unleash the power of collaborative AI with agent-swarm-kit! This library empowers you to create intelligent, modular agent networks that work together seamlessly—perfect for automating workflows, solving complex problems, or designing next-gen AI systems. With a simple API, robust validation, and flexible architecture, it’s your toolkit for building smarter solutions, faster. 🌟
9
+
9
10
 
10
11
  📚 **[Full Documentation](https://agent-swarm.github.io/modules.html)** | 🌟 **[Try It Now](https://github.com/tripolskypetr/agent-swarm-kit/blob/master/demo/repl-phone-seller/src/logic/agent/sales.agent.ts)**
11
12
 
@@ -13,31 +14,31 @@ Unleash the power of collaborative AI with `agent-swarm-kit`! This library empow
13
14
 
14
15
  ## ✨ Why Choose Agent Swarm Kit?
15
16
 
16
- - **Conversation Testbed**: Includes a unit testing framework with tool and agent override capabilities, enabling developers to simulate and validate agent interactions and tool integrations in isolated environments.
17
+ - 🧪 **Conversation Testbed**: Includes a unit testing framework with tool and agent override capabilities, enabling developers to simulate and validate agent interactions and tool integrations in isolated environments.
17
18
 
18
- - **Model Context Protocol Ready**: Seamlessly connect agents to multiple remote MCP servers, allowing integration with external tools written in various languages (e.g., C#, Python) via the reusable Model Context Protocol, originally developed for Claude Desktop.
19
+ - 🌐 **Model Context Protocol Ready**: Seamlessly connect agents to multiple remote MCP servers, allowing integration with external tools written in various languages (e.g., C#, Python) via the reusable Model Context Protocol, originally developed for Claude Desktop. 🔗
19
20
 
20
- - **Automatic Client Session Orchestration**: Automatically manages client sessions, handling message history, agent navigation, and resource disposal for efficient and scalable real-time interactions.
21
+ - ⚙️ **Automatic Client Session Orchestration**: Automatically manages client sessions, handling message history, agent navigation, and resource disposal for efficient and scalable real-time interactions. 🔄
21
22
 
22
- - **Operator Support**: Supports navigation to human operators through tool calls, enabling seamless escalation of conversations from AI agents to human support for enhanced user experience.
23
+ - 👥 **Operator Support**: Supports navigation to human operators through tool calls, enabling seamless escalation of conversations from AI agents to human support for enhanced user experience. 🙋
23
24
 
24
- - **Swarm of OpenAI, Grok, and Claude in One Chat**: An agent-agnostic framework that allows a single chat to leverage multiple AI models (e.g., OpenAI, Grok, Claude) within a swarm, providing flexibility and diversity in agent capabilities.
25
+ - 🤖 **Swarm of OpenAI, Grok, and Claude in One Chat**: An agent-agnostic framework that allows a single chat to leverage multiple AI models (e.g., OpenAI, Grok, Claude) within a swarm, providing flexibility and diversity in agent capabilities. 🧠
25
26
 
26
- - **Agent Schema to Markdown**: Generates Markdown documentation from agent schemas automatically in CI/CD, keeping project managers and teams updated on agent prompts, tools, and swarm structures without manual reporting. Changes are reflected instantly, streamlining communication and project tracking.
27
+ - 📝 **Agent Schema to Markdown**: Generates Markdown documentation from agent schemas automatically in CI/CD, keeping project managers and teams updated on agent prompts, tools, and swarm structures without manual reporting. Changes are reflected instantly, streamlining communication and project tracking. 📊
27
28
 
28
- - **Redis Storage Integration**: Persists state management, RAG (Retrieval-Augmented Generation) search data, and chat history in Redis, ensuring reliable, scalable, and high-performance storage. This enables safe and consistent access to agent states, vector search results, and conversation histories across distributed systems (Microservices).
29
+ - 💾 **Redis Storage Integration**: Persists state management, RAG (Retrieval-Augmented Generation) search data, and chat history in Redis, ensuring reliable, scalable, and high-performance storage. This enables safe and consistent access to agent states, vector search results, and conversation histories across distributed systems (Microservices). 🗄️
29
30
 
30
- - **Chat Independent Background Agent Sessions**: Enables the swarm to perform complex data processing computations in isolated contexts, such as financial analytics, allowing agents to handle intensive tasks like market trend analysis or portfolio optimization without interfering with the primary chat flow. Works the same way like [fork in POSIX](https://pubs.opengroup.org/onlinepubs/009696799/functions/fork.html)
31
+ - 🔄 **Chat Independent Background Agent Sessions**: Enables the swarm to perform complex data processing computations in isolated contexts, such as financial analytics, allowing agents to handle intensive tasks like market trend analysis or portfolio optimization without interfering with the primary chat flow. Works the same way like [fork in POSIX](https://pubs.opengroup.org/onlinepubs/009696799/functions/fork.html). 🔀
31
32
 
32
33
  ---
33
34
 
34
35
  ## 🚀 Getting Started
35
36
 
36
- > **Want a real-world demo?** Check out our **[Binance Candle Chat](https://github.com/tripolskypetr/agent-swarm-kit/blob/master/demo/binance-candle-chat/src/lib/swarm.ts)**—a practical example of a sales agent in action!
37
+ > **Want a real-world demo?** Check out our **[Binance Candle Chat](https://github.com/tripolskypetr/agent-swarm-kit/blob/master/demo/binance-candle-chat/src/lib/swarm.ts)**—a practical example of a sales agent in action! 📈
37
38
 
38
39
  ### First Look
39
40
 
40
- Read the [detailed instructions by the link](https://agent-swarm.github.io/documents/app_getting-started.html)
41
+ Read the [detailed instructions by the link](https://agent-swarm.github.io/documents/app_getting-started.html) 📖
41
42
 
42
43
  ### Installation
43
44
 
@@ -147,7 +148,8 @@ app.get("/api/v1/session/:clientId", upgradeWebSocket((ctx) => {
147
148
 
148
149
  ```
149
150
 
150
- The feature of this library is dependency inversion for agents injection. The agents are being lazy loaded during runtime, so you can declare them in separate modules and connect them to swarm with a string constant
151
+ The feature of this library is dependency inversion for agents injection. The agents are being lazy loaded during runtime, so you can declare them in separate modules and connect them to swarm with a string constant 🧩
152
+
151
153
 
152
154
  ```typescript
153
155
  export enum ToolName {
@@ -195,32 +197,35 @@ complete("I need a refund!").then(console.log);
195
197
 
196
198
  ## 🌟 Key Features
197
199
 
198
- - **Agent Orchestration**: Seamlessly switch between agents (e.g., triage → sales) with a single tool call.
199
- - **Shared History**: Agents share a rotating 25-message history, scoped to `assistant` and `user` roles.
200
- - **Custom Tools**: Define tools with validation and execution logic tailored to your needs.
201
- - **Model Recovery**: Automatically rescues invalid outputs with smart fallbacks like "Sorry, I missed that."
202
- - **Dependency Inversion**: Lazy-load agents at runtime for modular, scalable designs.
200
+
201
+ - 🤝 **Agent Orchestration**: Seamlessly switch between agents (e.g., triage sales) with a single tool call. 🔄
202
+ - 📜 **Shared History**: Agents share a rotating 25-message history, scoped to `assistant` and `user` roles. 🗂️
203
+ - 🛠️ **Custom Tools**: Define tools with validation and execution logic tailored to your needs. 🔧
204
+ - 🛡️ **Model Recovery**: Automatically rescues invalid outputs with smart fallbacks like "Sorry, I missed that." 🚑
205
+ - 📦 **Dependency Inversion**: Lazy-load agents at runtime for modular, scalable designs. 🧩
203
206
 
204
207
  ---
205
208
 
206
209
  ## 🎯 Use Cases
207
210
 
208
- - **Workflow Automation**: Automate customer support with triage, sales, and refund agents.
209
- - **Collaborative AI**: Build systems where agents solve problems together.
210
- - **Task Distribution**: Assign specialized tasks to dedicated agents.
211
- - **Chatbots & Beyond**: Create dynamic, multi-role conversational systems.
211
+
212
+ - 🤖 **Workflow Automation**: Automate customer support with triage, sales, and refund agents. 📞
213
+ - 🤝 **Collaborative AI**: Build systems where agents solve problems together. 🧑‍🤝‍🧑
214
+ - 📋 **Task Distribution**: Assign specialized tasks to dedicated agents. 📤
215
+ - 💬 **Chatbots & Beyond**: Create dynamic, multi-role conversational systems. 🌐
212
216
 
213
217
  ---
214
218
 
215
219
  ## 📖 API Highlights
216
220
 
217
- - **`addAgent`**: Define agents with custom prompts, tools, and completions.
218
- - **`addSwarm`**: Group agents into a coordinated network.
219
- - **`session`**: Start a client session with real-time message handling.
220
- - **`addTool`**: Create reusable tools with validation and execution logic.
221
- - **`Storage.take`**: Search and retrieve data using embeddings (e.g., vector search, RAG).
222
221
 
223
- Check out the **[API Reference](https://agent-swarm.github.io/modules.html)** for more!
222
+ - 🛠️ **`addAgent`**: Define agents with custom prompts, tools, and completions. 🤖
223
+ - 🌐 **`addSwarm`**: Group agents into a coordinated network. 🕸️
224
+ - 🔄 **`session`**: Start a client session with real-time message handling. 📨
225
+ - 🔧 **`addTool`**: Create reusable tools with validation and execution logic. 🛠️
226
+ - 🔍 **`Storage.take`**: Search and retrieve data using embeddings (e.g., vector search, RAG). 📊
227
+
228
+ Check out the **[API Reference](https://agent-swarm.github.io/modules.html)** for more! 📚
224
229
 
225
230
  ---
226
231
 
@@ -311,44 +316,44 @@ Storage.take<PhoneModel>({
311
316
 
312
317
  Here’s a rundown of the demo projects showcasing `agent-swarm-kit` in action:
313
318
 
314
- - [**binance-candle-chat**](./demo/binance-candle-chat/): A cryptocurrency trading swarm with a triage agent routing to specialized trader agents (BTC, ETH, BNB, XRP, SOL) that calculate buy/sell orders and predict trends using OpenAI completion.
315
319
 
316
- - [**it-consulting-swarm**](./demo/it-consulting-swarm/): A multi-agent system with a triage agent routing queries to specialized agents for tech trends, cybersecurity, environment, health, and finance, all powered by OpenAI completion.
320
+ - 📈 [**binance-candle-chat**](./demo/binance-candle-chat/): A cryptocurrency trading swarm with a triage agent routing to specialized trader agents (BTC, ETH, BNB, XRP, SOL) that calculate buy/sell orders and predict trends using OpenAI completion. 💹
317
321
 
318
- - [**langchain-stream**](./demo/langchain-stream/): A pharma sales demo with a triage agent using Cohere completion and LangChain for real-time token streaming, alongside Ollama and LMStudio, to assist with consultations and cart operations.
322
+ - 🖥️ [**it-consulting-swarm**](./demo/it-consulting-swarm/): A multi-agent system with a triage agent routing queries to specialized agents for tech trends, cybersecurity, environment, health, and finance, all powered by OpenAI completion. 🔒
319
323
 
320
- - [**redis-persist-chat**](./demo/redis-persist-chat/): A chat system with a triage agent using Saiga Yandex GPT, persisting chat history and states (like Tic-tac-toe) in Redis, with policies to restrict sensitive topics.
324
+ - 💊 [**langchain-stream**](./demo/langchain-stream/): A pharma sales demo with a triage agent using Cohere completion and LangChain for real-time token streaming, alongside Ollama and LMStudio, to assist with consultations and cart operations. 🛒
321
325
 
322
- - [**nginx-balancer-chat**](./demo/nginx-balancer-chat/): A test environment demonstrating load balancing across 5 chat instances via Nginx, with a single agent reporting the server port using OpenAI completion.
326
+ - 💾 [**redis-persist-chat**](./demo/redis-persist-chat/): A chat system with a triage agent using Saiga Yandex GPT, persisting chat history and states (like Tic-tac-toe) in Redis, with policies to restrict sensitive topics. 🎲
323
327
 
324
- - [**cohere-token-rotate**](./demo/cohere-token-rotate/): A pharma sales system with a triage agent using Cohere completion and a token rotation mechanism (10 trial tokens in parallel) for optimized API performance.
328
+ - 🌐 [**nginx-balancer-chat**](./demo/nginx-balancer-chat/): A test environment demonstrating load balancing across 5 chat instances via Nginx, with a single agent reporting the server port using OpenAI completion. ⚖️
325
329
 
326
- - [**whisper-voice-chat**](./demo/whisper-voice-chat/): A voice-based chat system using Whisper for real-time transcription and a single test agent powered by Nemotron Mini (via Ollama) to handle user interactions.
330
+ - 🔄 [**cohere-token-rotate**](./demo/cohere-token-rotate/): A pharma sales system with a triage agent using Cohere completion and a token rotation mechanism (10 trial tokens in parallel) for optimized API performance. 🔧
327
331
 
328
- - [**telegram-ollama-chat**](./demo/telegram-ollama-chat/): A Telegram-based pharma sales chatbot with a triage agent routing requests to a sales agent, both using Ollama for natural conversations and managing product data from a shared storage.
332
+ - 🎙️ [**whisper-voice-chat**](./demo/whisper-voice-chat/): A voice-based chat system using Whisper for real-time transcription and a single test agent powered by Nemotron Mini (via Ollama) to handle user interactions. 🗣️
329
333
 
330
- - [**repl-phone-seller**](./demo/repl-phone-seller/): A REPL terminal app featuring a sales agent that helps users add phones to a cart, leveraging Ollama completions and tools for searching phones by keywords or diagonal size.
334
+ - 📱 [**telegram-ollama-chat**](./demo/telegram-ollama-chat/): A Telegram-based pharma sales chatbot with a triage agent routing requests to a sales agent, both using Ollama for natural conversations and managing product data from a shared storage. 💬
331
335
 
332
- - [**client-server-chat**](./demo/client-server-chat/): A WebSocket-based pharma sales demo with a single test agent using Saiga Yandex GPT to provide consultations and manage a cart.
336
+ - 🛍️ [**repl-phone-seller**](./demo/repl-phone-seller/): A REPL terminal app featuring a sales agent that helps users add phones to a cart, leveraging Ollama completions and tools for searching phones by keywords or diagonal size. 📲
333
337
 
334
- ---
338
+ - 🌐 [**client-server-chat**](./demo/client-server-chat/): A WebSocket-based pharma sales demo with a single test agent using Saiga Yandex GPT to provide consultations and manage a cart. 🛠️
335
339
 
340
+ ---
336
341
 
337
342
  ## ❓ Orchestration Principles
338
343
 
339
- 1. Several chatgpt sessions (agents) [execute tool calls](https://ollama.com/blog/tool-support). Each agent can use different model, for example, [mistral 7b](https://ollama.com/library/mistral) for small talk, [nemotron](https://ollama.com/library/nemotron) for business conversation
344
+ 1. 🤖 Several chatgpt sessions (agents) [execute tool calls](https://ollama.com/blog/tool-support). Each agent can use different model, for example, [mistral 7b](https://ollama.com/library/mistral) for small talk, [nemotron](https://ollama.com/library/nemotron) for business conversation. 🧠
340
345
 
341
- 2. The agent swarm navigate messages to the active chatgpt session (agent) for each `WebSocket` channel [by using `clientId` url parameter](demo/client-server-chat/src/server.ts#L15)
346
+ 2. 🌐 The agent swarm navigate messages to the active chatgpt session (agent) for each `WebSocket` channel [by using `clientId` url parameter](demo/client-server-chat/src/server.ts#L15) 🔗
342
347
 
343
- 3. The active chatgpt session (agent) in the swarm could be changed [by executing function tool](https://platform.openai.com/docs/assistants/tools/function-calling)
348
+ 3. 🔄 The active chatgpt session (agent) in the swarm could be changed [by executing function tool](https://platform.openai.com/docs/assistants/tools/function-calling). ⚙️
344
349
 
345
- 4. Each client sessions [share the same chat message history](https://platform.openai.com/docs/api-reference/messages/getMessage) for all agents. Each client chat history keep the last 25 messages with rotation. Only `assistant` and `user` messages are shared between chatgpt sessions (agents), the `system` and `tool` messages are agent-scoped so each agent knows only those tools related to It. As a result, each chatgpt session (agent) has it's [unique system prompt](https://platform.openai.com/docs/api-reference/messages/createMessage#messages-createmessage-role)
350
+ 4. 📜 Each client sessions [share the same chat message history](https://platform.openai.com/docs/api-reference/messages/getMessage) for all agents. Each client chat history keep the last 25 messages with rotation. Only `assistant` and `user` messages are shared between chatgpt sessions (agents), the `system` and `tool` messages are agent-scoped so each agent knows only those tools related to It. As a result, each chatgpt session (agent) has it's [unique system prompt](https://platform.openai.com/docs/api-reference/messages/createMessage#messages-createmessage-role). 🗂️
346
351
 
347
- 5. If the agent output do not pass the validation (not existing tool call, tool call with invalid arguments, empty output, XML tags in output or JSON in output by default), the resque algorithm will try to fix the model. At first it will hide the previos messeges from a model, if this will not help, it return a placeholder like `Sorry, I missed that. Could you say it again?`
352
+ 5. 🛡️ If the agent output do not pass the validation (not existing tool call, tool call with invalid arguments, empty output, XML tags in output or JSON in output by default), the resque algorithm will try to fix the model. At first it will hide the previos messeges from a model, if this will not help, it return a placeholder like `Sorry, I missed that. Could you say it again?` 🚑
348
353
 
349
354
  ---
350
355
 
351
- # ⚡ Multithreading
356
+ ## ⚡ Multithreading
352
357
 
353
358
  The following example demonstrates how to use a background agent to generate a Bitcoin trading report using a [fork-like mechanism](https://en.wikipedia.org/wiki/Fork_(system_call)), ensuring the process runs independently of the main chat session:
354
359
 
@@ -406,19 +411,20 @@ export class SwingRangeReportPublicService {
406
411
  export default SwingRangeReportPublicService;
407
412
  ```
408
413
 
409
- P.S. [openai threads](https://platform.openai.com/docs/api-reference/threads) doc
414
+ P.S. [openai threads](https://platform.openai.com/docs/api-reference/threads) doc 📖
410
415
 
411
416
  ---
412
417
 
413
418
  ## ✅ Tested & Reliable
414
419
 
415
420
  `agent-swarm-kit` comes with a robust test suite covering:
416
- - **Validation**: Ensures all components (agents, tools, swarms) are properly configured.
417
- - **Recovery**: Handles edge cases like invalid tool calls or empty outputs.
418
- - **Navigation**: Smoothly switches between agents without deadlocks.
419
- - **Performance**: Efficient connection disposal and history management.
421
+ - 🛡️ **Validation**: Ensures all components (agents, tools, swarms) are properly configured.
422
+ - 🚑 **Recovery**: Handles edge cases like invalid tool calls or empty outputs. 🛠️
423
+ - 🔄 **Navigation**: Smoothly switches between agents without deadlocks. 🌐
424
+ - **Performance**: Efficient connection disposal and history management. 📈
420
425
 
421
- See the **[Test Cases](https://github.com/tripolskypetr/agent-swarm-kit/blob/master/TEST.md)** section in the docs for details.
426
+
427
+ See the **[Test Cases](https://github.com/tripolskypetr/agent-swarm-kit/blob/master/TEST.md)** section in the docs for details. 📚
422
428
 
423
429
  ---
424
430
 
@@ -428,31 +434,35 @@ The `agent-swarm-kit` ecosystem extends beyond the core library, offering comple
428
434
 
429
435
  ### Agent Tune Dataset Constructor
430
436
 
431
- > **[Explore Agent Tune](https://agent-tune.github.io)**
437
+ > **[Explore Agent Tune](https://agent-tune.github.io)** 🌟
438
+
439
+ The **Agent Tune Dataset Constructor** is a React-based tool designed for crafting fine-tuning datasets tailored for AI models, published on GitHub Pages at [agent-tune.github.io](https://agent-tune.github.io/). It provides a dynamic, user-friendly interface with list and grid layouts, enabling you to define user inputs, preferred and non-preferred outputs, and multi-turn chat histories—complete with tool definitions and calls. Built with the `react-declarative` library and styled using Material-UI, it’s optimized for creating JSONL files compatible with OpenAI’s fine-tuning API. 🛠️
432
440
 
433
- The **Agent Tune Dataset Constructor** is a React-based tool designed for crafting fine-tuning datasets tailored for AI models, published on GitHub Pages at [agent-tune.github.io](https://agent-tune.github.io). It provides a dynamic, user-friendly interface with list and grid layouts, enabling you to define user inputs, preferred and non-preferred outputs, and multi-turn chat histories—complete with tool definitions and calls. Built with the `react-declarative` library and styled using Material-UI, it’s optimized for creating JSONL files compatible with OpenAI’s fine-tuning API.
434
441
 
435
442
  #### Key Features
436
- - **Dynamic Forms**: Build dataset entries with configurable user inputs, outputs, and tools (up to five per entry), featuring autocomplete for tool names and enum values.
437
- - **Chat History**: Include conversational context with tool calls, supporting up to five messages per entry.
438
- - **Data Management**: Import/export datasets as JSONL files (`SFT` and `DPO` both), with automatic `tool_call_id` generation, and persist changes to local storage.
439
- - **Validation**: Ensures tool consistency, message order, and data integrity.
440
- - **Ease of Use**: Navigate with breadcrumbs, save drafts, and export directly for fine-tuning with commands like `openai api fine_tunes.create`.
443
+ - 📝 **Dynamic Forms**: Build dataset entries with configurable user inputs, outputs, and tools (up to five per entry), featuring autocomplete for tool names and enum values. 💻
444
+
445
+ - 💬 **Chat History**: Include conversational context with tool calls, supporting up to five messages per entry. 🗂️
446
+
447
+ - 💾 **Data Management**: Import/export datasets as JSONL files (`SFT` and `DPO` both), with automatic `tool_call_id` generation, and persist changes to local storage. 📥
448
+
449
+ - ✅ **Validation**: Ensures tool consistency, message order, and data integrity. 🛡️
450
+
451
+ - 🚀 **Ease of Use**: Navigate with breadcrumbs, save drafts, and export directly for fine-tuning with commands like openai api [fine_tunes.create](https://platform.openai.com/docs/api-reference/fine-tuning). 📤
441
452
 
442
453
  #### Use Case
443
- Perfect for preparing training data to fine-tune agents within `agent-swarm-kit`, Agent Tune lets you define precise behaviors—like how a sales agent responds or a triage agent routes requests—before integrating them into your swarm. Export your dataset and fine-tune your models to enhance performance across your agent network.
454
+ Perfect for preparing training data to fine-tune agents within `agent-swarm-kit`, Agent Tune lets you define precise behaviors—like how a sales agent responds or a triage agent routes requests—before integrating them into your swarm. Export your dataset and fine-tune your models to enhance performance across your agent network. 🌐
444
455
 
445
456
  #### Get Started
446
- Visit [agent-tune.github.io](https://agent-tune.github.io) to try it out, or clone the repository to customize it further. Combine it with `agent-swarm-kit` for a seamless workflow from dataset creation to agent deployment.
457
+ Visit [agent-tune.github.io](https://agent-tune.github.io/) to try it out, or clone the repository to customize it further. Combine it with `agent-swarm-kit` for a seamless workflow from dataset creation to agent deployment. 🚀
447
458
 
448
459
  ---
449
460
 
450
461
  ## 🤝 Contribute
451
462
 
452
- We’d love your input! Fork the repo, submit a PR, or open an issue on **[GitHub](https://github.com/tripolskypetr/agent-swarm-kit)**.
463
+ We’d love your input! Fork the repo, submit a PR, or open an issue on **[GitHub](https://github.com/tripolskypetr/agent-swarm-kit)**. 🙌
453
464
 
454
- ---
455
465
 
456
466
  ## 📜 License
457
467
 
458
- MIT © [tripolskypetr](https://github.com/tripolskypetr)
468
+ MIT © [tripolskypetr](https://github.com/tripolskypetr) 🖋️
package/build/index.cjs CHANGED
@@ -3425,7 +3425,7 @@ class AgentSchemaService {
3425
3425
  if (!agentSchema.operator && typeof agentSchema.completion !== "string") {
3426
3426
  throw new Error(`agent-swarm agent schema validation failed: missing completion for agentName=${agentSchema.agentName}`);
3427
3427
  }
3428
- if (!agentSchema.operator && typeof agentSchema.prompt !== "string") {
3428
+ if (!agentSchema.operator && agentSchema.prompt === undefined) {
3429
3429
  throw new Error(`agent-swarm agent schema validation failed: missing prompt for agentName=${agentSchema.agentName}`);
3430
3430
  }
3431
3431
  if (agentSchema.system && !Array.isArray(agentSchema.system)) {
@@ -3801,7 +3801,10 @@ const RUN_FN = async (incoming, self) => {
3801
3801
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} run begin`, { incoming });
3802
3802
  self.params.onRun &&
3803
3803
  self.params.onRun(self.params.clientId, self.params.agentName, incoming);
3804
- const messages = await self.params.history.toArrayForAgent(self.params.prompt ?? "", await self._resolveSystemPrompt());
3804
+ const prompt = typeof self.params.prompt === "string"
3805
+ ? self.params.prompt
3806
+ : await self.params.prompt(self.params.clientId, self.params.agentName);
3807
+ const messages = await self.params.history.toArrayForAgent(prompt, await self._resolveSystemPrompt());
3805
3808
  messages.push({
3806
3809
  agentName: self.params.agentName,
3807
3810
  content: incoming,
@@ -4337,7 +4340,10 @@ class ClientAgent {
4337
4340
  async getCompletion(mode, tools) {
4338
4341
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4339
4342
  this.params.logger.debug(`ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} getCompletion`);
4340
- const messages = await this.params.history.toArrayForAgent(this.params.prompt ?? "", await this._resolveSystemPrompt());
4343
+ const prompt = typeof this.params.prompt === "string"
4344
+ ? this.params.prompt
4345
+ : await this.params.prompt(this.params.clientId, this.params.agentName);
4346
+ const messages = await this.params.history.toArrayForAgent(prompt, await this._resolveSystemPrompt());
4341
4347
  const args = {
4342
4348
  clientId: this.params.clientId,
4343
4349
  agentName: this.params.agentName,
@@ -4381,7 +4387,10 @@ class ClientAgent {
4381
4387
  agentName: this.params.agentName,
4382
4388
  content: GLOBAL_CONFIG.CC_TOOL_CALL_EXCEPTION_RECOMPLETE_PROMPT,
4383
4389
  });
4384
- const messages = await this.params.history.toArrayForAgent(this.params.prompt ?? "", await this._resolveSystemPrompt());
4390
+ const prompt = typeof this.params.prompt === "string"
4391
+ ? this.params.prompt
4392
+ : await this.params.prompt(this.params.clientId, this.params.agentName);
4393
+ const messages = await this.params.history.toArrayForAgent(prompt, await this._resolveSystemPrompt());
4385
4394
  const args = {
4386
4395
  clientId: this.params.clientId,
4387
4396
  agentName: this.params.agentName,
@@ -6169,7 +6178,7 @@ class ToolSchemaService {
6169
6178
  if (toolSchema.validate && typeof toolSchema.validate !== "function") {
6170
6179
  throw new Error(`agent-swarm tool schema validation failed: missing validate for toolName=${toolSchema.toolName}`);
6171
6180
  }
6172
- if (!functoolsKit.isObject(toolSchema.function)) {
6181
+ if (!functoolsKit.isObject(toolSchema.function) && typeof toolSchema.function !== "function") {
6173
6182
  throw new Error(`agent-swarm tool schema validation failed: missing function for toolName=${toolSchema.toolName}`);
6174
6183
  }
6175
6184
  };
@@ -13325,7 +13334,7 @@ class DocService {
13325
13334
  result.push("");
13326
13335
  }
13327
13336
  }
13328
- if (agentSchema.prompt) {
13337
+ if (typeof agentSchema.prompt === "string") {
13329
13338
  result.push(`## Main prompt`);
13330
13339
  result.push("");
13331
13340
  result.push("```");
@@ -21575,7 +21584,10 @@ const getAgentHistoryInternal = beginContext(async (clientId, agentName) => {
21575
21584
  swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$b);
21576
21585
  swarm$1.agentValidationService.validate(agentName, METHOD_NAME$b);
21577
21586
  // Retrieve the agent's prompt configuration from the agent schema service
21578
- const { prompt } = swarm$1.agentSchemaService.get(agentName);
21587
+ const { prompt: upperPrompt } = swarm$1.agentSchemaService.get(agentName);
21588
+ const prompt = typeof upperPrompt === "string"
21589
+ ? upperPrompt
21590
+ : await upperPrompt(clientId, agentName);
21579
21591
  // Fetch the agent's history using the prompt and rescue tweaks via the history public service
21580
21592
  const history = await swarm$1.historyPublicService.toArrayForAgent(prompt, METHOD_NAME$b, clientId, agentName);
21581
21593
  // Return a shallow copy of the history array
package/build/index.mjs CHANGED
@@ -3423,7 +3423,7 @@ class AgentSchemaService {
3423
3423
  if (!agentSchema.operator && typeof agentSchema.completion !== "string") {
3424
3424
  throw new Error(`agent-swarm agent schema validation failed: missing completion for agentName=${agentSchema.agentName}`);
3425
3425
  }
3426
- if (!agentSchema.operator && typeof agentSchema.prompt !== "string") {
3426
+ if (!agentSchema.operator && agentSchema.prompt === undefined) {
3427
3427
  throw new Error(`agent-swarm agent schema validation failed: missing prompt for agentName=${agentSchema.agentName}`);
3428
3428
  }
3429
3429
  if (agentSchema.system && !Array.isArray(agentSchema.system)) {
@@ -3799,7 +3799,10 @@ const RUN_FN = async (incoming, self) => {
3799
3799
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} run begin`, { incoming });
3800
3800
  self.params.onRun &&
3801
3801
  self.params.onRun(self.params.clientId, self.params.agentName, incoming);
3802
- const messages = await self.params.history.toArrayForAgent(self.params.prompt ?? "", await self._resolveSystemPrompt());
3802
+ const prompt = typeof self.params.prompt === "string"
3803
+ ? self.params.prompt
3804
+ : await self.params.prompt(self.params.clientId, self.params.agentName);
3805
+ const messages = await self.params.history.toArrayForAgent(prompt, await self._resolveSystemPrompt());
3803
3806
  messages.push({
3804
3807
  agentName: self.params.agentName,
3805
3808
  content: incoming,
@@ -4335,7 +4338,10 @@ class ClientAgent {
4335
4338
  async getCompletion(mode, tools) {
4336
4339
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4337
4340
  this.params.logger.debug(`ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} getCompletion`);
4338
- const messages = await this.params.history.toArrayForAgent(this.params.prompt ?? "", await this._resolveSystemPrompt());
4341
+ const prompt = typeof this.params.prompt === "string"
4342
+ ? this.params.prompt
4343
+ : await this.params.prompt(this.params.clientId, this.params.agentName);
4344
+ const messages = await this.params.history.toArrayForAgent(prompt, await this._resolveSystemPrompt());
4339
4345
  const args = {
4340
4346
  clientId: this.params.clientId,
4341
4347
  agentName: this.params.agentName,
@@ -4379,7 +4385,10 @@ class ClientAgent {
4379
4385
  agentName: this.params.agentName,
4380
4386
  content: GLOBAL_CONFIG.CC_TOOL_CALL_EXCEPTION_RECOMPLETE_PROMPT,
4381
4387
  });
4382
- const messages = await this.params.history.toArrayForAgent(this.params.prompt ?? "", await this._resolveSystemPrompt());
4388
+ const prompt = typeof this.params.prompt === "string"
4389
+ ? this.params.prompt
4390
+ : await this.params.prompt(this.params.clientId, this.params.agentName);
4391
+ const messages = await this.params.history.toArrayForAgent(prompt, await this._resolveSystemPrompt());
4383
4392
  const args = {
4384
4393
  clientId: this.params.clientId,
4385
4394
  agentName: this.params.agentName,
@@ -6167,7 +6176,7 @@ class ToolSchemaService {
6167
6176
  if (toolSchema.validate && typeof toolSchema.validate !== "function") {
6168
6177
  throw new Error(`agent-swarm tool schema validation failed: missing validate for toolName=${toolSchema.toolName}`);
6169
6178
  }
6170
- if (!isObject$1(toolSchema.function)) {
6179
+ if (!isObject$1(toolSchema.function) && typeof toolSchema.function !== "function") {
6171
6180
  throw new Error(`agent-swarm tool schema validation failed: missing function for toolName=${toolSchema.toolName}`);
6172
6181
  }
6173
6182
  };
@@ -13323,7 +13332,7 @@ class DocService {
13323
13332
  result.push("");
13324
13333
  }
13325
13334
  }
13326
- if (agentSchema.prompt) {
13335
+ if (typeof agentSchema.prompt === "string") {
13327
13336
  result.push(`## Main prompt`);
13328
13337
  result.push("");
13329
13338
  result.push("```");
@@ -21573,7 +21582,10 @@ const getAgentHistoryInternal = beginContext(async (clientId, agentName) => {
21573
21582
  swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$b);
21574
21583
  swarm$1.agentValidationService.validate(agentName, METHOD_NAME$b);
21575
21584
  // Retrieve the agent's prompt configuration from the agent schema service
21576
- const { prompt } = swarm$1.agentSchemaService.get(agentName);
21585
+ const { prompt: upperPrompt } = swarm$1.agentSchemaService.get(agentName);
21586
+ const prompt = typeof upperPrompt === "string"
21587
+ ? upperPrompt
21588
+ : await upperPrompt(clientId, agentName);
21577
21589
  // Fetch the agent's history using the prompt and rescue tweaks via the history public service
21578
21590
  const history = await swarm$1.historyPublicService.toArrayForAgent(prompt, METHOD_NAME$b, clientId, agentName);
21579
21591
  // Return a shallow copy of the history array
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-swarm-kit",
3
- "version": "1.1.63",
3
+ "version": "1.1.65",
4
4
  "description": "A TypeScript library for building orchestrated framework-agnostic multi-agent AI systems",
5
5
  "author": {
6
6
  "name": "Petr Tripolsky",
package/types.d.ts CHANGED
@@ -3572,7 +3572,7 @@ interface IAgentSchemaInternal {
3572
3572
  /** The name of the completion mechanism used by the agent. REQUIRED WHEN AGENT IS NOT OPERATOR */
3573
3573
  completion?: CompletionName;
3574
3574
  /** The primary prompt guiding the agent's behavior. REQUIRED WHEN AGENT IS NOT OPERATOR */
3575
- prompt?: string;
3575
+ prompt?: string | ((clientId: string, agentName: AgentName) => (Promise<string> | string));
3576
3576
  /** Optional array of system prompts, typically used for tool-calling protocols. */
3577
3577
  system?: string[];
3578
3578
  /** Optional array of system prompts, alias for `system` */