adk-docs icon indicating copy to clipboard operation
adk-docs copied to clipboard

Following Loop Agent document,raise KeyError: 'Context variable not found: `initial_topic`.'

Open zyh3826 opened this issue 5 months ago • 2 comments

Hi, I'm totally new to ADK. When I follow the Loop Agent document, I got the error below:

KeyError: 'Context variable not found: `initial_topic`.'

Steps to reproduce:

  1. mkdir loop_agent, prepare everything
  2. pasting the code in the document to agent.py
  3. ran adk run loop_agent
  4. input any sentence
  5. The error above raised

How can I fix it? Can anyone help us? thanks

zyh3826 avatar Aug 27 '25 13:08 zyh3826

The problem is that the "initial_topic" is a key referenced in the initial_writer_agent instructions, but as seen in the documentation for state, the state values have to be initialized before reference in agent instructions: "Key Existence: Ensure that the key you reference in the instruction string exists in the session.state. If the key is missing, the agent will throw an error. To use a key that may or may not be present, you can include a question mark (?) after the key (e.g. {topic?})." Session State,

So to fix the problem you first have to include a default value for initial_topic in your session.state, you can do that in many ways such as when you initialize the session, or with a before_agent_callback.

I had the same problem at first and do think the documentation should include the state init aswell.

SimonEOA avatar Aug 28 '25 08:08 SimonEOA

It's a documentation issue.

hangfei avatar Oct 28 '25 23:10 hangfei