make a react agent in langgraph that I can chat with via terminal. make it highligh any…
- User
make a react agent in langgraph that I can chat with via terminal. make it highligh any tool calls in a rich text in terminal. print many infos for debug purposes. follow the following tutorial, but use from langchain_ollama import ChatOllama llm = ChatOllama( model="llama3.1", temperature=0, )
because this rund locally and doesnt need a api key :
How to create a ReAct agent from scratch
Using the prebuilt ReAct agent (create_react_agent) is a great way to get started, but sometimes you might want more control and customization. In those cases, you can create a custom ReAct agent. This guide shows how to implement ReAct agent from scratch using LangGraph. Setup
First, let's install the required packages and set our API keys
%%capture --no-stderr %pip install -U langgraph langchain-openai
import getpass import os
def _set_env(var: str): if not os.environ.get(var): os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
Set up LangSmith for better debugging
Sign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM aps built with LangGraph — read more about how to get started in the docs. Create ReAct agent
Now that you have installed the required packages and set your environment variables, we can code our ReAct agent! Define graph state
We are going to define the most basic ReAct state in this example, which will just contain a list of messages.
For your specific use case, feel free to add any other state keys that you need.
from typing import ( Annotated, Sequence, TypedDict, ) from langchain_core.messages import BaseMessage from langgraph.graph.message import add_messages
class AgentState(TypedDict): """The state of the agent."""
messages: Annotated[Sequence[BaseMessage], add_messages]Define model and tools
Next, let's define the tools and model we will use for our example.
from langchain_openai import ChatOpenAI from langchain_core.tools import tool
model = ChatOpenAI(model="gpt-4o-mini")
@tool def get_weather(location: str): """Call to get the weather from a specific location.""" # This is a placeholder for the actual implementation # Don't let the LLM know this though 😊 if any([city in location.lower() for city in ["sf", "san francisco"]]): return "It's sunny in San Francisco, but you better look out if you're a Gemini 😈." else: return f"I am not sure what the weather is in {location}"
tools = [get_weather]
model = model.bind_tools(tools)
Define nodes and edges
Next let's define our nodes and edges. In our basic ReAct agent there are only two nodes, one for calling the model and one for using tools, however you can modify this basic structure to work better for your use case. The tool node we define here is a simplified version of the prebuilt ToolNode, which has some additional features.
- Assistant