OpenApiToolkit
免责声明 ⚠️
此 Agent 可以向外部 API 发出请求。请谨慎使用,尤其是在授予用户访问权限时。
请注意,此 Agent 理论上可能会使用提供的凭据或其他敏感数据向未经验证或潜在恶意的 URL 发送请求 -- 尽管理论上绝不应该发生这种情况。
考虑限制可以通过 Agent 执行的操作、它可以访问的 API、可以传递的标头等等。
此外,考虑实施措施以在发送请求之前验证 URL,并安全地处理和保护敏感数据,例如凭据。
这将帮助您开始使用 OpenApiToolkit。有关所有 OpenApiToolkit 功能和配置的详细文档,请访问 API 参考。
OpenAPIToolkit
可以访问以下工具
名称 | 描述 |
---|---|
requests_get | 通往互联网的门户。当您需要从网站获取特定内容时使用此工具。输入应为 URL 字符串(即“https://www.google.com”)。输出将是 GET 请求的文本响应。 |
requests_post | 当您想要 POST 到网站时使用此工具。输入应为 JSON 字符串,其中包含两个键:“url”和“data”。“url”的值应为字符串,“data”的值应为您要作为 JSON 正文 POST 到 URL 的键值对字典。请注意,始终对 JSON 字符串中的字符串使用双引号。输出将是 POST 请求的文本响应。 |
json_explorer | 可用于回答有关 API 的 openapi 规范的问题。在尝试发出请求之前,请务必先使用此工具。此工具的示例输入:“GET 请求到 /bar 端点需要哪些查询参数?” “POST 请求到 /foo 端点的请求正文需要哪些参数?” 始终为此工具提供具体问题。 |
设置
此工具包需要 OpenAPI 规范文件。LangChain.js 仓库在 examples
目录中有一个 示例 OpenAPI 规范文件。您可以使用此文件来测试工具包。
如果您想从单个工具的运行中获取自动跟踪,您还可以通过取消注释下方内容来设置您的 LangSmith API 密钥
process.env.LANGSMITH_TRACING = "true";
process.env.LANGSMITH_API_KEY = "your-api-key";
安装
此工具包位于 langchain
包中
提示
有关安装集成包的一般说明,请参阅此部分。
- npm
- yarn
- pnpm
npm i langchain @langchain/core
yarn add langchain @langchain/core
pnpm add langchain @langchain/core
实例化
现在我们可以实例化我们的工具包。首先,我们需要定义我们想要在工具包中使用的 LLM。
选择您的聊天模型
- Groq
- OpenAI
- Anthropic
- FireworksAI
- MistralAI
- VertexAI
安装依赖项
提示
请参阅 此部分,获取有关安装集成包的一般说明.
- npm
- yarn
- pnpm
npm i @langchain/groq
yarn add @langchain/groq
pnpm add @langchain/groq
添加环境变量
GROQ_API_KEY=your-api-key
实例化模型
import { ChatGroq } from "@langchain/groq";
const llm = new ChatGroq({
model: "llama-3.3-70b-versatile",
temperature: 0
});
安装依赖项
提示
请参阅 此部分,获取有关安装集成包的一般说明.
- npm
- yarn
- pnpm
npm i @langchain/openai
yarn add @langchain/openai
pnpm add @langchain/openai
添加环境变量
OPENAI_API_KEY=your-api-key
实例化模型
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "gpt-4o-mini",
temperature: 0
});
安装依赖项
提示
请参阅 此部分,获取有关安装集成包的一般说明.
- npm
- yarn
- pnpm
npm i @langchain/anthropic
yarn add @langchain/anthropic
pnpm add @langchain/anthropic
添加环境变量
ANTHROPIC_API_KEY=your-api-key
实例化模型
import { ChatAnthropic } from "@langchain/anthropic";
const llm = new ChatAnthropic({
model: "claude-3-5-sonnet-20240620",
temperature: 0
});
安装依赖项
提示
请参阅 此部分,获取有关安装集成包的一般说明.
- npm
- yarn
- pnpm
npm i @langchain/community
yarn add @langchain/community
pnpm add @langchain/community
添加环境变量
FIREWORKS_API_KEY=your-api-key
实例化模型
import { ChatFireworks } from "@langchain/community/chat_models/fireworks";
const llm = new ChatFireworks({
model: "accounts/fireworks/models/llama-v3p1-70b-instruct",
temperature: 0
});
安装依赖项
提示
请参阅 此部分,获取有关安装集成包的一般说明.
- npm
- yarn
- pnpm
npm i @langchain/mistralai
yarn add @langchain/mistralai
pnpm add @langchain/mistralai
添加环境变量
MISTRAL_API_KEY=your-api-key
实例化模型
import { ChatMistralAI } from "@langchain/mistralai";
const llm = new ChatMistralAI({
model: "mistral-large-latest",
temperature: 0
});
安装依赖项
提示
请参阅 此部分,获取有关安装集成包的一般说明.
- npm
- yarn
- pnpm
npm i @langchain/google-vertexai
yarn add @langchain/google-vertexai
pnpm add @langchain/google-vertexai
添加环境变量
GOOGLE_APPLICATION_CREDENTIALS=credentials.json
实例化模型
import { ChatVertexAI } from "@langchain/google-vertexai";
const llm = new ChatVertexAI({
model: "gemini-1.5-flash",
temperature: 0
});
import { OpenApiToolkit } from "langchain/agents/toolkits";
import * as fs from "fs";
import * as yaml from "js-yaml";
import { JsonSpec, JsonObject } from "langchain/tools";
// Load & convert the OpenAPI spec from YAML to JSON.
const yamlFile = fs.readFileSync(
"../../../../../examples/openai_openapi.yaml",
"utf8"
);
const data = yaml.load(yamlFile) as JsonObject;
if (!data) {
throw new Error("Failed to load OpenAPI spec");
}
// Define headers for the API requests.
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
};
const toolkit = new OpenApiToolkit(new JsonSpec(data), llm, headers);
工具
查看可用工具
const tools = toolkit.getTools();
console.log(
tools.map((tool) => ({
name: tool.name,
description: tool.description,
}))
);
[
{
name: 'requests_get',
description: 'A portal to the internet. Use this when you need to get specific content from a website.\n' +
' Input should be a url string (i.e. "https://www.google.com"). The output will be the text response of the GET request.'
},
{
name: 'requests_post',
description: 'Use this when you want to POST to a website.\n' +
' Input should be a json string with two keys: "url" and "data".\n' +
' The value of "url" should be a string, and the value of "data" should be a dictionary of\n' +
' key-value pairs you want to POST to the url as a JSON body.\n' +
' Be careful to always use double quotes for strings in the json string\n' +
' The output will be the text response of the POST request.'
},
{
name: 'json_explorer',
description: '\n' +
'Can be used to answer questions about the openapi spec for the API. Always use this tool before trying to make a request. \n' +
'Example inputs to this tool: \n' +
" 'What are the required query parameters for a GET request to the /bar endpoint?'\n" +
" 'What are the required parameters in the request body for a POST request to the /foo endpoint?'\n" +
'Always give this tool a specific question.'
}
]
在 Agent 中使用
首先,确保您已安装 LangGraph
- npm
- yarn
- pnpm
npm i @langchain/langgraph
yarn add @langchain/langgraph
pnpm add @langchain/langgraph
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const agentExecutor = createReactAgent({ llm, tools });
const exampleQuery =
"Make a POST request to openai /chat/completions. The prompt should be 'tell me a joke.'. Ensure you use the model 'gpt-4o-mini'.";
const events = await agentExecutor.stream(
{ messages: [["user", exampleQuery]] },
{ streamMode: "values" }
);
for await (const event of events) {
const lastMsg = event.messages[event.messages.length - 1];
if (lastMsg.tool_calls?.length) {
console.dir(lastMsg.tool_calls, { depth: null });
} else if (lastMsg.content) {
console.log(lastMsg.content);
}
}
[
{
name: 'requests_post',
args: {
input: '{"url":"https://api.openai.com/v1/chat/completions","data":{"model":"gpt-4o-mini","messages":[{"role":"user","content":"tell me a joke."}]}}'
},
type: 'tool_call',
id: 'call_1HqyZrbYgKFwQRfAtsZA2uL5'
}
]
{
"id": "chatcmpl-9t36IIuRCs0WGMEy69HUqPcKvOc1w",
"object": "chat.completion",
"created": 1722906986,
"model": "gpt-4o-mini-2024-07-18",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Why don't skeletons fight each other? \n\nThey don't have the guts!"
},
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 12,
"completion_tokens": 15,
"total_tokens": 27
},
"system_fingerprint": "fp_48196bc67a"
}
Here's a joke for you:
**Why don't skeletons fight each other?**
They don't have the guts!
API 参考
有关所有 OpenApiToolkit 功能和配置的详细文档,请访问 API 参考。