import { ChatOpenAI } from "@langchain/openai";
import { tool } from "langchain";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import z from "zod";
const llm = new ChatOpenAI({
model: process.env.OPENAI_MODEL || "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY,
configuration: {
baseURL: process.env.OPENAI_BASE_URL,
},
});
const writePoem = tool(
async ({ topic }) => {
return (
await llm.invoke([
{
role: "system",
content:
"你是一位专业诗人。根据提供的主题写一首诗。",
},
{
role: "user",
content: topic,
},
])
).content as string;
},
{
name: "writePoem",
description: "写一首诗",
schema: z.object({
topic: z.string().describe("诗歌的主题"),
}),
}
);
const writeStory = tool(
async ({ topic }) => {
return (
await llm.invoke([
{
role: "system",
content:
"你是一位专业故事讲述者。根据提供的主题写一个故事。",
},
{
role: "user",
content: topic,
},
])
).content as string;
},
{
name: "writeStory",
description: "写一个故事",
schema: z.object({
topic: z.string().describe("故事的主题"),
}),
}
);
const writeJoke = tool(
async ({ topic }) => {
return (
await llm.invoke([
{
role: "system",
content:
"你是一位专业喜剧演员。根据提供的主题写一个笑话。",
},
{
role: "user",
content: topic,
},
])
).content as string;
},
{
name: "writeJoke",
description: "写一个笑话",
schema: z.object({
topic: z.string().describe("笑话的主题"),
}),
}
);
const tools = [writePoem, writeStory, writeJoke];
const toolNode = new ToolNode(tools);