"""Strict portable-content/function-tool conversion between LLM wire formats.
This module deliberately rejects fields whose semantics cannot be preserved.
It does not fabricate reasoning state, token counts, or server-side history.
"""
from __future__ import annotations
import json
import re
import secrets
import time
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass, field
from enum import StrEnum
from types import MappingProxyType
from typing import Any, TypedDict
from .custom_tools import custom_definition, encode_custom
from .documents import PDF, decode_pdf
from .errors import ConversionError, UnsupportedFeatureError
from .formats import (
OutputFormat,
decode_output_format,
encode_output_format,
validate_strict_tool_schema,
)
from .images import Image, decode_image
from .json_wire import decode_json, encode_json
from .reasoning import reasoning_item, response_reasoning
from .response_context import generated_response_metadata
[docs]
class Protocol(StrEnum):
"""Wire protocol of a request or response: ``chat`` (Chat Completions), ``messages`` (Anthropic Messages) or ``responses`` (OpenAI Responses)."""
CHAT = "chat"
MESSAGES = "messages"
RESPONSES = "responses"
@dataclass(slots=True)
class Part:
"""One portable content item of a turn: text, an image, a document, a tool call or a tool result."""
kind: str
text: str = ""
call_id: str = ""
name: str = ""
arguments: str = ""
image: Image | None = None
result_parts: list[Part] | None = None
tool_type: str = "function"
document: PDF | None = None
logprobs: list[dict[str, Any]] | None = None
@property
def image_value(self) -> Image:
"""``image``, which image parts always carry."""
if self.image is None:
raise ConversionError(f"{self.kind} part without an image")
return self.image
@property
def document_value(self) -> PDF:
"""``document``, which document parts always carry."""
if self.document is None:
raise ConversionError(f"{self.kind} part without a document")
return self.document
@dataclass(slots=True)
class Turn:
"""One conversation turn: a role (``system``, ``developer``, ``user``, ``assistant``, ``tool``) and its parts."""
role: str
parts: list[Part] = field(default_factory=list)
@dataclass(slots=True)
class Request:
"""A request decoded into the portable model shared by every protocol.
Only fields whose meaning survives every supported protocol are represented;
everything else is rejected by the decoders.
"""
model: str
turns: list[Turn]
tools: list[dict[str, Any]] = field(default_factory=list)
max_tokens: int | None = None
temperature: float | None = None
stream: bool = False
tool_choice: Any = None
parallel_tool_calls: bool | None = None
reasoning_effort: str | None = None
output_format: OutputFormat | None = None
top_p: float | None = None
stop_sequences: list[str] | None = None
frequency_penalty: float | None = None
presence_penalty: float | None = None
top_logprobs: int | None = None
logprobs: bool = False
@dataclass(slots=True)
class Result:
"""A completed response decoded into the portable model: output parts, finish reason and real token usage."""
model: str
parts: list[Part]
finish_reason: str
input_tokens: int | None = None
output_tokens: int | None = None
cached_input_tokens: int | None = None
cache_creation_input_tokens: int | None = None
reasoning_output_tokens: int | None = None
service_tier: str | None = None
def _reported_service_tier(value: Any) -> str | None:
"""Bounded common Chat/Responses observation, never a request default."""
if value is None:
return None
if not isinstance(value, str) or value not in {"auto", "default", "flex", "scale", "priority", "fast"}:
raise ConversionError("upstream service_tier is not supported by the portable contract")
return value
class Usage(TypedDict):
"""Token counts exactly as the provider reported them (``None`` when absent)."""
input_tokens: int | None
output_tokens: int | None
cached_input_tokens: int | None
cache_creation_input_tokens: int | None
reasoning_output_tokens: int | None
def _decode_usage(usage: dict[str, Any], source: Protocol) -> Usage:
"""Normalize total input tokens, not only Anthropic's uncached input."""
if source == Protocol.CHAT:
input_key, output_key = "prompt_tokens", "completion_tokens"
input_details = _object(usage.get("prompt_tokens_details") or {}, "prompt_tokens_details")
output_details = _object(usage.get("completion_tokens_details") or {}, "completion_tokens_details")
else:
input_key, output_key = "input_tokens", "output_tokens"
input_details = _object(usage.get("input_tokens_details") or {}, "input_tokens_details")
output_details = _object(usage.get("output_tokens_details") or {}, "output_tokens_details")
read = _optional_nonnegative_int(
usage.get("cache_read_input_tokens") if source == Protocol.MESSAGES else input_details.get("cached_tokens"),
"cached input tokens",
)
creation = _optional_nonnegative_int(
usage.get("cache_creation_input_tokens")
if source == Protocol.MESSAGES
else input_details.get("cache_write_tokens"),
"cache creation tokens",
)
inputs = _optional_nonnegative_int(usage.get(input_key), input_key)
outputs = _optional_nonnegative_int(usage.get(output_key), output_key)
reasoning = _optional_nonnegative_int(output_details.get("reasoning_tokens"), "reasoning tokens")
if source == Protocol.MESSAGES and inputs is not None:
inputs += (read or 0) + (creation or 0)
if inputs is not None and (read or 0) + (creation or 0) > inputs:
raise ConversionError("cached input tokens exceed total input tokens")
if outputs is not None and (reasoning or 0) > outputs:
raise ConversionError("reasoning tokens exceed total output tokens")
return {
"input_tokens": inputs,
"output_tokens": outputs,
"cached_input_tokens": read,
"cache_creation_input_tokens": creation,
"reasoning_output_tokens": reasoning,
}
def _encode_usage(value: Any, target: Protocol) -> dict[str, Any]:
inputs, outputs = value.input_tokens, value.output_tokens
cached, creation, reasoning = (
value.cached_input_tokens,
value.cache_creation_input_tokens,
value.reasoning_output_tokens,
)
if target == Protocol.MESSAGES:
usage = {
"input_tokens": inputs - (cached or 0) - (creation or 0) if inputs is not None else None,
"output_tokens": outputs,
}
if cached is not None:
usage["cache_read_input_tokens"] = cached
if creation is not None:
usage["cache_creation_input_tokens"] = creation
return usage
if target == Protocol.CHAT:
usage = {"prompt_tokens": inputs, "completion_tokens": outputs, "total_tokens": inputs + outputs}
if cached is not None:
usage["prompt_tokens_details"] = {"cached_tokens": cached}
if creation is not None:
usage.setdefault("prompt_tokens_details", {})["cache_write_tokens"] = creation
if reasoning is not None:
usage["completion_tokens_details"] = {"reasoning_tokens": reasoning}
return usage
input_details = {}
if cached is not None:
input_details["cached_tokens"] = cached
if creation is not None:
input_details["cache_write_tokens"] = creation
usage = {"input_tokens": inputs, "output_tokens": outputs, "total_tokens": inputs + outputs}
if input_details:
usage["input_tokens_details"] = input_details
if reasoning is not None:
usage["output_tokens_details"] = {"reasoning_tokens": reasoning}
return usage
def _object(value: Any, label: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise ConversionError(f"{label} must be an object")
return value
def _string(value: Any, label: str) -> str:
if not isinstance(value, str):
raise ConversionError(f"{label} must be a string")
return value
def _list(value: Any, label: str) -> list[Any]:
if not isinstance(value, list):
raise ConversionError(f"{label} must be an array")
return value
def _optional_list(value: Any, label: str) -> list[Any]:
return [] if value is None else _list(value, label)
def _optional_positive_int(value: Any, label: str) -> int | None:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
raise ConversionError(f"{label} must be a positive integer")
return value
def _optional_nonnegative_int(value: Any, label: str) -> int | None:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ConversionError(f"{label} must be a non-negative integer")
return value
def _optional_temperature(value: Any) -> float | None:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int | float) or not 0 <= value <= 2:
raise ConversionError("temperature must be a number between 0 and 2")
return float(value)
def _optional_penalty(value: Any, label: str) -> float | None:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int | float) or not -2 <= value <= 2:
raise ConversionError(f"{label} must be a number between -2 and 2")
return float(value)
def _disabled_logprobs(body: dict[str, Any], source: Protocol, *, allow_enabled: bool = False) -> int | None:
enabled = body.get("logprobs") if source == Protocol.CHAT else None
if enabled is not None and type(enabled) is not bool:
raise ConversionError("logprobs must be a boolean or null")
top = _optional_nonnegative_int(body.get("top_logprobs"), "top_logprobs")
if top is not None and top > 20:
raise ConversionError("top_logprobs must be between 0 and 20")
if (enabled is True or top not in (None, 0)) and not allow_enabled:
raise ConversionError("enabled logprobs cannot be preserved on translated routes")
if source == Protocol.CHAT and top not in (None, 0) and enabled is not True:
raise ConversionError("positive Chat top_logprobs requires logprobs=true")
return top if top is not None else 0 if enabled is False else None
def _stream_flag(value: Any) -> bool:
if not isinstance(value, bool):
raise ConversionError("stream must be a boolean")
return value
def _optional_top_p(value: Any) -> float | None:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int | float) or not 0 <= value <= 1:
raise ConversionError("top_p must be a number between 0 and 1")
return float(value)
def _stops(value: Any) -> list[str] | None:
if value is None:
return None
values = [value] if isinstance(value, str) else value
if (
not isinstance(values, list)
or not 1 <= len(values) <= 4
or any(not isinstance(item, str) or not item for item in values)
):
raise ConversionError("portable stop sequences require 1-4 nonempty strings")
return list(values)
def _strict_tool(tool: dict[str, Any]) -> dict[str, Any]:
if "strict" in tool and tool["strict"] is not None and not isinstance(tool["strict"], bool):
raise ConversionError("tool strict must be a boolean")
return {"strict": tool["strict"]} if tool.get("strict") is not None else {}
def _parallel_flag(value: Any) -> bool | None:
if value is not None and not isinstance(value, bool):
raise ConversionError("parallel_tool_calls must be a boolean")
return value
def _effort(value: Any) -> str | None:
if value is not None and value not in ("low", "medium", "high"):
raise ConversionError("only low, medium, and high effort are portable")
effort: str | None = value
return effort
def _only(obj: dict[str, Any], allowed: set[str], label: str) -> None:
extras = set(obj) - allowed
if extras:
raise ConversionError(f"{label}: unsupported fields: {', '.join(sorted(extras))}")
# Legacy/optional Chat output fields some OpenAI-compatible servers always
# emit. An explicit null carries no data, so it is equivalent to omission;
# any non-null value is still rejected by the strict field checks.
CHAT_NULLABLE_OUTPUT_FIELDS = frozenset({"function_call", "audio"})
def _drop_null_legacy(message: dict[str, Any]) -> dict[str, Any]:
return {key: value for key, value in message.items() if not (key in CHAT_NULLABLE_OUTPUT_FIELDS and value is None)}
def _arguments(value: Any, label: str) -> str:
raw = _string(value, label)
try:
parsed = decode_json(raw)
except ConversionError as exc:
raise ConversionError(f"{label} is not valid JSON") from exc
if not isinstance(parsed, dict):
raise ConversionError(f"{label} must contain a JSON object")
return raw
def _chat_content(value: Any, label: str) -> list[Part]:
if value is None:
return []
if isinstance(value, str):
return [Part("text", text=value)]
result: list[Part] = []
for block in _list(value, label):
block = _object(block, label)
if block.get("type") == "image_url":
result.append(Part("image", image=decode_image(block, "chat")))
continue
if block.get("type") == "file":
result.append(Part("document", document=decode_pdf(block, "chat")))
continue
if block.get("type") != "text":
raise ConversionError(f"{label}: only text content is supported")
_only(block, {"type", "text"}, label)
result.append(Part("text", text=_string(block.get("text"), label)))
return result
def _tool_choice(value: Any, source: Protocol) -> str | dict[str, Any] | None:
"""Normalize forced function selection without accepting hosted tools."""
if value is None:
return None
if source != Protocol.MESSAGES and isinstance(value, str) and value in {"auto", "none", "required"}:
return value
value = _object(value, "tool_choice")
if source == Protocol.MESSAGES:
_only(value, {"type", "name", "disable_parallel_tool_use"}, "tool_choice")
kind = value.get("type")
if isinstance(kind, str) and kind in {"auto", "any", "none"} and "name" not in value:
return {"auto": "auto", "any": "required", "none": "none"}[kind]
if kind == "tool":
return {"type": "function", "name": _string(value.get("name"), "tool_choice.name")}
elif value.get("type") in ("function", "custom"):
kind = value["type"]
if source == Protocol.CHAT:
_only(value, {"type", kind}, "tool_choice")
function = _object(value.get(kind), "tool_choice.tool")
_only(function, {"name"}, "tool_choice.function")
name = function.get("name")
else:
_only(value, {"type", "name"}, "tool_choice")
name = value.get("name")
return {"type": kind, "name": _string(name, "tool_choice.name")}
raise ConversionError("tool_choice is not portable")
def _validate_chat_call(call: dict[str, Any], index: int) -> None:
kind = call.get("type")
if kind not in ("function", "custom"):
raise ConversionError("only client-side function/custom calls are supported")
_only(call, {"id", "type", kind, "index"}, "tool_call")
# Some compatible providers include the streaming-style position in a
# completed JSON call. Accept it only when it agrees with array ordering.
if "index" in call and (type(call["index"]) is not int or call["index"] != index):
raise ConversionError("Chat tool_call index must match its array position")
def _chat_call(call: dict[str, Any], index: int) -> Part:
_validate_chat_call(call, index)
kind = call["type"]
fn = _object(call.get(kind), "tool_call body")
arg = "input" if kind == "custom" else "arguments"
_only(fn, {"name", arg}, "tool_call body")
raw = _string(fn.get(arg), arg) if kind == "custom" else _arguments(fn.get(arg), arg)
return Part(
"tool_call",
call_id=_string(call.get("id"), "call.id"),
name=_string(fn.get("name"), "call.name"),
arguments=raw,
tool_type=kind,
)
def _encode_chat_call(part: Part) -> dict[str, Any]:
return {
"id": part.call_id,
"type": part.tool_type,
part.tool_type: {"name": part.name, "input" if part.tool_type == "custom" else "arguments": part.arguments},
}
def _encode_response_call(part: Part) -> dict[str, Any]:
return {
"type": "custom_tool_call" if part.tool_type == "custom" else "function_call",
"call_id": part.call_id,
"name": part.name,
"input" if part.tool_type == "custom" else "arguments": part.arguments,
}
def _decode_chat(body: dict[str, Any], *, public_reasoning: bool = False) -> Request:
_only(
body,
{
"model",
"messages",
"tools",
"tool_choice",
"max_completion_tokens",
"max_tokens",
"temperature",
"top_p",
"stream",
"stream_options",
"parallel_tool_calls",
"reasoning_effort",
"response_format",
"stop",
"frequency_penalty",
"presence_penalty",
"logprobs",
"top_logprobs",
},
"Chat request",
)
if body.get("stream_options") is not None:
options = _object(body["stream_options"], "stream_options")
_only(options, {"include_usage"}, "stream_options")
if "include_usage" in options and not isinstance(options["include_usage"], bool):
raise ConversionError("stream_options.include_usage must be a boolean")
if body.get("stream") is not True or ("include_usage" in options and options["include_usage"] is not True):
raise UnsupportedFeatureError("stream_usage_policy")
if "max_completion_tokens" in body and "max_tokens" in body:
raise ConversionError("choose one Chat token limit field")
turns: list[Turn] = []
for item in _list(body.get("messages"), "messages"):
item = _object(item, "message")
role = _string(item.get("role"), "message.role")
if role in {"system", "developer", "user", "assistant"}:
if role != "assistant" and "tool_calls" in item:
raise ConversionError("Chat tool_calls require the assistant role")
_only(
item,
{"role", "content", "tool_calls"} | ({"reasoning_content"} if public_reasoning else set()),
"message",
)
parts = _chat_content(item.get("content"), "message.content")
if "reasoning_content" in item:
parts.insert(0, Part("reasoning_text", text=_string(item["reasoning_content"], "reasoning_content")))
if role == "assistant":
for index, call in enumerate(_optional_list(item.get("tool_calls"), "tool_calls")):
call = _object(call, "tool_call")
parts.append(_chat_call(call, index))
turns.append(Turn(role, parts))
elif role == "tool":
_only(item, {"role", "tool_call_id", "content"}, "tool message")
tool_content = item.get("content")
tool_rich = None
if isinstance(tool_content, list):
tool_parts = _chat_content(tool_content, "tool content")
if any(part.kind != "text" for part in tool_parts):
raise ConversionError("Chat tool results support text content only")
tool_text = "".join(part.text for part in tool_parts)
if tool_parts:
tool_rich = tool_parts
else:
tool_text = _string(tool_content, "tool content")
turns.append(
Turn(
"user",
[
Part(
"tool_result",
call_id=_string(item.get("tool_call_id"), "tool_call_id"),
text=tool_text,
result_parts=tool_rich,
)
],
)
)
else:
raise ConversionError(f"unsupported Chat role: {role}")
tools: list[dict[str, Any]] = []
for item in _optional_list(body.get("tools"), "tools"):
item = _object(item, "tool")
if item.get("type") == "custom":
_only(item, {"type", "custom"}, "tool")
tools.append(custom_definition(_object(item.get("custom"), "tool.custom"), "chat"))
continue
_only(item, {"type", "function"}, "tool")
if item.get("type") != "function":
raise ConversionError("only function tools are supported")
fn = _object(item.get("function"), "tool.function")
_only(fn, {"name", "description", "parameters", "strict"}, "tool.function")
tools.append(
{
"name": _string(fn.get("name"), "tool name"),
"description": fn.get("description", ""),
"parameters": fn.get("parameters", {"type": "object", "properties": {}}),
**_strict_tool(fn),
}
)
return Request(
_string(body.get("model"), "model"),
turns,
tools,
_optional_positive_int(body.get("max_completion_tokens", body.get("max_tokens")), "max_completion_tokens"),
_optional_temperature(body.get("temperature")),
_stream_flag(body.get("stream", False)),
_tool_choice(body.get("tool_choice"), Protocol.CHAT),
_parallel_flag(body.get("parallel_tool_calls")),
_effort(body.get("reasoning_effort")),
top_p=_optional_top_p(body.get("top_p")),
)
def _message_parts(content: Any, label: str) -> list[Part]:
if isinstance(content, str):
return [Part("text", text=content)]
parts: list[Part] = []
for block in _list(content, label):
block = _object(block, label)
kind = block.get("type")
if kind == "text":
_only(block, {"type", "text", "citations"}, label)
if block.get("citations") not in (None, []):
raise ConversionError("Messages citations cannot be preserved across protocols")
parts.append(Part("text", text=_string(block.get("text"), "text")))
elif kind == "image":
parts.append(Part("image", image=decode_image(block, "messages")))
elif kind == "document":
parts.append(Part("document", document=decode_pdf(block, "messages")))
elif kind == "tool_use":
_only(block, {"type", "id", "name", "input", "caller"}, label)
if "caller" in block and block["caller"] != {"type": "direct"}:
raise ConversionError("non-direct Messages tool callers cannot be preserved across protocols")
inputs = _object(block.get("input"), "tool_use.input")
arguments = _arguments(json.dumps(inputs, ensure_ascii=False), "tool_use.input")
parts.append(
Part(
"tool_call",
call_id=_string(block.get("id"), "tool_use.id"),
name=_string(block.get("name"), "tool_use.name"),
arguments=arguments,
)
)
elif kind == "tool_result":
_only(block, {"type", "tool_use_id", "content", "is_error"}, label)
if block.get("is_error") not in (None, False):
if not isinstance(block.get("is_error"), bool):
raise ConversionError("tool_result.is_error must be a boolean")
raise ConversionError("tool_result.is_error cannot be preserved in other protocols")
result = block.get("content", "")
rich = None
if not isinstance(result, str):
text_blocks = _message_parts(result, "tool_result.content")
if any(part.kind == "document" for part in text_blocks):
raise ConversionError("PDF tool results have no portable equivalent")
if any(part.kind not in {"text", "image"} for part in text_blocks):
raise ConversionError("tool results support text/image content only")
if any(part.kind in {"text", "image"} for part in text_blocks):
rich = text_blocks
result = "".join(part.text for part in text_blocks)
parts.append(
Part(
"tool_result",
call_id=_string(block.get("tool_use_id"), "tool_use_id"),
text=result,
result_parts=rich,
)
)
elif kind == "compaction":
raise UnsupportedFeatureError("compaction")
else:
raise ConversionError(f"unsupported Messages block: {kind}")
return parts
def _decode_messages(body: dict[str, Any]) -> Request:
if "context_management" in body:
raise UnsupportedFeatureError("compaction")
_only(
body,
{
"model",
"system",
"messages",
"tools",
"tool_choice",
"max_tokens",
"temperature",
"top_p",
"stream",
"output_config",
"stop_sequences",
},
"Messages request",
)
output_config = _object(body.get("output_config", {}), "output_config")
_only(output_config, {"effort", "format"}, "output_config")
turns: list[Turn] = []
if "system" in body:
system = body["system"]
parts = _message_parts(system, "system")
if any(part.kind != "text" for part in parts):
raise ConversionError("system must contain text only")
turns.append(Turn("system", parts))
for item in _list(body.get("messages"), "messages"):
item = _object(item, "message")
_only(item, {"role", "content"}, "message")
role = item.get("role")
if not isinstance(role, str) or role not in {"user", "assistant", "system"}:
raise ConversionError("Messages role must be user, assistant or system")
turns.append(Turn(role, _message_parts(item.get("content"), "message.content")))
tools: list[dict[str, Any]] = []
for item in _optional_list(body.get("tools"), "tools"):
item = _object(item, "tool")
_only(item, {"name", "description", "input_schema", "strict"}, "tool")
tools.append(
{
"name": _string(item.get("name"), "tool name"),
"description": item.get("description", ""),
"parameters": _object(item.get("input_schema"), "input_schema"),
**_strict_tool(item),
}
)
choice = body.get("tool_choice")
parallel = None
if choice is not None:
choice = _object(choice, "tool_choice")
if "disable_parallel_tool_use" in choice:
flag = choice["disable_parallel_tool_use"]
if not isinstance(flag, bool):
raise ConversionError("disable_parallel_tool_use must be a boolean")
parallel = not flag
choice = _tool_choice(choice, Protocol.MESSAGES)
return Request(
_string(body.get("model"), "model"),
turns,
tools,
_optional_positive_int(body.get("max_tokens"), "max_tokens"),
_optional_temperature(body.get("temperature")),
_stream_flag(body.get("stream", False)),
choice,
parallel,
_effort(output_config.get("effort")),
top_p=_optional_top_p(body.get("top_p")),
)
def _response_content(content: Any, label: str, *, text_logprobs: bool = False) -> list[Part]:
if isinstance(content, str):
return [Part("text", text=content)]
parts: list[Part] = []
for block in _list(content, label):
block = _object(block, label)
if block.get("type") == "refusal":
_only(block, {"type", "refusal"}, label)
_string(block.get("refusal"), "refusal")
raise UnsupportedFeatureError("refusal")
if block.get("type") == "input_image":
parts.append(Part("image", image=decode_image(block, "responses")))
continue
if block.get("type") == "input_file":
parts.append(Part("document", document=decode_pdf(block, "responses")))
continue
if block.get("type") not in ("input_text", "output_text"):
raise ConversionError(f"unsupported Responses content type: {block.get('type')}")
_only(block, {"type", "text", "annotations", "logprobs"}, label)
if block.get("annotations") or block.get("logprobs") and not text_logprobs:
raise ConversionError("Responses annotations and logprobs cannot be preserved")
text = _string(block.get("text"), "text")
probabilities = None
if text_logprobs and block.get("logprobs") is not None:
from .logprobs import align, records
probabilities = records(block["logprobs"])
align(probabilities, text, required=True)
elif text_logprobs and text:
raise ConversionError("upstream omitted requested text logprobs")
parts.append(Part("text", text=text, logprobs=probabilities))
return parts
def _decode_responses(body: dict[str, Any], *, public_reasoning: bool = False) -> Request:
if "context_management" in body:
raise UnsupportedFeatureError("compaction")
_only(
body,
{
"model",
"input",
"instructions",
"tools",
"tool_choice",
"max_output_tokens",
"temperature",
"top_p",
"stream",
"store",
"parallel_tool_calls",
"reasoning",
"text",
"frequency_penalty",
"presence_penalty",
"top_logprobs",
"include",
},
"Responses request",
)
include = body.get("include", [])
if not isinstance(include, list) or any(value != "message.output_text.logprobs" for value in include):
raise ConversionError("unsupported Responses include option")
reasoning = _object(body.get("reasoning", {}), "reasoning")
_only(reasoning, {"effort"}, "reasoning")
if body.get("store") is True:
raise ConversionError("store=true requires a stateful gateway")
turns: list[Turn] = []
if "instructions" in body:
turns.append(Turn("developer", [Part("text", text=_string(body["instructions"], "instructions"))]))
inputs = body.get("input")
if isinstance(inputs, str):
turns.append(Turn("user", [Part("text", text=inputs)]))
else:
for item in _list(inputs, "input"):
item = _object(item, "input item")
kind = item.get("type", "message")
if kind == "message":
_only(item, {"type", "id", "status", "role", "content"}, "input message")
role = _string(item.get("role"), "input.role")
if not isinstance(role, str) or role not in {"system", "developer", "user", "assistant"}:
raise ConversionError(f"unsupported Responses role: {role}")
if item.get("status") not in (None, "completed"):
raise ConversionError("incomplete Responses history message")
turns.append(Turn(role, _response_content(item.get("content"), "input.content")))
elif kind == "reasoning" and public_reasoning:
if item.get("status") == "incomplete":
raise ConversionError("incomplete public reasoning history cannot be replayed")
turns.append(Turn("assistant", [Part("reasoning_text", text=response_reasoning(item))]))
elif kind in ("function_call", "custom_tool_call"):
custom = kind == "custom_tool_call"
arg = "input" if custom else "arguments"
_only(item, {"type", "id", "status", "call_id", "name", arg}, kind)
if item.get("status") not in (None, "completed"):
raise ConversionError("incomplete Responses history call")
raw = _string(item.get(arg), arg) if custom else _arguments(item.get(arg), arg)
turns.append(
Turn(
"assistant",
[
Part(
"tool_call",
call_id=_string(item.get("call_id"), "call_id"),
name=_string(item.get("name"), "tool name"),
arguments=raw,
tool_type="custom" if custom else "function",
)
],
)
)
elif kind in ("function_call_output", "custom_tool_call_output"):
_only(item, {"type", "id", "call_id", "output"}, kind)
tool_type = "custom" if kind == "custom_tool_call_output" else "function"
output = item.get("output")
if isinstance(output, list):
output_parts = _response_content(output, "function_call_output.output")
if any(part.kind == "document" for part in output_parts):
raise ConversionError("PDF tool results have no portable equivalent")
if any(part.kind not in {"text", "image"} for part in output_parts):
raise ConversionError("tool results support text/image content only")
joined = "".join(part.text for part in output_parts)
turns.append(
Turn(
"user",
[
Part(
"tool_result",
call_id=_string(item.get("call_id"), "call_id"),
text=joined,
result_parts=output_parts,
tool_type=tool_type,
)
],
)
)
continue
turns.append(
Turn(
"user",
[
Part(
"tool_result",
call_id=_string(item.get("call_id"), "call_id"),
text=_string(output, "output"),
tool_type=tool_type,
)
],
)
)
elif kind == "compaction":
raise UnsupportedFeatureError("compaction")
else:
raise ConversionError(f"unsupported Responses item: {kind}")
grouped_turns: list[Turn] = []
for turn in turns:
if turn.role == "assistant" and grouped_turns and grouped_turns[-1].role == "assistant":
grouped_turns[-1].parts.extend(turn.parts)
else:
grouped_turns.append(turn)
turns = grouped_turns
tools: list[dict[str, Any]] = []
for item in _optional_list(body.get("tools"), "tools"):
item = _object(item, "tool")
if item.get("type") == "custom":
tools.append(custom_definition(item, "responses"))
continue
_only(item, {"type", "name", "description", "parameters", "strict"}, "tool")
if item.get("type") != "function":
raise ConversionError("only function tools are supported")
tools.append(
{
"name": _string(item.get("name"), "tool name"),
"description": item.get("description", ""),
"parameters": item.get("parameters", {"type": "object", "properties": {}}),
**_strict_tool(item),
}
)
return Request(
_string(body.get("model"), "model"),
turns,
tools,
_optional_positive_int(body.get("max_output_tokens"), "max_output_tokens"),
_optional_temperature(body.get("temperature")),
_stream_flag(body.get("stream", False)),
_tool_choice(body.get("tool_choice"), Protocol.RESPONSES),
_parallel_flag(body.get("parallel_tool_calls")),
_effort(reasoning.get("effort")),
top_p=_optional_top_p(body.get("top_p")),
)
def _check_function_names(names: Iterable[str], target: Protocol) -> None:
if target in {Protocol.CHAT, Protocol.RESPONSES} and any(
not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", name) for name in names
):
raise ConversionError(
"target function names require 1-64 ASCII letters, digits, underscores or dashes; enable tool_names='alias' on the gateway to preserve other names"
)
def _check_turns(request: Request, target: Protocol, *, messages_mid_system: bool = False) -> None:
custom = any(tool.get("type") == "custom" for tool in request.tools) or any(
part.tool_type == "custom" for turn in request.turns for part in turn.parts
)
if custom and target == Protocol.MESSAGES:
raise ConversionError("Messages cannot preserve native custom-tool formats")
if custom and request.stream:
raise ConversionError("cross-protocol custom-tool streaming is not verified")
if request.stop_sequences is not None and target == Protocol.RESPONSES:
raise ConversionError("Responses has no equivalent stop-sequence setting")
names = [tool["name"] for tool in request.tools]
wire_names = names + [part.name for turn in request.turns for part in turn.parts if part.kind == "tool_call"]
_check_function_names(wire_names, target)
if len(names) != len(set(names)):
raise ConversionError("duplicate tool definition name")
if isinstance(request.tool_choice, dict) and request.tool_choice["name"] not in names:
raise ConversionError("forced tool_choice must name a declared function")
if isinstance(request.tool_choice, dict) and not any(
tool["name"] == request.tool_choice["name"] and tool.get("type", "function") == request.tool_choice["type"]
for tool in request.tools
):
raise ConversionError("forced tool_choice type does not match its definition")
if request.tool_choice == "required" and not names:
raise ConversionError("required tool_choice requires function tools")
if target == Protocol.MESSAGES:
seen_conversation = False
for turn in request.turns:
if turn.role in {"system", "developer"}:
if (seen_conversation and not messages_mid_system) or turn.role == "developer":
raise ConversionError("Messages cannot preserve developer or mid-conversation instruction roles")
else:
seen_conversation = True
if messages_mid_system:
_check_mid_system_placement(request.turns)
calls: set[str] = set()
results: set[str] = set()
for turn in request.turns:
seen_ordinary = False
for part in turn.parts:
if part.kind == "tool_call" and turn.role != "assistant":
raise ConversionError("tool calls require the assistant role")
if part.kind == "tool_result" and turn.role != "user":
raise ConversionError("tool results require the user/tool-result role")
if (
part.result_parts is not None
and target == Protocol.CHAT
and any(item.kind == "image" for item in part.result_parts)
):
raise ConversionError("Chat cannot preserve image-bearing tool results without relocating their role")
if part.kind == "reasoning_text":
if target == Protocol.MESSAGES or turn.role != "assistant" or seen_ordinary:
raise ConversionError(
"unsigned public reasoning requires a Chat/Responses assistant prefix; Messages signatures cannot be fabricated"
)
else:
seen_ordinary = True
if any(part.kind in {"image", "document"} for part in turn.parts) and (
turn.role != "user" or any(part.kind not in {"text", "image", "document"} for part in turn.parts)
):
raise ConversionError("portable images require an ordinary user text/image message")
if target in {Protocol.CHAT, Protocol.RESPONSES}:
seen_tool_call = False
for part in turn.parts:
if part.kind == "tool_call":
seen_tool_call = True
elif part.kind == "text" and seen_tool_call:
raise ConversionError("text after a tool call cannot be preserved in this target protocol")
for part in turn.parts:
if part.kind == "tool_call":
if not part.call_id:
raise ConversionError("empty tool call ID")
if part.call_id in calls:
raise ConversionError("duplicate tool call ID")
calls.add(part.call_id)
elif part.kind == "tool_result":
if not part.call_id:
raise ConversionError("empty tool result call ID")
if part.call_id not in calls:
raise ConversionError(f"tool result has no matching call: {part.call_id}")
if part.call_id in results:
raise ConversionError("duplicate tool result for call ID")
results.add(part.call_id)
def _check_mid_system_placement(turns: list[Turn]) -> None:
"""Validate Anthropic's text-only mid-system placement, never relocate it."""
pending: set[str] = set()
conversation_started = False
following: list[str | None] = [None] * len(turns)
next_role = None
for index in range(len(turns) - 1, -1, -1):
following[index] = next_role
if turns[index].role != "system":
next_role = turns[index].role
previous_role = None
for index, turn in enumerate(turns):
if turn.role == "system" and conversation_started:
if previous_role != "user" or following[index] not in (None, "assistant") or pending:
raise ConversionError(
"mid-conversation Messages system text must follow a complete user/tool-result turn and precede assistant or end the array; history was not relocated"
)
elif turn.role != "system":
conversation_started = True
previous_role = turn.role
for part in turn.parts:
if part.kind == "tool_call":
pending.add(part.call_id)
elif part.kind == "tool_result":
pending.discard(part.call_id)
def _flush_chat_user_parts(messages: list[dict[str, Any]], role: str, parts: list[Part]) -> None:
if parts:
if any(p.kind in {"image", "document"} for p in parts):
content: Any = [
p.image_value.encode("chat")
if p.kind == "image"
else p.document_value.encode("chat")
if p.kind == "document"
else {"type": "text", "text": p.text}
for p in parts
]
else:
content = "".join(p.text for p in parts)
messages.append({"role": role, "content": content})
parts.clear()
def _encode_chat(req: Request) -> dict[str, Any]:
messages: list[dict[str, Any]] = []
for turn in req.turns:
text = "".join(p.text for p in turn.parts if p.kind == "text")
calls = [p for p in turn.parts if p.kind == "tool_call"]
results = [p for p in turn.parts if p.kind == "tool_result"]
if results:
if calls or turn.role != "user":
raise ConversionError("mixed tool calls and tool results cannot be preserved in Chat")
user_parts: list[Part] = []
for p in turn.parts:
if p.kind in {"text", "image", "document"}:
user_parts.append(p)
elif p.kind == "tool_result":
_flush_chat_user_parts(messages, turn.role, user_parts)
messages.append({"role": "tool", "tool_call_id": p.call_id, "content": p.text})
_flush_chat_user_parts(messages, turn.role, user_parts)
else:
msg: dict[str, Any] = {"role": turn.role, "content": text if text or not calls else None}
if any(p.kind in {"image", "document"} for p in turn.parts):
msg["content"] = [
p.image_value.encode("chat")
if p.kind == "image"
else p.document_value.encode("chat")
if p.kind == "document"
else {"type": "text", "text": p.text}
for p in turn.parts
]
if calls:
msg["tool_calls"] = [_encode_chat_call(p) for p in calls]
reasoning = [p.text for p in turn.parts if p.kind == "reasoning_text"]
if reasoning:
msg["reasoning_content"] = "".join(reasoning)
messages.append(msg)
out: dict[str, Any] = {"model": req.model, "messages": messages, "stream": req.stream}
if req.parallel_tool_calls is not None:
out["parallel_tool_calls"] = req.parallel_tool_calls
if req.reasoning_effort is not None:
out["reasoning_effort"] = req.reasoning_effort
if req.tools:
out["tools"] = [
encode_custom(t, "chat")
if t.get("type") == "custom"
else {
"type": "function",
"function": {
"name": t["name"],
"description": t["description"],
"parameters": t["parameters"],
**_strict_tool(t),
},
}
for t in req.tools
]
if req.stop_sequences is not None:
out["stop"] = list(req.stop_sequences)
if req.max_tokens is not None:
out["max_completion_tokens"] = req.max_tokens
if req.temperature is not None:
out["temperature"] = req.temperature
if req.top_p is not None:
out["top_p"] = req.top_p
for key in ("frequency_penalty", "presence_penalty"):
value = getattr(req, key)
if value is not None:
out[key] = value
if req.top_logprobs == 0:
out["logprobs"] = False
if req.logprobs:
out["logprobs"] = True
out["top_logprobs"] = req.top_logprobs if req.top_logprobs is not None else 0
if req.tool_choice is not None:
if isinstance(req.tool_choice, dict):
kind = req.tool_choice["type"]
out["tool_choice"] = {"type": kind, kind: {"name": req.tool_choice["name"]}}
elif isinstance(req.tool_choice, str) and req.tool_choice in {"auto", "none", "required"}:
out["tool_choice"] = req.tool_choice
else:
raise ConversionError("tool_choice is not portable")
return out
def _encode_messages(req: Request) -> dict[str, Any]:
system: list[dict[str, str]] = []
messages: list[dict[str, Any]] = []
for turn in req.turns:
if turn.role == "system" and not messages:
system.extend({"type": "text", "text": p.text} for p in turn.parts)
continue
blocks: list[dict[str, Any]] = []
for p in turn.parts:
if p.kind == "text":
blocks.append({"type": "text", "text": p.text})
elif p.kind == "image":
blocks.append(p.image_value.encode("messages"))
elif p.kind == "document":
blocks.append(p.document_value.encode("messages"))
elif p.kind == "tool_call":
blocks.append({"type": "tool_use", "id": p.call_id, "name": p.name, "input": json.loads(p.arguments)})
elif p.kind == "tool_result":
content = (
[
part.image_value.encode("messages")
if part.kind == "image"
else {"type": "text", "text": part.text}
for part in p.result_parts
]
if p.result_parts is not None
else p.text
)
blocks.append({"type": "tool_result", "tool_use_id": p.call_id, "content": content})
messages.append({"role": turn.role, "content": blocks})
if req.max_tokens is None:
raise ConversionError("Messages requires max_tokens; configure an explicit limit")
out: dict[str, Any] = {"model": req.model, "messages": messages, "max_tokens": req.max_tokens, "stream": req.stream}
if req.reasoning_effort is not None:
out["output_config"] = {"effort": req.reasoning_effort}
if system:
out["system"] = system
if req.tools:
out["tools"] = [
{"name": t["name"], "description": t["description"], "input_schema": t["parameters"], **_strict_tool(t)}
for t in req.tools
]
if req.temperature is not None:
out["temperature"] = req.temperature
if req.top_p is not None:
out["top_p"] = req.top_p
if req.stop_sequences is not None:
out["stop_sequences"] = list(req.stop_sequences)
if req.tool_choice is not None:
choice = req.tool_choice
if choice == "auto":
out["tool_choice"] = {"type": "auto"}
elif choice == "required":
out["tool_choice"] = {"type": "any"}
elif choice == "none":
out["tool_choice"] = {"type": "none"}
elif isinstance(choice, dict):
out["tool_choice"] = {"type": "tool", "name": choice["name"]}
else:
raise ConversionError("tool_choice is not portable")
if req.parallel_tool_calls is False and req.tools:
choice = out.setdefault("tool_choice", {"type": "auto"})
if choice.get("type") != "none":
choice["disable_parallel_tool_use"] = True
return out
def _flush_response_text(inputs: list[dict[str, Any]], role: str, parts: list[Part]) -> None:
if parts:
item: dict[str, Any] = {
"role": role,
"content": [
p.image_value.encode("responses")
if p.kind == "image"
else p.document_value.encode("responses")
if p.kind == "document"
else {"type": "output_text" if role == "assistant" else "input_text", "text": p.text}
for p in parts
],
}
if role == "assistant":
item.update({"type": "message", "id": "msg_" + secrets.token_hex(12), "status": "completed"})
inputs.append(item)
parts.clear()
def _encode_responses(req: Request) -> dict[str, Any]:
inputs: list[dict[str, Any]] = []
for turn in req.turns:
text_parts: list[Part] = []
for p in turn.parts:
if p.kind in {"text", "image", "document"}:
text_parts.append(p)
elif p.kind == "reasoning_text":
inputs.append(reasoning_item(p.text))
elif p.kind == "tool_call":
_flush_response_text(inputs, turn.role, text_parts)
inputs.append(_encode_response_call(p))
elif p.kind == "tool_result":
_flush_response_text(inputs, turn.role, text_parts)
content = (
[
part.image_value.encode("responses")
if part.kind == "image"
else {"type": "input_text", "text": part.text}
for part in p.result_parts
]
if p.result_parts is not None
else p.text
)
inputs.append(
{
"type": "custom_tool_call_output" if p.tool_type == "custom" else "function_call_output",
"call_id": p.call_id,
"output": content,
}
)
_flush_response_text(inputs, turn.role, text_parts)
out: dict[str, Any] = {"model": req.model, "input": inputs, "stream": req.stream, "store": False}
if req.parallel_tool_calls is not None:
out["parallel_tool_calls"] = req.parallel_tool_calls
if req.reasoning_effort is not None:
out["reasoning"] = {"effort": req.reasoning_effort}
if req.tools:
out["tools"] = [
encode_custom(t, "responses")
if t.get("type") == "custom"
else {
"type": "function",
"name": t["name"],
"description": t["description"],
"parameters": t["parameters"],
"strict": t.get("strict", False),
}
for t in req.tools
]
if req.max_tokens is not None:
out["max_output_tokens"] = req.max_tokens
if req.temperature is not None:
out["temperature"] = req.temperature
if req.top_p is not None:
out["top_p"] = req.top_p
if req.tool_choice is not None:
if isinstance(req.tool_choice, dict):
out["tool_choice"] = dict(req.tool_choice)
elif isinstance(req.tool_choice, str) and req.tool_choice in {"auto", "none", "required"}:
out["tool_choice"] = req.tool_choice
else:
raise ConversionError("tool_choice is not portable")
return out
[docs]
def convert_request(
body: dict[str, Any],
source: Protocol | str,
target: Protocol | str,
*,
messages_mid_system: bool = False,
public_reasoning: bool = False,
text_logprobs: bool = False,
responses_penalties: bool = False,
) -> dict[str, Any]:
"""Convert JSON input, including stream requests; reject unsupported semantics."""
source, target = Protocol(source), Protocol(target)
if type(responses_penalties) is not bool:
raise TypeError("responses_penalties must be a boolean")
if responses_penalties and target != Protocol.RESPONSES:
raise ConversionError("Responses penalty contract requires a Responses target")
if type(text_logprobs) is not bool:
raise TypeError("text_logprobs must be a boolean")
if text_logprobs and Protocol.MESSAGES in (source, target):
raise ConversionError("Messages cannot preserve token logprobs")
if not isinstance(messages_mid_system, bool):
raise TypeError("messages_mid_system must be a boolean")
if not isinstance(public_reasoning, bool):
raise TypeError("public_reasoning must be a boolean")
if source == target:
return body.copy()
options = {"public_reasoning": public_reasoning} if source in {Protocol.CHAT, Protocol.RESPONSES} else {}
request = CODECS[source].decode_request(_object(body, "request"), **options)
request.frequency_penalty = _optional_penalty(body.get("frequency_penalty"), "frequency_penalty")
request.presence_penalty = _optional_penalty(body.get("presence_penalty"), "presence_penalty")
if (
target != Protocol.CHAT
and not responses_penalties
and any(value is not None for value in (request.frequency_penalty, request.presence_penalty))
):
raise ConversionError("penalties require a Chat target; no equivalent target control is enabled")
if source != Protocol.MESSAGES:
from .logprobs import requested
request.logprobs = requested(body, source)
if request.logprobs and not text_logprobs:
raise ConversionError("enabled logprobs require text_logprobs=True")
request.top_logprobs = _disabled_logprobs(body, source, allow_enabled=text_logprobs)
if source == Protocol.RESPONSES and request.top_logprobs not in (None, 0) and not request.logprobs:
raise ConversionError("positive top_logprobs requires the probability include option")
# Preserve field-specific validation errors before checking opaque schemas.
encode_json(body)
if Protocol.MESSAGES in (source, target):
if request.temperature is not None and request.temperature > 1:
raise ConversionError("Messages temperature must be between 0 and 1")
for tool in request.tools:
if tool.get("strict") is True:
validate_strict_tool_schema(tool["parameters"])
call_types = {}
for turn in request.turns:
for part in turn.parts:
if part.kind == "tool_call":
call_types[part.call_id] = part.tool_type
elif part.kind == "tool_result":
expected = call_types.get(part.call_id)
if source == Protocol.CHAT and expected is not None:
part.tool_type = expected
elif expected is not None and expected != part.tool_type:
raise ConversionError("tool result type does not match its call")
request.stop_sequences = (
_stops(body.get("stop" if source == Protocol.CHAT else "stop_sequences"))
if source != Protocol.RESPONSES
else None
)
request.output_format = decode_output_format(body, source)
_check_turns(request, target, messages_mid_system=messages_mid_system)
output = CODECS[target].encode_request(request)
if responses_penalties:
for key in ("frequency_penalty", "presence_penalty"):
value = getattr(request, key)
if value is not None:
output[key] = value
if target == Protocol.RESPONSES and request.top_logprobs == 0:
output["top_logprobs"] = 0
if target == Protocol.RESPONSES and request.logprobs:
output["include"] = ["message.output_text.logprobs"]
output["top_logprobs"] = request.top_logprobs if request.top_logprobs is not None else 0
formatted = encode_output_format(request.output_format, target)
if "output_config" in formatted:
output.setdefault("output_config", {}).update(formatted["output_config"])
else:
output.update(formatted)
return output
def _validate_response_item(item: dict[str, Any], label: str) -> None:
if item.get("type") == "message":
_only(item, {"type", "id", "status", "role", "content"}, label)
elif item.get("type") == "function_call":
_only(item, {"type", "id", "status", "call_id", "name", "arguments", "namespace"}, label)
if item.get("namespace") is not None:
raise ConversionError("upstream Responses namespace cannot be preserved in this protocol")
elif item.get("type") == "custom_tool_call":
_only(item, {"type", "id", "status", "call_id", "name", "input", "namespace"}, label)
if item.get("namespace") is not None:
raise ConversionError("upstream Responses namespace cannot be preserved in this protocol")
def _decode_result(
body: dict[str, Any],
source: Protocol,
*,
public_reasoning: bool = False,
text_logprobs: bool = False,
omit_reasoning: bool = False,
) -> Result:
return _decode_result_parts(
body, source, public_reasoning=public_reasoning, text_logprobs=text_logprobs, omit_reasoning=omit_reasoning
)
def _omittable_reasoning(body: dict[str, Any], source: Protocol, public_reasoning: bool) -> tuple[dict[str, Any], bool]:
"""Remove upstream reasoning a route cannot represent (explicit omit policy)."""
if source == Protocol.CHAT:
choices = body.get("choices")
if (
not isinstance(choices, list)
or len(choices) != 1
or not isinstance(choices[0], dict)
or not isinstance(choices[0].get("message"), dict)
):
return body, False
message = dict(choices[0]["message"])
keep = set()
if public_reasoning:
keep.add("reasoning_content" if message.get("reasoning_content") is not None else "reasoning")
dropped = [
key
for key in ("reasoning", "reasoning_content", "reasoning_details")
if key not in keep and message.get(key) not in (None, "", [])
]
for key in dropped:
message.pop(key)
return {**body, "choices": [{**choices[0], "message": message}]}, bool(dropped)
if source == Protocol.MESSAGES:
content = body.get("content")
if not isinstance(content, list):
return body, False
kept = [
block
for block in content
if not (isinstance(block, dict) and block.get("type") in ("thinking", "redacted_thinking"))
]
return {**body, "content": kept}, len(kept) != len(content)
output = body.get("output")
if public_reasoning or not isinstance(output, list):
return body, False
kept = [item for item in output if not (isinstance(item, dict) and item.get("type") == "reasoning")]
return {**body, "output": kept}, len(kept) != len(output)
def _decode_result_parts(
body: dict[str, Any],
source: Protocol,
*,
public_reasoning: bool = False,
text_logprobs: bool = False,
omit_reasoning: bool = False,
) -> Result:
if type(omit_reasoning) is not bool:
raise TypeError("omit_reasoning must be a boolean")
if omit_reasoning:
body, _ = _omittable_reasoning(body, source, public_reasoning)
return CODECS[source].decode_result(body, public_reasoning=public_reasoning, text_logprobs=text_logprobs)
def _decode_chat_result(body: dict[str, Any], *, public_reasoning: bool = False, text_logprobs: bool = False) -> Result:
choices = _list(body.get("choices"), "choices")
if len(choices) != 1:
raise ConversionError("only one choice is supported")
choice = _object(choices[0], "choice")
if choice.get("logprobs") and not text_logprobs:
raise ConversionError("Chat logprobs cannot be preserved")
msg = _drop_null_legacy(_object(choice.get("message"), "message"))
_only(
msg,
{
"role",
"content",
"tool_calls",
"refusal",
"annotations",
"reasoning",
"reasoning_content",
"reasoning_details",
},
"Chat response message",
)
rejected_reasoning = (
(("reasoning_details",) if msg.get("reasoning_content") is None else ("reasoning", "reasoning_details"))
if public_reasoning
else ("reasoning", "reasoning_content", "reasoning_details")
)
if any(msg.get(key) not in (None, "", []) for key in rejected_reasoning):
raise ConversionError("Chat reasoning cannot be preserved across protocols")
if msg.get("role") != "assistant":
raise ConversionError("Chat response message must have assistant role")
if msg.get("annotations"):
raise ConversionError("Chat annotations cannot be preserved")
if msg.get("refusal") is not None and not isinstance(msg["refusal"], str):
raise ConversionError("Chat refusal must be a string or null")
if msg.get("refusal"):
raise UnsupportedFeatureError("refusal")
parts = _chat_content(msg.get("content"), "message.content")
if text_logprobs:
from .logprobs import align, chat_records
probabilities = chat_records(choice.get("logprobs"))
if probabilities or parts:
if len(parts) != 1 or parts[0].kind != "text":
raise ConversionError("Chat logprobs require one text output")
align(probabilities, parts[0].text, required=True)
parts[0].logprobs = probabilities
if public_reasoning and msg.get("reasoning_content") is not None:
parts.insert(0, Part("reasoning_text", text=_string(msg["reasoning_content"], "reasoning_content")))
elif public_reasoning and msg.get("reasoning") not in (None, ""):
# OpenRouter's unsigned public reasoning field.
parts.insert(0, Part("reasoning_text", text=_string(msg["reasoning"], "reasoning")))
for index, call in enumerate(_optional_list(msg.get("tool_calls"), "tool_calls")):
call = _object(call, "tool_call")
parts.append(_chat_call(call, index))
usage = _object(body.get("usage") or {}, "usage")
reason = choice.get("finish_reason")
if reason == "content_filter":
raise UnsupportedFeatureError("content_filter")
if reason not in ("stop", "tool_calls", "length"):
raise ConversionError(f"unsupported Chat finish_reason: {reason}")
if reason != "length" and (reason == "tool_calls") != any(p.kind == "tool_call" for p in parts):
raise ConversionError("Chat tool_calls finish reason does not match output")
return Result(
_string(body.get("model"), "model"),
parts,
reason,
service_tier=_reported_service_tier(body.get("service_tier")),
**_decode_usage(usage, Protocol.CHAT),
)
def _decode_messages_result(
body: dict[str, Any], *, public_reasoning: bool = False, text_logprobs: bool = False
) -> Result:
# Messages has no public reasoning or text logprobs to carry.
if body.get("role") not in (None, "assistant"):
raise ConversionError("Messages response must have assistant role")
parts = _message_parts(body.get("content"), "content")
if any(p.kind == "tool_result" for p in parts):
raise ConversionError("tool result is not a valid Messages response")
usage = _object(body.get("usage") or {}, "usage")
reason = body.get("stop_reason")
if reason in ("refusal", "stop_sequence", "pause_turn"):
raise UnsupportedFeatureError(reason)
if reason not in ("end_turn", "tool_use", "max_tokens"):
raise ConversionError(f"unsupported Messages stop_reason: {reason}")
if reason != "max_tokens" and (reason == "tool_use") != any(p.kind == "tool_call" for p in parts):
raise ConversionError("Messages tool_use stop reason does not match output")
return Result(
_string(body.get("model"), "model"),
parts,
"length" if reason == "max_tokens" else ("tool_calls" if reason == "tool_use" else "stop"),
**_decode_usage(usage, Protocol.MESSAGES),
)
def _decode_responses_result(
body: dict[str, Any], *, public_reasoning: bool = False, text_logprobs: bool = False
) -> Result:
parts = []
for item in _list(body.get("output"), "output"):
item = _object(item, "output item")
_validate_response_item(item, "output item")
if item.get("type") == "message":
allowed_status = (
(None, "completed", "incomplete") if body.get("status") == "incomplete" else (None, "completed")
)
if item.get("role") not in (None, "assistant") or item.get("status") not in allowed_status:
raise ConversionError("Responses output message must be a completed assistant message")
parts.extend(_response_content(item.get("content"), "message.content", text_logprobs=text_logprobs))
elif item.get("type") == "reasoning" and public_reasoning:
if item.get("status") == "incomplete" and body.get("status") != "incomplete":
raise ConversionError("incomplete public reasoning in a completed response")
parts.append(Part("reasoning_text", text=response_reasoning(item)))
elif item.get("type") == "function_call":
if item.get("status") not in (None, "completed"):
raise ConversionError("Responses function call is incomplete")
parts.append(
Part(
"tool_call",
call_id=_string(item.get("call_id"), "call_id"),
name=_string(item.get("name"), "name"),
arguments=_arguments(item.get("arguments"), "arguments"),
)
)
elif item.get("type") == "custom_tool_call":
if item.get("status") not in (None, "completed"):
raise ConversionError("Responses custom tool call is incomplete")
parts.append(
Part(
"tool_call",
call_id=_string(item.get("call_id"), "call_id"),
name=_string(item.get("name"), "name"),
arguments=_string(item.get("input"), "input"),
tool_type="custom",
)
)
elif item.get("type") == "compaction":
raise UnsupportedFeatureError("compaction")
else:
raise ConversionError(f"unsupported Responses output item: {item.get('type')}")
usage = _object(body.get("usage") or {}, "usage")
status = body.get("status")
if status not in ("completed", "incomplete"):
raise ConversionError(f"unsupported Responses status: {status}")
if status == "incomplete":
details = _object(body.get("incomplete_details"), "incomplete_details")
if details.get("reason") == "content_filter":
raise UnsupportedFeatureError("content_filter")
if details.get("reason") != "max_output_tokens":
raise ConversionError("unsupported Responses incomplete reason")
reason = "length"
else:
reason = "tool_calls" if any(p.kind == "tool_call" for p in parts) else "stop"
return Result(
_string(body.get("model"), "model"),
parts,
reason,
service_tier=_reported_service_tier(body.get("service_tier")),
**_decode_usage(usage, Protocol.RESPONSES),
)
@dataclass(frozen=True, slots=True)
class _ResultContent:
"""What every response encoder needs, validated once for all protocols."""
text: str
reasoning: list[str]
calls: list[Part]
probabilities: list[dict[str, Any]]
def _encode_result(result: Result, target: Protocol) -> dict[str, Any]:
from .logprobs import align
codec = CODECS[target]
probabilities = [record for part in result.parts for record in (part.logprobs or [])]
if probabilities and not codec.result_logprobs:
raise ConversionError(f"{codec.label} cannot preserve token logprobs")
if not codec.custom_tools and any(part.tool_type == "custom" for part in result.parts):
raise ConversionError(f"{codec.label} cannot preserve native custom-tool formats")
seen_ordinary = False
for part in result.parts:
if part.kind == "reasoning_text":
if not codec.unsigned_reasoning or seen_ordinary:
raise ConversionError(
"unsigned public reasoning requires a Chat/Responses assistant prefix; Messages signatures cannot be fabricated"
)
else:
seen_ordinary = True
reasoning = [p.text for p in result.parts if p.kind == "reasoning_text"]
if not codec.text_after_tool_call:
seen_tool_call = False
for part in result.parts:
if part.kind == "tool_call":
seen_tool_call = True
elif part.kind == "text" and seen_tool_call:
raise ConversionError("text after a tool call cannot be preserved in this target response")
text = "".join(p.text for p in result.parts if p.kind == "text")
align(probabilities, text)
calls = [p for p in result.parts if p.kind == "tool_call"]
return codec.encode_result(result, _ResultContent(text, reasoning, calls, probabilities))
def _encode_chat_result(result: Result, content: _ResultContent) -> dict[str, Any]:
text, reasoning, calls, probabilities = content.text, content.reasoning, content.calls, content.probabilities
message: dict[str, Any] = {"role": "assistant", "content": text or None}
if reasoning:
message["reasoning_content"] = "".join(reasoning)
if calls:
message["tool_calls"] = [_encode_chat_call(p) for p in calls]
out: dict[str, Any] = {
"id": "chatcmpl-" + secrets.token_hex(12),
"created": int(time.time()),
"object": "chat.completion",
"model": result.model,
"choices": [{"index": 0, "message": message, "finish_reason": result.finish_reason}],
}
if probabilities:
out["choices"][0]["logprobs"] = {"content": probabilities, "refusal": None}
if result.service_tier is not None:
out["service_tier"] = _reported_service_tier(result.service_tier)
if result.input_tokens is not None and result.output_tokens is not None:
out["usage"] = _encode_usage(result, Protocol.CHAT)
return out
def _encode_messages_result(result: Result, content: _ResultContent) -> dict[str, Any]:
# Messages writes text and tool calls in part order, from result.parts.
if result.input_tokens is None or result.output_tokens is None:
raise ConversionError("Messages response requires real upstream token usage")
blocks: list[dict[str, Any]] = []
for p in result.parts:
if p.kind == "text":
blocks.append({"type": "text", "text": p.text})
elif p.kind == "tool_call":
blocks.append({"type": "tool_use", "id": p.call_id, "name": p.name, "input": json.loads(p.arguments)})
out = {
"id": "msg_" + secrets.token_hex(12),
"type": "message",
"role": "assistant",
"model": result.model,
"content": blocks,
"stop_reason": {"stop": "end_turn", "tool_calls": "tool_use", "length": "max_tokens"}[result.finish_reason],
"stop_sequence": None,
"usage": _encode_usage(result, Protocol.MESSAGES),
}
return out
def _encode_responses_result(result: Result, content: _ResultContent) -> dict[str, Any]:
text, reasoning, calls, probabilities = content.text, content.reasoning, content.calls, content.probabilities
output: list[dict[str, Any]] = []
if reasoning:
output.append(
reasoning_item(
"".join(reasoning),
identifier="rs_" + secrets.token_hex(12),
status="incomplete" if result.finish_reason == "length" else "completed",
)
)
if text:
output.append(
{
"id": "msg_" + secrets.token_hex(12),
"type": "message",
"role": "assistant",
"status": "incomplete" if result.finish_reason == "length" else "completed",
"content": [{"type": "output_text", "text": text, "annotations": [], "logprobs": probabilities}],
}
)
output.extend(
{
"id": ("ct_" if p.tool_type == "custom" else "fc_") + secrets.token_hex(12),
**_encode_response_call(p),
"status": "completed",
}
for p in calls
)
out = {
"id": "resp_" + secrets.token_hex(12),
"created_at": int(time.time()),
"object": "response",
"model": result.model,
"status": "incomplete" if result.finish_reason == "length" else "completed",
"output": output,
"error": None,
"incomplete_details": {"reason": "max_output_tokens"} if result.finish_reason == "length" else None,
}
# Facts about this newly generated, non-persisted Responses envelope.
# Request context can restore actual instructions/limits at the gateway;
# provider sampling defaults and token details must remain unknown.
out.update(generated_response_metadata())
if result.service_tier is not None:
out["service_tier"] = _reported_service_tier(result.service_tier)
out["completed_at"] = int(time.time()) if out["status"] == "completed" else None
if result.input_tokens is not None and result.output_tokens is not None:
out["usage"] = _encode_usage(result, Protocol.RESPONSES)
return out
@dataclass(frozen=True, slots=True)
class Codec:
"""Everything protocol-specific about one wire format.
Requests and completed responses are decoded into the portable model and
encoded back through these functions; the flags state which response
features the format can represent. Adding a protocol means adding a codec.
"""
protocol: Protocol
label: str
decode_request: Callable[..., Request]
encode_request: Callable[[Request], dict[str, Any]]
decode_result: Callable[..., Result]
encode_result: Callable[[Result, _ResultContent], dict[str, Any]]
#: Token logprobs on output text.
result_logprobs: bool
#: Native custom (free-form input) tool calls.
custom_tools: bool
#: Unsigned public reasoning ahead of the answer.
unsigned_reasoning: bool
#: Text after a tool call within one response.
text_after_tool_call: bool
CODECS: Mapping[Protocol, Codec] = MappingProxyType(
{
Protocol.CHAT: Codec(
Protocol.CHAT,
"Chat",
_decode_chat,
_encode_chat,
_decode_chat_result,
_encode_chat_result,
result_logprobs=True,
custom_tools=True,
unsigned_reasoning=True,
text_after_tool_call=False,
),
Protocol.MESSAGES: Codec(
Protocol.MESSAGES,
"Messages",
_decode_messages,
_encode_messages,
_decode_messages_result,
_encode_messages_result,
result_logprobs=False,
custom_tools=False,
unsigned_reasoning=False,
text_after_tool_call=True,
),
Protocol.RESPONSES: Codec(
Protocol.RESPONSES,
"Responses",
_decode_responses,
_encode_responses,
_decode_responses_result,
_encode_responses_result,
result_logprobs=True,
custom_tools=True,
unsigned_reasoning=True,
text_after_tool_call=False,
),
}
)
[docs]
def convert_response(
body: dict[str, Any],
source: Protocol | str,
target: Protocol | str,
*,
public_reasoning: bool = False,
request_context: dict[str, Any] | None = None,
text_logprobs: bool = False,
max_top_logprobs: int | None = None,
omit_reasoning: bool = False,
) -> dict[str, Any]:
"""Convert a completed text/function response without inventing usage.
``omit_reasoning`` is an explicit policy that drops upstream reasoning the
target route cannot represent instead of rejecting the response.
"""
source, target = Protocol(source), Protocol(target)
if type(text_logprobs) is not bool:
raise TypeError("text_logprobs must be a boolean")
if text_logprobs and Protocol.MESSAGES in (source, target):
raise ConversionError("Messages cannot preserve token logprobs")
if not isinstance(public_reasoning, bool):
raise TypeError("public_reasoning must be a boolean")
transform = None
if request_context is not None:
if target != Protocol.RESPONSES or source == target:
raise ConversionError("request_context requires translated Responses output")
from .response_context import bind_response_context
transform = bind_response_context(request_context)
if source == target:
return body.copy()
encode_json(body)
result = _decode_result(
_object(body, "response"),
source,
public_reasoning=public_reasoning,
text_logprobs=text_logprobs,
omit_reasoning=omit_reasoning,
)
if text_logprobs:
from .logprobs import records
limit = max_top_logprobs if max_top_logprobs is not None else (request_context or {}).get("top_logprobs")
records([], limit)
for part in result.parts:
if part.logprobs is not None:
records(part.logprobs, limit)
_check_function_names((part.name for part in result.parts if part.kind == "tool_call"), target)
if any(part.kind in {"image", "document"} for part in result.parts):
raise ConversionError("image output is not supported across protocols")
call_ids = [part.call_id for part in result.parts if part.kind == "tool_call"]
if any(not value for value in call_ids) or len(call_ids) != len(set(call_ids)):
raise ConversionError("empty or duplicate response tool call ID")
output = _encode_result(result, target)
return transform(output) if transform is not None else output