Tool-augmented chat
A conversational assistant needs to answer questions using external functions such as weather lookup.
AI Agents · Function
Creates a prebuilt ReAct agent graph from a language model and tools. The agent can invoke tools during a message-driven execution loop before returning a response.
createReactAgent constructs a prebuilt agent graph from a language model and tools. The graph repeatedly lets the model choose whether to call a tool, executes selected tools, and continues until the model produces a final response.
createReactAgent({ llm: model, tools: [tool] })| Name | Type | Description |
|---|---|---|
llm | BaseChatModel or compatible language-model runnable | Language model used to reason and select whether to call tools. |
tools | Array of tools | Tools available to the agent during its execution loop. |
An agent graph runnable that accepts message state and produces the resulting agent state.
import { createReactAgent, tool } from "langchain";
import { ChatAnthropic } from "@langchain/anthropic";
import { z } from "zod";
const getWeather = tool(
async ({ location }) => `Weather for ${location}: sunny`,
{ name: "get_weather", schema: z.object({ location: z.string() }) }
);
const agent = createReactAgent({
llm: new ChatAnthropic({ model: "claude-3-7-sonnet-latest" }),
tools: [getWeather],
});
const result = await agent.invoke({
messages: [{ role: "user", content: "What is the weather in SF?" }],
});
console.log(result.messages.at(-1)?.content);Creates an agent with a chat model and weather tool, then invokes it with a user message.
A conversational assistant needs to answer questions using external functions such as weather lookup.
A model must decide dynamically whether a supplied capability is needed for each request.
An application wants a ready-made agent loop without manually wiring model and tool nodes.
It creates a ReAct agent graph that combines a language model with tools. The returned graph can be invoked with a messages state, and the model may use the supplied tools before answering.
Follow-up: How would you add another capability? Pass another tool in the tools array, ensuring it has a callable implementation and schema suitable for model tool selection.
The llm option supplies the chat model responsible for deciding whether to respond or call a tool. The tools option supplies the functions available to that model.
Follow-up: What happens if no tool is appropriate? The model can finish with a direct response, so tool execution is not required for every invocation.
Invoke the returned agent with an object whose messages field contains the conversation, such as a user role and content. The result contains the agent's resulting message state.
Follow-up: How can a conversation continue? Preserve the returned messages and provide them in a later invocation together with the next user message.
toolChatAnthropicagent.invokemessages