LangChain agents can use tools autonomously. Here’s a complete agent setup:
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIToolsAgent } from 'langchain/agents';
import { DynamicTool } from '@langchain/core/tools';
import { ChatPromptTemplate } from '@langchain/core/prompts';
const tools = [
new DynamicTool({
name: 'calculator',
description: 'Performs math calculations',
func: async (input) => {
return String(eval(input)); // Use mathjs in production
}
}),
new DynamicTool({
name: 'search',
description: 'Search the web',
func: async (query) => {
// Your search API here
return `Results for: ${query}`;
}
})
];
const llm = new ChatOpenAI({ model: 'gpt-4' });
const prompt = ChatPromptTemplate.fromMessages([
['system', 'You are a helpful assistant with access to tools.'],
['human', '{input}'],
['placeholder', '{agent_scratchpad}']
]);
const agent = await createOpenAIToolsAgent({ llm, tools, prompt });
const executor = new AgentExecutor({ agent, tools });
const result = await executor.invoke({
input: 'What is 25 * 48 and search for Node.js news'
});
