|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +"""Maps Agent Framework span tag messages to A365 versioned message format. |
| 5 | +
|
| 6 | +Agent Framework sets ``gen_ai.input.messages`` / ``gen_ai.output.messages`` as span |
| 7 | +tags containing JSON arrays of ``{role, parts[{type, content}], finish_reason?}``. |
| 8 | +This mapper converts them to :class:`InputMessages` / :class:`OutputMessages`. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import json |
| 14 | +import logging |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +from microsoft_agents_a365.observability.core.message_utils import serialize_messages |
| 18 | +from microsoft_agents_a365.observability.core.models.messages import ( |
| 19 | + BlobPart, |
| 20 | + ChatMessage, |
| 21 | + FilePart, |
| 22 | + GenericPart, |
| 23 | + InputMessages, |
| 24 | + MessagePart, |
| 25 | + MessageRole, |
| 26 | + OutputMessage, |
| 27 | + OutputMessages, |
| 28 | + ReasoningPart, |
| 29 | + TextPart, |
| 30 | + ToolCallRequestPart, |
| 31 | + ToolCallResponsePart, |
| 32 | + UriPart, |
| 33 | +) |
| 34 | + |
| 35 | +logger = logging.getLogger(__name__) |
| 36 | + |
| 37 | +_ROLE_MAP: dict[str, MessageRole] = { |
| 38 | + "system": MessageRole.SYSTEM, |
| 39 | + "user": MessageRole.USER, |
| 40 | + "assistant": MessageRole.ASSISTANT, |
| 41 | + "tool": MessageRole.TOOL, |
| 42 | +} |
| 43 | + |
| 44 | + |
| 45 | +def map_input_messages(messages_json: str) -> str | None: |
| 46 | + """Map a ``gen_ai.input.messages`` tag value to a serialized A365 JSON string. |
| 47 | +
|
| 48 | + Args: |
| 49 | + messages_json: The raw JSON string from the span attribute. |
| 50 | +
|
| 51 | + Returns: |
| 52 | + Serialized :class:`InputMessages` JSON string, or ``None`` if the |
| 53 | + input is empty or cannot be parsed. |
| 54 | + """ |
| 55 | + try: |
| 56 | + raw = json.loads(messages_json) |
| 57 | + except (json.JSONDecodeError, TypeError): |
| 58 | + logger.debug("Failed to parse input messages JSON: %s", messages_json[:200]) |
| 59 | + return None |
| 60 | + |
| 61 | + if not isinstance(raw, list): |
| 62 | + return None |
| 63 | + |
| 64 | + chat_messages: list[ChatMessage] = [] |
| 65 | + for msg in raw: |
| 66 | + if not isinstance(msg, dict): |
| 67 | + continue |
| 68 | + role = _map_role(msg.get("role"), MessageRole.USER) |
| 69 | + parts = _map_parts(msg) |
| 70 | + if parts: |
| 71 | + chat_messages.append(ChatMessage(role=role, parts=parts, name=msg.get("name"))) |
| 72 | + |
| 73 | + if not chat_messages: |
| 74 | + return None |
| 75 | + |
| 76 | + return serialize_messages(InputMessages(messages=chat_messages)) |
| 77 | + |
| 78 | + |
| 79 | +def map_output_messages(messages_json: str) -> str | None: |
| 80 | + """Map a ``gen_ai.output.messages`` tag value to a serialized A365 JSON string. |
| 81 | +
|
| 82 | + Args: |
| 83 | + messages_json: The raw JSON string from the span attribute. |
| 84 | +
|
| 85 | + Returns: |
| 86 | + Serialized :class:`OutputMessages` JSON string, or ``None`` if the |
| 87 | + input is empty or cannot be parsed. |
| 88 | + """ |
| 89 | + try: |
| 90 | + raw = json.loads(messages_json) |
| 91 | + except (json.JSONDecodeError, TypeError): |
| 92 | + logger.debug("Failed to parse output messages JSON: %s", messages_json[:200]) |
| 93 | + return None |
| 94 | + |
| 95 | + if not isinstance(raw, list): |
| 96 | + return None |
| 97 | + |
| 98 | + output_messages: list[OutputMessage] = [] |
| 99 | + for msg in raw: |
| 100 | + if not isinstance(msg, dict): |
| 101 | + continue |
| 102 | + role = _map_role(msg.get("role"), MessageRole.ASSISTANT) |
| 103 | + parts = _map_parts(msg) |
| 104 | + finish_reason = msg.get("finish_reason") |
| 105 | + if parts: |
| 106 | + output_messages.append( |
| 107 | + OutputMessage(role=role, parts=parts, finish_reason=finish_reason) |
| 108 | + ) |
| 109 | + |
| 110 | + if not output_messages: |
| 111 | + return None |
| 112 | + |
| 113 | + return serialize_messages(OutputMessages(messages=output_messages)) |
| 114 | + |
| 115 | + |
| 116 | +# --------------------------------------------------------------------------- |
| 117 | +# Internal helpers |
| 118 | +# --------------------------------------------------------------------------- |
| 119 | + |
| 120 | + |
| 121 | +def _map_role(role: str | None, default: MessageRole) -> MessageRole: |
| 122 | + """Map a raw role string to a :class:`MessageRole` enum.""" |
| 123 | + if not role: |
| 124 | + return default |
| 125 | + return _ROLE_MAP.get(role.lower(), default) |
| 126 | + |
| 127 | + |
| 128 | +def _map_parts(msg: dict[str, Any]) -> list[MessagePart]: |
| 129 | + """Map all parts in a raw message dict.""" |
| 130 | + parts_data = msg.get("parts", []) |
| 131 | + if not isinstance(parts_data, list): |
| 132 | + return [] |
| 133 | + mapped = [_map_single_part(p) for p in parts_data if isinstance(p, dict)] |
| 134 | + return [p for p in mapped if p is not None] |
| 135 | + |
| 136 | + |
| 137 | +def _map_single_part(part: dict[str, Any]) -> MessagePart | None: |
| 138 | + """Map a single raw part dict to the appropriate A365 message part.""" |
| 139 | + part_type = part.get("type", "") |
| 140 | + |
| 141 | + if part_type == "text": |
| 142 | + content = part.get("content", "") |
| 143 | + return TextPart(content=content) if content else None |
| 144 | + |
| 145 | + if part_type == "reasoning": |
| 146 | + content = part.get("content", "") |
| 147 | + return ReasoningPart(content=content) if content else None |
| 148 | + |
| 149 | + if part_type == "tool_call": |
| 150 | + name = part.get("name") |
| 151 | + if not name: |
| 152 | + return None |
| 153 | + return ToolCallRequestPart( |
| 154 | + name=name, |
| 155 | + id=part.get("id"), |
| 156 | + arguments=part.get("arguments"), |
| 157 | + ) |
| 158 | + |
| 159 | + if part_type == "tool_call_response": |
| 160 | + return ToolCallResponsePart( |
| 161 | + id=part.get("id"), |
| 162 | + response=part.get("response"), |
| 163 | + ) |
| 164 | + |
| 165 | + if part_type == "blob": |
| 166 | + modality = part.get("modality", "") |
| 167 | + content = part.get("content", "") |
| 168 | + if not modality or not content: |
| 169 | + return None |
| 170 | + return BlobPart(modality=modality, content=content, mime_type=part.get("mime_type")) |
| 171 | + |
| 172 | + if part_type == "file": |
| 173 | + modality = part.get("modality", "") |
| 174 | + file_id = part.get("file_id", "") |
| 175 | + if not modality or not file_id: |
| 176 | + return None |
| 177 | + return FilePart(modality=modality, file_id=file_id, mime_type=part.get("mime_type")) |
| 178 | + |
| 179 | + if part_type == "uri": |
| 180 | + modality = part.get("modality", "") |
| 181 | + uri = part.get("uri", "") |
| 182 | + if not modality or not uri: |
| 183 | + return None |
| 184 | + return UriPart(modality=modality, uri=uri, mime_type=part.get("mime_type")) |
| 185 | + |
| 186 | + # Fallback: GenericPart for unknown/future part types |
| 187 | + data = {k: v for k, v in part.items() if k != "type"} |
| 188 | + return GenericPart(type=part_type, data=data) if part_type else None |
0 commit comments