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

# Requests 工具包集成

> 使用 LangChain Python 集成 Requests 工具包。

我们可以使用 Requests [工具包](/oss/python/integrations/tools/requests) 来构建生成 HTTP 请求的代理。

有关所有 API 工具包功能和配置的详细文档，请前往 [RequestsToolkit](https://reference.langchain.com/python/langchain-community/agent_toolkits/openapi/toolkit/RequestsToolkit) 的 API 参考。

## ⚠️ 安全提示 ⚠️

赋予模型执行现实世界操作的自主权存在固有风险。请采取预防措施以降低这些风险：

* 确保与工具相关的权限范围狭窄（例如，用于数据库操作或 API 请求）；
* 在需要时，利用Human in the Loop的工作流程。

## 设置

### 安装

此工具包位于 `langchain-community` 包中：

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

要启用对单个工具的自动跟踪，请设置您的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 实例化

首先，我们将演示一个最小示例。

**注意**：赋予模型执行现实世界操作的自主权存在固有风险。我们必须通过设置 `allow_dangerous_request=True` 来“选择启用”这些风险，才能使用这些工具。
**这可能对调用不需要的请求造成危险**。请确保您的自定义 OpenAPI 规范 (yaml) 是安全的，并且与工具相关的权限范围狭窄。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ALLOW_DANGEROUS_REQUEST = True
```

我们可以使用 [JSONPlaceholder](https://jsonplaceholder.typicode.com) API 作为测试环境。

让我们创建其 API 规范（的一个子集）：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from typing import Any, Dict, Union

import requests
import yaml


def _get_schema(response_json: Union[dict, list]) -> dict:
    if isinstance(response_json, list):
        response_json = response_json[0] if response_json else {}
    return {key: type(value).__name__ for key, value in response_json.items()}


def _get_api_spec() -> str:
    base_url = "https://jsonplaceholder.typicode.com"
    endpoints = [
        "/posts",
        "/comments",
    ]
    common_query_parameters = [
        {
            "name": "_limit",
            "in": "query",
            "required": False,
            "schema": {"type": "integer", "example": 2},
            "description": "限制结果数量",
        }
    ]
    openapi_spec: Dict[str, Any] = {
        "openapi": "3.0.0",
        "info": {"title": "JSONPlaceholder API", "version": "1.0.0"},
        "servers": [{"url": base_url}],
        "paths": {},
    }
    # 遍历端点以构建路径
    for endpoint in endpoints:
        response = requests.get(base_url + endpoint)
        if response.status_code == 200:
            schema = _get_schema(response.json())
            openapi_spec["paths"][endpoint] = {
                "get": {
                    "summary": f"获取 {endpoint[1:]}",
                    "parameters": common_query_parameters,
                    "responses": {
                        "200": {
                            "description": "成功响应",
                            "content": {
                                "application/json": {
                                    "schema": {"type": "object", "properties": schema}
                                }
                            },
                        }
                    },
                }
            }
    return yaml.dump(openapi_spec, sort_keys=False)


api_spec = _get_api_spec()
```

接下来，我们可以实例化工具包。此 API 不需要授权或其他头部信息：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.agent_toolkits.openapi.toolkit import RequestsToolkit
from langchain_community.utilities.requests import TextRequestsWrapper

toolkit = RequestsToolkit(
    requests_wrapper=TextRequestsWrapper(headers={}),
    allow_dangerous_requests=ALLOW_DANGEROUS_REQUEST,
)
```

## 工具

查看可用工具：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
tools = toolkit.get_tools()

tools
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[RequestsGetTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type='text', verify=True), allow_dangerous_requests=True),
 RequestsPostTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type='text', verify=True), allow_dangerous_requests=True),
 RequestsPatchTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type='text', verify=True), allow_dangerous_requests=True),
 RequestsPutTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type='text', verify=True), allow_dangerous_requests=True),
 RequestsDeleteTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type='text', verify=True), allow_dangerous_requests=True)]
```

* [RequestsGetTool](https://reference.langchain.com/python/langchain-community/tools/requests/tool/RequestsGetTool)
* [RequestsPostTool](https://reference.langchain.com/python/langchain-community/tools/requests/tool/RequestsPostTool)
* [RequestsPatchTool](https://reference.langchain.com/python/langchain-community/tools/requests/tool/RequestsPatchTool)
* [RequestsPutTool](https://reference.langchain.com/python/langchain-community/tools/requests/tool/RequestsPutTool)
* [RequestsDeleteTool](https://reference.langchain.com/python/langchain-community/tools/requests/tool/RequestsDeleteTool)

## 在代理中使用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent


model = ChatOpenAI(model="gpt-5.4-mini")

system_message = """
您可以访问一个 API 来帮助回答用户查询。
以下是 API 文档：
{api_spec}
""".format(api_spec=api_spec)

agent = create_agent(model, tools, system_prompt=system_message)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
example_query = "获取前两篇文章。它们的标题是什么？"

events = agent.stream(
    {"messages": [("user", example_query)]},
    stream_mode="values",
)
for event in events:
    event["messages"][-1].pretty_print()
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
================================ Human Message =================================

获取前两篇文章。它们的标题是什么？
================================== Ai Message ==================================
Tool Calls:
  requests_get (call_RV2SOyzCnV5h2sm4WPgG8fND)
 Call ID: call_RV2SOyzCnV5h2sm4WPgG8fND
  Args:
    url: https://jsonplaceholder.typicode.com/posts?_limit=2
================================= Tool Message =================================
Name: requests_get

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]
================================== Ai Message ==================================

前两篇文章的标题是：
1. "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
2. "qui est esse"
```

***

## API 参考

有关所有 API 工具包功能和配置的详细文档，请前往 [RequestsToolkit](https://reference.langchain.com/python/langchain-community/agent_toolkits/openapi/toolkit/RequestsToolkit) 的 API 参考。

***

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