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

Session Not Found

Open NitishDhakal opened this issue 1 year ago • 8 comments

Describe the bug Getting Session Not Found error while running the basic agent example in the adk site. adk doc link

Desktop (please complete the following information):

  • OS: Debian GNU/linux - 11
  • Python version(python -V): 3.11
  • ADK version(pip show google-adk): 1.0.0

Code:

from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools import google_search
from google.genai import types

APP_NAME = "google_search_agent"
USER_ID = "user1234"
SESSION_ID = "1234"


root_agent = Agent(
    name="basic_search_agent",
    model="gemini-2.0-flash",
    description="Agent to answer questions using Google Search.",
    instruction="I can answer your questions by searching the internet. Just ask me anything!",
    # google_search is a pre-built tool which allows the agent to perform Google searches.
    tools=[google_search]
)

# Session and Runner
session_service = InMemorySessionService()
session = session_service.create_session(
    app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=root_agent, app_name=APP_NAME,
                session_service=session_service)


# Agent Interaction
def call_agent(query):
    """
    Helper function to call the agent with a query.
    """
    content = types.Content(role='user', parts=[types.Part(text=query)])
    events = runner.run(
        user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    for event in events:
        if event.is_final_response():
            final_response = event.content.parts[0].text
            print("Agent Response: ", final_response)


call_agent("what's the latest ai news?")

Error:

Exception in thread Thread-14 (_asyncio_thread_main):
Traceback (most recent call last):
  File "/home/jupyter/.local/share/uv/python/cpython-3.11.11-linux-x86_64-gnu/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
    self.run()
  File "/home/jupyter/---/.venv/lib/python3.11/site-packages/ipykernel/ipkernel.py", line 766, in run_closure
    _threading_Thread_run(self)
  File "/home/jupyter/.local/share/uv/python/cpython-3.11.11-linux-x86_64-gnu/lib/python3.11/threading.py", line 982, in run
    self._target(*self._args, **self._kwargs)
  File "/home/jupyter/---/.venv/lib/python3.11/site-packages/google/adk/runners.py", line 137, in _asyncio_thread_main
    asyncio.run(_invoke_run_async())
  File "/home/jupyter/.local/share/uv/python/cpython-3.11.11-linux-x86_64-gnu/lib/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/home/jupyter/.local/share/uv/python/cpython-3.11.11-linux-x86_64-gnu/lib/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jupyter/.local/share/uv/python/cpython-3.11.11-linux-x86_64-gnu/lib/python3.11/asyncio/base_events.py", line 654, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/home/jupyter/---/.venv/lib/python3.11/site-packages/google/adk/runners.py", line 125, in _invoke_run_async
    async for event in self.run_async(
  File "/home/jupyter/---/.venv/lib/python3.11/site-packages/google/adk/runners.py", line 178, in run_async
    raise ValueError(f'Session not found: {session_id}')
ValueError: Session not found: 1234

NitishDhakal avatar May 21 '25 14:05 NitishDhakal

Figured out myself. The doc is not updated yet. session_service.create_session is coroutine now. session = await session_service.create_session( app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)

NitishDhakal avatar May 21 '25 14:05 NitishDhakal

This is still a problem. Just putting await in front is syntactically wrong; we have to couple this with async, but then there are the docs, which are super misleading.

MSHRA-P avatar May 29 '25 06:05 MSHRA-P

I couldn't get it to work either.

todo avatar May 29 '25 10:05 todo

+1

hachristinee avatar Jun 02 '25 12:06 hachristinee

Still an issue

franciscopiccini avatar Jun 11 '25 22:06 franciscopiccini

Here is the working code

`import asyncio from google.adk.agents import Agent from google.adk.runners import Runner from google.adk.sessions import InMemorySessionService from google.adk.tools import google_search from google.genai import types

APP_NAME = "Google_Search_agent" USER_ID = "user1234" SESSION_ID = "1234"

root_agent = Agent( name="basic_search_agent", model="gemini-2.0-flash", description="Agent to answer questions using Google Search.", instruction="I can answer your questions by searching the internet. Just ask me anything!", tools=[google_search], )

session_service = InMemorySessionService() runner = Runner(agent=root_agent, app_name=APP_NAME, session_service=session_service)

async def call_agent_async(query): print(f"\n--- Asking the agent: '{query}' ---") content = types.Content(role="user", parts=[types.Part(text=query)])

async for event in runner.run_async(
    user_id=USER_ID, session_id=SESSION_ID, new_message=content
):
    if event.is_final_response():
        final_response = event.content.parts[0].text
        print("Agent Response: ", final_response)

async def main(): # THE MISSING PIECE! We create the session inside the async function # so that we can use the 'await' keyword you discovered. session = await session_service.create_session( app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID )

await call_agent_async("what is the revenue of alphabet in 2025?")

if name == "main": try: asyncio.run(main()) except RuntimeError as e: if "cannot be called from a running event loop" in str(e): print("Running in an existing event loop. Awaiting main().") loop = asyncio.get_event_loop() loop.create_task(main()) else: raise e`

nabilrehman avatar Jun 12 '25 03:06 nabilrehman

Fixed: Session not found with new google-adk update For google-adk >= 1.0, I encountered the same issue. The following change worked for me:

from google.genai import types
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner

APP_NAME = "Testpp"
USER_ID = "test_user"
SESSION_ID = "1233344"

session_service = InMemorySessionService()

# Use asyncio.run() to execute the async session creation**
session = asyncio.run(session_service.create_session(
    app_name=APP_NAME,
    user_id=USER_ID,
    session_id=SESSION_ID
))

print(session)
runner = Runner(agent=refinement_loop, app_name=APP_NAME, session_service=session_service)

def call_agent(query):
    content = types.Content(role='user', parts=[types.Part(text=query)])
    events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)
    
    for event in events:
        print(f"Content: {event.content}")
        if event.is_final_response():
            final_response = event.content.parts[0].text
            print("Agent Response: ", final_response)

pamudu123 avatar Jun 12 '25 04:06 pamudu123

Thanks! Using asyncio.run worked for me @pamudu123

lkshay avatar Sep 27 '25 00:09 lkshay