diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index 3d3c280f6..b15a71b92 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -1151,6 +1151,44 @@ async def process_chat_response( return content.strip() + def convert_content_blocks_to_messages(content_blocks): + messages = [] + + temp_blocks = [] + for idx, block in enumerate(content_blocks): + if block["type"] == "tool_calls": + messages.append( + { + "role": "assistant", + "content": serialize_content_blocks(temp_blocks), + "tool_calls": block.get("content"), + } + ) + + results = block.get("results", []) + + for result in results: + messages.append( + { + "role": "tool", + "tool_call_id": result["tool_call_id"], + "content": result["content"], + } + ) + temp_blocks = [] + else: + temp_blocks.append(block) + + if temp_blocks: + messages.append( + { + "role": "assistant", + "content": serialize_content_blocks(temp_blocks), + } + ) + + return messages + def tag_content_handler(content_type, tags, content, content_blocks): end_flag = False @@ -1611,21 +1649,7 @@ async def process_chat_response( "tools": form_data["tools"], "messages": [ *form_data["messages"], - { - "role": "assistant", - "content": serialize_content_blocks( - content_blocks, raw=True - ), - "tool_calls": response_tool_calls, - }, - *[ - { - "role": "tool", - "tool_call_id": result["tool_call_id"], - "content": result["content"], - } - for result in results - ], + *convert_content_blocks_to_messages(content_blocks), ], }, user,