功能
持續數小時的迴圈
執行高步驟數且逾時時間長的代理程式迴圈。代理程式 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 持久保存狀態。暫停以進行人工審查,或在部署後重新啟動,並從先前中斷的位置繼續執行。