源码: main.rs:3091-3130 将内部消息格式转为 Anthropic API 接受的格式。
(messages: list[Message])
| 74 | # ============================================================ |
| 75 | |
| 76 | def _convert_messages(messages: list[Message]) -> list[dict]: |
| 77 | """源码: main.rs:3091-3130 |
| 78 | |
| 79 | 将内部消息格式转为 Anthropic API 接受的格式。 |
| 80 | """ |
| 81 | result: list[dict] = [] |
| 82 | |
| 83 | for msg in messages: |
| 84 | if msg.role == "tool": |
| 85 | # tool → user + tool_result content blocks |
| 86 | content = [] |
| 87 | for block in msg.content: |
| 88 | if isinstance(block, ToolResultContentBlock): |
| 89 | tr: dict = { |
| 90 | "type": "tool_result", |
| 91 | "tool_use_id": block.id, |
| 92 | "content": block.output, |
| 93 | } |
| 94 | if block.is_error: |
| 95 | tr["is_error"] = True |
| 96 | content.append(tr) |
| 97 | if content: |
| 98 | result.append({"role": "user", "content": content}) |
| 99 | |
| 100 | elif msg.role == "assistant": |
| 101 | content = [] |
| 102 | for block in msg.content: |
| 103 | if isinstance(block, TextContentBlock): |
| 104 | content.append({"type": "text", "text": block.text}) |
| 105 | elif isinstance(block, ToolContentBlock): |
| 106 | # input: string → dict |
| 107 | try: |
| 108 | input_dict = json.loads(block.input) |
| 109 | except (json.JSONDecodeError, TypeError): |
| 110 | input_dict = {"raw": block.input} |
| 111 | content.append({ |
| 112 | "type": "tool_use", |
| 113 | "id": block.id, |
| 114 | "name": block.name, |
| 115 | "input": input_dict, |
| 116 | }) |
| 117 | if content: |
| 118 | result.append({"role": "assistant", "content": content}) |
| 119 | |
| 120 | elif msg.role == "user": |
| 121 | content = [] |
| 122 | for block in msg.content: |
| 123 | if isinstance(block, TextContentBlock): |
| 124 | content.append({"type": "text", "text": block.text}) |
| 125 | if content: |
| 126 | result.append({"role": "user", "content": content}) |
| 127 | |
| 128 | # 合并连续相同 role 的消息 (API 要求交替) |
| 129 | merged: list[dict] = [] |
| 130 | for entry in result: |
| 131 | if merged and merged[-1]["role"] == entry["role"]: |
| 132 | merged[-1]["content"].extend(entry["content"]) |
| 133 | else: |