Spaces:
Running
Running
File size: 25,256 Bytes
0157ac7 574e4e7 0ba585f 574e4e7 0ba585f 574e4e7 0ba585f 574e4e7 0157ac7 574e4e7 0ba585f 574e4e7 0ba585f 574e4e7 0ba585f 574e4e7 0157ac7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 | """Message and tool format converters."""
import json
from dataclasses import dataclass, field
from enum import StrEnum
from typing import Any
from pydantic import BaseModel
from .content import get_block_attr, get_block_type
from .utils import set_if_not_none
class OpenAIConversionError(Exception):
"""Raised when Anthropic content cannot be converted to OpenAI chat without data loss."""
class ReasoningReplayMode(StrEnum):
"""How assistant reasoning history is replayed to OpenAI-compatible providers."""
DISABLED = "disabled"
THINK_TAGS = "think_tags"
REASONING_CONTENT = "reasoning_content"
def _openai_reject_native_only_top_level_fields(request_data: Any) -> None:
"""OpenAI chat providers may only convert known top-level request fields.
First-class model fields (e.g. ``context_management``) are not forwarded to
the OpenAI API but are allowed so clients do not hit spurious 400s.
Unknown extra keys (``__pydantic_extra__``) are still rejected.
"""
if not isinstance(request_data, BaseModel):
return
extra = getattr(request_data, "__pydantic_extra__", None)
if not extra:
return
raise OpenAIConversionError(
"OpenAI chat conversion does not support these top-level request fields: "
f"{sorted(str(k) for k in extra)}. Use a native Anthropic transport provider."
)
def _tool_name(tool: Any) -> str:
return str(getattr(tool, "name", "") or "")
def _tool_input_schema(tool: Any) -> dict[str, Any]:
schema = getattr(tool, "input_schema", None)
if isinstance(schema, dict):
return schema
return {"type": "object", "properties": {}}
def _serialize_tool_result_content(tool_content: Any) -> str:
"""Serialize tool_result content for OpenAI ``role: tool`` messages (stable JSON for structured values)."""
if tool_content is None:
return ""
if isinstance(tool_content, str):
return tool_content
if isinstance(tool_content, dict):
return json.dumps(tool_content, ensure_ascii=False)
if isinstance(tool_content, list):
parts: list[str] = []
for item in tool_content:
if isinstance(item, dict) and item.get("type") == "text":
parts.append(str(item.get("text", "")))
elif isinstance(item, dict):
parts.append(json.dumps(item, ensure_ascii=False))
else:
parts.append(str(item))
return "\n".join(parts)
return str(tool_content)
def _clean_reasoning_content(value: Any) -> str | None:
if not isinstance(value, str):
return None
return value if value else None
def _think_tag_content(reasoning: str) -> str:
return f"<think>\n{reasoning}\n</think>"
@dataclass
class _PendingAfterTools:
"""Assistant content that appears after ``tool_use`` in an Anthropic message.
OpenAI ``chat.completions`` cannot place assistant text after ``tool_calls`` in the
same message, so it is deferred until the corresponding ``role: tool`` results have
been replayed in order.
"""
# Tool use IDs still missing a ``role: tool`` result before post-tool text may be replayed.
remaining_tool_ids: set[str] = field(default_factory=set)
deferred_blocks: list[Any] = field(default_factory=list)
top_level_reasoning: str | None = None
reasoning_replay: ReasoningReplayMode = ReasoningReplayMode.THINK_TAGS
# True after deferred assistant text has been added to the OpenAI transcript.
deferred_emitted: bool = False
def needs_deferred(self) -> bool:
return bool(self.deferred_blocks) and not self.deferred_emitted
def _index_first_tool_use(blocks: list[Any]) -> int | None:
for i, block in enumerate(blocks):
if get_block_type(block) == "tool_use":
return i
return None
def _iter_tool_uses_in_order(blocks: list[Any]) -> list[dict[str, Any]]:
tool_calls: list[dict[str, Any]] = []
for block in blocks:
if get_block_type(block) == "tool_use":
tool_input = get_block_attr(block, "input", {})
tool_calls.append(
{
"id": get_block_attr(block, "id"),
"type": "function",
"function": {
"name": get_block_attr(block, "name"),
"arguments": json.dumps(tool_input)
if isinstance(tool_input, dict)
else str(tool_input),
},
}
)
return tool_calls
def _deferred_post_tool_blocks(
content: list[Any], *, first_tool_index: int
) -> list[Any]:
return [
b
for i, b in enumerate(content)
if i > first_tool_index and get_block_type(b) != "tool_use"
]
def _assert_no_forbidden_assistant_block(block: Any) -> None:
block_type = get_block_type(block)
if block_type == "image":
raise OpenAIConversionError(
"Assistant image blocks are not supported for OpenAI chat conversion."
)
if block_type in (
"server_tool_use",
"web_search_tool_result",
"web_fetch_tool_result",
):
raise OpenAIConversionError(
"OpenAI chat conversion does not support Anthropic server tool blocks "
f"({block_type!r} in an assistant message). Use a native Anthropic transport provider."
)
class AnthropicToOpenAIConverter:
"""Convert Anthropic message format to OpenAI-compatible format."""
@staticmethod
def convert_messages(
messages: list[Any],
*,
reasoning_replay: ReasoningReplayMode = ReasoningReplayMode.THINK_TAGS,
) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
pending: _PendingAfterTools | None = None
for msg in messages:
role = msg.role
content = msg.content
reasoning_content = _clean_reasoning_content(
getattr(msg, "reasoning_content", None)
)
if role == "assistant" and isinstance(content, list):
if pending is not None and pending.needs_deferred():
# Orphan: expected tool result; emit deferred to avoid a stuck session.
result.extend(
AnthropicToOpenAIConverter._deferred_post_tool_to_messages(
pending,
)
)
pending.deferred_emitted = True
pending = None
if (first_i := _index_first_tool_use(content)) is not None:
for block in content:
if get_block_type(block) == "tool_use":
continue
_assert_no_forbidden_assistant_block(block)
out, new_pending = (
AnthropicToOpenAIConverter._convert_assistant_message_with_split(
content,
first_tool_index=first_i,
reasoning_content=reasoning_content,
reasoning_replay=reasoning_replay,
)
)
result.extend(out)
if new_pending is not None:
pending = new_pending
else:
for block in content:
_assert_no_forbidden_assistant_block(block)
result.extend(
AnthropicToOpenAIConverter._convert_assistant_message(
content,
reasoning_content=reasoning_content,
reasoning_replay=reasoning_replay,
)
)
elif isinstance(content, str):
if role == "user" and pending is not None and pending.needs_deferred():
result.extend(
AnthropicToOpenAIConverter._deferred_post_tool_to_messages(
pending
)
)
pending.deferred_emitted = True
pending = None
converted = {"role": role, "content": content}
if role == "assistant" and reasoning_content:
if reasoning_replay == ReasoningReplayMode.REASONING_CONTENT:
converted["reasoning_content"] = reasoning_content
elif reasoning_replay == ReasoningReplayMode.THINK_TAGS:
content_parts = [_think_tag_content(reasoning_content)]
if content:
content_parts.append(content)
converted["content"] = "\n\n".join(content_parts)
result.append(converted)
elif isinstance(content, list):
if role == "user":
if pending is not None and pending.needs_deferred():
if not pending.remaining_tool_ids:
result.extend(
AnthropicToOpenAIConverter._deferred_post_tool_to_messages(
pending
)
)
pending.deferred_emitted = True
pending = None
result.extend(
AnthropicToOpenAIConverter._convert_user_message(
content
)
)
else:
pieces = AnthropicToOpenAIConverter._convert_user_message_with_injection(
content, pending
)
result.extend(pieces["messages"])
if pieces["cleared_pending"]:
pending = None
else:
result.extend(
AnthropicToOpenAIConverter._convert_user_message(content)
)
else:
if role == "user" and pending is not None and pending.needs_deferred():
result.extend(
AnthropicToOpenAIConverter._deferred_post_tool_to_messages(
pending
)
)
pending.deferred_emitted = True
pending = None
result.append({"role": role, "content": str(content)})
if pending is not None and pending.needs_deferred():
result.extend(
AnthropicToOpenAIConverter._deferred_post_tool_to_messages(pending)
)
return result
@staticmethod
def _convert_assistant_message_with_split(
content: list[Any],
*,
first_tool_index: int,
reasoning_content: str | None,
reasoning_replay: ReasoningReplayMode,
) -> tuple[list[dict[str, Any]], _PendingAfterTools | None]:
pre = content[:first_tool_index]
tool_calls = _iter_tool_uses_in_order(content)
if not tool_calls:
return (
AnthropicToOpenAIConverter._convert_assistant_message(
content,
reasoning_content=reasoning_content,
reasoning_replay=reasoning_replay,
),
None,
)
deferred_blocks = _deferred_post_tool_blocks(
content, first_tool_index=first_tool_index
)
pre_msg: dict[str, Any]
if not pre:
pre_msg = {
"role": "assistant",
"content": "",
}
if reasoning_replay == ReasoningReplayMode.REASONING_CONTENT:
replay = reasoning_content
if replay:
pre_msg["reasoning_content"] = replay
else:
pre_msg = AnthropicToOpenAIConverter._convert_assistant_message(
pre,
reasoning_content=reasoning_content,
reasoning_replay=reasoning_replay,
)[0]
pre_msg["tool_calls"] = tool_calls
if tool_calls and pre_msg.get("content") == " ":
pre_msg["content"] = ""
pnd: _PendingAfterTools | None = None
if deferred_blocks:
res_ids: set[str] = set()
for tc in tool_calls:
tid = tc.get("id")
if tid is not None and str(tid).strip() != "":
res_ids.add(str(tid))
pnd = _PendingAfterTools(
remaining_tool_ids=res_ids,
deferred_blocks=deferred_blocks,
top_level_reasoning=reasoning_content,
reasoning_replay=reasoning_replay,
)
return [pre_msg], pnd
@staticmethod
def _convert_assistant_message(
content: list[Any],
*,
reasoning_content: str | None = None,
reasoning_replay: ReasoningReplayMode = ReasoningReplayMode.THINK_TAGS,
) -> list[dict[str, Any]]:
content_parts: list[str] = []
thinking_parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
for block in content:
block_type = get_block_type(block)
if block_type == "text":
content_parts.append(get_block_attr(block, "text", ""))
elif block_type == "thinking":
if reasoning_replay == ReasoningReplayMode.DISABLED:
continue
thinking = get_block_attr(block, "thinking", "")
if reasoning_replay == ReasoningReplayMode.THINK_TAGS:
content_parts.append(_think_tag_content(thinking))
elif reasoning_content is None:
thinking_parts.append(thinking)
elif block_type == "redacted_thinking":
# Opaque provider continuation data; do not materialize as model-visible text
# or reasoning_content for OpenAI chat upstreams.
continue
elif block_type == "tool_use":
tool_input = get_block_attr(block, "input", {})
tool_calls.append(
{
"id": get_block_attr(block, "id"),
"type": "function",
"function": {
"name": get_block_attr(block, "name"),
"arguments": json.dumps(tool_input)
if isinstance(tool_input, dict)
else str(tool_input),
},
}
)
else:
_assert_no_forbidden_assistant_block(block)
content_str = "\n\n".join(content_parts)
if not content_str and not tool_calls:
content_str = " "
msg: dict[str, Any] = {
"role": "assistant",
"content": content_str,
}
if tool_calls:
msg["tool_calls"] = tool_calls
if reasoning_replay == ReasoningReplayMode.REASONING_CONTENT:
replay_reasoning = reasoning_content or "\n".join(thinking_parts)
if replay_reasoning:
msg["reasoning_content"] = replay_reasoning
return [msg]
@staticmethod
def _deferred_post_tool_to_messages(
pending: _PendingAfterTools,
) -> list[dict[str, Any]]:
if not pending.deferred_blocks:
return []
return AnthropicToOpenAIConverter._convert_assistant_message(
pending.deferred_blocks,
reasoning_content=pending.top_level_reasoning,
reasoning_replay=pending.reasoning_replay,
)
@staticmethod
def _convert_user_message_with_injection(
content: list[Any], pending: _PendingAfterTools
) -> dict[str, Any]:
"""Convert user list blocks, emitting deferred assistant after all tool results."""
if not pending.needs_deferred() or not pending.remaining_tool_ids:
return {
"messages": AnthropicToOpenAIConverter._convert_user_message(content),
"cleared_pending": False,
}
result: list[dict[str, Any]] = []
text_parts: list[str] = []
cleared = False
def flush_text() -> None:
if text_parts:
result.append({"role": "user", "content": "\n".join(text_parts)})
text_parts.clear()
for block in content:
block_type = get_block_type(block)
if block_type == "text":
text_parts.append(get_block_attr(block, "text", ""))
elif block_type == "image":
# Convert Anthropic image block to OpenAI image_url format
source = get_block_attr(block, "source", {})
source_type = source.get("type", "base64")
if source_type == "base64":
media_type = source.get("media_type", "image/png")
data = source.get("data", "")
# Size guard - check estimated decoded size
estimated_size = len(data) * 4 // 3
# Use a reasonable default (20MB) as max image size
max_image_bytes = 20 * 1024 * 1024
if estimated_size > max_image_bytes:
raise OpenAIConversionError(
f"Image size ({estimated_size / 1024 / 1024:.1f}MB) exceeds limit "
f"({max_image_bytes / 1024 / 1024:.1f}MB)"
)
image_url = f"data:{media_type};base64,{data}"
result.append(
{"type": "image_url", "image_url": {"url": image_url}}
)
elif source_type == "url":
# Handle URL-based images
url = source.get("url", "")
result.append({"type": "image_url", "image_url": {"url": url}})
else:
logger.warning("Unsupported image source type: {}", source_type)
elif block_type == "tool_result":
flush_text()
tool_content = get_block_attr(block, "content", "")
serialized = _serialize_tool_result_content(tool_content)
tuid = get_block_attr(block, "tool_use_id")
tuid_s = str(tuid) if tuid is not None else ""
result.append(
{
"role": "tool",
"tool_call_id": tuid,
"content": serialized if serialized else "",
}
)
if tuid_s in pending.remaining_tool_ids:
pending.remaining_tool_ids.discard(tuid_s)
if not pending.remaining_tool_ids:
result.extend(
AnthropicToOpenAIConverter._deferred_post_tool_to_messages(
pending
)
)
pending.deferred_emitted = True
cleared = True
else:
pass
flush_text()
return {"messages": result, "cleared_pending": cleared}
@staticmethod
def _convert_user_message(content: list[Any]) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
text_parts: list[str] = []
def flush_text() -> None:
if text_parts:
result.append({"role": "user", "content": "\n".join(text_parts)})
text_parts.clear()
for block in content:
block_type = get_block_type(block)
if block_type == "text":
text_parts.append(get_block_attr(block, "text", ""))
elif block_type == "image":
# Convert Anthropic image block to OpenAI image_url format
source = get_block_attr(block, "source", {})
source_type = source.get("type", "base64")
if source_type == "base64":
media_type = source.get("media_type", "image/png")
data = source.get("data", "")
# Size guard - check estimated decoded size
estimated_size = len(data) * 4 // 3
# Use a reasonable default (20MB) as max image size
max_image_bytes = 20 * 1024 * 1024
if estimated_size > max_image_bytes:
raise OpenAIConversionError(
f"Image size ({estimated_size / 1024 / 1024:.1f}MB) exceeds limit "
f"({max_image_bytes / 1024 / 1024:.1f}MB)"
)
image_url = f"data:{media_type};base64,{data}"
result.append(
{"type": "image_url", "image_url": {"url": image_url}}
)
elif source_type == "url":
# Handle URL-based images
url = source.get("url", "")
result.append({"type": "image_url", "image_url": {"url": url}})
else:
logger.warning("Unsupported image source type: {}", source_type)
elif block_type == "tool_result":
flush_text()
tool_content = get_block_attr(block, "content", "")
serialized = _serialize_tool_result_content(tool_content)
result.append(
{
"role": "tool",
"tool_call_id": get_block_attr(block, "tool_use_id"),
"content": serialized if serialized else "",
}
)
flush_text()
return result
@staticmethod
def convert_tools(tools: list[Any]) -> list[dict[str, Any]]:
return [
{
"type": "function",
"function": {
"name": tool.name,
"description": tool.description or "",
"parameters": _tool_input_schema(tool),
},
}
for tool in tools
]
@staticmethod
def convert_tool_choice(tool_choice: Any) -> Any:
if not isinstance(tool_choice, dict):
return tool_choice
choice_type = tool_choice.get("type")
if choice_type == "tool":
name = tool_choice.get("name")
if name:
return {"type": "function", "function": {"name": name}}
if choice_type == "any":
return "required"
if choice_type in {"auto", "none", "required"}:
return choice_type
if choice_type == "function" and isinstance(tool_choice.get("function"), dict):
return tool_choice
return tool_choice
@staticmethod
def convert_system_prompt(system: Any) -> dict[str, str] | None:
if isinstance(system, str):
return {"role": "system", "content": system}
if isinstance(system, list):
text_parts = [
get_block_attr(block, "text", "")
for block in system
if get_block_type(block) == "text"
]
if text_parts:
return {"role": "system", "content": "\n\n".join(text_parts).strip()}
return None
def build_base_request_body(
request_data: Any,
*,
default_max_tokens: int | None = None,
reasoning_replay: ReasoningReplayMode = ReasoningReplayMode.THINK_TAGS,
) -> dict[str, Any]:
"""Build the common parts of an OpenAI-format request body."""
_openai_reject_native_only_top_level_fields(request_data)
messages = AnthropicToOpenAIConverter.convert_messages(
request_data.messages,
reasoning_replay=reasoning_replay,
)
system = getattr(request_data, "system", None)
if system:
system_msg = AnthropicToOpenAIConverter.convert_system_prompt(system)
if system_msg:
messages.insert(0, system_msg)
body: dict[str, Any] = {"model": request_data.model, "messages": messages}
max_tokens = getattr(request_data, "max_tokens", None)
set_if_not_none(body, "max_tokens", max_tokens or default_max_tokens)
set_if_not_none(body, "temperature", getattr(request_data, "temperature", None))
set_if_not_none(body, "top_p", getattr(request_data, "top_p", None))
stop_sequences = getattr(request_data, "stop_sequences", None)
if stop_sequences:
body["stop"] = stop_sequences
tools = getattr(request_data, "tools", None)
if tools:
body["tools"] = AnthropicToOpenAIConverter.convert_tools(tools)
tool_choice = getattr(request_data, "tool_choice", None)
if tool_choice:
body["tool_choice"] = AnthropicToOpenAIConverter.convert_tool_choice(
tool_choice
)
return body
|