{"id":44448069,"url":"https://github.com/microfox-ai/ai-router","last_synced_at":"2026-04-02T14:26:39.146Z","repository":{"id":311129932,"uuid":"1042562644","full_name":"microfox-ai/ai-router","owner":"microfox-ai","description":"express.js styled agent orchestration Library for typescript community","archived":false,"fork":false,"pushed_at":"2026-03-26T23:59:03.000Z","size":4099,"stargazers_count":4,"open_issues_count":11,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-27T11:32:52.454Z","etag":null,"topics":["agent-framework","ai-sdk","nextjs","typescript"],"latest_commit_sha":null,"homepage":"https://docs.microfox.app/ai-router","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microfox-ai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-22T08:02:17.000Z","updated_at":"2026-03-26T23:57:06.000Z","dependencies_parsed_at":"2025-08-22T10:34:53.459Z","dependency_job_id":"0feafff3-efa8-4a58-89b6-5a9f61ff2b3c","html_url":"https://github.com/microfox-ai/ai-router","commit_stats":null,"previous_names":["microfox-ai/ai-router"],"tags_count":26,"template":false,"template_full_name":null,"purl":"pkg:github/microfox-ai/ai-router","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microfox-ai%2Fai-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microfox-ai%2Fai-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microfox-ai%2Fai-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microfox-ai%2Fai-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microfox-ai","download_url":"https://codeload.github.com/microfox-ai/ai-router/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microfox-ai%2Fai-router/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31307991,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-02T12:59:32.332Z","status":"ssl_error","status_checked_at":"2026-04-02T12:54:48.875Z","response_time":89,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["agent-framework","ai-sdk","nextjs","typescript"],"created_at":"2026-02-12T16:00:41.485Z","updated_at":"2026-04-02T14:26:39.126Z","avatar_url":"https://github.com/microfox-ai.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AI Router\n\n**If you know Express, you already know AI Router.**\n\nAI Router brings a familiar middleware-style architecture to the world of AI Agents. It provides a robust foundation for orchestrating complex AI workflows with multiple agents, tools, and dynamic routing, all while integrating seamlessly with the [Vercel AI SDK](https://ai-sdk.dev/docs/introduction).\n\n## The Problem\n\nModern AI applications, especially those using helpers like the Vercel AI SDK's `useChat`, typically connect the frontend to a single backend API endpoint. This creates a significant challenge: how do you manage a complex, multi-agent system through that single route?\n\n```typescript\n// Your frontend connects to ONE endpoint\nconst { messages, append } = useChat({\n  api: '/api/chat', // Single endpoint for everything\n});\n```\n\nCramming an entire agentic orchestration logic—with multiple specialized agents, tools, and state management—into a single function is complex, hard to maintain, and quickly becomes unmanageable.\n\n## The Solution: AI Router\n\nAI Router solves this with the **Principle of Singularity**. It allows you to build a sophisticated web of agents, middleware, and tools, each with its own path, and then serve the entire system through a single handler.\n\nYour frontend communicates with one endpoint, while your backend remains modular, organized, and scalable.\n\n## Core Principles\n\n### 1. **Principle of Singularity**\n\nYour frontend connects to one endpoint, but your backend is modular and organized:\n\n```typescript\n// Frontend: Still one endpoint\nconst { messages, append } = useChat({\n  api: '/api/chat',\n});\n\n// Backend: Clean, modular agents \u0026 routing logic\nrouter.agent('/code-generator', codeGeneratorHandler);\nrouter.agent('/data-analyzer', dataAnalyzerHandler);\nrouter.agent('/content-writer', contentWriterHandler);\n```\n\n### 2. **Express.js Familiarity**\n\nIf you know Express.js, you already know AI Router:\n\n```typescript\n// Express.js style routing\nrouter.use('*', authMiddleware);\nrouter.agent('/users/:id', userAgent);\n```\n\n### 3. **Agent-as-Tools Pattern**\n\nAgents can be attached as tools to LLM calls, enabling agent sub-agent architecture similar to Google's Agent Development Kit:\n\n```typescript\nrouter.agent('/blog-writer', async (ctx) =\u003e {\n  const { topic } = ctx.request.params;\n  const { text } = await generateText({\n    model: openai('gpt-4'),\n    prompt: `Write a blog post about ${topic}.`,\n    tools: {\n      // Attach the existing agent as a tool for the LLM to use\n      ...ctx.next.agentAsTool('/research'),\n    },\n  });\n  ctx.response.write({ type: 'text', text });\n});\n```\n\n### 4. **Leaner Orchestration** with Internal Shared State\n\n```typescript\n// Main orchestrator\nrouter.agent('/', async (ctx) =\u003e {\n  const stream = streamText({\n    model: openai('gpt-4'),\n    prompt: `Write a blog post about ${topic}.`,\n    tools: {\n      ...ctx.next.agentAsTool('/agent-1'),\n      ...ctx.next.agentAsTool('/agent-2'),\n    },\n  });\n});\n\n// Agent 1: Sets state\nrouter.agent('/agent-1', async (ctx) =\u003e {\n  ctx.state.topic = 'LONG RESEARCH INFORMATION';\n  return { action: 'done' };\n});\n\n// Agent 2: Accesses state\nrouter.agent('/agent-2', async (ctx) =\u003e {\n  const { topic } = ctx.request.state;\n  const { text } = await generateText({\n    model: openai('gpt-4'),\n    prompt: `Write a blog post about ${topic}.`,\n  });\n});\n```\n\n## Getting Started\n\n### Installation\n\n```bash\nnpm install @microfox/ai-router\n```\n\n### Basic Setup\n\n```typescript\nimport { AiRouter, MemoryStore } from '@microfox/ai-router';\n\n// Create a new router instance\nconst router = new AiRouter();\n\n// Define your agents\nrouter.agent('/', async (ctx) =\u003e {\n  return { message: 'Hello from AI Router!' };\n});\n\n// Next.js API Route\nexport async function POST(request: Request) {\n  const body = await request.json();\n  const { messages, ...restOfBody } = body;\n\n  const response = router.handle('/', {\n    request: {\n      ...restOfBody,\n      messages: messages || [],\n    },\n  });\n\n  return response;\n}\n```\n\n## Agents\n\nAgents are the primary handlers in your AI Router application. They are async functions that receive a context object and can interact with users, call other agents, or be exposed as tools for LLM integration.\n\n### Basic Agent\n\n```typescript\nrouter.agent('/path', async (ctx) =\u003e {\n  // Agent logic here\n  return { message: 'Hello from agent!' };\n});\n```\n\n### Dynamic Paths with Parameters\n\n```typescript\nrouter.agent('/users/:userId', async (ctx) =\u003e {\n  const { userId } = ctx.request.params;\n  return { user: { id: userId, name: `User ${userId}` } };\n});\n```\n\n### Agent-to-Agent Communication\n\n```typescript\nrouter.agent('/orchestrator', async (ctx) =\u003e {\n  // Call another agent and wait for result\n  const result = await ctx.next.callAgent('/worker', { task: 'process-data' });\n\n  if (result.ok) {\n    return { message: `Result: ${result.data}` };\n  } else {\n    return { error: 'Worker failed', details: result.error.message };\n  }\n});\n\nrouter.agent('/worker', async (ctx) =\u003e {\n  const { task } = ctx.request.params;\n  return { processed: `Processed: ${task}` };\n});\n```\n\n## Agent-as-Tools\n\nThe **Agent-as-Tools** pattern allows you to expose any agent as a reusable tool that can be used by LLMs and other agents, creating powerful orchestration capabilities.\n\n### Creating an Agent as a Tool\n\n```typescript\nimport { z } from 'zod';\n\nconst researchAgent = new AiRouter();\n\nresearchAgent\n  .agent('/', async (ctx) =\u003e {\n    const { query } = ctx.request.params;\n    const summary = await researchService.search(query);\n    return {\n      summary,\n      sources: summary.sources,\n      timestamp: new Date().toISOString(),\n    };\n  })\n  .actAsTool('/', {\n    id: 'research',\n    name: 'Research Agent',\n    description: 'Performs comprehensive web research on any topic',\n    inputSchema: z.object({\n      query: z.string().describe('The research query or topic to investigate'),\n      depth: z\n        .enum(['shallow', 'deep'])\n        .optional()\n        .describe('Research depth level'),\n    }),\n    outputSchema: z.object({\n      summary: z.string().describe('Research summary'),\n      sources: z.array(z.string()).describe('List of source URLs'),\n      timestamp: z.string().describe('When the research was performed'),\n    }),\n    metadata: {\n      icon: '🔍',\n      title: 'Research',\n      category: 'information',\n    },\n  });\n\n// Mount the agent\nrouter.agent('/research', researchAgent);\n```\n\n### Using Agents as Tools\n\n```typescript\nrouter.agent('/blog-writer', async (ctx) =\u003e {\n  const { topic } = ctx.request.params;\n\n  const stream = streamText({\n    model: openai('gpt-4'),\n    prompt: `Write a comprehensive blog post about ${topic}. Use research to gather current information.`,\n    tools: {\n      research: ctx.next.agentAsTool('/research'),\n    },\n  });\n\n  return stream;\n});\n```\n\n## Next.js Integration\n\nAI Router integrates seamlessly with Next.js App Router:\n\n```typescript\n// app/api/chat/route.ts\nimport { AiRouter, MemoryStore } from '@microfox/ai-router';\n\nconst router = new AiRouter();\nrouter.setStore(new MemoryStore());\n\nrouter.agent('/', async (ctx) =\u003e {\n  return { message: 'Hello from ai-router!' };\n});\n\nexport async function POST(request: Request) {\n  const body = await request.json();\n  const { messages, ...restOfBody } = body;\n\n  const response = router.handle('/', {\n    request: {\n      ...restOfBody,\n      messages: messages || [],\n    },\n  });\n\n  return response;\n}\n```\n\n```typescript\n// app/page.tsx\n'use client';\n\nimport { useChat } from 'ai/react';\n\nexport default function Chat() {\n  const { messages, input, handleInputChange, handleSubmit } = useChat({\n    api: '/api/chat', // Single endpoint for all AI functionality\n  });\n\n  return (\n    \u003cdiv\u003e\n      {messages.map((message) =\u003e (\n        \u003cdiv key={message.id}\u003e\n          {message.role}: {message.content}\n        \u003c/div\u003e\n      ))}\n\n      \u003cform onSubmit={handleSubmit}\u003e\n        \u003cinput\n          value={input}\n          onChange={handleInputChange}\n          placeholder=\"Ask me anything...\"\n        /\u003e\n        \u003cbutton type=\"submit\"\u003eSend\u003c/button\u003e\n      \u003c/form\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n## Key Features\n\n- **Express.js Familiarity**: If you know Express, you already know AI Router\n- **Agent-as-Tools**: Expose agents as tools for LLM integration\n- **Hierarchical Routing**: Build complex, multi-agent systems with clear separation of concerns\n- **State Management**: Shared state across agents with internal state management\n- **Streaming Support**: Built on top of Vercel AI SDK v5 for real-time responses\n- **Type Safety**: Full TypeScript support with Zod schema validation\n- **Middleware Support**: Cross-cutting concerns with familiar middleware patterns\n- **Token Optimization**: Leaner orchestration with shared state\n\n## Prerequisites\n\nIt helps if you already have a good understanding of the following frameworks \u0026 packages:\n\n- Ai-SDK v5\n- Next.js\n- Tailwind CSS\n\n## Documentation\n\nFor comprehensive documentation, examples, and advanced usage patterns, visit our [documentation site](https://docs.microfox.ai/ai-router).\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrofox-ai%2Fai-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmicrofox-ai%2Fai-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrofox-ai%2Fai-router/lists"}