> ## 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.

# SerpAPI 集成

> 使用 LangChain Python 与 SerpAPI 工具集成。

本笔记本介绍如何使用 [SerpApi](https://serpapi.com/) 组件进行网络搜索。

在[注册页面](https://serpapi.com/users/sign_up)注册 SerpApi 账户，每月可获得 250 次免费搜索。注册后，您可以在[仪表板](https://serpapi.com/manage-api-key)上找到您的 API 密钥。

然后在 `.env` 文件中设置环境变量 `SERPAPI_API_KEY` 为您的 API 密钥。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
os.environ["SERPAPI_API_KEY"] = SERPAPI_API_KEY
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.utilities import SerpAPIWrapper
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
search = SerpAPIWrapper()
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
search.run("Obama's first name?")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'Barack Hussein Obama II'
```

## 自定义参数

您还可以使用任意参数自定义 SerpAPI 封装器。例如，在下面的示例中，我们将使用 `bing` 而不是 `google`。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
params = {
    "engine": "bing",
    "gl": "us",
    "hl": "en",
}
search = SerpAPIWrapper(params=params)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
search.run("Obama's first name?")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'Barack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American presi…New content will be added above the current area of focus upon selectionBarack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American president of the United States. He previously served as a U.S. senator from Illinois from 2005 to 2008 and as an Illinois state senator from 1997 to 2004, and previously worked as a civil rights lawyer before entering politics.Wikipediabarackobama.com'
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.tools import tool

# 您可以创建工具传递给代理
@tool
def web_search(query: str) -> str:
    """在网络上搜索信息。"""
    return search.run(query)
```

***

<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/serpapi.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
