Skip to content

本页介绍 OpenRouter callModel 的文本生成核心用法:如何传入不同格式的输入(字符串、消息数组、多模态图片),如何选择模型及配置 fallback,如何控制 temperature/maxTokens 等生成参数,以及如何处理响应和错误。适合需要快速上手文本生成的开发者。

基本用法

typescript
import { OpenRouter } from '@openrouter/agent';

const openrouter = new OpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});

const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  input: 'Explain quantum computing in one sentence.',
});

const text = await result.getText();

输入格式

字符串输入

最简单的输入方式:

typescript
const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  input: 'What is the speed of light?',
});

消息数组

支持多轮对话历史:

typescript
const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  input: [
    { role: 'user', content: 'My name is Alice.' },
    { role: 'assistant', content: 'Hello Alice! How can I help you today?' },
    { role: 'user', content: 'What is my name?' },
  ],
});

多模态输入

发送图片(需支持视觉的模型):

typescript
const result = openrouter.callModel({
  model: 'openai/gpt-5.2',
  input: [
    {
      type: 'message',
      role: 'user',
      content: [
        { type: 'input_text', text: 'What is in this image?' },
        {
          type: 'input_image',
          imageUrl: 'https://example.com/image.jpg',
          detail: 'auto',
        },
      ],
    },
  ],
});

System 指令

typescript
const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  instructions: 'You are a helpful coding assistant. Be concise and provide working code examples.',
  input: 'How do I read a file in Node.js?',
});

模型选择

单一模型

typescript
const result = openrouter.callModel({
  model: 'anthropic/claude-sonnet-4.5',
  input: 'Hello!',
});

模型 Fallback

按优先级列出多个模型,SDK 依次尝试直到成功:

typescript
const result = openrouter.callModel({
  models: ['anthropic/claude-sonnet-4.5', 'openai/gpt-5.2', 'google/gemini-pro'],
  input: 'Hello!',
});

响应方法

getText()

typescript
const text = await result.getText();
console.log(text); // "The speed of light is approximately 299,792 km/s."

getResponse()

获取完整响应,含 token 用量:

typescript
const response = await result.getResponse();

console.log(response.output); // 完整输出数组
console.log(response.usage);  // token 用量信息
// - inputTokens: prompt 消耗的 token
// - outputTokens: 生成的 token
// - cachedTokens: 命中缓存的 token(节省费用)

生成参数

typescript
const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  input: 'Write a creative story.',

  // temperature: 0 = 确定性,2 = 高创意
  temperature: 0.7,

  // 最大生成 token 数
  maxOutputTokens: 1000,

  // Top-p 采样
  topP: 0.9,
});

响应格式

强制模型输出 JSON:

typescript
const result = openrouter.callModel({
  model: 'openai/gpt-5-nano',
  input: 'List three programming languages.',
  text: {
    format: {
      type: 'json_object',
    },
  },
});

const text = await result.getText();
const data = JSON.parse(text);

错误处理

typescript
try {
  const result = openrouter.callModel({
    model: 'openai/gpt-5-nano',
    input: 'Hello!',
  });

  const text = await result.getText();
} catch (error) {
  if (error instanceof Error && 'statusCode' in error) {
    if (error.statusCode === 401) {
      console.error('Invalid API key');
    } else if (error.statusCode === 429) {
      console.error('Rate limited - try again later');
    } else if (error.statusCode === 503) {
      console.error('Model unavailable');
    }
  } else {
    console.error('Unexpected error:', error);
  }
}

并发请求

多个独立请求可以并行发起:

typescript
const [result1, result2, result3] = await Promise.all([
  openrouter.callModel({ model: 'openai/gpt-5-nano', input: 'Question 1' }).getText(),
  openrouter.callModel({ model: 'openai/gpt-5-nano', input: 'Question 2' }).getText(),
  openrouter.callModel({ model: 'openai/gpt-5-nano', input: 'Question 3' }).getText(),
]);

常见问题

Q: modelmodels 参数有什么区别?

A: model 指定单一模型,失败即报错。models 是 fallback 列表,SDK 按顺序尝试,第一个成功的模型返回结果,适合需要高可用性的生产场景。

Q: temperature 设为 0 会影响创意写作吗?

A: 会。temperature: 0 让模型输出尽可能确定,适合需要精确答案的场景(代码生成、事实问答)。创意写作建议设 0.7~1.2 之间。

Q: maxOutputTokens 超过模型上限会怎样?

A: SDK 会按模型实际上限截断,不会报错。建议根据具体模型文档设置合理值,避免浪费费用。