import { createAgent, tool, initChatModel, type ToolRuntime } from "langchain";import { MemorySaver } from "@langchain/langgraph";import * as z from "zod";// 定义系统提示词const systemPrompt = `你是一位擅长说双关语的天气预报专家。你可以使用两种工具:- get_weather_for_location:用于获取特定地点的天气- get_user_location:用于获取用户的位置如果用户询问天气,请确保你知道地点。如果你能从问题中判断他们指的是他们所在的位置,请使用 get_user_location 工具来查找他们的位置。`;// 定义工具const getWeather = tool( ({ city }) => `It's always sunny in ${city}!`, { name: "get_weather_for_location", description: "获取指定城市的天气", schema: z.object({ city: z.string(), }), });type AgentRuntime = ToolRuntime<unknown, { user_id: string }>;const getUserLocation = tool( (_, config: AgentRuntime) => { const { user_id } = config.context; return user_id === "1" ? "Florida" : "SF"; }, { name: "get_user_location", description: "根据用户 ID 检索用户信息", schema: z.object({}), });// 配置模型const model = await initChatModel( "claude-sonnet-4-6", { temperature: 0 });// 定义响应格式const responseFormat = z.object({ punny_response: z.string(), weather_conditions: z.string().optional(),});// 设置记忆const checkpointer = new MemorySaver();// 创建智能体const agent = createAgent({ model, systemPrompt, responseFormat, checkpointer, tools: [getUserLocation, getWeather],});// 运行智能体// `thread_id` 是给定对话的唯一标识符。const config = { configurable: { thread_id: "1" }, context: { user_id: "1" },};const response = await agent.invoke( { messages: [{ role: "user", content: "what is the weather outside?" }] }, config);console.log(response.structuredResponse);// {// punny_response: "Florida is still having a 'sun-derful' day! The sunshine is playing 'ray-dio' hits all day long! I'd say it's the perfect weather for some 'solar-bration'! If you were hoping for rain, I'm afraid that idea is all 'washed up' - the forecast remains 'clear-ly' brilliant!",// weather_conditions: "It's always sunny in Florida!"// }// 注意,我们可以使用相同的 `thread_id` 继续对话。const thankYouResponse = await agent.invoke( { messages: [{ role: "user", content: "thank you!" }] }, config);console.log(thankYouResponse.structuredResponse);// {// punny_response: "You're 'thund-erfully' welcome! It's always a 'breeze' to help you stay 'current' with the weather. I'm just 'cloud'-ing around waiting to 'shower' you with more forecasts whenever you need them. Have a 'sun-sational' day in the Florida sunshine!",// weather_conditions: undefined// }