Is Runner
re-usable across requests from frontend?
#3141
Replies: 1 comment
-
Response from ADK Answering Agent (experimental, answer may be inaccurate) TLDR: Yes, the You've made a great observation by looking into the The Creating a new For a FastAPI application, the recommended approach is to initialize the from contextlib import asynccontextmanager
from fastapi import FastAPI
from google.adk.runners import Runner
from your_project import orchestrator_agent, APP_NAME, session_service
# Global variable to hold the runner
adk_runner = None
@asynccontextmanager
async def lifespan(app: FastAPI):
# Code to run on startup
global adk_runner
print("Initializing ADK Runner...")
adk_runner = Runner(
agent=orchestrator_agent,
app_name=APP_NAME,
session_service=session_service
)
# The application is now ready to accept requests
yield
# Code to run on shutdown (optional)
print("Shutting down...")
app = FastAPI(lifespan=lifespan)
@app.post("/chat")
async def call_orchestrator(req: QueryRequest):
# Now, you can reuse the global adk_runner object here
# instead of creating a new one.
# ... your existing logic for session handling ...
# We need to exhaust the generator to ensure proper cleanup,
# even if we find the response early.
agent_response: str = FALLBACK_RESPONSE_WHEN_NO_RESPONSE_FROM_AGENT
async for event in adk_runner.run_async(
user_id=req.user_id, session_id=session.id, new_message=user_message
):
if event.is_final_response():
if event.content and event.content.parts:
agent_response = event.content.parts[0].text
# ... rest of your response logic ... This approach ensures that the [1] https://github.com/google/adk-python/blob/main/src/google/adk/cli/adk_web_server.py |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I am building a multi-agent app that needs to be exposed via an API. I am using a FastAPI app (not the one provided by
get_fast_api_app
fromgoogle.adk.cli.fast_api
. Because I don't want to expose all the endpoints created by ADK and have a requirement to get custom fields in the request body from frontend.)To achieve above, I have a route in my FastAPI app that uses
Runner
class to instantiate a runner object for every request.Is it correct to instantiate a runner object for each request?
Or can it be reused across multiple requests from frontend?
I didn't find explicit instructions about this in the ADK documentation. But when I checked Python code of ADK. I found in
ADKWebServer
class that it actually reuses runner objects by caching them (Link)Please help me to understand the correct use of this Runner object.
Beta Was this translation helpful? Give feedback.
All reactions