@@ -58,6 +58,16 @@ def _is_valid_guid(value: str | None) -> bool:
5858 return False
5959
6060
61+ def _get_message_user_id (message : Message ) -> str | None :
62+ """Return the message's explicit user id: a valid ``user_id`` property, else a GUID ``author_name``."""
63+ potential_user_id = (message .additional_properties or {}).get ("user_id" )
64+ if isinstance (potential_user_id , str ) and _is_valid_guid (potential_user_id ):
65+ return potential_user_id
66+ if _is_valid_guid (message .author_name ):
67+ return message .author_name
68+ return None
69+
70+
6171# RFC 2397: data:[<mediatype>][;base64],<data>, where <mediatype> may be followed by any number of
6272# ";parameter=value" segments (for example "data:text/plain;charset=utf-8;base64,..."). The optional
6373# parameters have to be matched explicitly, otherwise a parameterised media type fails to decode and
@@ -212,12 +222,13 @@ async def process_messages(
212222 messages: The messages to process
213223 activity: The activity type (e.g., UPLOAD_TEXT)
214224 session_id: Optional session/conversation id. Else, a new GUID is generated.
215- user_id: Optional user_id to use for all messages. If provided, this is the fallback.
225+ user_id: Optional user_id to use for all messages when the credential does not identify a user.
226+ Otherwise, each message is evaluated under its own user id.
216227
217228 Returns:
218229 A tuple of (should_block: bool, resolved_user_id: str | None).
219- The resolved_user_id can be stored and passed back when processing the response
220- to ensure the same user context is maintained throughout the request/response cycle .
230+ The resolved_user_id is the user id of the last message. It can be stored and passed back when
231+ processing the response so the response is evaluated under the same user context .
221232 """
222233 pc_requests , resolved_user_id = await self ._map_messages (messages , activity , session_id , user_id )
223234 should_block = False
@@ -245,10 +256,12 @@ async def _map_messages(
245256 messages: The messages to map
246257 activity: The activity type
247258 session_id: Optional session/conversation id to use for correlation
248- provided_user_id: Optional user_id to use. If provided, this is the fallback.
259+ provided_user_id: Optional user_id to use for all messages when the credential does not identify a
260+ user. Otherwise, each message uses its own user id, and messages without one inherit the latest
261+ explicit user id in the batch.
249262
250263 Returns:
251- A tuple of (requests, resolved_user_id)
264+ A tuple of (requests, resolved_user_id), where resolved_user_id is the user id of the last message.
252265 """
253266 results : list [ProcessContentRequest ] = []
254267 token_info = await self ._client .get_user_info_from_token (tenant_id = self ._settings .get ("tenant_id" ))
@@ -257,34 +270,32 @@ async def _map_messages(
257270 if not tenant_id or not _is_valid_guid (tenant_id ):
258271 raise ValueError ("Tenant id required or must be inferable from credential" )
259272
260- resolved_user_id = (token_info or {}).get ("user_id" )
261- resolved_author_name = None
262- if not resolved_user_id :
263- resolved_user_id = provided_user_id if provided_user_id and _is_valid_guid (provided_user_id ) else None
264-
265- if not resolved_user_id :
266- for m in messages :
267- if m .additional_properties :
268- potential_user_id = m .additional_properties .get ("user_id" )
269- if _is_valid_guid (potential_user_id ):
270- resolved_user_id = potential_user_id
271- break
272- if m .author_name and _is_valid_guid (m .author_name ) and not resolved_author_name :
273- resolved_author_name = m .author_name
273+ message_list = list (messages )
274+ override_user_id = (token_info or {}).get ("user_id" )
275+ if not override_user_id :
276+ override_user_id = provided_user_id if provided_user_id and _is_valid_guid (provided_user_id ) else None
274277
275- if not resolved_user_id and resolved_author_name :
276- resolved_user_id = resolved_author_name
278+ # Leading messages without an identity (e.g. system or generated messages) use the first explicit identity.
279+ inherited_user_id = override_user_id or next (
280+ (uid for uid in map (_get_message_user_id , message_list ) if uid ), None
281+ )
277282
278283 # Fail closed: without a resolvable user identity no policy can be evaluated,
279284 # so the content must not be allowed through unevaluated.
280- if not resolved_user_id or not _is_valid_guid (resolved_user_id ):
285+ if not inherited_user_id or not _is_valid_guid (inherited_user_id ):
281286 raise ValueError (
282287 "No user id provided or inferred for Purview request. Please provide an Entra user id in each "
283288 "message, pass a user id to the processor, or configure the credential to authenticate to an "
284289 "Entra user."
285290 )
286291
287- for m in messages :
292+ for m in message_list :
293+ if not override_user_id :
294+ # Messages without an identity (e.g. assistant or tool messages) are attributed to the
295+ # latest explicitly identified user, without overriding later explicit identities.
296+ inherited_user_id = _get_message_user_id (m ) or inherited_user_id
297+ resolved_user_id = inherited_user_id
298+
288299 message_id = m .message_id or str (uuid .uuid4 ())
289300 correlation_id = (session_id or str (uuid .uuid4 ())) + "@AF"
290301 # This would be c# ticks equivalent and needs to fit inside c# long
@@ -337,13 +348,13 @@ async def _map_messages(
337348 )
338349 req = ProcessContentRequest (
339350 content_to_process = ctp ,
340- user_id = resolved_user_id , # Use the resolved user_id for all messages
351+ user_id = resolved_user_id ,
341352 tenant_id = tenant_id ,
342353 correlation_id = correlation_id ,
343354 process_inline = None , # Will be set based on execution mode
344355 )
345356 results .append (req )
346- return results , resolved_user_id
357+ return results , inherited_user_id
347358
348359 async def _process_with_scopes (self , pc_request : ProcessContentRequest ) -> ProcessContentResponse :
349360 app_location = pc_request .content_to_process .protected_app_metadata .application_location
0 commit comments