|
| 1 | +"""Serialization helpers for converting Mistral API payloads to OTEL GenAI convention formats. |
| 2 | +
|
| 3 | +These are pure functions with no OTEL dependencies — they transform dicts to JSON strings |
| 4 | +matching the GenAI semantic convention schemas for input/output messages and tool definitions. |
| 5 | +
|
| 6 | +Schemas: |
| 7 | +- Input messages: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-input-messages.json |
| 8 | +- Output messages: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-output-messages.json |
| 9 | +- Tool definitions: https://github.com/Cirilla-zmh/semantic-conventions/blob/cc4d07e7e56b80e9aa5904a3d524c134699da37f/docs/gen-ai/gen-ai-tool-definitions.json |
| 10 | +""" |
| 11 | + |
| 12 | +import json |
| 13 | +from typing import Any |
| 14 | + |
| 15 | + |
| 16 | +def _content_to_parts(content) -> list[dict]: |
| 17 | + """Convert Mistral message content to OTEL parts array. |
| 18 | +
|
| 19 | + Mistral content is either a string or an array of content chunks. |
| 20 | + """ |
| 21 | + if content is None: |
| 22 | + return [] |
| 23 | + if isinstance(content, str): |
| 24 | + return [{"type": "text", "content": content}] |
| 25 | + # Content chunks array — map known Mistral types to OTEL part types |
| 26 | + parts = [] |
| 27 | + for chunk in content: |
| 28 | + if isinstance(chunk, str): |
| 29 | + parts.append({"type": "text", "content": chunk}) |
| 30 | + elif isinstance(chunk, dict): |
| 31 | + chunk_type = chunk.get("type", "") |
| 32 | + if chunk_type == "text": |
| 33 | + parts.append({"type": "text", "content": chunk.get("text", "")}) |
| 34 | + elif chunk_type == "thinking": |
| 35 | + thinking = chunk.get("thinking", "") |
| 36 | + if isinstance(thinking, list): |
| 37 | + text_parts = [ |
| 38 | + sub.get("text", "") |
| 39 | + for sub in thinking |
| 40 | + if isinstance(sub, dict) and sub.get("type") == "text" |
| 41 | + ] |
| 42 | + content_str = "\n".join(text_parts) |
| 43 | + else: # Fallback |
| 44 | + content_str = str(thinking) |
| 45 | + parts.append({"type": "reasoning", "content": content_str}) |
| 46 | + elif chunk_type == "image_url": |
| 47 | + url = chunk.get("image_url", {}) |
| 48 | + uri = url.get("url", "") if isinstance(url, dict) else str(url) |
| 49 | + parts.append({"type": "uri", "modality": "image", "uri": uri}) |
| 50 | + else: |
| 51 | + # Catch-all for other content chunk types |
| 52 | + parts.append({"type": chunk_type}) |
| 53 | + return parts |
| 54 | + |
| 55 | + |
| 56 | +def _tool_calls_to_parts(tool_calls: list[dict] | None) -> list[dict]: |
| 57 | + """Convert Mistral tool_calls to OTEL ToolCallRequestPart entries.""" |
| 58 | + if not tool_calls: |
| 59 | + return [] |
| 60 | + parts = [] |
| 61 | + for tc in tool_calls: |
| 62 | + func = tc.get("function", {}) or {} |
| 63 | + part: dict = { |
| 64 | + "type": "tool_call", |
| 65 | + "name": func.get("name", ""), |
| 66 | + } |
| 67 | + if (tc_id := tc.get("id")) is not None: |
| 68 | + part["id"] = tc_id |
| 69 | + if (arguments := func.get("arguments")) is not None: |
| 70 | + part["arguments"] = arguments |
| 71 | + parts.append(part) |
| 72 | + return parts |
| 73 | + |
| 74 | + |
| 75 | +def serialize_input_message(message: dict[str, Any]) -> str: |
| 76 | + """Serialize a single input message per the OTEL GenAI convention. |
| 77 | +
|
| 78 | + Schema: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-input-messages.json |
| 79 | + ChatMessage: {role (required), parts (required), name?} |
| 80 | +
|
| 81 | + Conversation entry objects (e.g. function.result) don't carry a "role" |
| 82 | + field — they are detected via their "type" and mapped to the closest |
| 83 | + OTEL role. |
| 84 | + """ |
| 85 | + entry_type = message.get("type") |
| 86 | + |
| 87 | + # Conversation entry: function.result → OTEL tool role |
| 88 | + if entry_type == "function.result": |
| 89 | + part: dict = {"type": "tool_call_response", "response": message.get("result")} |
| 90 | + if (tool_call_id := message.get("tool_call_id")) is not None: |
| 91 | + part["id"] = tool_call_id |
| 92 | + return json.dumps({"role": "tool", "parts": [part]}) |
| 93 | + |
| 94 | + # TODO: may need to handle other types for conversations (e.g. agent handoff) |
| 95 | + |
| 96 | + role = message.get("role", "unknown") |
| 97 | + parts: list[dict] = [] |
| 98 | + |
| 99 | + if role == "tool": |
| 100 | + # Tool messages are responses to tool calls |
| 101 | + tool_part: dict = { |
| 102 | + "type": "tool_call_response", |
| 103 | + "response": message.get("content"), |
| 104 | + } |
| 105 | + if (tool_call_id := message.get("tool_call_id")) is not None: |
| 106 | + tool_part["id"] = tool_call_id |
| 107 | + parts.append(tool_part) |
| 108 | + else: |
| 109 | + parts.extend(_content_to_parts(message.get("content"))) |
| 110 | + parts.extend(_tool_calls_to_parts(message.get("tool_calls"))) |
| 111 | + |
| 112 | + return json.dumps({"role": role, "parts": parts}) |
| 113 | + |
| 114 | + |
| 115 | +def serialize_output_message(choice: dict[str, Any]) -> str: |
| 116 | + """Serialize a single output choice/message per the OTEL GenAI convention. |
| 117 | +
|
| 118 | + Schema: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-output-messages.json |
| 119 | + OutputMessage: {role (required), parts (required), finish_reason (required), name?} |
| 120 | + """ |
| 121 | + message = choice.get("message", {}) or {} |
| 122 | + parts: list[dict] = [] |
| 123 | + parts.extend(_content_to_parts(message.get("content"))) |
| 124 | + parts.extend(_tool_calls_to_parts(message.get("tool_calls"))) |
| 125 | + |
| 126 | + return json.dumps( |
| 127 | + { |
| 128 | + "role": message.get("role", "assistant"), |
| 129 | + "parts": parts, |
| 130 | + "finish_reason": choice.get("finish_reason", ""), |
| 131 | + } |
| 132 | + ) |
| 133 | + |
| 134 | + |
| 135 | +def serialize_tool_definition(tool: dict[str, Any]) -> str | None: |
| 136 | + """Flatten a Mistral tool definition to the OTEL GenAI convention schema. |
| 137 | +
|
| 138 | + Mistral format: {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}} |
| 139 | + OTEL format: {"type": "function", "name": ..., "description": ..., "parameters": ...} |
| 140 | +
|
| 141 | + Schema, still under review: https://github.com/Cirilla-zmh/semantic-conventions/blob/cc4d07e7e56b80e9aa5904a3d524c134699da37f/docs/gen-ai/gen-ai-tool-definitions.json |
| 142 | + """ |
| 143 | + # Early exit conditions: only functions supported for now, and name is required |
| 144 | + type = tool.get("type", "function") |
| 145 | + func = tool.get("function") |
| 146 | + if not func: |
| 147 | + return None |
| 148 | + name = func.get("name") |
| 149 | + if not name: |
| 150 | + return None |
| 151 | + serialized: dict = {"type": type, "name": name} |
| 152 | + if (description := func.get("description")) is not None: |
| 153 | + serialized["description"] = description |
| 154 | + if (parameters := func.get("parameters")) is not None: |
| 155 | + serialized["parameters"] = parameters |
| 156 | + return json.dumps(serialized) |
0 commit comments