Hey everyone! Recently I've been working on a thes...
# dev-help
r
Hey everyone! Recently I've been working on a thesis project which aims to modify OpenHands into a 'tutor agent' for computer science courses at my university. As a result, I've attempted to incorporate a new RAG-based search tool into the ReadOnlyAgent, which queries an external index via an api request and returns the top search results. The ReadOnlyAgent is the 'main' agent for my use-case. To ensure that no course-specific questions asked by a student are met with non course-specific answers, the system prompt is written in a way which ensures that the search tool is called upon each user message received. To perform this task, I created a new action-observation pair. Currently, the search tool is correctly being called, and the expected results are correctly returned, but the search tool is then continuously called again and again by the agent, until an AgentStuckInLoopError is returned. It has been extremely difficult to diagnose and pinpoint the exact cause of the infinite looping, so I'm hoping someone in here can point me in the right direction. To summarize the changes that have currently been made to the code base, I have created the following files: • openhands/agenthub/readonly_agent/tools/search.py • openhands/events/action/search.py • openhands/events/observation/search.py And modified the following files: • openhands/agenthub/readonly_agent/function_calling.py • openhands/agenthub/readonly_agent/prompts/system_prompt.j2 • openhands/agenthub/readonly_agent/readonly_agent.py • openhands/agenthub/readonly_agent/tools/__init__.py • openhands/core/schema/action.py • openhands/core/schema/observation.py • openhands/events/action/__init__.py • openhands/events/observation/__init__.py • openhands/events/serialization/action.py • openhands/events/serialization/observation.py • openhands/memory/conversation_memory.py • openhands/runtime/action_execution_server.py • openhands/runtime/impl/action_execution/action_execution_client.py • poetry.lock • pyproject.toml Please let me know if there is anything obvious that I'm missing! Any tips on how to proceed with debugging this issue would be much appreciated. Thank you :)
m
I would suggest disabling/removing search tool first and see if your agent loop finishes as expected.
Maybe you didn’t include the “finish” tool?
d
Hi, I'm working on the same code as Keenen. I tried disabling the search by simply commenting it out of the list of tools given to the agent. The agent does indeed finish, even when running bash and file read tools as part of its agent loop.
m
Okay then I’d debug what is the response from the search tool. Maybe its result is not properly fed into the event stream - causing LLM to repeatedly calling it
d
What I know is that the search tool successfully returns a SearchObservation. This is received in ConversationMemory the same way other observations like the FileReadObservation are. I've been trying to pattern the SearchObservation the same way the FileRead one is... Are there other places that observations need to be handled?
Looking at the agent history shows continual looping of different SearchAction and SearchObservation pairs, so that's making it there, at least.
Oooh. I think the "last_user_message" is not getting updated because the tool observation source is the agent and not the user...? Let me inspect the logic of it working normally without the search tool.
m
tool call source should indeed be agent IIRC
you might want to dump the trajectory. Your
config.toml
shall be like
Copy code
[core]
save_trajectory_path="./trajectories"
From the trajectory you can check what fields are different for your tool call v.s. other tool calls
👍 1
d
Sorry, how do you see the trajectories? Added that to my config, and i see there's an app route to get a trajectory in
trajectory.py
, but I don't see a generated file
m
are you using headless/cli mode, or GUI mode?
On GUI mode you could actually simply click on the export button
On headless/CLI mode, the trajectory shall be saved automatically to your local folder once the agent finishes or exits on error
r
Hey! So we compared the two trajectories, and it initially looked like the only difference was in the 'message' field of the events, where our tool call did NOT have a human-readable 'description' of what had occurred. E.g., 'I have completed a search of the following query: ....' However, after we modified the observation to correctly convey this 'message' attribute, it was evident that it didn't fix our issue. Are there any other ways in which we could move forward?
d
For context, this is the part of the trajectory produced after one of the search tool calls, with the details of the actual query/search result abstracted:
Copy code
{
    "id": 9,
    "timestamp": "2025-08-06T19:08:42.096286",
    "source": "agent",
    "message": "I have completed a search for the following query: [QUERY].",
    "cause": 8,
    "observation": "search",
    "tool_call_metadata": {
      "function_name": "search",
      "tool_call_id": "call_YJAyG9PKL2Z0CcIpjHB2xmpU",
      "model_response": {
        "id": "chatcmpl-C1UQNUECyt5WlFaQAVRC2ORDmPbKM",
        "created": 1754471315,
        "model": "o3-2025-04-16",
        "object": "chat.completion",
        "system_fingerprint": null,
        "choices": [
          {
            "finish_reason": "tool_calls",
            "index": 0,
            "message": {
              "content": null,
              "role": "assistant",
              "tool_calls": [
                {
                  "function": {
                    "arguments": "{\"query\":\"[QUERY]"}",
                    "name": "search"
                  },
                  "id": "call_YJAyG9PKL2Z0CcIpjHB2xmpU",
                  "type": "function"
                }
              ],
              "function_call": null,
              "annotations": []
            }
          }
        ],
        "usage": {
          "completion_tokens": 91,
          "prompt_tokens": 2145,
          "total_tokens": 2236,
          "completion_tokens_details": {
            "accepted_prediction_tokens": 0,
            "audio_tokens": 0,
            "reasoning_tokens": 64,
            "rejected_prediction_tokens": 0
          },
          "prompt_tokens_details": {
            "audio_tokens": 0,
            "cached_tokens": 0
          }
        },
        "service_tier": "default"
      },
      "total_calls_in_response": 1
    },
    "content": "[RESULT OF TOOL CALL]",
    "extras": {
      "query": "[QUERY]"
    }
  },
