|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +"""Maps LangChain messages to A365 versioned message format. |
| 5 | +
|
| 6 | +LangChain provides ``BaseMessage`` objects (``HumanMessage``, ``AIMessage``, |
| 7 | +``SystemMessage``, ``ToolMessage``) in ``run.inputs["messages"]`` and |
| 8 | +``run.outputs["generations"]``. This mapper converts them to the A365 |
| 9 | +versioned format (``InputMessages`` / ``OutputMessages``). |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import logging |
| 15 | +from collections.abc import Iterable, Mapping |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +from langchain_core.messages import BaseMessage |
| 19 | + |
| 20 | +from microsoft_agents_a365.observability.core.message_utils import serialize_messages |
| 21 | +from microsoft_agents_a365.observability.core.models.messages import ( |
| 22 | + ChatMessage, |
| 23 | + InputMessages, |
| 24 | + MessagePart, |
| 25 | + MessageRole, |
| 26 | + OutputMessage, |
| 27 | + OutputMessages, |
| 28 | + TextPart, |
| 29 | + ToolCallRequestPart, |
| 30 | + ToolCallResponsePart, |
| 31 | +) |
| 32 | + |
| 33 | +logger = logging.getLogger(__name__) |
| 34 | + |
| 35 | +_ROLE_MAP: dict[str, MessageRole] = { |
| 36 | + "human": MessageRole.USER, |
| 37 | + "user": MessageRole.USER, |
| 38 | + "ai": MessageRole.ASSISTANT, |
| 39 | + "assistant": MessageRole.ASSISTANT, |
| 40 | + "system": MessageRole.SYSTEM, |
| 41 | + "tool": MessageRole.TOOL, |
| 42 | +} |
| 43 | + |
| 44 | + |
| 45 | +def map_input_messages(inputs: Mapping[str, Any] | None) -> str | None: |
| 46 | + """Map LangChain input messages to a serialized A365 InputMessages JSON string. |
| 47 | +
|
| 48 | + Args: |
| 49 | + inputs: The ``run.inputs`` mapping from a LangChain run. |
| 50 | +
|
| 51 | + Returns: |
| 52 | + Serialized InputMessages JSON string, or None if no messages found. |
| 53 | + """ |
| 54 | + if not inputs or not isinstance(inputs, Mapping): |
| 55 | + return None |
| 56 | + |
| 57 | + multiple_messages = inputs.get("messages") |
| 58 | + if not multiple_messages or not isinstance(multiple_messages, Iterable): |
| 59 | + return None |
| 60 | + |
| 61 | + first_messages = next(iter(multiple_messages), None) |
| 62 | + if not first_messages: |
| 63 | + return None |
| 64 | + |
| 65 | + # Normalize to a list |
| 66 | + if isinstance(first_messages, BaseMessage): |
| 67 | + first_messages = [first_messages] |
| 68 | + elif not isinstance(first_messages, list): |
| 69 | + return None |
| 70 | + |
| 71 | + chat_messages: list[ChatMessage] = [] |
| 72 | + for msg in first_messages: |
| 73 | + mapped = _map_base_message(msg) |
| 74 | + if mapped is not None: |
| 75 | + chat_messages.append(mapped) |
| 76 | + |
| 77 | + if not chat_messages: |
| 78 | + return None |
| 79 | + |
| 80 | + return serialize_messages(InputMessages(messages=chat_messages)) |
| 81 | + |
| 82 | + |
| 83 | +def map_output_messages(outputs: Mapping[str, Any] | None) -> str | None: |
| 84 | + """Map LangChain output messages to a serialized A365 OutputMessages JSON string. |
| 85 | +
|
| 86 | + Args: |
| 87 | + outputs: The ``run.outputs`` mapping from a LangChain run. |
| 88 | +
|
| 89 | + Returns: |
| 90 | + Serialized OutputMessages JSON string, or None if no messages found. |
| 91 | + """ |
| 92 | + if not outputs or not isinstance(outputs, Mapping): |
| 93 | + return None |
| 94 | + |
| 95 | + multiple_generations = outputs.get("generations") |
| 96 | + if not multiple_generations or not isinstance(multiple_generations, Iterable): |
| 97 | + return None |
| 98 | + |
| 99 | + first_generations = next(iter(multiple_generations), None) |
| 100 | + if not first_generations or not isinstance(first_generations, Iterable): |
| 101 | + return None |
| 102 | + |
| 103 | + output_messages: list[OutputMessage] = [] |
| 104 | + for generation in first_generations: |
| 105 | + if not isinstance(generation, Mapping): |
| 106 | + continue |
| 107 | + message_data = generation.get("message") |
| 108 | + if message_data is None: |
| 109 | + continue |
| 110 | + |
| 111 | + mapped = _map_to_output_message(message_data, generation) |
| 112 | + if mapped is not None: |
| 113 | + output_messages.append(mapped) |
| 114 | + |
| 115 | + if not output_messages: |
| 116 | + return None |
| 117 | + |
| 118 | + return serialize_messages(OutputMessages(messages=output_messages)) |
| 119 | + |
| 120 | + |
| 121 | +# --------------------------------------------------------------------------- |
| 122 | +# Internal helpers |
| 123 | +# --------------------------------------------------------------------------- |
| 124 | + |
| 125 | + |
| 126 | +def _map_role( |
| 127 | + msg: BaseMessage | Mapping[str, Any], default: MessageRole = MessageRole.USER |
| 128 | +) -> MessageRole: |
| 129 | + """Extract the role from a LangChain message.""" |
| 130 | + if isinstance(msg, BaseMessage): |
| 131 | + role_str = msg.type |
| 132 | + elif isinstance(msg, Mapping): |
| 133 | + # Direct type field (e.g. "human", "ai", "system", "tool") |
| 134 | + role_str = msg.get("type", "") |
| 135 | + # LC serialization uses "constructor" as type with role in kwargs |
| 136 | + if role_str == "constructor": |
| 137 | + kwargs = msg.get("kwargs", {}) |
| 138 | + role_str = kwargs.get("type", "") if isinstance(kwargs, Mapping) else "" |
| 139 | + # Also check "role" field |
| 140 | + if not role_str or role_str not in _ROLE_MAP: |
| 141 | + role_str = msg.get("role", role_str) |
| 142 | + else: |
| 143 | + role_str = "" |
| 144 | + return _ROLE_MAP.get(role_str.lower(), default) |
| 145 | + |
| 146 | + |
| 147 | +def _extract_parts(msg: BaseMessage | Mapping[str, Any]) -> list[MessagePart]: |
| 148 | + """Extract message parts from a LangChain message.""" |
| 149 | + parts: list[MessagePart] = [] |
| 150 | + |
| 151 | + # Extract content and tool_calls |
| 152 | + if isinstance(msg, BaseMessage): |
| 153 | + content = msg.content |
| 154 | + tool_calls = getattr(msg, "tool_calls", None) |
| 155 | + msg_type = msg.type |
| 156 | + tool_call_id = getattr(msg, "tool_call_id", None) |
| 157 | + elif isinstance(msg, Mapping): |
| 158 | + # Handle LC serialization: {"type": "constructor", "kwargs": {content, type, ...}} |
| 159 | + kwargs = msg.get("kwargs", {}) if msg.get("type") == "constructor" else msg |
| 160 | + if not isinstance(kwargs, Mapping): |
| 161 | + kwargs = msg |
| 162 | + content = kwargs.get("content", "") or msg.get("content", "") |
| 163 | + tool_calls = kwargs.get("tool_calls") or msg.get("tool_calls") |
| 164 | + msg_type = kwargs.get("type", "") or msg.get("type", "") |
| 165 | + tool_call_id = kwargs.get("tool_call_id") or msg.get("tool_call_id") |
| 166 | + else: |
| 167 | + return parts |
| 168 | + |
| 169 | + # Tool response (from ToolMessage) — handle before text to avoid double-counting |
| 170 | + if msg_type == "tool": |
| 171 | + response = content if isinstance(content, str) else str(content) if content else "" |
| 172 | + if response or tool_call_id: |
| 173 | + parts.append(ToolCallResponsePart(id=tool_call_id, response=response)) |
| 174 | + return parts |
| 175 | + |
| 176 | + # Text content |
| 177 | + if content and isinstance(content, str) and content.strip(): |
| 178 | + parts.append(TextPart(content=content)) |
| 179 | + |
| 180 | + # Tool calls (from AIMessage.tool_calls) |
| 181 | + if tool_calls and isinstance(tool_calls, list): |
| 182 | + for tc in tool_calls: |
| 183 | + if not isinstance(tc, Mapping): |
| 184 | + continue |
| 185 | + name = tc.get("name") |
| 186 | + if not name: |
| 187 | + continue |
| 188 | + args = tc.get("args") |
| 189 | + args_str = None |
| 190 | + if args is not None: |
| 191 | + import json |
| 192 | + |
| 193 | + try: |
| 194 | + args_str = json.dumps(args) if not isinstance(args, str) else args |
| 195 | + except (TypeError, ValueError): |
| 196 | + args_str = str(args) |
| 197 | + |
| 198 | + parts.append( |
| 199 | + ToolCallRequestPart( |
| 200 | + name=name, |
| 201 | + id=tc.get("id"), |
| 202 | + arguments=args_str, |
| 203 | + ) |
| 204 | + ) |
| 205 | + |
| 206 | + return parts |
| 207 | + |
| 208 | + |
| 209 | +def _map_base_message(msg: BaseMessage | Mapping[str, Any]) -> ChatMessage | None: |
| 210 | + """Map a single LangChain message to an A365 ChatMessage.""" |
| 211 | + role = _map_role(msg) |
| 212 | + parts = _extract_parts(msg) |
| 213 | + if not parts: |
| 214 | + return None |
| 215 | + |
| 216 | + name = None |
| 217 | + if isinstance(msg, BaseMessage): |
| 218 | + name = getattr(msg, "name", None) |
| 219 | + |
| 220 | + return ChatMessage(role=role, parts=parts, name=name) |
| 221 | + |
| 222 | + |
| 223 | +def _map_to_output_message( |
| 224 | + message_data: BaseMessage | Mapping[str, Any], |
| 225 | + generation: Mapping[str, Any], |
| 226 | +) -> OutputMessage | None: |
| 227 | + """Map a LangChain generation to an A365 OutputMessage.""" |
| 228 | + role = _map_role(message_data, default=MessageRole.ASSISTANT) |
| 229 | + parts = _extract_parts(message_data) |
| 230 | + if not parts: |
| 231 | + return None |
| 232 | + |
| 233 | + # Extract finish_reason from generation metadata |
| 234 | + finish_reason = None |
| 235 | + gen_info = generation.get("generation_info") |
| 236 | + if isinstance(gen_info, Mapping): |
| 237 | + finish_reason = gen_info.get("finish_reason") |
| 238 | + |
| 239 | + return OutputMessage(role=role, parts=parts, finish_reason=finish_reason) |
0 commit comments