多模态Agent:让AI看懂图片听懂语音
AI · 技术

多模态Agent:让AI看懂图片听懂语音

模块 11:多模态 Agent

AI Agent 的「五感」—— 让 Agent 看见、听见、操作,突破纯文本的限制

1. 什么是多模态 Agent

传统 Agent 只能处理文本,多模态 Agent 能够理解和生成多种模态的信息:

传统 Agent(纯文本):
  文本输入 → LLM → 文本输出

多模态 Agent:
  文本 + 图片 + 音频 + 视频 → LLM → 文本 + 图片 + 语音 + 操作
                                           │
                                           ▼
                                    GUI 操作(点击、输入、滚动)

多模态能力矩阵:

能力 输入 输出 典型场景
视觉理解 图片、截图、PDF 文本描述 图表分析、OCR、UI理解
语音交互 音频、实时语音 语音回复 语音助手、会议记录
视频理解 视频流 文本摘要 视频分析、监控
GUI 操作 屏幕截图 鼠标键盘操作 自动化操作、RPA
图像生成 文本描述 图片 设计、营销素材

2. 视觉理解

2.1 图片输入 API

# OpenAI Vision
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "这张图片里有什么?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/image.png",
                        "detail": "high"  # low / high / auto
                    }
                }
            ]
        }
    ]
)
print(response.choices[0].message.content)
# Anthropic Claude Vision
import anthropic
import base64

client = anthropic.Anthropic()

# 从文件读取图片
with open("image.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode("utf-8")

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/png",
                        "data": image_data
                    }
                },
                {
                    "type": "text",
                    "text": "这张图片里有什么?"
                }
            ]
        }
    ]
)
print(message.content[0].text)

2.2 多图对比分析

async def analyze_images(image_paths: list[str], question: str) -> str:
    """多图对比分析"""
    content = []
    for path in image_paths:
        with open(path, "rb") as f:
            data = base64.standard_b64encode(f.read()).decode()
        content.append({
            "type": "image",
            "source": {"type": "base64", "media_type": "image/png", "data": data}
        })

    content.append({"type": "text", "text": question})

    message = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=2048,
        messages=[{"role": "user", "content": content}]
    )
    return message.content[0].text

2.3 OCR 文字提取

class OCRTool:
    """基于 LLM 的 OCR 工具"""
    name = "ocr"
    description = "从图片中提取文字内容"

    async def execute(self, image_path: str) -> str:
        with open(image_path, "rb") as f:
            data = base64.standard_b64encode(f.read()).decode()

        message = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=4096,
            messages=[{
                "role": "user",
                "content": [
                    {
                        "type": "image",
                        "source": {"type": "base64", "media_type": "image/png", "data": data}
                    },
                    {"type": "text", "text": "请提取图片中的所有文字,保持原始格式和布局。"}
                ]
            }]
        )
        return message.content[0].text

2.4 图表分析

class ChartAnalysisTool:
    """图表分析工具"""
    name = "analyze_chart"
    description = "分析图表数据,提取关键信息"

    async def execute(self, image_path: str, question: str = None) -> str:
        prompt = question or "请分析这张图表:1. 图表类型 2. 数据趋势 3. 关键数据点 4. 异常值"

        with open(image_path, "rb") as f:
            data = base64.standard_b64encode(f.read()).decode()

        message = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=2048,
            messages=[{
                "role": "user",
                "content": [
                    {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": data}},
                    {"type": "text", "text": prompt}
                ]
            }]
        )
        return message.content[0].text

3. 语音交互

3.1 语音识别(STT)

# OpenAI Whisper
from openai import OpenAI

client = OpenAI()

def transcribe_audio(audio_path: str) -> str:
    """语音转文字"""
    with open(audio_path, "rb") as f:
        transcript = client.audio.transcriptions.create(
            model="whisper-1",
            file=f,
            language="zh"  # 指定语言提高准确率
        )
    return transcript.text

3.2 语音合成(TTS)

def text_to_speech(text: str, output_path: str, voice: str = "alloy"):
    """文字转语音"""
    response = client.audio.speech.create(
        model="tts-1",
        voice=voice,  # alloy, echo, fable, onyx, nova, shimmer
        input=text
    )
    response.stream_to_file(output_path)

3.3 实时语音对话

import asyncio
import websockets

class VoiceAgent:
    """语音 Agent"""

    def __init__(self, agent):
        self.agent = agent
        self.stt_client = OpenAI()
        self.tts_client = OpenAI()

    async def process_audio(self, audio_data: bytes) -> bytes:
        """处理语音输入,返回语音输出"""
        # 1. 语音转文字
        transcript = self.stt_client.audio.transcriptions.create(
            model="whisper-1",
            file=("audio.wav", audio_data)
        )
        user_text = transcript.text

        # 2. Agent 处理
        response = await self.agent.run(user_text)

        # 3. 文字转语音
        speech = self.tts_client.audio.speech.create(
            model="tts-1",
            voice="nova",
            input=response
        )
        return speech.content

