Claude 模型图片识别
Claude 提供多个支持图片识别(Vision)的模型。本文档以 claude-sonnet-4-5-20250929 为例,演示如何通过 Anthropic Messages API 进行图片识别。
基础配置
在开始使用 API 之前,请确保您已经获取了 API Key。如果还没有,请参考创建 API Key。
基础信息
- API Base URL:
https://api.agentsflare.com/anthropic/v1/messages - 认证方式:Bearer Token(通过
x-api-key请求头传递) - 内容类型:
application/json - Anthropic 版本:
2023-06-01
请求示例
图片识别
下方示例统一使用 base64 传递图片,可兼容 Anthropic 专属通道与 AWS Bedrock 标准通道。
python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
import mimetypes
import os
import sys
import anthropic
BASE_URL = "https://api.agentsflare.com/anthropic"
API_KEY = ""
MODEL = "claude-sonnet-4-5-20250929"
def file_to_base64(path: str) -> tuple[str, str]:
if not os.path.isfile(path):
raise FileNotFoundError(f"找不到文件:{path}")
mime, _ = mimetypes.guess_type(path)
if mime is None:
mime = "image/jpeg"
with open(path, "rb") as f:
data = base64.b64encode(f.read()).decode("utf-8")
return data, mime
def main():
if len(sys.argv) < 2:
print(f"用法:{sys.argv[0]} /path/to/image.jpg")
sys.exit(1)
image_path = sys.argv[1]
image_data, media_type = file_to_base64(image_path)
client = anthropic.Anthropic(
api_key=API_KEY,
base_url=BASE_URL,
)
message = client.messages.create(
model=MODEL,
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "请详细分析这张图片,描述你看到的内容、场景、主体、可能的文字信息,以及任何值得注意的细节。",
},
{
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": image_data,
},
},
],
}
],
)
print(message.content[0].text)
if __name__ == "__main__":
main()javascript
import fs from "fs";
import path from "path";
import Anthropic from "@anthropic-ai/sdk";
const BASE_URL = "https://api.agentsflare.com/anthropic";
const API_KEY = process.env.ANTHROPIC_API_KEY || ""; // 建议用环境变量
const MODEL = "claude-sonnet-4-5-20250929";
function fileToBase64(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`找不到文件:${filePath}`);
}
const ext = path.extname(filePath).toLowerCase();
let mediaType = "image/jpeg";
if (ext === ".png") mediaType = "image/png";
else if (ext === ".webp") mediaType = "image/webp";
else if (ext === ".gif") mediaType = "image/gif";
const data = fs.readFileSync(filePath).toString("base64");
return { data, mediaType };
}
async function main() {
const imagePath = process.argv[2];
if (!imagePath) {
console.error(`用法:${process.argv[1]} /path/to/image.jpg`);
process.exit(1);
}
if (!API_KEY) {
console.error("请设置 ANTHROPIC_API_KEY 环境变量或在代码里填入 API_KEY。");
process.exit(1);
}
const { data, mediaType } = fileToBase64(imagePath);
const client = new Anthropic({
apiKey: API_KEY,
baseURL: BASE_URL,
});
const message = await client.messages.create({
model: MODEL,
max_tokens: 1024,
messages: [
{
role: "user",
content: [
{
type: "text",
text: "请详细分析这张图片,描述你看到的内容、场景、主体、可能的文字信息,以及任何值得注意的细节。",
},
{
type: "image",
source: {
type: "base64",
media_type: mediaType,
data: data,
},
},
],
},
],
});
console.log(message.content[0].text);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});javascript
const fs = require("fs");
const path = require("path");
const Anthropic = require("@anthropic-ai/sdk");
const BASE_URL = "https://api.agentsflare.com/anthropic";
const API_KEY = process.env.ANTHROPIC_API_KEY || ""; // 建议用环境变量
const MODEL = "claude-sonnet-4-5-20250929";
function fileToBase64(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`找不到文件:${filePath}`);
}
const ext = path.extname(filePath).toLowerCase();
let mediaType = "image/jpeg";
if (ext === ".png") mediaType = "image/png";
else if (ext === ".webp") mediaType = "image/webp";
else if (ext === ".gif") mediaType = "image/gif";
const data = fs.readFileSync(filePath).toString("base64");
return { data, mediaType };
}
async function main() {
const imagePath = process.argv[2];
if (!imagePath) {
console.error(`用法:${process.argv[1]} /path/to/image.jpg`);
process.exit(1);
}
if (!API_KEY) {
console.error("请设置 ANTHROPIC_API_KEY 环境变量或在代码里填入 API_KEY。");
process.exit(1);
}
const { data, mediaType } = fileToBase64(imagePath);
const client = new Anthropic({
apiKey: API_KEY,
baseURL: BASE_URL,
});
const message = await client.messages.create({
model: MODEL,
max_tokens: 1024,
messages: [
{
role: "user",
content: [
{
type: "text",
text: "请详细分析这张图片,描述你看到的内容、场景、主体、可能的文字信息,以及任何值得注意的细节。",
},
{
type: "image",
source: {
type: "base64",
media_type: mediaType,
data: data,
},
},
],
},
],
});
console.log(message.content[0].text);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});go
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
)
const (
BASE_URL = "https://api.agentsflare.com/anthropic/v1"
MODEL = "claude-sonnet-4-5-20250929"
)
func fileToBase64(path string) (string, string, error) {
info, err := os.Stat(path)
if err != nil || info.IsDir() {
return "", "", fmt.Errorf("找不到文件:%s", path)
}
ext := filepath.Ext(path)
mediaType := mime.TypeByExtension(ext)
if mediaType == "" {
mediaType = "image/jpeg"
}
b, err := os.ReadFile(path)
if err != nil {
return "", "", err
}
return base64.StdEncoding.EncodeToString(b), mediaType, nil
}
func main() {
if len(os.Args) < 2 {
fmt.Printf("用法:%s /path/to/image.jpg\n", os.Args[0])
os.Exit(1)
}
apiKey := os.Getenv("ANTHROPIC_API_KEY")
if apiKey == "" {
fmt.Println("请设置 ANTHROPIC_API_KEY 环境变量。")
os.Exit(1)
}
imagePath := os.Args[1]
imageData, mediaType, err := fileToBase64(imagePath)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
reqBody := map[string]any{
"model": MODEL,
"max_tokens": 1024,
"messages": []any{
map[string]any{
"role": "user",
"content": []any{
map[string]any{
"type": "text",
"text": "请详细分析这张图片,描述你看到的内容、场景、主体、可能的文字信息,以及任何值得注意的细节。",
},
map[string]any{
"type": "image",
"source": map[string]any{
"type": "base64",
"media_type": mediaType,
"data": imageData,
},
},
},
},
},
}
bodyBytes, _ := json.Marshal(reqBody)
req, err := http.NewRequest("POST", BASE_URL+"/messages", bytes.NewReader(bodyBytes))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
req.Header.Set("x-api-key", apiKey)
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer resp.Body.Close()
respBytes, _ := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
fmt.Printf("HTTP %d\n%s\n", resp.StatusCode, string(respBytes))
os.Exit(1)
}
var out struct {
Content []struct {
Text string `json:"text"`
Type string `json:"type"`
} `json:"content"`
}
if err := json.Unmarshal(respBytes, &out); err != nil {
fmt.Println(string(respBytes))
return
}
if len(out.Content) == 0 {
fmt.Println("")
return
}
fmt.Println(out.Content[0].Text)
}注意:单个图片大小建议不要超过 20M,否则模型可能返回错误。
通道差异说明
Claude 图片识别在不同通道下对图片来源的支持有所不同:
| 通道 | 图片 URL | base64 | 说明 |
|---|---|---|---|
| Anthropic 专属通道 | ✅ 支持 | ✅ 支持 | 可直接使用图片 URL,也可以上传 base64。 |
| AWS Bedrock 标准通道 | ❌ 不支持 | ✅ 支持 | 仅支持 base64 编码的图片,不能使用 URL。 |
因此,上方示例统一使用 base64 方式,可同时兼容两种通道。如果你确定使用的是 Anthropic 专属通道,也可以将 image 块的 source 改为 URL 形式:
json
{
"type": "image",
"source": {
"type": "url",
"url": "https://example.com/image.jpg"
}
}支持的模型
以下 Claude 模型支持图片识别(Vision),可通过本接口调用(按推荐程度排序):
claude-sonnet-4-5-20250929推荐claude-sonnet-4-6推荐claude-opus-4-7Newclaude-opus-4-8Newclaude-sonnet-5Newclaude-fable-5Newclaude-mythos-5Newclaude-haiku-4-5-20251001claude-opus-4-6claude-opus-4-5-20251101claude-opus-4-1-20250805claude-sonnet-4-20250514即将下线claude-opus-4-20250514即将下线
💡 提示
请求示例中的 model 字段可替换为上方任意模型名称。
