@@ -1952,6 +1952,74 @@ def _run_agent(
19521952 os .environ ["GOOGLE_CLOUD_LOCATION" ] = original_location
19531953
19541954
1955+ def _create_agent_engine_session (
1956+ * ,
1957+ agent_engine : types .AgentEngine ,
1958+ user_id : str ,
1959+ session_state : Optional [dict [str , Any ]] = None ,
1960+ ) -> Any :
1961+ """Creates a session for an agent engine and returns the session ID.
1962+
1963+ First attempts to use the agent engine's own `create_session` operation
1964+ (available for agents deployed via AdkApp). If the agent engine does not
1965+ have `create_session` registered, falls back to the managed Vertex AI
1966+ Sessions API.
1967+
1968+ Args:
1969+ agent_engine: The AgentEngine instance.
1970+ user_id: The user ID for the session.
1971+ session_state: Optional initial state for the session.
1972+
1973+ Returns:
1974+ The session ID string.
1975+
1976+ Raises:
1977+ RuntimeError: If the session could not be created via either path.
1978+ """
1979+ try :
1980+ session = agent_engine .create_session ( # type: ignore[attr-defined]
1981+ user_id = user_id ,
1982+ state = session_state ,
1983+ )
1984+ return session ["id" ]
1985+ except AttributeError as exc :
1986+ # Agent engine does not have create_session registered (e.g. deployed
1987+ # via Console, gcloud, or source code deployment without AdkApp).
1988+ # Fall back to the managed Vertex AI Sessions API.
1989+ logger .info (
1990+ "Agent engine does not have 'create_session' operation registered."
1991+ " Falling back to managed Sessions API."
1992+ )
1993+ if agent_engine .api_resource is None :
1994+ raise RuntimeError (
1995+ "Failed to create session: agent_engine.api_resource is None."
1996+ ) from exc
1997+ if agent_engine .api_client is None :
1998+ raise RuntimeError (
1999+ "Failed to create session: agent_engine.api_client is None."
2000+ ) from exc
2001+ operation = agent_engine .api_client .sessions .create (
2002+ name = agent_engine .api_resource .name ,
2003+ user_id = user_id ,
2004+ config = types .CreateAgentEngineSessionConfig (
2005+ session_state = session_state ,
2006+ ),
2007+ )
2008+ if operation .response and operation .response .name :
2009+ # Session name format:
2010+ # projects/{p}/locations/{l}/reasoningEngines/{re}/sessions/{id}
2011+ return operation .response .name .split ("/" )[- 1 ]
2012+ elif operation .error :
2013+ raise RuntimeError (
2014+ f"Failed to create session via managed API: { operation .error } "
2015+ ) from exc
2016+ else :
2017+ raise RuntimeError (
2018+ "Failed to create session via managed API: "
2019+ "operation returned no response."
2020+ ) from exc
2021+
2022+
19552023def _execute_agent_run_with_retry (
19562024 row : pd .Series ,
19572025 contents : Union [genai_types .ContentListUnion , genai_types .ContentListUnionDict ],
@@ -1963,9 +2031,10 @@ def _execute_agent_run_with_retry(
19632031 session_inputs = _get_session_inputs (row )
19642032 user_id = session_inputs .user_id
19652033 session_state = session_inputs .state
1966- session = agent_engine .create_session ( # type: ignore[attr-defined]
2034+ session_id = _create_agent_engine_session (
2035+ agent_engine = agent_engine ,
19672036 user_id = user_id ,
1968- state = session_state ,
2037+ session_state = session_state ,
19692038 )
19702039 except KeyError as e :
19712040 return {"error" : f"Failed to get all required agent engine inputs: { e } " }
@@ -1976,7 +2045,7 @@ def _execute_agent_run_with_retry(
19762045 responses = []
19772046 for event in agent_engine .stream_query ( # type: ignore[attr-defined]
19782047 user_id = user_id ,
1979- session_id = session [ "id" ] ,
2048+ session_id = session_id ,
19802049 message = contents ,
19812050 ):
19822051 if event and CONTENT in event and PARTS in event [CONTENT ]:
0 commit comments