4. GUI Agent(屏幕操作)

4.1 什么是 GUI Agent

GUI Agent 能够"看"屏幕截图,理解界面元素,然后执行鼠标键盘操作:

截图 → 视觉模型理解 → 识别可操作元素 → 决定操作 → 执行点击/输入/滚动

4.2 Anthropic Computer Use

# Anthropic 的 Computer Use 能力
import anthropic

client = anthropic.Anthropic()

# 截图
def take_screenshot() -> str:
    """截取当前屏幕"""
    import pyautogui
    screenshot = pyautogui.screenshot()
    buffer = io.BytesIO()
    screenshot.save(buffer, format="PNG")
    return base64.standard_b64encode(buffer.getvalue()).decode()

# 发送给 Claude 分析并操作
def computer_use_step(screenshot_b64: str, task: str):
    message = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        tools=[{
            "name": "computer",
            "description": "控制计算机",
            "input_schema": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["click", "type", "key", "scroll", "screenshot"]
                    },
                    "coordinate": {"type": "array", "items": {"type": "integer"}},
                    "text": {"type": "string"}
                },
                "required": ["action"]
            }
        }],
        messages=[{
            "role": "user",
            "content": [
                {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": screenshot_b64}},
                {"type": "text", "text": task}
            ]
        }]
    )
    return message

4.3 基于 Playwright 的 Web Agent

from playwright.async_api import async_playwright

class WebAgent:
    """网页操作 Agent"""

    def __init__(self, llm):
        self.llm = llm
        self.browser = None
        self.page = None

    async def start(self):
        self.playwright = await async_playwright().start()
        self.browser = await self.playwright.chromium.launch(headless=False)
        self.page = await self.browser.new_page()

    async def navigate(self, url: str):
        await self.page.goto(url)

    async def screenshot(self) -> str:
        """截取当前页面"""
        screenshot = await self.page.screenshot()
        return base64.b64encode(screenshot).decode()

    async def get_accessibility_tree(self) -> str:
        """获取页面可访问性树"""
        snapshot = await self.page.accessibility.snapshot()
        return format_accessibility_tree(snapshot)

    async def execute_action(self, action: dict):
        """执行页面操作"""
        act = action["action"]

        if act == "click":
            await self.page.click(action["selector"])
        elif act == "type":
            await self.page.fill(action["selector"], action["text"])
        elif act == "press":
            await self.page.keyboard.press(action["key"])
        elif act == "scroll":
            await self.page.mouse.wheel(0, action["delta_y"])

    async def run_task(self, task: str):
        """执行网页任务"""
        for step in range(20):
            # 截图 + 获取页面结构
            screenshot = await self.screenshot()
            tree = await self.get_accessibility_tree()

            # 让 LLM 决定下一步操作
            action = await self.llm.chat(f"""
任务:{task}
当前页面结构:{tree}
请决定下一步操作,返回 JSON:
{{"action": "click|type|press|scroll|done", "selector": "...", "text": "...", "key": "..."}}
""")

            if action.get("action") == "done":
                return "任务完成"

            await self.execute_action(action)

4.4 屏幕理解 Agent

class ScreenUnderstandingAgent:
    """屏幕理解 Agent - 理解屏幕上发生了什么"""

    async def analyze_screen(self, screenshot_b64: str) -> dict:
        """分析屏幕截图"""
        message = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=2048,
            messages=[{
                "role": "user",
                "content": [
                    {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": screenshot_b64}},
                    {"type": "text", "text": """分析这个屏幕截图,返回 JSON:
{
  "app": "当前应用名称",
  "page": "当前页面/视图",
  "elements": [
    {"type": "button|input|link|text", "label": "元素标签", "position": "大致位置"}
  ],
  "suggested_actions": ["可以执行的操作"]
}"""}
                ]
            }]
        )
        return json.loads(message.content[0].text)

5. 多模态 RAG

5.1 图片检索

# 使用 CLIP 进行图文检索
from transformers import CLIPProcessor, CLIPModel
import torch

model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")

def get_image_embedding(image_path: str):
    from PIL import Image
    image = Image.open(image_path)
    inputs = processor(images=image, return_tensors="pt")
    with torch.no_grad():
        embedding = model.get_image_features(**inputs)
    return embedding.numpy().tolist()[0]

