egeorge
egeorge

Reputation: 682

LangChain ReAct agent not performing multiple cycles

I am struggling with getting my ReAct agent in LangChain to do any more than one cycle. It will select tools, and run them, but it won't ever decide that it needs to run any again. Very occasionally some combination of prompts will result in multiple cycles, but it is never repeatable.

It is important to note that I am using langgraph.prebuilt.create_react_agent to create the agent. I know there are a bunch of other ways to create the agent, but after looking through the langgraph.prebuilt code, I don't see any reason why it won't work.

At the end I also have a list of things I have tried which I can provide details for if necessary.

Library Versions:

langchain-core==0.3.10
langchain-ollama==0.2.0
langgraph==0.2.39
langgraph-checkpoint==2.0.2

Agent Code (color print method omitted):

import os
import asyncio
import json
import uuid

from dotenv import load_dotenv
from langchain_core.messages import HumanMessage
from langchain_ollama import ChatOllama

from langchain_core.tools import tool
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent

load_dotenv("../.env")

thing_list = [
    {"name": "Thing0", "location": "paris"},
    {"name": "Thing1", "location": "london"},
    {"name": "Thing2", "location": "berlin"},
    {"name": "Thing3", "location": "paris"},
]

@tool
def get_thing_location(symbol: str) -> str:
    """
    Retrieves the location of the thing.

    Args:
        symbol (str): The symbol of the thing to find.
    Returns:
        str: the location value.
    """
    thing = next((item for item in thing_list if item["name"] == symbol), None)
    return thing["location"] if thing else None

@tool
def find_things_by_location(location: str) -> list:
    """
    Retrieves a list of things based on their location.

    Args:
        location (str): The location to look for things.
    Returns:
        list: list of things at the location.
    """

    return [thing for thing in thing_list if thing["location"] == location]


modelName=os.getenv("LLM_MODEL", "llama3.2:3b")
ollamaUrl=os.getenv("OLLAMA_URL")

model = ChatOllama(model=modelName, base_url=ollamaUrl)

memory = MemorySaver()
threadId = "thing-agent"
config = {"configurable": {"thread_id": threadId}}

agent = create_react_agent(
    model=model,
    tools=[find_things_by_location, get_thing_location],
    checkpointer=memory,
)

thingLoc = get_thing_location('Thing0');
print(f"Location of Thing0: {thingLoc}")
otherThings = find_things_by_location(thingLoc)
print(f"Things in same location: {otherThings}")

msgs = [
    HumanMessage(content="""
      What is the location of Thing0? 
      What other things are in the same location?
    """),
]

from color_outputs import print_event
async def run():
    async for event in (agent.astream_events(
            {"messages": msgs},
            version="v2", config=config)):
        print_event(event)

asyncio.run(run())

Output:

Location of Thing0: paris
Things in same location: [{'name': 'Thing0', 'location': 'paris'}, {'name': 'Thing3', 'location': 'paris'}]

agent on_chain_start (['graph:step:1'])
    Starting agent: agent with input messages: 
        Human: 
      What is the location of Thing0? 
      What other things are in the same location?
    
        -------------
--------------------
get_thing_location on_tool_start (['seq:step:1'])
    Starting tool: get_thing_location with inputs: {'symbol': 'Thing0'}
--------------------
find_things_by_location on_tool_start (['seq:step:1'])
    Starting tool: find_things_by_location with inputs: {'location': 'get_thing_location', 'symbol': 'Thing0'}
--------------------
find_things_by_location on_tool_end (['seq:step:1'])
    Done tool: find_things_by_location
    Tool output was: content=[] name='find_things_by_location' tool_call_id='8f012dd4-6082-4bd1-bbaa-e82eba61eca0'
--------------------
get_thing_location on_tool_end (['seq:step:1'])
    Done tool: get_thing_location
    Tool output was: content='paris' name='get_thing_location' tool_call_id='7fc27e00-29be-48b1-ab7a-d640cee96212'
--------------------
agent on_chain_start (['graph:step:3'])
    Starting agent: agent with input messages: 
        Human: 
      What is the location of Thing0? 
      What other things are in the same location?
    
        -------------
        AI:  
        -------------
        Tool: get_thing_location: paris
        -------------
        Tool: find_things_by_location: []
        -------------
--------------------

Process finished with exit code 0

As you can see, it doesn't try to do a find_things_by_location call after receiving the location information from the previous call. Sometimes it does use that tool, but not with meaningful input (either nothing or something it makes up).

Things I have tried:

Upvotes: 0

Views: 279

Answers (0)

Related Questions