以编程方式使用文档

Tavily 是一个专为 AI 代理(LLM)构建的搜索引擎,提供实时、准确和事实性的结果,速度极快。Tavily 提供一个 Extract 端点,可用于从一个或多个 URL 中提取内容。

概述

集成详情

可序列化JS 支持版本
TavilyExtractlangchain-tavily!PyPI - 版本

工具特性

返回产物原生异步返回数据价格
raw content and images1,000 free credits / month

设置

该集成位于 langchain-tavily package.

pip install -qU langchain-tavily

凭据

我们还需要设置 Tavily API 密钥。您可以通过访问 此网站 并创建一个账户来获取 API 密钥。

if not os.environ.get("TAVILY_API_KEY"):
    os.environ["TAVILY_API_KEY"] = getpass.getpass("Tavily API key:\n")

实例化

该工具在实例化时接受以下参数:

  • - extract_depth (可选,字符串):提取深度,可以是 "basic" 或 "advanced"。默认为 "basic"。
  • - include_images (可选,布尔值):是否在提取中包含图像。默认为 False。

有关可用参数的完整概述,请参阅 Tavily Extract API 文档

from langchain_tavily import TavilyExtract

tool = TavilyExtract(
    extract_depth="basic",
    include_images=False,
)

调用

直接使用参数调用

Tavily Extract 工具在调用时接受以下参数:

  • - urls (必填):要从中提取内容的 URL 列表。
  • - 两者都可以 extract_depthinclude_images 也可以在调用时设置

注意:可选参数可供代理动态设置。如果您在实例化时设置了一个参数,然后使用不同的值调用该工具,该工具将使用您在调用时传递的值。

tool.invoke({"urls": ["https://en.wikipedia.org/wiki/Lionel_Messi"]})
{'results': [{'url': 'https://en.wikipedia.org/wiki/Lionel_Messi',
   'raw_content': 'Lionel Messi - Wikipedia\nJump to content\nMain menu\nMain menu\nmove to sidebar hide\nNavigation\n\nMain page\nContents\nCurrent events\nRandom article\nAbout Wikipedia\nContact us\n\nContribute\n\nHelp\nLearn to edit\nCommunity portal\nRecent changes\nUpload file\nSpecial pages\n\n  \nSearch\nSearch\nAppearance\n\nDonate\nCreate account\nLog in\n\nPersonal tools\n\nDonate\nCreate account\nLog in\n\nPages for logged out editors learn more\n\nContributions\nTalk\n\nContents\nm... (truncated) ',
   'images': []}],
 'failed_results': [],
 'response_time': 0.02}

使用 ToolCall 调用

我们还可以使用模型生成的 ToolCall 来调用该工具,在这种情况下会返回一个 ToolMessage:

# This is usually generated by a model, but we'll create a tool call directly for demo purposes.
model_generated_tool_call = {
    "args": {"urls": ["https://en.wikipedia.org/wiki/Lionel_Messi"]},
    "id": "1",
    "name": "tavily",
    "type": "tool_call",
}
tool_msg = tool.invoke(model_generated_tool_call)

