fix: use try/except to create session if get_session raises in ADK 1.x
This commit is contained in:
parent
7e1af38474
commit
4ef0683c7c
|
|
@ -52,6 +52,28 @@ class RunResponse(BaseModel):
|
|||
response: str
|
||||
|
||||
|
||||
def _ensure_session(user_id: str, session_id: str):
|
||||
"""Get existing session or create a new one. Handles both ADK 1.x and 2.x."""
|
||||
try:
|
||||
session = session_service.get_session(
|
||||
app_name=APP_NAME,
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
)
|
||||
if session is not None:
|
||||
return session
|
||||
except Exception:
|
||||
pass # session doesn't exist — fall through to create
|
||||
|
||||
session = session_service.create_session(
|
||||
app_name=APP_NAME,
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
)
|
||||
logger.info(f"Created new session: {session_id} for user: {user_id}")
|
||||
return session
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return JSONResponse({"status": "ok", "service": APP_NAME})
|
||||
|
|
@ -60,19 +82,7 @@ async def health():
|
|||
@app.post("/run", response_model=RunResponse)
|
||||
async def run(req: RunRequest):
|
||||
try:
|
||||
# Always ensure session exists — create if missing
|
||||
session = session_service.get_session(
|
||||
app_name=APP_NAME,
|
||||
user_id=req.user_id,
|
||||
session_id=req.session_id,
|
||||
)
|
||||
if session is None:
|
||||
session = session_service.create_session(
|
||||
app_name=APP_NAME,
|
||||
user_id=req.user_id,
|
||||
session_id=req.session_id,
|
||||
)
|
||||
logger.info(f"Created new session: {req.session_id}")
|
||||
_ensure_session(req.user_id, req.session_id)
|
||||
|
||||
runner = Runner(
|
||||
agent=root_agent,
|
||||
|
|
@ -96,9 +106,7 @@ async def run(req: RunRequest):
|
|||
if part.text:
|
||||
final_response += part.text
|
||||
|
||||
logger.info(
|
||||
f"[{req.user_id}/{req.session_id}] Response length: {len(final_response)}"
|
||||
)
|
||||
logger.info(f"[{req.user_id}/{req.session_id}] Response length: {len(final_response)}")
|
||||
return RunResponse(
|
||||
user_id=req.user_id,
|
||||
session_id=req.session_id,
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user