Skip to content

@openrouter/agent 是构建 AI agent 应用的核心 SDK,提供 callModeltool()、stop conditions 三大原语。和 Client SDK 的单次请求/响应不同,Agent SDK 自动处理多轮推理循环:模型调用工具 → SDK 执行工具 → 结果回传模型 → 循环直到满足终止条件。本页介绍 SDK 的适用场景、安装方式、完整快速示例,以及与 Client SDK 的选型对比。

什么时候用 Agent SDK

当你需要 agentic 行为——即多步推理,模型需要调用工具、处理结果、再决定下一步——选 Agent SDK:

  • 多轮 agent 循环callModel 自动循环直到满足 stop condition
  • Tool 定义 — 用 tool() helper 定义工具,SDK 自动执行
  • Stop conditions — 用 stepCountIshasToolCallmaxCost 等控制循环终止
  • 对话状态管理 — SDK 跨轮次自动追踪 messages、tool results 和上下文
  • Streaming — 每个 agent 步骤内实时 token 输出
  • 动态参数 — 根据上下文在轮次之间切换 model、temperature 或 tools

如果只需要简单的请求/响应调用,不涉及 agent 循环,Client SDK 更轻量。

安装

bash
npm install @openrouter/agent

快速示例

typescript
import { callModel, tool } from '@openrouter/agent';
import { z } from 'zod';

const weatherTool = tool({
  name: 'get_weather',
  description: 'Get the current weather for a location',
  inputSchema: z.object({
    location: z.string().describe('City name'),
  }),
  execute: async ({ location }) => {
    return { temperature: 72, condition: 'sunny', location };
  },
});

const result = await callModel({
  model: 'anthropic/claude-sonnet-4',
  messages: [
    { role: 'user', content: 'What is the weather in San Francisco?' },
  ],
  tools: [weatherTool],
});

const text = await result.getText();
console.log(text);

SDK 会自动完成:发送消息 → 接收 tool call → 执行 get_weather → 把结果回传 → 返回最终响应,全部在一次 callModel 调用内完成。

核心概念

callModel

主入口。运行一个推理循环:

  1. 向模型发送 messages
  2. 如果模型返回 tool calls,自动执行它们
  3. 把 tool results 追加到对话
  4. 重复,直到满足 stop condition 或不再有 tool calls

Tools

tool() helper 定义工具,每个工具包含名称、描述、Zod 参数 schema 和 execute 函数:

typescript
import { tool } from '@openrouter/agent';
import { z } from 'zod';

const searchTool = tool({
  name: 'search',
  description: 'Search the web',
  inputSchema: z.object({ query: z.string() }),
  execute: async ({ query }) => {
    return { results: ['...'] };
  },
});

Stop conditions

控制 agent 循环何时终止:

typescript
import { callModel, stepCountIs, maxCost } from '@openrouter/agent';

const result = await callModel({
  model: 'anthropic/claude-sonnet-4',
  messages: [{ role: 'user', content: 'Research this topic thoroughly' }],
  tools: [searchTool],
  stopWhen: [stepCountIs(10), maxCost(0.50)],
});

Agent SDK vs Client SDK 选型

Agent SDKClient SDK
定位Agent 原语——多轮循环、工具调用、stop conditions轻量 API 客户端——直接映射 REST API,完整类型安全
选择时机需要内置 agent 循环、工具执行和状态管理需要直接调用模型,自己管理编排逻辑
对话状态callModel 自动管理自行维护
工具执行tool() helper 自动执行自行派发 tool calls
语言支持TypeScriptTypeScript、Python、Go

常见问题

Q: Agent SDK 和 Client SDK 可以混用吗?

A: 可以。两者都通过 OpenRouter API 调用模型,只是抽象层级不同。简单场景用 Client SDK,复杂 agent 逻辑用 Agent SDK,按需选择即可。

Q: stop condition 同时设多个时,哪个先满足就停止?

A: 是的,stopWhen 数组里任意一个 condition 满足,循环就会终止。stepCountIs(10)maxCost(0.50) 任意一个触发都会停止。

Q: callModel 支持 streaming 吗?

A: 支持。使用 result.getTextStream() 获取实时文本流,或 result.getItemsStream() 获取包含 reasoning、tool calls 等所有类型的完整 item 流。详见 Streaming 文档