routing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Routing - Complete API Reference

路由 - 完整API参考

Route messages to specialized agents, configure channel bindings, and manage tool access policies.

将消息路由至专用Agent,配置通道绑定,并管理工具访问策略。

Chat Commands

聊天命令

Agent Management

Agent管理

/agents                                     List available agents
/agent trading                              Switch to trading agent
/agent research                             Switch to research agent
/agent main                                 Switch to main agent
/agent status                               Current agent info
/agents                                     列出可用Agent
/agent trading                              切换至交易Agent
/agent research                             切换至研究Agent
/agent main                                 切换至主Agent
/agent status                               查看当前Agent信息

Channel Bindings

通道绑定

/bind trading                               Bind channel to trading agent
/bind research                              Bind channel to research agent
/unbind                                     Remove channel binding
/bindings                                   List all bindings
/bind trading                               将通道绑定至交易Agent
/bind research                              将通道绑定至研究Agent
/unbind                                     解除通道绑定
/bindings                                   列出所有绑定关系

Tool Policies (Admin)

工具策略(管理员)

/tools                                      List available tools
/tools allow <agent> <tool>                 Allow tool for agent
/tools deny <agent> <tool>                  Deny tool for agent
/tools policy <agent>                       View agent's tool policy

/tools                                      列出可用工具
/tools allow <agent> <tool>                 允许Agent使用指定工具
/tools deny <agent> <tool>                  禁止Agent使用指定工具
/tools policy <agent>                       查看Agent的工具策略

TypeScript API Reference

TypeScript API参考

Create Routing Service

创建路由服务

typescript
import { createRoutingService } from 'clodds/routing';

const routing = createRoutingService({
  // Default agent
  defaultAgent: 'main',

  // Agent definitions
  agents: {
    main: {
      name: 'Main',
      description: 'General assistant',
      model: 'claude-3-sonnet',
      systemPrompt: 'You are a helpful trading assistant...',
      allowedTools: ['*'],  // All tools
    },
    trading: {
      name: 'Trading',
      description: 'Order execution specialist',
      model: 'claude-3-haiku',
      systemPrompt: 'You execute trades efficiently...',
      allowedTools: ['execute', 'portfolio', 'markets', 'feeds'],
    },
    research: {
      name: 'Research',
      description: 'Market analysis expert',
      model: 'claude-3-opus',
      systemPrompt: 'You provide deep market analysis...',
      allowedTools: ['web-search', 'web-fetch', 'markets', 'news'],
    },
    alerts: {
      name: 'Alerts',
      description: 'Notification handler',
      model: 'claude-3-haiku',
      systemPrompt: 'You manage price alerts...',
      allowedTools: ['alerts', 'feeds'],
    },
  },

  // Storage
  storage: 'sqlite',
  dbPath: './routing.db',
});
typescript
import { createRoutingService } from 'clodds/routing';

const routing = createRoutingService({
  // 默认Agent
  defaultAgent: 'main',

  // Agent定义
  agents: {
    main: {
      name: 'Main',
      description: '通用助手',
      model: 'claude-3-sonnet',
      systemPrompt: '你是一个乐于助人的交易助手...',
      allowedTools: ['*'],  // 所有工具
    },
    trading: {
      name: 'Trading',
      description: '订单执行专家',
      model: 'claude-3-haiku',
      systemPrompt: '你能高效执行交易...',
      allowedTools: ['execute', 'portfolio', 'markets', 'feeds'],
    },
    research: {
      name: 'Research',
      description: '市场分析专家',
      model: 'claude-3-opus',
      systemPrompt: '你能提供深度市场分析...',
      allowedTools: ['web-search', 'web-fetch', 'markets', 'news'],
    },
    alerts: {
      name: 'Alerts',
      description: '通知处理程序',
      model: 'claude-3-haiku',
      systemPrompt: '你负责管理价格提醒...',
      allowedTools: ['alerts', 'feeds'],
    },
  },

  // 存储
  storage: 'sqlite',
  dbPath: './routing.db',
});

