@@ -240,9 +240,14 @@ def __init__(self, **kwargs):
240240 )
241241 # The authorizations of the user, keyed by authorization ID.
242242
243- self .user_id : Optional [str ] = kwargs .get ("user_id" ) or kwargs .get (
244- "userId" , _DEFAULT_USER_ID
245- )
243+ if kwargs .get ("user_id" ) is not None :
244+ self .user_id : Optional [str ] = kwargs ["user_id" ]
245+ elif kwargs .get ("userId" ) is not None :
246+ self .user_id = kwargs ["userId" ]
247+ elif "user_id" in kwargs or "userId" in kwargs :
248+ self .user_id = None
249+ else :
250+ self .user_id = _DEFAULT_USER_ID
246251 # The user ID.
247252
248253 self .session_id : Optional [str ] = kwargs .get ("session_id" ) or kwargs .get (
@@ -588,6 +593,12 @@ def _asyncio_thread_main():
588593 return outcome .get ("result" )
589594
590595
596+ def _validate_user_id (user_id : Any ) -> None :
597+ """Validates that user_id is a non-empty string."""
598+ if not isinstance (user_id , str ) or not user_id .strip ():
599+ raise ValueError ("user_id must be a non-empty string." )
600+
601+
591602def _validate_run_config (run_config : Optional [Dict [str , Any ]]):
592603 """Validates the run config."""
593604 from google .adk .agents .run_config import RunConfig
@@ -1372,6 +1383,7 @@ async def async_stream_query(
13721383 from agentplatform ._genai import _runtimes_utils
13731384 from google .genai import types
13741385
1386+ _validate_user_id (user_id )
13751387 if isinstance (message , Dict ):
13761388 content = types .Content .model_validate (message )
13771389 elif isinstance (message , str ):
@@ -1497,6 +1509,7 @@ def stream_query(
14971509 from agentplatform ._genai import _runtimes_utils
14981510 from google .genai import types
14991511
1512+ _validate_user_id (user_id )
15001513 if isinstance (message , Dict ):
15011514 content = types .Content .model_validate (message )
15021515 elif isinstance (message , str ):
@@ -1554,6 +1567,7 @@ async def streaming_agent_run_with_events(self, request_json: str):
15541567 from google .genai .errors import ClientError
15551568
15561569 request = _StreamRunRequest (** json .loads (request_json ))
1570+ _validate_user_id (request .user_id )
15571571 if not any (
15581572 self ._tmpl_attrs .get (service )
15591573 for service in (
@@ -1688,6 +1702,7 @@ async def async_get_session(
16881702 Raises:
16891703 RuntimeError: If the session is not found.
16901704 """
1705+ _validate_user_id (user_id )
16911706 if not self ._tmpl_attrs .get ("session_service" ):
16921707 self .set_up ()
16931708 session = await self ._tmpl_attrs .get ("session_service" ).get_session (
@@ -1742,6 +1757,7 @@ async def async_list_sessions(self, *, user_id: str, **kwargs):
17421757 Returns:
17431758 ListSessionsResponse: The list of sessions.
17441759 """
1760+ _validate_user_id (user_id )
17451761 if not self ._tmpl_attrs .get ("session_service" ):
17461762 self .set_up ()
17471763 return await self ._tmpl_attrs .get ("session_service" ).list_sessions (
@@ -1798,6 +1814,7 @@ async def async_create_session(
17981814 Returns:
17991815 Session: The newly created session instance.
18001816 """
1817+ _validate_user_id (user_id )
18011818 if not self ._tmpl_attrs .get ("session_service" ):
18021819 self .set_up ()
18031820 session = await self ._tmpl_attrs .get ("session_service" ).create_session (
@@ -1858,6 +1875,7 @@ async def async_delete_session(
18581875 Optional. Additional keyword arguments to pass to the
18591876 session service.
18601877 """
1878+ _validate_user_id (user_id )
18611879 if not self ._tmpl_attrs .get ("session_service" ):
18621880 self .set_up ()
18631881 await self ._tmpl_attrs .get ("session_service" ).delete_session (
@@ -1897,24 +1915,32 @@ def delete_session(
18971915 async def async_add_session_to_memory (self , * , session : Dict [str , Any ]):
18981916 """Generates memories.
18991917
1918+ Always reloads the canonical session from `session_service` (ignoring
1919+ caller-supplied `events` and `app_name`).
1920+
19001921 Args:
19011922 session (Dict[str, Any]):
19021923 Required. The session to use for generating memories. It should
19031924 be a dictionary representing an ADK Session object, e.g.
19041925 session.model_dump(mode="json").
1926+
1927+ Raises:
1928+ TypeError: If session is not a Session object or dictionary.
1929+ ValueError: If session.user_id is not a non-empty string.
1930+ RuntimeError: If the session is not found in session_service.
19051931 """
19061932 from google .adk .sessions .session import Session
19071933
19081934 if isinstance (session , Dict ):
19091935 session = Session .model_validate (session )
19101936 elif not isinstance (session , Session ):
19111937 raise TypeError ("session must be a Session object." )
1912- if not session . events :
1913- # Get the latest version of the session in case it was updated .
1914- session = await self .async_get_session (
1915- user_id = session .user_id ,
1916- session_id = session .id ,
1917- )
1938+ # Always fetch the canonical session from the session service rather
1939+ # than trusting caller-supplied events or app_name .
1940+ session = await self .async_get_session (
1941+ user_id = session .user_id ,
1942+ session_id = session .id ,
1943+ )
19181944 if not self ._tmpl_attrs .get ("memory_service" ):
19191945 self .set_up ()
19201946 return await self ._tmpl_attrs .get ("memory_service" ).add_session_to_memory (
@@ -1931,6 +1957,7 @@ async def async_search_memory(self, *, user_id: str, query: str):
19311957 Returns:
19321958 A SearchMemoryResponse containing the matching memories.
19331959 """
1960+ _validate_user_id (user_id )
19341961 if not self ._tmpl_attrs .get ("memory_service" ):
19351962 self .set_up ()
19361963 return await self ._tmpl_attrs .get ("memory_service" ).search_memory (
@@ -1969,6 +1996,7 @@ async def async_save_artifact(
19691996 Returns:
19701997 int: The revision ID.
19711998 """
1999+ _validate_user_id (user_id )
19722000 if isinstance (artifact , str ):
19732001 try :
19742002 from google .genai import types
@@ -2018,6 +2046,7 @@ async def async_load_artifact(
20182046 Returns:
20192047 Optional[types.Part]: The artifact or None if not found.
20202048 """
2049+ _validate_user_id (user_id )
20212050 if not self ._tmpl_attrs .get ("artifact_service" ):
20222051 self .set_up ()
20232052 return await self ._tmpl_attrs .get ("artifact_service" ).load_artifact (
@@ -2050,6 +2079,7 @@ async def async_list_artifact_keys(
20502079 Returns:
20512080 list[str]: A list of artifact filenames.
20522081 """
2082+ _validate_user_id (user_id )
20532083 if not self ._tmpl_attrs .get ("artifact_service" ):
20542084 self .set_up ()
20552085 return await self ._tmpl_attrs .get ("artifact_service" ).list_artifact_keys (
@@ -2080,6 +2110,7 @@ async def async_delete_artifact(
20802110 Optional. Additional keyword arguments to pass to the
20812111 artifact service.
20822112 """
2113+ _validate_user_id (user_id )
20832114 if not self ._tmpl_attrs .get ("artifact_service" ):
20842115 self .set_up ()
20852116 await self ._tmpl_attrs .get ("artifact_service" ).delete_artifact (
@@ -2114,6 +2145,7 @@ async def async_list_versions(
21142145 Returns:
21152146 list[int]: A list of all available versions of the artifact.
21162147 """
2148+ _validate_user_id (user_id )
21172149 if not self ._tmpl_attrs .get ("artifact_service" ):
21182150 self .set_up ()
21192151 return await self ._tmpl_attrs .get ("artifact_service" ).list_versions (
@@ -2148,6 +2180,7 @@ async def async_list_artifact_versions(
21482180 Returns:
21492181 list[ArtifactVersion]: A list of ArtifactVersion objects.
21502182 """
2183+ _validate_user_id (user_id )
21512184 if not self ._tmpl_attrs .get ("artifact_service" ):
21522185 self .set_up ()
21532186 return await self ._tmpl_attrs .get ("artifact_service" ).list_artifact_versions (
@@ -2185,6 +2218,7 @@ async def async_get_artifact_version(
21852218 Returns:
21862219 Optional[ArtifactVersion]: An ArtifactVersion object or None.
21872220 """
2221+ _validate_user_id (user_id )
21882222 if not self ._tmpl_attrs .get ("artifact_service" ):
21892223 self .set_up ()
21902224 return await self ._tmpl_attrs .get ("artifact_service" ).get_artifact_version (
0 commit comments