跳到内容

使用 Anthropic 的 Web 搜索与 Instructor 结合获取实时数据

Anthropic 的新 Web 搜索工具与 Instructor 结合使用时,提供了一种强大的方式来从 Web 获取实时结构化数据。这使您能够构建可以回答问题并提供最新信息的应用程序,超越了大型语言模型的知识截止日期。

在这篇博文中,我们将探讨如何使用 web_search 工具与 Instructor 结合来获取最新信息,并将其结构化为 Pydantic 模型。即使是简单的结构,对于清晰度和进一步处理也非常有效。

工作原理

Web 搜索工具使 Claude 模型能够在生成过程中执行 Web 搜索。当您在 API 请求中提供 web_search 工具时,如果提示需要 Claude 没有的信息,Claude 可以决定使用它。API 然后执行搜索,将结果返回给 Claude,Claude 就可以使用这些信息来生成响应。重要的是,Claude 会引用其搜索结果中的来源。您可以在Anthropic 官方文档中找到更多详细信息。

Instructor 通过允许您为所需的输出结构定义 Pydantic 模型来简化此过程。当 Claude 使用 Web 搜索工具并生成答案时,Instructor 会确保最终输出符合您定义的 schema。

示例:获取最新的 UFC 结果

让我们来看一个实际示例。我们想获取最新的 UFC 比赛结果。

首先,确保您已安装 instructoranthropic

uv add instructor anthropic

现在,让我们定义用于响应的 Pydantic 模型

import instructor
from pydantic import BaseModel


# Noticed thhat we use JSON not TOOLS mode
client = instructor.from_provider(
    "anthropic/claude-3-7-sonnet-latest",
    mode=instructor.Mode.ANTHROPIC_JSON,
    async_client=False,
)


class Citation(BaseModel):
    id: int
    url: str


class Response(BaseModel):
    citations: list[Citation]
    response: str

这个 Response 模型很简单。它让模型在生成答案之前,先生成一个引用文章的列表。

这有助于将其响应基于它检索到的来源,并提供更高质量的响应。

现在,我们可以进行 API 调用

response_data, completion_details = client.messages.create_with_completion(
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant that summarizes news articles. Your final response should be only contain a single JSON object returned in your final message to the user. Make sure to provide the exact ids for the citations that support the information you provide in the form of inline citations as [1] [2] [3] which correspond to a unique id you generate for a url that you find in the web search tool which is relevant to your final response.",
        },
        {
            "role": "user",
            "content": "What are the latest results for the UFC and who won? Answer this in a concise response that's under 3 sentences.",
        },
    ],
    tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 3}],
    response_model=Response,
)

print("Response:")
print(response_data.response)
print("\nCitations:")
for citation in response_data.citations:
    print(f"{citation.id}: {citation.url}")

这种方法提供了一种清晰的方式将 LLM 的答案放入定义的 Pydantic 对象中。examples/anthropic-web-tool/run.py 脚本反映了此实现。

预期输出(将根据实时 Web 搜索数据而异)

Response:
The latest UFC event was UFC Fight Night: Sandhagen vs Figueiredo held on May 3, 2025, in Des Moines, Iowa. Cory Sandhagen defeated former champion Deiveson Figueiredo by TKO (knee injury) in the main event, while Reinier de Ridder upset previously undefeated prospect Bo Nickal by TKO in the co-main event [1][2]. The next major UFC event is UFC 315 on May 10, featuring a welterweight championship bout between Belal Muhammad and Jack Della Maddalena [3].

Citations:
1: https://www.ufc.com/news/main-card-results-highlights-winner-interviews-ufc-fight-night-sandhagen-vs-figueiredo-wells-fargo-arena-des-moines
2: https://www.mmamania.com/2025/5/4/24423285/ufc-des-moines-results-sooo-about-last-night-sandhagen-vs-figueiredo-espn-mma-bo-nickal
3: https://en.wikipedia.org/wiki/UFC_315

主要优势

  • 实时信息:直接从 Web 获取最新数据。
  • 结构化输出:即使使用简单的模型,Instructor 也能确保输出是 Pydantic 对象,使其易于通过程序处理。
  • 来源引用:Claude 会自动引用来源,便于验证(详细信息在 API 响应中,本简化示例未显示)。
  • 减少幻觉:通过依赖 Web 搜索获取真实的、最新的数据,LLM 提供不正确或过时信息的可能性降低。

配置 Web 搜索工具

Anthropic 提供了几种配置 Web 搜索工具的选项

  • max_uses:限制 Claude 在单个请求中可以执行的搜索次数。
  • allowed_domains:将搜索限制在特定域名的列表中。
  • blocked_domains:阻止在某些域名上进行搜索。
  • user_location:通过提供大致位置(城市、地区、国家、时区)来本地化搜索结果。

例如,将搜索限制为 3 次,且仅允许来自 espn.comufc.com 的结果

    tools=[{
            "type": "web_search_20250305",
            "name": "web_search",
            "max_uses": 3,
            "allowed_domains": ["espn.com", "ufc.com"]
        }
    ],

您不能在同一请求中同时使用 allowed_domainsblocked_domains

结论

将 Anthropic 的 Web 搜索工具与 Instructor 的结构化数据能力相结合,为构建动态的、信息丰富的应用程序开辟了令人兴奋的可能性。无论您是跟踪体育比分、新闻更新还是市场趋势,这个强大的组合都可以帮助您有效地访问和组织实时 Web 数据,即使是使用简单的 Pydantic 模型。

请查看 examples/anthropic-web-tool/run.py 中的示例代码以了解此实现,并参阅Anthropic Web 搜索文档以获取有关该工具功能的更深入信息。