Agents are autonomous systems that use language models to decide which actions to take. Unlike simple chains that follow a predetermined sequence, agents can reason about tasks, choose tools dynamically, and iterate until they achieve their goal.
LangChain.js provides a production-ready ReAct agent implementation via createAgent() in the langchain package
const agent = createAgent({ llm: "openai:gpt-4o", tools: [searchTool], prompt: "You are a helpful research assistant. Always cite your sources.",});
Using SystemMessage:
import { SystemMessage } from "@langchain/core/messages";const agent = createAgent({ llm: "openai:gpt-4o", tools: [searchTool], prompt: new SystemMessage( "You are a helpful research assistant. Always cite your sources." ),});
const result = await agent.invoke({ messages: [{ role: "user", content: "What's the weather in SF?" }],});// Access the final responseconst finalMessage = result.messages[result.messages.length - 1];console.log(finalMessage.content);
const researchAgent = createAgent({ llm: "openai:gpt-4o", tools: [searchTool, wikipediaTool, arxivTool], prompt: `You are a research assistant. For each query:1. Search multiple sources2. Cross-reference information3. Provide citations4. Summarize findings`,});
The agent uses tool descriptions to decide when to call them:
// ✓ Good - Clear and specificconst tool = tool(fn, { name: "search_products", description: "Search our product catalog by name or category. Returns up to 10 results with prices and availability.", schema: productSchema,});// ✗ Avoid - Vagueconst tool = tool(fn, { name: "search", description: "Search for things", schema: schema,});
Provide Context in Prompts
Give the agent context about its role and capabilities:
const agent = createAgent({ llm: "openai:gpt-4o", tools: [weatherTool, newsTool], prompt: `You are a helpful assistant with access to:- Weather information for any location- Current news articlesAlways provide sources for news. Weather data is real-time.`,});
Handle Tool Errors
Tools should return informative error messages:
const weatherTool = tool( async ({ location }) => { try { return await getWeather(location); } catch (error) { return `Unable to get weather for ${location}. Please check the location name.`; } }, { /* ... */ });
Infinite Loops: Agents can get stuck if tools always suggest more tools. Use toolCallLimitMiddleware to prevent this.
Vague Tool Descriptions: If tool descriptions aren’t clear, the agent may use them incorrectly. Be specific about what each tool does and when to use it.
No Error Handling: Always handle tool errors gracefully. Return helpful error messages that the agent can use to try alternative approaches.