Skip to content

Commit 8968490

Browse files
authored
Merge pull request #387 from gooose09009/fix/tool-call-content-nesting
fix(converter): 修复多轮工具调用 content 嵌套字符串扩散
2 parents 86b82ee + 579da69 commit 8968490

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

src/converter/gemini_fix.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -827,8 +827,18 @@ async def normalize_gemini_request(
827827
text_value = part["text"]
828828
if isinstance(text_value, list):
829829
# 如果是列表,合并为字符串
830+
# 注意: list 中的元素可能是 dict(如 {"type":"text","text":"..."}),不能直接 str(dict)
831+
# 否则会产生 Python repr 字符串 "{'type': 'text', 'text': '...'}",污染 model 历史
830832
log.warning(f"[GEMINI_FIX] text 字段是列表,自动合并: {text_value}")
831-
part["text"] = " ".join(str(t) for t in text_value if t)
833+
text_parts = []
834+
for t in text_value:
835+
if isinstance(t, dict) and "text" in t:
836+
text_parts.append(str(t["text"]))
837+
elif isinstance(t, str):
838+
text_parts.append(t)
839+
elif t is not None:
840+
text_parts.append(str(t))
841+
part["text"] = " ".join(text_parts)
832842
elif isinstance(text_value, str):
833843
# 清理尾随空格
834844
part["text"] = text_value.rstrip()

src/converter/openai2gemini.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1301,8 +1301,26 @@ def flush_pending_tool_parts():
13011301
parts = []
13021302

13031303
# 如果有文本内容,先添加文本
1304+
# 注意: content 可能是 str、list(OpenAI content block 格式 [{"type":"text","text":"..."}])、dict 或 None
1305+
# 必须解包为纯字符串,否则 text 字段会变成 list,触发 gemini_fix 的 str(dict) 产生嵌套字符串
13041306
if content:
1305-
parts.append({"text": content})
1307+
if isinstance(content, list):
1308+
for _part in content:
1309+
if isinstance(_part, dict):
1310+
if _part.get("type") == "text" or "text" in _part:
1311+
_t = _part.get("text", "")
1312+
if _t:
1313+
parts.append({"text": _t})
1314+
elif isinstance(_part, str) and _part:
1315+
parts.append({"text": _part})
1316+
elif isinstance(content, str):
1317+
parts.append({"text": content})
1318+
elif isinstance(content, dict):
1319+
_t = content.get("text", "")
1320+
if _t:
1321+
parts.append({"text": _t})
1322+
else:
1323+
parts.append({"text": str(content)})
13061324

13071325
# 添加每个工具调用
13081326
for tool_call in tool_calls:

0 commit comments

Comments
 (0)