def get_text_embedding(text: str):
    inputs = processor(text=[text], return_tensors="pt", padding=True)
    with torch.no_grad():
        embedding = model.get_text_features(**inputs)
    return embedding.numpy().tolist()[0]

5.2 多模态 RAG Pipeline

class MultimodalRAG:
    """多模态 RAG - 同时检索文本和图片"""

    def __init__(self, text_db, image_db, llm):
        self.text_db = text_db
        self.image_db = image_db
        self.llm = llm

    async def query(self, question: str) -> str:
        # 1. 同时检索文本和图片
        text_results = self.text_db.search(question, limit=3)
        image_results = self.image_db.search(question, limit=2)

        # 2. 构建多模态上下文
        content = [{"type": "text", "text": f"问题:{question}\n\n相关文本:\n"}]

        for doc in text_results:
            content.append({"type": "text", "text": doc.text})

        for img in image_results:
            content.append({
                "type": "image",
                "source": {"type": "base64", "media_type": "image/png", "data": img.base64}
            })

        content.append({"type": "text", "text": "\n请基于以上文本和图片回答问题。"})

        # 3. 生成回答
        message = self.llm.chat(content)
        return message

6. 多模态 Agent 架构

用户输入
  ├── 文本消息
  ├── 语音消息 → STT → 文本
  ├── 图片 → Vision API → 描述
  └── 屏幕截图 → Vision API → 界面理解
       │
       ▼
  ┌──────────────┐
  │  多模态融合   │  统一表示
  └──────┬───────┘
         │
         ▼
  ┌──────────────┐
  │  Agent 核心   │  推理 + 规划
  └──────┬───────┘
         │
  ┌──────┴──────┐
  ▼            ▼
工具调用      输出生成
  │            │
  ├── 搜索     ├── 文本回复
  ├── 计算     ├── TTS 语音
  ├── GUI 操作  ├── 图片生成
  └── API 调用  └── 文件操作

7. 多模态工具示例

# 图片生成工具
class ImageGenerationTool:
    name = "generate_image"
    description = "根据文字描述生成图片"

    async def execute(self, prompt: str, size: str = "1024x1024") -> str:
        response = client.images.generate(
            model="dall-e-3",
            prompt=prompt,
            size=size,
            quality="standard"
        )
        return response.data[0].url

# 图片编辑工具
class ImageEditTool:
    name = "edit_image"
    description = "编辑现有图片"

    async def execute(self, image_path: str, instruction: str) -> str:
        # 用 Vision 理解图片 + 用 DALL-E 编辑
        analysis = await analyze_image(image_path, instruction)
        # 生成编辑后的图片
        response = client.images.edit(
            model="dall-e-2",
            image=open(image_path, "rb"),
            prompt=instruction
        )
        return response.data[0].url

# PDF 分析工具
class PDFAnalysisTool:
    name = "analyze_pdf"
    description = "分析 PDF 文档内容"

    async def execute(self, pdf_path: str, question: str = None) -> str:
        import fitz  # PyMuPDF
        doc = fitz.open(pdf_path)

        # 提取文本和图片
        content = []
        for page_num, page in enumerate(doc):
            text = page.get_text()
            content.append({"type": "text", "text": f"--- 第 {page_num+1} 页 ---\n{text}"})

            # 提取图片
            for img in page.get_images():
                # 转为 base64
                pix = fitz.Pixmap(doc, img[0])
                img_b64 = pix.tobytes("png")
                content.append({
                    "type": "image",
                    "source": {"type": "base64", "media_type": "image/png", "data": base64.b64encode(img_b64).decode()}
                })

        question = question or "请总结这个 PDF 的主要内容"
        content.append({"type": "text", "text": f"\n{question}"})

        message = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=4096,
            messages=[{"role": "user", "content": content}]
        )
        return message.content[0].text

8. 最佳实践

1. 图片输入优化
   - 压缩图片大小(< 5MB)
   - 裁剪关键区域,减少噪声
   - 高分辨率用于 OCR,低分辨率用于分类

2. 语音交互优化
   - 流式 STT 减少延迟
   - 打断检测(VAD)
   - 语音 + 文本双通道

3. GUI Agent 优化
   - 优先用 Accessibility Tree 而非截图
   - 截图压缩 + 关键区域裁剪
   - 操作前截图确认

4. 成本控制
   - 图片 detail: "low" 省 token
   - 视频抽取关键帧而非全帧
   - 缓存视觉分析结果

9. 延伸阅读


小码提示: 多模态是 Agent 的下一个爆发点。先掌握 Vision API(图片理解),再尝试 GUI Agent(屏幕操作)。视觉理解 + 工具调用的组合,能解锁很多纯文本做不到的场景。