Route Message

消息路由

typescript
// Route determines best agent
const route = await routing.route({
  message: 'Buy 100 shares of Trump YES',
  channelId: 'telegram-123',
  userId: 'user-456',
});

console.log(`Routed to: ${route.agent}`);
console.log(`Confidence: ${route.confidence}`);
console.log(`Reason: ${route.reason}`);
typescript
// 路由模块确定最优Agent
const route = await routing.route({
  message: '买入100股Trump YES',
  channelId: 'telegram-123',
  userId: 'user-456',
});

console.log(`路由至: ${route.agent}`);
console.log(`置信度: ${route.confidence}`);
console.log(`原因: ${route.reason}`);

Get Available Agents

获取可用Agent

typescript
const agents = routing.getAgents();

for (const [id, agent] of Object.entries(agents)) {
  console.log(`${id}: ${agent.name}`);
  console.log(`  ${agent.description}`);
  console.log(`  Model: ${agent.model}`);
  console.log(`  Tools: ${agent.allowedTools.join(', ')}`);
}
typescript
const agents = routing.getAgents();

for (const [id, agent] of Object.entries(agents)) {
  console.log(`${id}: ${agent.name}`);
  console.log(`  ${agent.description}`);
  console.log(`  模型: ${agent.model}`);
  console.log(`  工具: ${agent.allowedTools.join(', ')}`);
}

Add Custom Agent

添加自定义Agent

typescript
routing.addAgent({
  id: 'defi',
  name: 'DeFi Specialist',
  description: 'Solana and EVM DeFi expert',
  model: 'claude-3-sonnet',
  systemPrompt: 'You are an expert in DeFi protocols...',
  allowedTools: ['solana', 'evm', 'bridge', 'portfolio'],
  patterns: [
    /swap|dex|liquidity|pool/i,
    /solana|jupiter|raydium/i,
    /uniswap|1inch|bridge/i,
  ],
});
typescript
routing.addAgent({
  id: 'defi',
  name: 'DeFi Specialist',
  description: 'Solana与EVM DeFi专家',
  model: 'claude-3-sonnet',
  systemPrompt: '你是DeFi协议领域的专家...',
  allowedTools: ['solana', 'evm', 'bridge', 'portfolio'],
  patterns: [
    /swap|dex|liquidity|pool/i,
    /solana|jupiter|raydium/i,
    /uniswap|1inch|bridge/i,
  ],
});

Update Agent

更新Agent

typescript
routing.updateAgent('trading', {
  model: 'claude-3-sonnet',  // Upgrade model
  allowedTools: [...currentTools, 'futures'],
});
typescript
routing.updateAgent('trading', {
  model: 'claude-3-sonnet',  // 升级模型
  allowedTools: [...currentTools, 'futures'],
});

Channel Bindings

通道绑定

typescript
// Bind channel to specific agent
await routing.addBinding({
  channelId: 'telegram-trading-group',
  agentId: 'trading',
});

// Get binding for channel
const binding = await routing.getBinding('telegram-trading-group');
console.log(`Channel bound to: ${binding?.agentId || 'default'}`);

// List all bindings
const bindings = await routing.getBindings();
for (const b of bindings) {
  console.log(`${b.channelId}${b.agentId}`);
}

// Remove binding
await routing.removeBinding('telegram-trading-group');
typescript
// 将通道绑定至指定Agent
await routing.addBinding({
  channelId: 'telegram-trading-group',
  agentId: 'trading',
});

// 获取通道绑定关系
const binding = await routing.getBinding('telegram-trading-group');
console.log(`通道绑定至: ${binding?.agentId || '默认Agent'}`);

// 列出所有绑定关系
const bindings = await routing.getBindings();
for (const b of bindings) {
  console.log(`${b.channelId}${b.agentId}`);
}

// 解除绑定
await routing.removeBinding('telegram-trading-group');

Tool Policies

工具策略

