def _split_system_messages(
        self, messages: list[dict]
    ) -> tuple[list[dict], Optional[str]]:
        """
        Process messages for Anthropic API, ensuring proper format for tool use and thinking blocks.
        Now with image optimization.
        """
        # First preprocess to resize any images
        messages = self._preprocess_messages(messages)

        system_msg = None
        filtered: list[dict[str, Any]] = []
        pending_tool_results: list[dict[str, Any]] = []

        # Look for pairs of tool_use and tool_result
        i = 0
        while i < len(messages):
            m = copy.deepcopy(messages[i])

            # Handle system message
            if m["role"] == "system" and system_msg is None:
                system_msg = m["content"]
                i += 1
                continue

            # Case 1: Message with list format content (thinking blocks or tool blocks)
            if (
                isinstance(m.get("content"), list)
                and len(m["content"]) > 0
                and isinstance(m["content"][0], dict)
            ):
                filtered.append({"role": m["role"], "content": m["content"]})
                i += 1
                continue

            # Case 2: Message with structured_content field
            elif m.get("structured_content") and m["role"] == "assistant":
                filtered.append(
                    {"role": "assistant", "content": m["structured_content"]}
                )
                i += 1
                continue

            # Case 3: Tool calls in an assistant message
            elif m.get("tool_calls") and m["role"] == "assistant":
                # Add content if it exists
                if m.get("content") and not isinstance(m["content"], list):
                    content_to_add = m["content"]
                    # Handle content with thinking tags
                    if "<think>" in content_to_add:
                        thinking_start = content_to_add.find("<think>")
                        thinking_end = content_to_add.find("</think>")
                        if (
                            thinking_start >= 0
                            and thinking_end > thinking_start
                        ):
                            thinking_content = content_to_add[
                                thinking_start + 7 : thinking_end
                            ]
                            text_content = content_to_add[
                                thinking_end + 8 :
                            ].strip()
                            filtered.append(
                                {
                                    "role": "assistant",
                                    "content": [
                                        {
                                            "type": "thinking",
                                            "thinking": thinking_content,
                                            "signature": "placeholder_signature",  # This is a placeholder
                                        },
                                        {"type": "text", "text": text_content},
                                    ],
                                }
                            )
                        else:
                            filtered.append(
                                {
                                    "role": "assistant",
                                    "content": content_to_add,
                                }
                            )
                    else:
                        filtered.append(
                            {"role": "assistant", "content": content_to_add}
                        )

                # Add tool use blocks
                tool_uses = []
                for call in m["tool_calls"]:
                    tool_uses.append(
                        {
                            "type": "tool_use",
                            "id": call["id"],
                            "name": call["function"]["name"],
                            "input": json.loads(call["function"]["arguments"]),
                        }
                    )

                filtered.append({"role": "assistant", "content": tool_uses})

                # Check if next message is a tool result for this tool call
                if i + 1 < len(messages) and messages[i + 1]["role"] in [
                    "function",
                    "tool",
                ]:
                    next_m = copy.deepcopy(messages[i + 1])

                    # Make sure this is a tool result for the current tool use
                    if next_m.get("tool_call_id") in [
                        call["id"] for call in m["tool_calls"]
                    ]:
                        # Add tool result as a user message
                        filtered.append(
                            {
                                "role": "user",
                                "content": [
                                    {
                                        "type": "tool_result",
                                        "tool_use_id": next_m["tool_call_id"],
                                        "content": next_m["content"],
                                    }
                                ],
                            }
                        )
                        i += 2  # Skip both the tool call and result
                        continue

                i += 1
                continue

            # Case 4: Direct tool result (might be missing its paired tool call)
            elif m["role"] in ["function", "tool"] and m.get("tool_call_id"):
                # Add a user message with the tool result
                filtered.append(
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "tool_result",
                                "tool_use_id": m["tool_call_id"],
                                "content": m["content"],
                            }
                        ],
                    }
                )
                i += 1
                continue

            # Default case: normal message
            elif m["role"] in ["function", "tool"]:
                # Collect tool results to combine them
                pending_tool_results.append(
                    {
                        "type": "tool_result",
                        "tool_use_id": m.get("tool_call_id"),
                        "content": m["content"],
                    }
                )

                # If we have all expected results, add them as one message
                if len(filtered) > 0 and len(
                    filtered[-1].get("content", [])
                ) == len(pending_tool_results):
                    filtered.append(
                        {"role": "user", "content": pending_tool_results}
                    )
                    pending_tool_results = []
            else:
                filtered.append(openai_message_to_anthropic_block(m))
                i += 1

        # Final validation: ensure no tool_use is at the end without a tool_result
        if filtered and len(filtered) > 1:
            last_msg = filtered[-1]
            if (
                last_msg["role"] == "assistant"
                and isinstance(last_msg.get("content"), list)
                and any(
                    block.get("type") == "tool_use"
                    for block in last_msg["content"]
                )
            ):
                logger.warning(
                    "Found tool_use at end of conversation without tool_result - removing it"
                )
                filtered.pop()  # Remove problematic message

        return filtered, system_msg

        Process messages for Anthropic API, ensuring proper format for tool use and thinking blocks.
        Now with image optimization.
        
py/core/providers/llm/anthropic.py