# The content is a JSON string of results
print(tool_msg.content[:400])
{"results": [{"url": "https://en.wikipedia.org/wiki/Lionel_Messi", "raw_content": "Lionel Messi - Wikipedia\nJump to content\nMain menu\nMain menu\nmove to sidebar hide\nNavigation\n\nMain page\nContents\nCurrent events\nRandom article\nAbout Wikipedia\nContact us\n\nContribute\n\nHelp\nLearn to edit\nCommunity portal\nRecent changes\nUpload file\nSpecial pages\n\n  \nSearch\nSearch\nAppearance\n\

在代理中使用

我们可以通过将工具绑定到代理来直接与代理执行器一起使用我们的工具。这使代理能够动态设置 Tavily 搜索工具的可用参数。

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OPENAI_API_KEY:\n")
from langchain.chat_models import init_chat_model

model = init_chat_model(model="gpt-5.5", model_provider="openai", temperature=0)
from langchain_tavily import TavilyExtract
from langchain.agents import create_agent


tavily_extract_tool = TavilyExtract()

agent = create_agent(model, [tavily_extract_tool])

user_input = "['https://en.wikipedia.org/wiki/Albert_Einstein','https://en.wikipedia.org/wiki/Theoretical_physics']"

stream = agent.stream_events({"messages": user_input}, version="v3")
for snapshot in stream.values:
    snapshot["messages"][-1].pretty_print()
================================ Human Message =================================

['https://en.wikipedia.org/wiki/Albert_Einstein','https://en.wikipedia.org/wiki/Theoretical_physics']
================================== Ai Message ==================================
Tool Calls:
  tavily_extract (call_BAK906Cpy8fDZttwqYTMdkKp)
 Call ID: call_BAK906Cpy8fDZttwqYTMdkKp
  Args:
    urls: ['https://en.wikipedia.org/wiki/Albert_Einstein']
    extract_depth: advanced
    include_images: False
  tavily_extract (call_4NFRB92QpiI5jnCTGr76dgMX)
 Call ID: call_4NFRB92QpiI5jnCTGr76dgMX
  Args:
    urls: ['https://en.wikipedia.org/wiki/Theoretical_physics']
    extract_depth: advanced
    include_images: False
================================= Tool Message =================================
Name: tavily_extract

{"results": [{"url": "https://en.wikipedia.org/wiki/Theoretical_physics", "raw_content": "Published Time: 2003-09-21T15:11:11Z\nTheoretical physics - Wikipedia\nJump to content\nMain menu\nMain menu\nmove to sidebar hide\nNavigation\n\nMain page\nContents\nCurrent events\nRandom article\nAbout Wikipedia\nContact us\n\nContribute\n\nHelp\nLearn to edit\nCommunity portal\nRecent changes\nUpload file\nSpecial pages\n\n  \nSearch\nSearch\nAppearance\n\nDonate\nCreate account\nLog in\n\nPersonal tools\n\nDonate\nCreate account\nLog in\n\nPages for logged out editors learn more\n\nContributions\nTalk\n\nContents\nmove to sidebar hide\n\n(Top)\n\n1 Overview\n\n\n2 History\n\n\n3 Mainstream theories... (truncated) ...", "images": []}], "failed_results": [], "response_time": 0.01}
================================== Ai Message ==================================

Here is a summary of the content from the Wikipedia pages on Albert Einstein and Theoretical Physics:

### Albert Einstein
Albert Einstein was a German-born theoretical physicist renowned for developing the theory of relativity, which revolutionized our understanding of space, time, and energy. His mass-energy equivalence formula, E=mc², is one of the most famous equations in physics. Einstein received the 1921 Nobel Prize in Physics for his explanation of the photoelectric effect, which was pivotal in establishing quantum theory.

Einstein's early life was marked by a deep interest in mathematics and physics, leading him to study at the Swiss Federal Polytechnic in Zurich. He worked at the Swiss Patent Office while developing his theories. His "miracle year" in 1905 saw the publication of four groundbreaking papers, including those on special relativity and the photoelectric effect.

Throughout his career, Einstein made significant contributions to statistical mechanics, quantum theory, and cosmology. He was a vocal advocate for civil rights and pacifism, and he played a role in alerting the U.S. to the potential of nuclear weapons during World War II. Einstein spent his later years at the Institute for Advanced Study in Princeton, New Jersey, where he continued to work on a unified field theory until his death in 1955.

### Theoretical Physics
Theoretical physics is a branch of physics that uses mathematical models and abstractions to explain and predict natural phenomena. It contrasts with experimental physics, which uses empirical methods to test these theories. Theoretical physics has been instrumental in developing major scientific theories, such as relativity and quantum mechanics.

The field involves creating models to describe physical events and is judged by how well these models predict empirical observations. Theoretical physics has a rich history, dating back to ancient philosophers and evolving significantly during the Scientific Revolution with figures like Galileo and Newton.

Modern theoretical physics seeks to unify existing theories and explore new concepts, often using advanced mathematics. It includes mainstream theories like the Big Bang, chaos theory, and quantum mechanics, as well as proposed and fringe theories that are still under investigation. Thought experiments, such as Schrödinger's cat, play a crucial role in theoretical physics by exploring scenarios that are not easily tested in reality.

Both pages highlight the interplay between theory and experimentation in advancing our understanding of the universe, with Einstein's work serving as a prime example of theoretical physics' impact.

API 参考

有关所有 Tavily Extract API 功能和配置的详细文档,请访问 API 参考: docs.tavily.com/documentation/api-reference/endpoint/extract