c
Source should not be ‘agent’, I think it needs to be ‘user’, here, or if the LLM API allows, then maybe ‘tool’
(but there’s no need to set ‘tool’ normally, litellm should handle it if suitable)
Ah, the example looks a bit strange… sorry, maybe I need to read it again, but the point about the observation source is that: whether we like it or not, this API is chat-like, one message from user, one from assistant. In that pattern, the tool call is assistant (it’s from the model), and the observation (from us) should be ‘user’
d
This is interesting to me as when I observed the trajectories from running the main/unmodified version of OpenHands, getting it to do file read operations, it appeared as though the tool call and observation were both sourced from the agent, like so:
Copy code
{
    "id": 10,
    "timestamp": "2025-08-06T15:57:11.617842",
    "source": "agent",
    "message": "Reading file: [FILEPATH]",
    "action": "read",
    "tool_call_metadata": {
      "function_name": "view",
      "tool_call_id": "call_KG2XY1diL8diUvaLJEPrmB9v",
      "model_response": {
        "id": "chatcmpl-C1RR7ADh5kFYUCZaAkmsHQKcRwn6R",
        "created": 1754459829,
        "model": "o3-2025-04-16",
        "object": "chat.completion",
        "system_fingerprint": null,
        "choices": [
          {
            "finish_reason": "tool_calls",
            "index": 0,
            "message": {
              "content": null,
              "role": "assistant",
              "tool_calls": [
                {
                  "function": {
                    "arguments": "{\"path\":\"[FILEPATH]"}",
                    "name": "view"
                  },
                  "id": "call_KG2XY1diL8diUvaLJEPrmB9v",
                  "type": "function"
                }
              ],
              "function_call": null,
              "annotations": []
            }
          }
        ],
        "usage": {...},
        "service_tier": "default"
      },
      "total_calls_in_response": 1
    },
    "llm_metrics": {...},
    "args": {
      "path": "[FILEPATH]",
      "start": 0,
      "end": -1,
      "thought": "",
      "impl_source": "oh_aci",
      "view_range": null
    }
  },
  {
    "id": 11,
    "timestamp": "2025-08-06T15:57:11.704735",
    "source": "agent",
    "message": "I read the file [FILEPATH].",
    "cause": 10,
    "observation": "read",
    "tool_call_metadata": {
      "function_name": "view",
      "tool_call_id": "call_KG2XY1diL8diUvaLJEPrmB9v",
      "model_response": {
        "id": "chatcmpl-C1RR7ADh5kFYUCZaAkmsHQKcRwn6R",
        "created": 1754459829,
        "model": "o3-2025-04-16",
        "object": "chat.completion",
        "system_fingerprint": null,
        "choices": [
          {
            "finish_reason": "tool_calls",
            "index": 0,
            "message": {
              "content": null,
              "role": "assistant",
              "tool_calls": [
                {
                  "function": {
                    "arguments": "{\"path\":\"[FILEPATH]"}",
                    "name": "view"
                  },
                  "id": "call_KG2XY1diL8diUvaLJEPrmB9v",
                  "type": "function"
                }
              ],
              "function_call": null,
              "annotations": []
            }
          }
        ],
        "usage": {...}
        },
        "service_tier": "default"
      },
      "total_calls_in_response": 1
    },
    "content": "Here's the result of running `cat -n` on [FILEPATH]:\n[RESULT]",
    "extras": {
      "path": "[FILEPATH]",
      "impl_source": "oh_aci"
    }
  },
