What are Agents?
Agents are autonomous systems that use LLMs to decide which actions to take. Unlike chains with predetermined steps, agents dynamically choose their actions based on user input and available tools. They can reason, plan, and execute multi-step tasks.
🛠️ Agent Components
- LLM: The reasoning engine that decides what to do
- Tools: Functions the agent can call to take actions
- Prompt: Instructions that guide agent behavior
- Memory: Optional conversation history
Creating Tools
Tools are functions that agents can use to interact with the world:
Define tools with input schemas so the agent can call them safely and predictably.
import { tool } from "@langchain/core/tools";
import { z } from "zod";
// Simple calculator tool
const calculatorTool = tool(
async ({ operation, a, b }) => {
switch (operation) {
case "add": return String(a + b);
case "subtract": return String(a - b);
case "multiply": return String(a * b);
case "divide": return String(a / b);
default: return "Unknown operation";
}
},
{
name: "calculator",
description: "Performs basic arithmetic operations",
schema: z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
a: z.number().describe("First number"),
b: z.number().describe("Second number"),
}),
}
);
// Web search tool
const searchTool = tool(
async ({ query }) => {
// Implement actual search
return `Search results for: ${query}`;
},
{
name: "web_search",
description: "Search the web for current information",
schema: z.object({
query: z.string().describe("The search query"),
}),
}
);
Built-in Tools
LangChain ships common tools so you can add search, Wikipedia, or calculator capabilities quickly.
// Tavily Search (requires API key)
import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
const searchTool = new TavilySearchResults({ maxResults: 3 });
// Wikipedia
import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
const wikiTool = new WikipediaQueryRun({ topKResults: 3 });
// Calculator
import { Calculator } from "langchain/tools/calculator";
const calcTool = new Calculator();
Creating an Agent
Create a ReAct agent by combining a model with the tools it can access.
import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const model = new ChatOpenAI({
modelName: "gpt-4",
temperature: 0,
});
const tools = [calculatorTool, searchTool];
// Create a ReAct agent
const agent = createReactAgent({
llm: model,
tools,
});
// Run the agent
const result = await agent.invoke({
messages: [{ role: "user", content: "What is 25 * 4, and then search for information about that number" }],
});
console.log(result.messages[result.messages.length - 1].content);
Agent with Custom Prompt
Customize agent behavior by providing a system prompt that guides its reasoning.
import { ChatPromptTemplate } from "@langchain/core/prompts";
const systemPrompt = `You are a helpful assistant that can use tools to answer questions.
Always explain your reasoning step by step.
If you're unsure, say so rather than making up information.`;
const agent = createReactAgent({
llm: model,
tools,
messageModifier: systemPrompt,
});
Streaming Agent Responses
Stream agent events to show thinking steps and tool calls in real time.
const stream = await agent.stream({
messages: [{ role: "user", content: "Search for the latest news about AI" }],
});
for await (const event of stream) {
// Handle different event types
if (event.agent) {
console.log("Agent thinking:", event.agent.messages[0].content);
}
if (event.tools) {
console.log("Tool called:", event.tools.messages[0].name);
}
}
Tool Calling with Function Calling
The model can request tool execution, and you feed the tool output back to complete the response.
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage, ToolMessage } from "@langchain/core/messages";
const model = new ChatOpenAI({ modelName: "gpt-4" });
const modelWithTools = model.bindTools([calculatorTool, searchTool]);
// Initial call
const response = await modelWithTools.invoke([
new HumanMessage("What is 15 + 27?"),
]);
// Check for tool calls
if (response.tool_calls && response.tool_calls.length > 0) {
const toolCall = response.tool_calls[0];
// Execute the tool
const toolResult = await calculatorTool.invoke(toolCall.args);
// Send result back to model
const finalResponse = await modelWithTools.invoke([
new HumanMessage("What is 15 + 27?"),
response,
new ToolMessage({
tool_call_id: toolCall.id,
content: toolResult,
}),
]);
console.log(finalResponse.content);
}
Multi-Tool Agent Example
Combine multiple tools so the agent can solve multi-step tasks by selecting the right tool.
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
// Define multiple tools
const getCurrentWeather = tool(
async ({ city }) => {
// Mock implementation
return JSON.stringify({ city, temp: 72, condition: "sunny" });
},
{
name: "get_weather",
description: "Get current weather for a city",
schema: z.object({ city: z.string() }),
}
);
const getNews = tool(
async ({ topic }) => {
return `Latest news about ${topic}: [Mock news results]`;
},
{
name: "get_news",
description: "Get latest news about a topic",
schema: z.object({ topic: z.string() }),
}
);
const sendEmail = tool(
async ({ to, subject, body }) => {
console.log(`Email sent to ${to}`);
return "Email sent successfully";
},
{
name: "send_email",
description: "Send an email to someone",
schema: z.object({
to: z.string().email(),
subject: z.string(),
body: z.string(),
}),
}
);
// Create agent with all tools
const agent = createReactAgent({
llm: new ChatOpenAI({ modelName: "gpt-4", temperature: 0 }),
tools: [getCurrentWeather, getNews, sendEmail],
});
// Agent will decide which tools to use
const result = await agent.invoke({
messages: [{
role: "user",
content: "What's the weather in NYC? Then send an email to user@example.com with the weather report.",
}],
});
⚠️ Agent Safety
Agents can take real actions. Always implement proper validation, rate limiting, and confirmation steps for sensitive operations like sending emails or making purchases.
💡 Key Takeaways
- • Agents dynamically decide which tools to use based on the task
- • Tools are functions with schemas that define their inputs
- • ReAct agents reason step-by-step before taking action
- • Use streaming for real-time feedback on agent progress
- • Always validate agent actions for production use
📚 Learn More
-
Agents Documentation →
Complete guide to building agents.
-
LangGraph.js →
Build more complex agent workflows with graphs.