mirror of
https://github.com/zhayujie/chatgpt-on-wechat.git
synced 2026-07-20 13:47:15 +08:00
fix: issues with empty tool calls and handling excessively long tool results
This commit is contained in:
@@ -233,56 +233,66 @@ class OpenAICompatibleBot:
|
||||
# Separate text content and tool_result blocks
|
||||
text_parts = []
|
||||
tool_results = []
|
||||
|
||||
|
||||
for block in content:
|
||||
if block.get("type") == "text":
|
||||
text_parts.append(block.get("text", ""))
|
||||
elif block.get("type") == "tool_result":
|
||||
tool_results.append(block)
|
||||
|
||||
|
||||
# First, add tool result messages (must come immediately after assistant with tool_calls)
|
||||
for block in tool_results:
|
||||
tool_call_id = block.get("tool_use_id") or ""
|
||||
if not tool_call_id:
|
||||
logger.warning(f"[OpenAICompatible] tool_result missing tool_use_id, using empty string")
|
||||
# Ensure content is a string (some providers require string content)
|
||||
result_content = block.get("content", "")
|
||||
if not isinstance(result_content, str):
|
||||
result_content = json.dumps(result_content, ensure_ascii=False)
|
||||
openai_messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": block.get("tool_use_id"),
|
||||
"content": block.get("content", "")
|
||||
"tool_call_id": tool_call_id,
|
||||
"content": result_content
|
||||
})
|
||||
|
||||
|
||||
# Then, add text content as a separate user message if present
|
||||
if text_parts:
|
||||
openai_messages.append({
|
||||
"role": "user",
|
||||
"content": " ".join(text_parts)
|
||||
})
|
||||
|
||||
|
||||
# Check if this is an assistant message with tool_use blocks
|
||||
elif role == "assistant":
|
||||
# Separate text content and tool_use blocks
|
||||
text_parts = []
|
||||
tool_calls = []
|
||||
|
||||
|
||||
for block in content:
|
||||
if block.get("type") == "text":
|
||||
text_parts.append(block.get("text", ""))
|
||||
elif block.get("type") == "tool_use":
|
||||
tool_id = block.get("id") or ""
|
||||
if not tool_id:
|
||||
logger.warning(f"[OpenAICompatible] tool_use missing id for '{block.get('name')}'")
|
||||
tool_calls.append({
|
||||
"id": block.get("id"),
|
||||
"id": tool_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": block.get("name"),
|
||||
"arguments": json.dumps(block.get("input", {}))
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
# Build OpenAI format assistant message
|
||||
openai_msg = {
|
||||
"role": "assistant",
|
||||
"content": " ".join(text_parts) if text_parts else None
|
||||
}
|
||||
|
||||
|
||||
if tool_calls:
|
||||
openai_msg["tool_calls"] = tool_calls
|
||||
|
||||
|
||||
openai_messages.append(openai_msg)
|
||||
else:
|
||||
# Other list content, keep as is
|
||||
|
||||
Reference in New Issue
Block a user