功能
持续数小时的循环
以高步数和长超时时间运行智能体循环。智能体 SDK 为您编排工具调用、重试和逐轮状态。
费用与步骤上限
使用 maxCost 和 stepCountIs 等停止条件限制运行。组合多个保护条件,让智能体在预算耗尽时正常结束。
可恢复状态
持久化保存对话消息、工具结果和共享上下文。在崩溃、部署或人工审核后重放或恢复长时间运行的任务。
流式进度
实时流式传输 token、工具调用和步骤事件,让仪表板和用户界面能够显示长时间运行任务的进度。
退避重试
针对临时 API 错误的自动重试可让运行数小时的智能体在提供商短暂故障期间持续运行,无需人工干预。
语音输入
接入 /api/v1/audio/transcriptions,即可通过电话、按键通话或实时麦克风驱动同一个智能体循环。
人工介入
在高风险工具调用时暂停以等待批准,注入修正内容,然后保留完整上下文继续同一次运行。
自问与复核
将 callModel 封装在对抗式自我审查循环中,持续运行直到智能体输出 [DONE]。在交付前发现遗漏、幻觉和未经核实的断言。
一次循环,数小时工作
智能体 SDK 让长时程运行保持精简。使用相同的原语设置上限、持久化状态并流式传输进度。
TypeScript
import { OpenRouter, tool, stepCountIs, maxCost } from '@openrouter/agent';
import { z } from '@openrouter-monorepo/lib-zod';
const openrouter = new OpenRouter();
const searchTool = tool({
name: 'search',
description: 'Search the web for information',
inputSchema: z.object({ query: z.string() }),
execute: async ({ query }) => {
return { results: await fetchResults(query) };
},
});
// Run for up to 200 steps OR $5 — whichever comes first
const result = openrouter.callModel({
model: '~anthropic/claude-opus-latest',
input: 'Research the fusion energy landscape and write a 5-page report.',
tools: [searchTool],
stopWhen: [stepCountIs(200), maxCost(5)],
});
// Stream tool calls as they happen so dashboards stay live
for await (const call of result.getToolCallsStream()) {
console.log('tool', call.name, call.arguments);
}
const text = await result.getText();语音输入,语音输出
通过电话、按键通话应用或实时麦克风驱动同一个智能体循环。OpenRouter 提供专用的 /api/v1/audio/transcriptions 和 /api/v1/audio/speech 端点。
转录
将音频发送到 /api/v1/audio/transcriptions,并选择 OpenRouter 上的任意 STT 模型,包括 Whisper。
运行智能体
将转录文本传递给 callModel,并使用与文本驱动运行相同的工具、停止条件和状态。
语音回复
将结果传入 /api/v1/audio/speech,以返回语音回复或向调用方流式传输音频。
通过三次调用构建语音驱动的智能体
TypeScript
import { OpenRouter } from '@openrouter/sdk';
import { OpenRouter as Agent, stepCountIs, maxCost } from '@openrouter/agent';
import { readFile, writeFile } from 'node:fs/promises';
const sdk = new OpenRouter();
const agent = new Agent();
// 1. Voice in -> text
const audio = await readFile('./request.wav');
const { text: prompt } = await sdk.stt.createTranscription({
model: 'openai/whisper-1',
inputAudio: { data: audio.toString('base64'), format: 'wav' },
});
// 2. Long-horizon agent loop with ceilings + tool calls
const result = agent.callModel({
model: '~anthropic/claude-opus-latest',
input: prompt,
stopWhen: [stepCountIs(50), maxCost(2)],
});
const reply = await result.getText();
// 3. Text -> voice out
const stream = await sdk.tts.createSpeech({
model: 'openai/gpt-4o-mini-tts-2025-12-15',
input: reply,
voice: 'alloy',
responseFormat: 'mp3',
});
const chunks: Uint8Array[] = [];
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
await writeFile('./reply.mp3', Buffer.concat(chunks));工作原理
1
捕获
接收文本或语音输入。需要时,只需一次 API 调用即可获得 Whisper 级别的语音转文本能力。
2
运行
将请求交给 callModel ,并提供工具和停止条件。SDK 负责处理循环、重试和流式传输。
3
继续
使用 StateAccessor 持久化状态。暂停以供人工审核,或在部署后重启,然后从上次中断的位置继续。