> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Exa 搜索集成

> 使用 LangChain Python 集成 Exa 搜索工具。

Exa 是一个完全为 LLM 设计的搜索引擎。使用**自然语言查询**在互联网上搜索文档，然后从所需文档中检索**清理后的 HTML 内容**。

与基于关键词的搜索（如 Google）不同，Exa 的神经搜索能力使其能够语义理解查询并返回相关文档。例如，我们可以搜索 `"fascinating article about cats"`，并比较来自 [Google](https://www.google.com/search?q=fascinating+article+about+cats) 和 [Exa](https://search.exa.ai/search?q=fascinating%20article%20about%20cats\&autopromptString=Here%20is%20a%20fascinating%20article%20about%20cats%3A) 的搜索结果。Google 基于关键词 "fascinating" 给我们返回 SEO 优化的列表文章。Exa 则直接有效。

本笔记本将介绍如何将 Exa 搜索与 LangChain 结合使用。

## 设置

### 安装

安装 LangChain Exa 集成包：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-exa

# 以及本笔记本的一些依赖项
pip install -qU langchain langchain-openai langchain-community
```

### 凭证

您需要一个 Exa API 密钥才能使用此集成。通过[在此注册](https://dashboard.exa.ai/)可获得 10 美元免费额度（完成某些操作如首次搜索可获得更多）。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass
import os

if not os.environ.get("EXA_API_KEY"):
    os.environ["EXA_API_KEY"] = getpass.getpass("Exa API key:\n")
```

## 使用 ExaSearchResults 工具

ExaSearchResults 是一个可与 LangChain 代理一起使用的工具，用于执行 Exa 搜索。它为搜索操作提供了更结构化的接口：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_exa import ExaSearchResults

# 初始化 ExaSearchResults 工具
search_tool = ExaSearchResults(exa_api_key=os.environ["EXA_API_KEY"])

# 执行搜索查询
search_results = search_tool._run(
    query="When was the last time the New York Knicks won the NBA Championship?",
    num_results=5,
    text_contents_options=True,
    highlights=True,
)

print("Search Results:", search_results)
```

### ExaSearchResults 的高级功能

您可以使用高级搜索选项，如控制搜索类型、实时爬取和内容过滤：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 使用高级选项执行搜索查询
search_results = search_tool._run(
    query="Latest AI research papers",
    num_results=10,  # 结果数量 (1-100)
    type="auto",  # 可以是 "neural"、"keyword" 或 "auto"
    livecrawl="always",  # 可以是 "always"、"fallback" 或 "never"
    text_contents_options={"max_characters": 2000},  # 限制文本长度
    summary={"query": "generate one liner"},  # 自定义摘要提示
)

print("Advanced Search Results:")
print(search_results)
```

## 使用 ExaFindSimilarResults 工具

ExaFindSimilarResults 允许您查找与给定 URL 类似的网页。这对于查找相关内容或竞争分析很有用：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_exa import ExaFindSimilarResults

# 初始化 ExaFindSimilarResults 工具
find_similar_tool = ExaFindSimilarResults(exa_api_key=os.environ["EXA_API_KEY"])

# 基于 URL 查找类似结果
similar_results = find_similar_tool._run(
    url="http://espn.com", num_results=5, text_contents_options=True, highlights=True
)

print("Similar Results:", similar_results)
```

## 在代理中使用

我们可以将 ExaSearchResults 和 ExaFindSimilarResults 工具与 LangGraph 代理一起使用。这使代理能够根据用户的查询动态搜索信息并查找类似内容。

首先，让我们设置语言模型。您需要提供您的 OpenAI API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API key:\n")
```

我们需要安装 langgraph：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langgraph
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.chat_models import init_chat_model
from langchain_exa import ExaFindSimilarResults, ExaSearchResults
from langchain.agents import create_agent


# 初始化语言模型
model = init_chat_model(model="gpt-5.4", model_provider="openai", temperature=0)

# 初始化 Exa 工具
exa_search = ExaSearchResults(
    exa_api_key=os.environ["EXA_API_KEY"],
    max_results=5,
)

exa_find_similar = ExaFindSimilarResults(
    exa_api_key=os.environ["EXA_API_KEY"],
    max_results=5,
)

# 创建包含两个工具的代理
agent = create_agent(model, [exa_search, exa_find_similar])

# 示例 1：基本搜索
user_input = "What are the latest developments in quantum computing?"

for step in agent.stream(
    {"messages": user_input},
    stream_mode="values",
):
    step["messages"][-1].pretty_print()
```

## 使用 ExaSearchRetriever

ExaSearchRetriever 是一个使用 Exa 搜索来检索相关文档的检索器。

<Note>
  **用于 **TextContentsOptions** 的 `max_characters` 参数以前称为 `max_length`，现已弃用。请确保使用 `max_characters`。**
</Note>

### 基本用法

以下是使用 ExaSearchRetriever 的一个简单示例：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_exa import ExaSearchRetriever

# 创建 ExaSearchRetriever 的新实例
exa = ExaSearchRetriever(exa_api_key=os.environ["EXA_API_KEY"])

# 搜索查询并保存结果
results = exa.invoke("What is the capital of France?")

# 打印结果
print(results)
```

### 高级功能

您可以使用高级功能，如控制结果数量、搜索类型、实时爬取、摘要和文本内容选项：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_exa import ExaSearchRetriever

# 使用高级选项创建新实例
exa = ExaSearchRetriever(
    exa_api_key=os.environ["EXA_API_KEY"],
    k=20,  # 结果数量 (1-100)
    type="auto",  # 可以是 "neural"、"keyword" 或 "auto"
    livecrawl="always",  # 可以是 "always"、"fallback" 或 "never"
    text_contents_options={"max_characters": 3000},  # 限制文本长度
    # 用于 LLM 生成页面内容摘要的自定义提示
    summary={"query": "generate one line summary in simple words."},
)

# 使用高级选项进行搜索
results = exa.invoke("Latest developments in quantum computing")
print(f"Found {len(results)} results")
for result in results[:3]:  # 打印前 3 个结果
    print(f"Title: {result.metadata.get('title', 'N/A')}")
    print(f"URL: {result.metadata.get('url', 'N/A')}")
    print(f"Summary: {result.metadata.get('summary', 'N/A')}")
    print("-" * 80)
```

***

## API 参考

有关所有 Exa API 功能和配置的详细文档，请访问 [Exa API 文档](https://docs.exa.ai/)。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/tools/exa_search.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
