功能
多模态
多模态功能让你可以向模型发送图片、PDF 等非文本内容。
支持的模态
| 模态 | 支持的 Provider | 说明 |
|---|---|---|
| 图片 | OpenAI, Anthropic, Google | 分析图片内容 |
| Anthropic, Google | 读取文档内容 | |
| 音频 | OpenAI (Whisper) | 语音转文字 |
图片输入
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: '这张图片里有什么?' },
{
type: 'image_url',
image_url: {
url: 'https://example.com/image.jpg',
},
},
],
},
],
});import fs from 'fs';
const imageBuffer = fs.readFileSync('image.jpg');
const base64Image = imageBuffer.toString('base64');
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: '描述这张图片' },
{
type: 'image_url',
image_url: {
url: `data:image/jpeg;base64,${base64Image}`,
},
},
],
},
],
});多张图片
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: '比较这两张图片的区别' },
{
type: 'image_url',
image_url: { url: 'https://example.com/image1.jpg' },
},
{
type: 'image_url',
image_url: { url: 'https://example.com/image2.jpg' },
},
],
},
],
});图片质量设置
对于 OpenAI 的模型,可以设置图片处理质量:
{
type: 'image_url',
image_url: {
url: 'https://example.com/image.jpg',
detail: 'high', // 'auto' | 'low' | 'high'
},
}| 选项 | 说明 | Token 消耗 |
|---|---|---|
auto | 自动选择 | 根据图片大小 |
low | 低分辨率 | 85 tokens |
high | 高分辨率 | 根据图片大小,最高 1105+ tokens |
PDF 输入
PDF 支持仅限 Anthropic 和 Google 模型。
Anthropic Claude
const response = await client.chat.completions.create({
model: 'claude-3-5-sonnet-20241022',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: '总结这份文档的主要内容' },
{
type: 'document',
source: {
type: 'base64',
media_type: 'application/pdf',
data: pdfBase64,
},
},
],
},
],
});跨 Provider 格式
BYOKS 统一了不同 Provider 的多模态格式:
统一的图片格式
// 这个格式适用于所有支持图片的 Provider
{
type: 'image_url',
image_url: {
url: 'https://example.com/image.jpg',
// 或 data:image/jpeg;base64,xxx
},
}Provider 映射
| BYOKS 格式 | OpenAI | Anthropic | |
|---|---|---|---|
image_url.url | 直接使用 | 转为 source.url | 转为 inlineData |
detail | 直接使用 | 忽略 | 忽略 |
最佳实践
图片大小
- 建议压缩大图片以减少 Token 消耗
- 对于简单任务使用
detail: 'low'
图片格式
- 支持:JPEG, PNG, GIF, WebP
- 推荐:JPEG(更小的文件大小)
多模态 + 流式
多模态请求也支持流式响应:
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: '详细描述这张图片' },
{ type: 'image_url', image_url: { url: '...' } },
],
},
],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}