OpenRouter 入门与概览

OpenRouter 入门与概览

图像理解

4 分钟阅读

图像输入

如何向 OpenRouter 模型发送图像

向多模态模型发送包含图像的请求,可通过 /api/v1/chat/completions API 使用多部分 messages 参数完成。image_url 可以是 URL,也可以是 Base64 编码的图像。注意,多张图像可以放在 content 数组的不同条目中发送。单次请求可发送的图像数量因模型服务提供商和模型而异。由于内容的解析方式,我们建议先发送文本提示词,再发送图像。如果必须把图像放在前面,建议将其放在系统提示词中。

OpenRouter 的图像同时支持直接 URLBase64 编码数据

  • URL:对于可公开访问的图像更高效,因为不需要在本地编码
  • Base64:本地文件或无法公开访问的私有图像必须使用

使用图像 URL

以下是使用 URL 发送图像的方法:

import { OpenRouter } from '@openrouter/sdk';

const openRouter = new OpenRouter({
  apiKey: '<OPENROUTER_API_KEY>',
});

const result = await openRouter.chat.send({
  model: 'google/gemini-3-flash-preview',
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'text',
          text: '这张图片里有什么?',
        },
        {
          type: 'image_url',
          imageUrl: {
            url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg',
          },
        },
      ],
    },
  ],
  stream: false,
});

console.log(result);

使用 Base64 编码的图像

对于本地存储的图像,可以使用 Base64 编码发送。方法如下:

import { OpenRouter } from '@openrouter/sdk';
import * as fs from 'fs';

const openRouter = new OpenRouter({
  apiKey: '<OPENROUTER_API_KEY>',
});

async function encodeImageToBase64(imagePath: string): Promise<string> {
  const imageBuffer = await fs.promises.readFile(imagePath);
  const base64Image = imageBuffer.toString('base64');
  return `data:image/jpeg;base64,${base64Image}`;
}

// 读取图像并进行编码
const imagePath = 'path/to/your/image.jpg';
const base64Image = await encodeImageToBase64(imagePath);

const result = await openRouter.chat.send({
  model: 'google/gemini-3-flash-preview',
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'text',
          text: '这张图片里有什么?',
        },
        {
          type: 'image_url',
          imageUrl: {
            url: base64Image,
          },
        },
      ],
    },
  ],
  stream: false,
});

console.log(result);

支持的图像内容类型包括:

  • image/png
  • image/jpeg
  • image/webp
  • image/gif