使用 Claude Vision 和 GPT-4V 的图像 + 文本智能体
在 API 调用中发送图像、进行视觉接地并使用感知图像的工具
使用 Claude Vision 和 GPT-4V 的图像 + 文本智能体 是 CoddyKit 上的免费 AI Agents 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
多模态智能体:图像 + 文本
多模态智能体不仅能阅读,还能看见。在同一次应用程序接口调用中同时发送图像和文本后,智能体就能回答有关照片的问题、分析图表、读取屏幕截图并描述示意图,所有操作都在同一个对话循环中完成。
使用 OpenAI 接口发送图像
OpenAI 的视觉模型(GPT-4o、GPT-4V)接受 content 数组,而不是普通字符串。每个元素要么是 text 对象,要么是 image_url 对象。图像可以是公开网址,也可以是经过 Base64 编码的数据网址。
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
# Using a public URL
response = client.chat.completions.create(
model='gpt-4o',
messages=[
{
'role': 'user',
'content': [
{
'type': 'image_url',
'image_url': {
'url': 'https://example.com/chart.png'
}
},
{
'type': 'text',
'text': 'What trend does this chart show?'
}
]
}
],
max_tokens=512
)
print(response.choices[0].message.content)Base64 图像编码
对于无法公开访问的图像(本地文件、屏幕截图、用户上传内容),请将其编码为 Base64,并使用 data:image/jpeg;base64,... 网址方案直接嵌入应用程序接口调用中。
import base64
from pathlib import Path
Path('screenshot.png').write_bytes(b'\x89PNG\r\n\x1a\n' + bytes(range(40)))
def encode_image_to_base64(image_path: str) -> str:
with open(image_path, 'rb') as f:
return base64.b64encode(f.read()).decode('utf-8')
def build_image_message(image_path: str, question: str, mime: str = 'jpeg') -> dict:
b64 = encode_image_to_base64(image_path)
data_url = f'data:image/{mime};base64,{b64}'
return {
'role': 'user',
'content': [
{'type': 'image_url', 'image_url': {'url': data_url}},
{'type': 'text', 'text': question}
]
}
message = build_image_message('screenshot.png', 'What error is shown?', mime='png')
print('Message built, image size:', len(message['content'][0]['image_url']['url']))克劳德视觉接口
Anthropic 的克劳德模型同样支持视觉能力。内容块使用包含 type: base64 和 media_type 的 source 字段。其结构与 OpenAI 的结构略有不同,但同样强大。
import anthropic
import base64
client = anthropic.Anthropic(api_key='YOUR_ANTHROPIC_API_KEY')
with open('diagram.png', 'rb') as f:
image_data = base64.standard_b64encode(f.read()).decode('utf-8')
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=512,
messages=[
{
'role': 'user',
'content': [
{
'type': 'image',
'source': {
'type': 'base64',
'media_type': 'image/png',
'data': image_data
}
},
{
'type': 'text',
'text': 'Describe the architecture shown in this diagram.'
}
]
}
]
)
print(response.content[0].text)根据文件扩展名检测 MIME 类型
不同的图像格式(JPEG、PNG、GIF、WebP)使用不同的 MIME 类型。请根据文件扩展名自动检测 MIME 类型,这样就不必在智能体代码中对其进行硬编码。
import os
import base64
with open('photo.jpg', 'wb') as f:
f.write(b'\xff\xd8\xff' + bytes(range(30)))
MIME_MAP = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp'
}
def get_mime_type(image_path: str) -> str:
ext = os.path.splitext(image_path)[1].lower()
mime = MIME_MAP.get(ext)
if not mime:
raise ValueError(f'Unsupported image format: {ext}')
return mime
def load_image_as_base64(image_path: str) -> tuple:
"""Returns (base64_string, mime_type)"""
mime = get_mime_type(image_path)
with open(image_path, 'rb') as f:
b64 = base64.b64encode(f.read()).decode('utf-8')
return b64, mime
b64, mime = load_image_as_base64('photo.jpg')
print(f'MIME: {mime}, Size: {len(b64)} bytes base64')智能体循环中的图像分析
在智能体循环中,图像分析是一种工具。智能体会像调用其他工具一样决定何时调用它。请在工具架构中定义该工具,并返回结构化数据(JSON),以便智能体通过程序对其进行推理。
def analyze_image_tool(image_path: str, query: str) -> dict:
"""
Agent tool: analyse an image and return structured findings.
"""
import anthropic, base64
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
b64, mime = load_image_as_base64(image_path)
structured_query = (
query + '\n\nRespond with JSON only: '
'{"description": str, "objects": [str], "text_found": str, "confidence": float}'
)
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=512,
messages=[{
'role': 'user',
'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': mime, 'data': b64}},
{'type': 'text', 'text': structured_query}
]
}]
)
import json
return json.loads(response.content[0].text)控制图像详细程度(OpenAI)
OpenAI 的视觉接口接受 detail 参数:low(快速、低成本,85 个词元)、high(详细,会将图像分块,最多 1105 个词元)或 auto(由模型决定)。简单的是非问题请使用 low,读取小字体等细粒度分析请使用 high。
def query_image_openai(
image_path: str,
question: str,
detail: str = 'auto' # 'low', 'high', or 'auto'
) -> str:
import base64
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
b64, mime = load_image_as_base64(image_path)
data_url = f'data:{mime};base64,{b64}'
response = client.chat.completions.create(
model='gpt-4o',
max_tokens=512,
messages=[{
'role': 'user',
'content': [
{
'type': 'image_url',
'image_url': {'url': data_url, 'detail': detail}
},
{'type': 'text', 'text': question}
]
}]
)
return response.choices[0].message.content多图像对话
您可以在一条消息中发送多张图像,也可以在对话的多轮消息中发送图像。这支持图像比较任务:“比较这两张屏幕截图,并描述发生了哪些变化。”
def compare_two_images(
image_path_1: str,
image_path_2: str,
comparison_question: str
) -> str:
import anthropic, base64
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
b64_1, mime_1 = load_image_as_base64(image_path_1)
b64_2, mime_2 = load_image_as_base64(image_path_2)
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=512,
messages=[{
'role': 'user',
'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': mime_1, 'data': b64_1}},
{'type': 'image', 'source': {'type': 'base64',
'media_type': mime_2, 'data': b64_2}},
{'type': 'text', 'text': comparison_question}
]
}]
)
return response.content[0].text图像智能体:屏幕截图读取器
一个实用场景是:智能体读取应用程序屏幕截图,提取表单字段值、错误消息或用户界面状态。这对于测试自动化和监控流程很有帮助。
SCREENSHOT_READER_PROMPT = (
'You are a UI analyser. Given this application screenshot, extract:\n'
'1. The current page/screen name\n'
'2. Any error messages\n'
'3. Key UI elements visible (buttons, form fields, text)\n'
'4. The overall app state\n\n'
'Return JSON: {"screen": str, "errors": [str], '
'"elements": [str], "state": str}'
)
def read_screenshot(screenshot_path: str) -> dict:
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
b64, mime = load_image_as_base64(screenshot_path)
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=512,
messages=[{
'role': 'user',
'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': mime, 'data': b64}},
{'type': 'text', 'text': SCREENSHOT_READER_PROMPT}
]
}]
)
return json.loads(response.content[0].text)优化视觉调用成本
视觉接口调用的成本明显高于纯文本调用。您可以通过以下方式优化成本:在编码前调整图像大小(大多数模型接受 512×512–2048×2048 的图像)、对简单任务使用 detail=low、缓存未发生变化的图像的分析结果,以及将多个问题合并到一次调用中。
from PIL import Image
import io, base64
def resize_and_encode(
image_path: str,
max_dim: int = 1024
) -> tuple:
img = Image.open(image_path)
# Resize maintaining aspect ratio
ratio = min(max_dim / img.width, max_dim / img.height)
if ratio < 1.0:
new_w = int(img.width * ratio)
new_h = int(img.height * ratio)
img = img.resize((new_w, new_h), Image.LANCZOS)
print(f'Resized to {new_w}x{new_h} (from {img.width}x{img.height})')
# Convert to JPEG for smaller size
buf = io.BytesIO()
img.save(buf, format='JPEG', quality=85)
b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
return b64, 'image/jpeg'视觉能力的局限与回退方案
视觉模型存在一些局限:它们无法可靠地读取非常小的文字,难以处理高度压缩的图像,并且可能臆造细节。请始终验证关键的提取数据(例如图表中的数字),并使用要求提供置信度分数的回退提示词。
def analyze_with_confidence(
image_path: str,
question: str,
confidence_threshold: float = 0.7
) -> dict:
import anthropic, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
b64, mime = load_image_as_base64(image_path)
prompt = (
question + '\n\nAlso rate your confidence (0.0-1.0) in the answer.\n'
'Return JSON: {"answer": str, "confidence": float, '
'"uncertainty_reason": str}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=256,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': mime, 'data': b64}},
{'type': 'text', 'text': prompt}
]}]
)
result = json.loads(response.content[0].text)
if result['confidence'] < confidence_threshold:
result['action'] = 'human_review_needed'
return result知识检查
OpenAI 视觉接口中,哪个参数控制图像分析的详细程度和成本?
回顾:图像-文本智能体
做得很好!您已经学习了以下内容:
- OpenAI 视觉能力:使用包含
image_url和text对象的content数组;支持网址和 Base64 - 克劳德视觉能力:使用带有
media_type的source.type: base64 - Base64 编码:读取文件 → 进行 Base64 编码 → 作为数据网址嵌入
- 详细程度:使用
low实现快速、低成本处理,使用high进行细粒度分析 - 成本优化:调整图像大小、合并问题、缓存结果
下一步:使用 Whisper 转写和 TTS 响应的音频-文本智能体工作流。
用 AI 导师学习 AI Agents — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 60
- 课程
- 239
常见问题解答
「使用 Claude Vision 和 GPT-4V 的图像 + 文本智能体」课时是免费的吗?
是的 — 「使用 Claude Vision 和 GPT-4V 的图像 + 文本智能体」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「使用 Claude Vision 和 GPT-4V 的图像 + 文本智能体」这节课中我会学到什么?
在 API 调用中发送图像、进行视觉接地并使用感知图像的工具 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「使用 Claude Vision 和 GPT-4V 的图像 + 文本智能体」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 Claude Vision 和 GPT-4V 的图像 + 文本智能体
- 音频 + 文本智能体工作流
- 智能体中的视频理解
- 跨模态推理模式