OpenAPI 툴킷 통합
OpenAPI 툴킷 통합 (OpenAPI toolkit integration)
LangChain JavaScript로 OpenAPI 툴킷과 통합해요.
이 에이전트가 이론상 그럴 일은 없지만, 제공된 자격 증명이나 기타 민감한 데이터를 검증되지 않았거나 잠재적으로 악의적인 URL로 보낼 수 있다는 점을 인지하세요.
에이전트를 통해 수행할 수 있는 작업, 접근할 수 있는 API, 전달할 수 있는 헤더 등에 제한을 추가하는 것을 고려하세요.
또한 요청을 보내기 전에 URL을 검증하는 조치를 구현하고, 자격 증명 같은 민감한 데이터를 안전하게 처리·보호하는 것을 고려하세요.
OpenApiToolkit OpenAPI 툴킷 시작을 도와드려요. OpenApiToolkit은 이제 @langchain/classic에 있어요. 마이그레이션 세부 사항은 LangChain v1 마이그레이션 가이드를 참고하세요.
OpenAPIToolkit은 다음 툴에 접근할 수 있어요:
| 이름 | 설명 |
|---|---|
requests_get |
인터넷으로 가는 포털이에요. 웹사이트에서 특정 콘텐츠를 가져와야 할 때 사용하세요. 입력은 URL 문자열이어야 해요 (예: "www.google.com"). 출력은 GET 요청의 텍스트 응답이에요. |
requests_post |
웹사이트에 POST하고 싶을 때 사용하세요. 입력은 "url"과 "data" 두 키를 가진 json 문자열이어야 해요. "url"의 값은 문자열이어야 하고, "data"의 값은 JSON 본문으로 URL에 POST하려는 키-값 쌍의 딕셔너리여야 해요. json 문자열의 문자열에는 항상 큰따옴표를 사용하세요. 출력은 POST 요청의 텍스트 응답이에요. |
json_explorer |
API의 openapi 스펙에 대한 질문에 답하는 데 사용할 수 있어요. 요청을 시도하기 전에 항상 이 툴을 먼저 사용하세요. 예시 입력: '/bar 엔드포인트로 GET 요청에 필요한 쿼리 파라미터는 무엇인가?', '/foo 엔드포인트로 POST 요청의 요청 본문에 필요한 파라미터는 무엇인가?'. 항상 이 툴에 구체적인 질문을 주세요. |
설정 (Setup)
이 툴킷에는 OpenAPI 스펙 파일이 필요해요. LangChain.js 리포지토리에는 예제 디렉터리에 샘플 OpenAPI 스펙 파일이 있어요. 이 파일로 툴킷을 테스트할 수 있어요.
개별 툴 실행의 자동 추적을 받으려면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:
process.env.LANGSMITH_TRACING="true"
process.env.LANGSMITH_API_KEY="your-api-key"
설치 (Installation)
이 툴킷은 langchain 패키지에 있어요:
yarn add langchain @langchain/core
pnpm add langchain @langchain/core
인스턴스화 (Instantiation)
이제 툴킷을 인스턴스화할 수 있어요. 먼저 툴킷에 사용할 LLM을 정의해야 해요.
// @lc-docs-hide-cell
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "gpt-5.4-mini",
temperature: 0,
})
import { OpenApiToolkit } from "@langchain/classic/agents/toolkits"
import * as fs from "fs";
import * as yaml from "js-yaml";
import { JsonSpec, JsonObject } from "@langchain/classic/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: *** ${process.env.OPENAI_API_KEY}`,
};
const toolkit = new OpenApiToolkit(new JsonSpec(data), llm, headers);
툴 (Tools)
사용 가능한 툴 보기:
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.'
}
]
에이전트 내에서 사용 (Use within an agent)
먼저 LangGraph가 설치되어 있는지 확인하세요:
yarn add @langchain/langgraph
pnpm add @langchain/langgraph
import { createAgent } from "@langchain/classic"
const agentExecutor = createAgent({ 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-5.4-mini'."
const stream = await agentExecutor.streamEvents(
{ messages: [["user", exampleQuery]] },
{ version: "v3" },
);
for await (const snapshot of stream.values) {
const lastMsg = snapshot.messages[snapshot.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-5.4-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-5.4-mini",
"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 reference
OpenApiToolkit에 대한 전용 API reference 페이지는 @langchain/classic에 현재 없어요. 구현 세부 사항은 langchainjs의 OpenApiToolkit 소스를 참고하세요.
출처: 문서
본문
OpenApiToolkit은 OpenAPI 스펙을 토대로 requests_get·requests_post·json_explorer 툴을 제공하는 툴킷이에요. YAML 스펙을 로드해 JsonSpec으로 변환하고, LLM·헤더와 함께 OpenApiToolkit을 구성한 뒤 createAgent에 연결해 에이전트가 REST API와 상호작용할 수 있게 해요. 외부 API를 호출하므로 자격 증명·URL 검증 등에 주의가 필요해요.