{"id":27715826,"url":"https://github.com/joshmu/ts-swarm","last_synced_at":"2025-04-27T01:32:59.976Z","repository":{"id":259394307,"uuid":"877695140","full_name":"joshmu/ts-swarm","owner":"joshmu","description":"Minimal agentic library mixing the simplicity of OpenAI Swarm with the flexibility of the Vercel AI SDK. 🐝","archived":false,"fork":false,"pushed_at":"2024-11-20T04:32:23.000Z","size":628,"stargazers_count":25,"open_issues_count":0,"forks_count":4,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-23T01:06:28.979Z","etag":null,"topics":["agentic-ai","agentic-workflow","agents","ai","javascript","node","openai","typescript","vercel"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/ts-swarm","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/joshmu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-24T04:50:24.000Z","updated_at":"2025-03-18T19:42:58.000Z","dependencies_parsed_at":"2024-10-25T03:44:00.137Z","dependency_job_id":"58360091-e887-4476-aae1-3f6a43220b5d","html_url":"https://github.com/joshmu/ts-swarm","commit_stats":null,"previous_names":["joshmu/ts-swarm"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshmu%2Fts-swarm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshmu%2Fts-swarm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshmu%2Fts-swarm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshmu%2Fts-swarm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joshmu","download_url":"https://codeload.github.com/joshmu/ts-swarm/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251077102,"owners_count":21532607,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agentic-ai","agentic-workflow","agents","ai","javascript","node","openai","typescript","vercel"],"created_at":"2025-04-27T01:32:13.499Z","updated_at":"2025-04-27T01:32:59.933Z","avatar_url":"https://github.com/joshmu.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TS-SWARM 🐝\n\n[![npm version](https://img.shields.io/npm/v/ts-swarm.svg)](https://www.npmjs.com/package/ts-swarm?link=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2Fts-swarm)\n![NPM Downloads](https://img.shields.io/npm/d18m/ts-swarm?link=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2Fts-swarm)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.6.3-blue.svg)](https://www.typescriptlang.org/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## Overview\n\nTS-SWARM is a minimal TypeScript Agentic library mixing the simplicity of [OpenAI Swarm API](https://github.com/openai/swarm) with the flexibility of the [Vercel AI SDK](https://github.com/vercel/ai).\n\n## Features\n\n- **Minimal Interface**: `createAgent` \u0026 `\u003cagent\u003e.run()`, that's it!\n- **Multi-Agent System**: Create and manage multiple AI agents with different roles and capabilities.\n- **Flexible Agent Configuration**: Easily define agent behaviors, instructions, and available functions.\n- **Task Delegation**: Agents can transfer tasks to other specialized agents.\n- **Tools**: Agents can use tools to perform tasks.\n- **Zod Validation**: Tools can use zod validation to ensure the input is correct.\n- **Model Choice**: Easily switch between different LLMs by changing a single line of code.\n- **Local Agents**: Option to run locally with the [ollama-ai-provider](https://sdk.vercel.ai/providers/community-providers/ollama).\n\n## Examples\n\nSome examples of agents and agentic patterns, additionally take a look at [`examples/run.ts`](./examples/run.ts) on how to have a conversation with agents.\n\n- [Local Agent with Ollama](./examples/local/localAgent.ts)\n- [Pokemon Agent](./examples/pokemon/pokemonAgent.ts)\n- [Web Scraper Agent](./examples/webscraper/webScraperAgent.ts)\n- [Filesystem Agent](./examples/filesystem/filesystemAgent.ts)\n- [Triage Weather Email Agents](./examples/triage-weather-email/index.ts)\n- [All Agents Connected](./examples/all/index.ts)\n\n\u003e [!TIP]\n\u003e Grab the repo and invoke the examples via scripts provided in the [package.json](./package.json) :)\n\nDemo using the [All Agents Connected](./examples/all/index.ts) example:\n![All Agents Chat Example](./assets/all_agents_chat_example.jpg)\n\n## Installation\n\nUse your preferred package manager:\n\n```bash\npnpm add ts-swarm ai zod\n```\n\nDepending on the LLM you want to use via the Vercel AI SDK, you will need to install the appropriate package.\n\n**Run via an LLM provider service** such as OpenAI:\n\n```bash\n# OpenAI - Ensure OPENAI_API_KEY environment variable is set\npnpm add @ai-sdk/openai\n```\n\n**Or run locally** with [ollama-ai-provider](https://sdk.vercel.ai/providers/community-providers/ollama):\n\n```bash\n# Ollama - Ensure you leverage a model that supports tool calling\npnpm add ollama-ai-provider\n```\n\n## Usage\n\nTS-SWARM is kept minimal and simple. `createAgent` will create agents. Once you have your agent, `\u003cyour-agent\u003e.run()` method will orchestrate the swarm conversation allowing for tool calling and agent handoffs.\n\n\u003e [!TIP]\n\u003e The `createAgent` util is a thin wrapper over [`generateText` from the Vercel AI SDK](https://sdk.vercel.ai/docs/reference/ai-sdk-core/generate-text). Thus you have access to **tools**, **zod validation**, and **model choice**. ⚡\n\n```typescript\nimport { createAgent } from 'ts-swarm';\nimport { openai } from '@ai-sdk/openai'; // Ensure OPENAI_API_KEY environment variable is set\nimport { z } from 'zod';\n\n// Create the Weather Agent\nconst weatherAgent = createAgent({\n  id: 'Weather_Agent',\n  model: openai('gpt-4o-2024-08-06', { structuredOutputs: true }),\n  system: `\n    You are a weather assistant. \n    Your role is to:\n      - Provide weather information for requested locations\n      - Use the weather tool to fetch weather data`,\n  tools: [\n    {\n      id: 'weather',\n      description: 'Get the weather for a specific location',\n      parameters: z.object({\n        location: z.string().describe('The location to get weather for'),\n      }),\n      execute: async ({ location }) =\u003e {\n        // Mock weather API call\n        return `The weather in ${location} is sunny with a high of 67°F.`;\n      },\n    },\n  ],\n});\n\n// Create the Triage Agent\nconst triageAgent = createAgent({\n  id: 'Triage_Agent',\n  model: openai('gpt-4o-2024-08-06', { structuredOutputs: true }),\n  system: `\n    You are a helpful triage agent. \n    Your role is to:\n      - Answer the user's questions by transferring to the appropriate agent`,\n  tools: [\n    // Add ability to transfer to the weather agent\n    weatherAgent,\n  ],\n});\n\nasync function demo() {\n  /**\n   * Run the triage agent with swarm orchestration\n   * Enabling tool calling and agent handoffs\n   */\n  const result = await triageAgent.run({\n    // Example conversation passed in\n    messages: [\n      { role: 'user', content: \"What's the weather like in New York?\" },\n    ],\n  });\n\n  /**\n   * We could wrap this logic in a loop to continue the conversation by\n   * utilizing `result.activeAgent` which represents the last active agent during the run\n   * For this example `result.activeAgent` would now be the weather agent\n   * Refer to the `run.ts` example for an example of this\n   */\n\n  // Log the last message (or the entire conversation if you prefer)\n  const lastMessage = result.messages.at(-1);\n  console.log(\n    `${lastMessage?.swarmMeta?.agentId || 'User'}: ${lastMessage?.content}`,\n  );\n}\n\ndemo();\n// Query: What's the weather like in New York?\n// Triage_Agent: transferring...\n// Result: Weather_Agent: The weather in New York is sunny with a high of 67°F.\n```\n\nThe following diagram demonstrates the usage above. A simple multi-agent system that allows for delegation of tasks to specialized agents.\n\n![Swarm Diagram](./assets/swarm_diagram.png)\n\nTo see more examples, check out the [examples](./examples) directory.\n\nOtherwise, for more examples please refer to the original openai repo: [swarm](https://github.com/openai/swarm)\n\nThe primary goal of Swarm is to showcase the handoff \u0026 routines patterns explored in the [Orchestrating Agents: Handoffs \u0026 Routines cookbook](https://cookbook.openai.com/examples/orchestrating_agents)\n\n## createAgent()\n\n`createAgent` defines your agent. It's a thin wrapper over [`generateText` from the Vercel AI SDK](https://sdk.vercel.ai/docs/reference/ai-sdk-core/generate-text).\n\n### Arguments\n\n| Argument | Type                          | Description                                                                                                         | Default    |\n| -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------- |\n| id       | `string`                      | Unique identifier for the agent (must match `/^[a-zA-Z0-9_-]+$/`)                                                   | (required) |\n| model    | `LanguageModelV1`             | Refer to [Providers and Models from the Vercel AI SDK](https://sdk.vercel.ai/docs/foundations/providers-and-models) | (required) |\n| tools    | `SwarmTool[]`                 | Array of core tools or agents to transfer to                                                                        | `[]`       |\n| ...rest  | `Partial\u003cGenerateTextParams\u003e` | Refer to [`generateText` from the Vercel AI SDK](https://sdk.vercel.ai/docs/reference/ai-sdk-core/generate-text)    | `{}`       |\n\n### Returns\n\nReturns an `Agent` object containing:\n\n- `id`: Agent's unique identifier\n- `generate`: Function to generate a response\n- `run`: **Function to run the agent with swarm orchestration allowing for tool calls and agent transfers**\n- `tools`: Array of available tools\n\n## agent.run()\n\nThe `\u003cagent\u003e.run()` method handles the LLM request loop through an agent-based system, managing tool calls and agent handoffs.\n\n### Arguments\n\n| Argument    | Type                            | Description                                                 | Default       |\n| ----------- | ------------------------------- | ----------------------------------------------------------- | ------------- |\n| messages    | `Message[]`                     | Array of llm message objects with additional swarm metadata | (required)    |\n| activeAgent | `Agent`                         | option to override the current active agent to be called    | current agent |\n| onMessages  | `(messages: Message[]) =\u003e void` | Callback when new messages are received                     | `undefined`   |\n| debug       | `boolean`                       | Enables debug logging when true                             | `false`       |\n| maxTurns    | `number`                        | Maximum number of conversational turns allowed              | `10`          |\n\n### Returns\n\nReturns a `SwarmResult` object containing:\n\n- `messages`: Array of llm messages from the conversation\n- `activeAgent`: Current active agent on completion of the run (useful for continuing the conversation)\n\n## runDemoLoop()\n\nThe `runDemoLoop` function is a convenience function to allow you to test your agents in the terminal. It's a simple while loop that continues to run until the user decides to 'exit'. It is what is used in most of the examples and the source code can be viewed in [`examples/run.ts`](./examples/run.ts).\n\n### Arguments\n\n| Argument            | Type     | Description                                                                 |\n| ------------------- | -------- | --------------------------------------------------------------------------- |\n| initialAgentMessage | `string` | The initial message from the agent to the user to commence the conversation |\n| initialAgent        | `Agent`  | The initial agent to start the conversation with                            |\n\n## Roadmap\n\n- [ ] Support streaming\n- [ ] Additional context passing\n- [ ] Provide agentic design pattern examples\n- [ ] More test coverage\n- [ ] Bash the bugs\n- [ ] Continue to find as much simplicity while maintaining flexibility :)\n\n## Contributing\n\nWe welcome contributions to TS-SWARM! If you'd like to contribute, please see [CONTRIBUTING.md](./CONTRIBUTING.md) for more information.\n\n## Troubleshooting\n\nIf you're experiencing issues, please [open an issue](https://github.com/joshmu/ts-swarm/issues) on the GitHub repository with a detailed description of the problem and steps to reproduce it.\n\n## Acknowledgements\n\nIt goes without saying that this project would not have been possible without the original work done by the OpenAI \u0026 Vercel teams. :) Go give the [Swarm API](https://github.com/openai/swarm) \u0026 [Vercel AI SDK](https://github.com/vercel/ai) a star! ⭐\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](./LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoshmu%2Fts-swarm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoshmu%2Fts-swarm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoshmu%2Fts-swarm/lists"}