跳至主要内容

Requests 工具包

我们可以使用 Requests 工具包 来构建生成 HTTP 请求的代理。

有关所有 API 工具包功能和配置的详细文档,请转到 API 参考以获取 RequestsToolkit

⚠️ 安全提示 ⚠️

授予模型执行现实世界操作的自由裁量权存在固有风险。请采取预防措施以减轻这些风险

  • 确保与工具相关的权限范围狭窄(例如,用于数据库操作或 API 请求);
  • 在需要时,请使用人工干预流程。

设置

安装

此工具包位于 langchain-community 包中

%pip install -qU langchain-community

请注意,如果您希望从单个工具运行中获得自动跟踪,还可以通过取消下面的注释来设置您的 LangSmith API 密钥

# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

实例化

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

注意:授予模型执行现实世界操作的自由裁量权存在固有风险。为了使用这些工具,我们必须通过设置 allow_dangerous_request=True 来“选择加入”这些风险。这对于调用不需要的请求可能是危险的。请确保您的自定义 OpenAPI 规范(yaml)是安全的,并且与工具相关的权限范围狭窄。

ALLOW_DANGEROUS_REQUEST = True

我们可以使用 JSONPlaceholder API 作为测试平台。

让我们创建(它的一部分)API 规范

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": "Limit the number of results",
}
]
openapi_spec: Dict[str, Any] = {
"openapi": "3.0.0",
"info": {"title": "JSONPlaceholder API", "version": "1.0.0"},
"servers": [{"url": base_url}],
"paths": {},
}
# Iterate over the endpoints to construct the 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"Get {endpoint[1:]}",
"parameters": common_query_parameters,
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {"type": "object", "properties": schema}
}
},
}
},
}
}
return yaml.dump(openapi_spec, sort_keys=False)


api_spec = _get_api_spec()

接下来,我们可以实例化工具包。对于此 API,我们不需要授权或其他标头

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,
)

工具

查看可用的工具

tools = toolkit.get_tools()

tools
[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)]

在代理中使用

from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

llm = ChatOpenAI(model="gpt-4o-mini")

system_message = """
You have access to an API to help answer user queries.
Here is documentation on the API:
{api_spec}
""".format(api_spec=api_spec)

agent_executor = create_react_agent(llm, tools, state_modifier=system_message)
example_query = "Fetch the top two posts. What are their titles?"

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

Fetch the top two posts. What are their titles?
================================== 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 ==================================

The titles of the top two posts are:
1. "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
2. "qui est esse"

API 参考

有关所有 API 工具包功能和配置的详细文档,请转到 API 参考以获取 RequestsToolkit


此页面是否有帮助?


您也可以留下详细的反馈 在 GitHub 上.