Skip to main content

OpenAPI Agent Toolkit

This example shows how to load and use an agent with a OpenAPI toolkit.

npm install @langchain/openai
import * as fs from "fs";
import * as yaml from "js-yaml";
import { OpenAI } from "@langchain/openai";
import { JsonSpec, JsonObject } from "langchain/tools";
import { createOpenApiAgent, OpenApiToolkit } from "langchain/agents";

export const run = async () => {
let data: JsonObject;
try {
const yamlFile = fs.readFileSync("openai_openapi.yaml", "utf8");
data = yaml.load(yamlFile) as JsonObject;
if (!data) {
throw new Error("Failed to load OpenAPI spec");
}
} catch (e) {
console.error(e);
return;
}

const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
};
const model = new OpenAI({ temperature: 0 });
const toolkit = new OpenApiToolkit(new JsonSpec(data), model, headers);
const executor = createOpenApiAgent(model, toolkit);

const input = `Make a POST request to openai /completions. The prompt should be 'tell me a joke.'`;
console.log(`Executing with input "${input}"...`);

const result = await executor.invoke({ input });
console.log(`Got output ${result.output}`);

console.log(
`Got intermediate steps ${JSON.stringify(
result.intermediateSteps,
null,
2
)}`
);
};

Disclaimer ⚠️

This agent can make requests to external APIs. Use with caution, especially when granting access to users.

Be aware that this agent could theoretically send requests with provided credentials or other sensitive data to unverified or potentially malicious URLs --although it should never in theory.

Consider adding limitations to what actions can be performed via the agent, what APIs it can access, what headers can be passed, and more.

In addition, consider implementing measures to validate URLs before sending requests, and to securely handle and protect sensitive data such as credentials.


Was this page helpful?


You can also leave detailed feedback on GitHub.