c
It gets really confusing, yes… What I mean, is that when we sent the messages to the LLM, this is user: https://github.com/All-Hands-AI/OpenHands/blob/1c6634780399780fd844ef7279e3a96be7f307ee/openhands/memory/conversation_memory.py#L427
d
Ah, yes, we do something similar in that file:
Copy code
elif isinstance(obs, KnowledgeBaseSearchObservation):
            text = truncate_content(obs.content, max_message_chars)
            message = Message(role='user', content=[TextContent(text=text)])
c
Ah okay 🤔
Could you perhaps confirm that this logic works, although… if it’s looping, it seems it has to https://github.com/All-Hands-AI/OpenHands/blob/1c6634780399780fd844ef7279e3a96be7f307ee/openhands/controller/agent_controller.py#L347
Maybe also • just a silly thought, in the conversation_memory, where you quoted above, maybe print the content, is it what you’d expect to send over? • is the code setting somewhere the
_cause
attribute of the observation, to be the id of the action?
d
Conversation memory, iirc, is what's in the history of the agent state, which does have the expected results:
The results of each observation are different, by the way, they're separate calls to the tool with the same query.
c
Ahh, they’re different?
d
Yes, and in the UI, you can see the tool calls looping like so (I stopped this one after two). They're marked as successful tool calls
c
Just to make sure I understand correctly: SearchObs with index 5 has a different
content
than SearchObs with index 7?
d
Yes. It's not always so obvious, because it's the same query, but I let the breakpoint continue for a few more iterations:
c
Ah actually, it seems then that SearchAction with index 10 has a slightly different
query
?
d
Ah yes - good catch, I didn't spot that straight away. So it's generating a new query, instead of rerunning the exact same one again
For some reason perhaps, it isn't recognising the results as received, although it's in the conversation history already... ?
c
Maybe the LLM isn’t actually receiving… hmm, the pair action/obs. At the end of the execution flow in conversation_memory, there are a few private method calls that check / verify the validity of the actions in history
and they may drop events, if they don’t fit the rules
so the dropped events are never sent to the LLM
Two things you may want to consider • enable DEBUG=1 in env, and check the logs/llm folder for the logs sent to the LLM, there are prompts and responses
👍 1
d
Noted! I'll do that in a bit, I'm curious about the filter there. Since this is an entirely new tool it's quite possible that it's simply being filtered out... thanks for the help! I'll pop back in if I get stuck again after I've done some more debugging of my own, haha
c
Yes, or right after those function calls, it’s the
return messages
line, if you just print that array, does it still contain them? That array goes to the LLM
p
(sorry, don't mean to interrupt the fun debugging session here) I had a question about your RAG system design: how do you ensure it does not hallucinate or allow pretrained knowledge to pollute your responses? my take is a critic node to eval grounding: https://gitlab.com/deposition.cloud/apps/relay/agent/-/blob/main/src/relay_agent/graphs/qa_agent.py?ref_type=heads#L16 but I may not be going about it in a SOTA sort of way 🙂, open to suggestions I'm building something similar to what you're doing, but for my personal locally cloned git code repositories; and I want the agent to not hallucinate with "knowledge" existing outside the RAG system. The end-user CLI-based experience currently looks like: