跳到内容

图像、音频和文档输入

一些 LLM 现在能够理解音频、图像和文档内容。

图像输入

信息

一些模型不支持图像输入。请查看模型的文档以确认它是否支持图像输入。

如果您有图像的直接 URL,您可以使用 ImageUrl

main.py
from pydantic_ai import Agent, ImageUrl

agent = Agent(model='openai:gpt-4o')
result = agent.run_sync(
    [
        'What company is this logo from?',
        ImageUrl(url='https://iili.io/3Hs4FMg.png'),
    ]
)
print(result.data)
#> This is the logo for Pydantic, a data validation and settings management library in Python.

如果您在本地有图像,您也可以使用 BinaryContent

main.py
import httpx

from pydantic_ai import Agent, BinaryContent

image_response = httpx.get('https://iili.io/3Hs4FMg.png')  # Pydantic logo

agent = Agent(model='openai:gpt-4o')
result = agent.run_sync(
    [
        'What company is this logo from?',
        BinaryContent(data=image_response.content, media_type='image/png'),  # (1)!
    ]
)
print(result.data)
#> This is the logo for Pydantic, a data validation and settings management library in Python.
  1. 为了确保示例可运行,我们从网络下载此图像,但您也可以使用 Path().read_bytes() 读取本地文件的内容。

音频输入

信息

一些模型不支持音频输入。请查看模型的文档以确认它是否支持音频输入。

您可以使用 AudioUrlBinaryContent 提供音频输入。该过程与上面的示例类似。

文档输入

信息

一些模型不支持文档输入。请查看模型的文档以确认它是否支持文档输入。

警告

当使用 Gemini 模型时,无论您使用 DocumentUrl 还是 BinaryContent,文档内容将始终作为二进制数据发送。这是由于 Vertex AI 和 Google AI 处理文档输入的方式不同。

有关更多详细信息,请参阅 此讨论

如果您对此行为不满意,请在 GitHub 上提出 issue 让我们知道。

您可以使用 DocumentUrlBinaryContent 提供文档输入。该过程与上面的示例类似。

如果您有文档的直接 URL,您可以使用 DocumentUrl

main.py
from pydantic_ai import Agent, DocumentUrl

agent = Agent(model='anthropic:claude-3-sonnet')
result = agent.run_sync(
    [
        'What is the main content of this document?',
        DocumentUrl(url='https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf'),
    ]
)
print(result.data)
#> This document is the technical report introducing Gemini 1.5, Google's latest large language model...

支持的文档格式因模型而异。

您也可以使用 BinaryContent 直接传递文档数据

main.py
from pathlib import Path
from pydantic_ai import Agent, BinaryContent

pdf_path = Path('document.pdf')
agent = Agent(model='anthropic:claude-3-sonnet')
result = agent.run_sync(
    [
        'What is the main content of this document?',
        BinaryContent(data=pdf_path.read_bytes(), media_type='application/pdf'),
    ]
)
print(result.data)
#> The document discusses...