构建一个基本智能体
首先创建一个简单的智能体,使其能够回答问题和调用工具。该智能体将使用Claude Sonnet 4.5作为其语言模型,一个基本的天气功能作为工具,以及一个简单的提示来引导其行为。import { createAgent, tool } from "langchain";
import * as z from "zod";
const getWeather = tool(
(input) => `It's always sunny in ${input.city}!`,
{
name: "get_weather",
description: "Get the weather for a given city",
schema: z.object({
city: z.string().describe("The city to get the weather for"),
}),
}
);
const agent = createAgent({
model: "anthropic:claude-sonnet-4-5",
tools: [getWeather],
});
console.log(
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in Tokyo?" }],
})
);
对于这个示例,您需要设置一个 Claude (Anthropic) 账户并获取一个API密钥。然后,在您的终端中设置
ANTHROPIC_API_KEY 环境变量。构建一个真实世界的智能体
接下来,构建一个实用的天气预报智能体,以展示关键的生产概念:- 详细的系统提示以实现更好的智能体行为
- 创建工具以与外部数据集成
- 模型配置以实现一致的响应
- 结构化输出以获得可预测的结果
- 对话记忆以实现类似聊天的交互
- 创建和运行智能体创建一个功能齐全的智能体
Define the system prompt
系统提示定义了智能体的角色和行为。请保持其具体且可执行:
const systemPrompt = `You are an expert weather forecaster, who speaks in puns.
You have access to two tools:
- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location
If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.`;
Create tools
工具 是您的智能体可以调用的函数。通常,工具会希望连接到外部系统,并依赖于运行时配置来实现这一点。注意这里
getUserLocation 工具正是这样做的:import { type Runtime } from "@langchain/langgraph";
import { tool } from "langchain";
import * as z from "zod";
const getWeather = tool(
(input) => `It's always sunny in ${input.city}!`,
{
name: "get_weather_for_location",
description: "Get the weather for a given city",
schema: z.object({
city: z.string().describe("The city to get the weather for"),
}),
}
);
type AgentRuntime = Runtime<{ user_id: string }>;
const getUserLocation = tool(
(_, config: AgentRuntime) => {
const { user_id } = config.context;
return user_id === "1" ? "Florida" : "SF";
},
{
name: "get_user_location",
description: "Retrieve user information based on user ID",
}
);
Zod 是一个用于验证和解析预定义模式的库。您可以使用它来定义工具的输入模式,以确保智能体只使用正确的参数调用工具。或者,您可以将
schema 属性定义为 JSON schema 对象。请注意,JSON schemas 不会在运行时进行验证。Example: Using JSON schema for tool input
Example: Using JSON schema for tool input
const getWeather = tool(
({ city }) => `It's always sunny in ${city}!`,
{
name: "get_weather_for_location",
description: "Get the weather for a given city",
schema: {
type: "object",
properties: {
city: {
type: "string",
description: "The city to get the weather for"
}
},
required: ["city"]
},
}
);
Define response format
可选地,如果您需要智能体的响应与特定模式匹配,可以定义一个结构化响应格式。
const responseFormat = z.object({
punny_response: z.string(),
weather_conditions: z.string().optional(),
});
Create and run the agent
现在将所有组件组装到您的智能体中并运行它!
JSX_CLOSE_22
import { createAgent } from "langchain";
const agent = createAgent({
model: "anthropic:claude-sonnet-4-5",
prompt: systemPrompt,
tools: [getUserLocation, getWeather],
responseFormat,
checkpointer,
});
// `thread_id` is a unique identifier for a given conversation.
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 ...",
// weather_conditions: "It's always sunny in Florida!"
// }
// Note that we can continue the conversation using the same `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! ...",
// weather_conditions: undefined
// }
Show Full example code
Show Full example code
import { createAgent, tool, initChatModel } from "langchain";
import { MemorySaver, type Runtime } from "@langchain/langgraph";
import * as z from "zod";
// Define system prompt
const systemPrompt = `You are an expert weather forecaster, who speaks in puns.
You have access to two tools:
- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location
If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.`;
// Define tools
const getWeather = tool(
({ city }) => `It's always sunny in ${city}!`,
{
name: "get_weather_for_location",
description: "Get the weather for a given city",
schema: z.object({
city: z.string(),
}),
}
);
const getUserLocation = tool(
(_, config: Runtime<{ user_id: string}>) => {
const { user_id } = config.context;
return user_id === "1" ? "Florida" : "SF";
},
{
name: "get_user_location",
description: "Retrieve user information based on user ID",
schema: z.object({}),
}
);
// Configure model
const model = await initChatModel(
"anthropic:claude-sonnet-4-5",
{ temperature: 0 }
);
// Define response format
const responseFormat = z.object({
punny_response: z.string(),
weather_conditions: z.string().optional(),
});
// Set up memory
const checkpointer = new MemorySaver();
// Create agent
const agent = createAgent({
model: "anthropic:claude-sonnet-4-5",
prompt: systemPrompt,
tools: [getUserLocation, getWeather],
responseFormat,
checkpointer,
});
// Run agent
// `thread_id` is a unique identifier for a given conversation.
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!"
// }
// Note that we can continue the conversation using the same `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
// }
- 理解上下文并记住对话
- 智能使用多个工具
- 以一致格式提供结构化响应
- 通过上下文处理特定用户信息
- 在交互中维持对话状态