typescript
// Check if tool is allowed for agent
const allowed = routing.isToolAllowed('trading', 'web-search');
console.log(`web-search allowed for trading: ${allowed}`);

// Get allowed tools for agent
const tools = routing.getAllowedTools('trading');
console.log(`Trading agent tools: ${tools.join(', ')}`);

// Update tool policy
routing.setToolPolicy('trading', {
  allow: ['execute', 'portfolio', 'futures'],
  deny: ['web-search', 'browser'],
});

typescript
// 检查Agent是否被允许使用指定工具
const allowed = routing.isToolAllowed('trading', 'web-search');
console.log(`交易Agent是否可使用web-search: ${allowed}`);

// 获取Agent的可用工具
const tools = routing.getAllowedTools('trading');
console.log(`交易Agent可用工具: ${tools.join(', ')}`);

// 更新工具策略
routing.setToolPolicy('trading', {
  allow: ['execute', 'portfolio', 'futures'],
  deny: ['web-search', 'browser'],
});

Built-in Agents

内置Agent

AgentModelPurposeTools
mainSonnetGeneral assistantAll
tradingHaikuFast order executionExecute, Portfolio
researchOpusDeep analysisSearch, Fetch, News
alertsHaikuNotificationsAlerts, Feeds

Agent模型用途工具
mainSonnet通用助手全部
tradingHaiku快速订单执行Execute、Portfolio
researchOpus深度分析Search、Fetch、News
alertsHaiku通知管理Alerts、Feeds

Routing Rules

路由规则

Messages are routed based on:
  1. Channel binding — If channel is bound, use that agent
  2. Pattern matching — Match against agent patterns
  3. Keyword detection — Trading terms → trading agent
  4. Default fallback — Use main agent
消息路由依据以下优先级:
  1. 通道绑定 — 若通道已绑定,则使用对应Agent
  2. 模式匹配 — 匹配Agent预设的正则模式
  3. 关键词检测 — 交易类术语→交易Agent
  4. 默认回退 — 使用主Agent

Pattern Examples

模式示例

typescript
{
  trading: [/buy|sell|order|position|close/i],
  research: [/analyze|research|explain|why/i],
  alerts: [/alert|notify|when|watch/i],
}

typescript
{
  trading: [/buy|sell|order|position|close/i],
  research: [/analyze|research|explain|why/i],
  alerts: [/alert|notify|when|watch/i],
}

Tool Categories

工具分类

CategoryTools
Executionexecute, portfolio, markets
Datafeeds, news, web-search, web-fetch
Cryptosolana, evm, bridge
Systemfiles, browser, docker

分类工具
执行类execute, portfolio, markets
数据类feeds, news, web-search, web-fetch
加密货币类solana, evm, bridge
系统类files, browser, docker

Workspace Isolation

工作区隔离

Each agent can have isolated workspace:
typescript
routing.addAgent({
  id: 'research',
  workspace: {
    directory: '/tmp/research',
    allowedPaths: ['/tmp/research/**'],
    sandboxed: true,
  },
});

每个Agent可拥有独立工作区:
typescript
routing.addAgent({
  id: 'research',
  workspace: {
    directory: '/tmp/research',
    allowedPaths: ['/tmp/research/**'],
    sandboxed: true,
  },
});

Best Practices

最佳实践

  1. Use fast models for trading — Haiku for time-sensitive operations
  2. Restrict tools appropriately — Trading agent doesn't need browser
  3. Channel bindings — Dedicated channels for specific workflows
  4. Custom agents — Create specialized agents for your use case
  5. Monitor routing — Check logs to see routing decisions
  1. 交易场景使用快速模型 — 对时间敏感的操作选用Haiku模型
  2. 合理限制工具权限 — 交易Agent无需浏览器权限
  3. 利用通道绑定 — 为特定工作流设置专用通道
  4. 创建自定义Agent — 针对业务场景构建专用Agent
  5. 监控路由情况 — 查看日志跟踪路由决策