fix: synthesize OpenAI tool calls from json and python fallback

This commit is contained in:
mmc
2026-05-06 13:41:29 +08:00
parent 4c7f6cc0a1
commit 26858e1aba
2 changed files with 98 additions and 18 deletions

View File

@@ -161,6 +161,27 @@ def _json_object_from_text(text: str) -> dict[str, Any] | None:
return parsed if isinstance(parsed, dict) else None
def _json_tool_candidate_from_text(text: str) -> dict[str, Any] | None:
raw = text.strip()
if not raw:
return None
if raw.startswith("```") and raw.endswith("```"):
raw = raw[3:-3].strip()
if raw.lower().startswith("json"):
raw = raw[4:].strip()
try:
parsed = json.loads(raw)
except Exception:
return None
if isinstance(parsed, dict):
return parsed
if isinstance(parsed, list) and parsed:
first = parsed[0]
if isinstance(first, dict):
return first
return None
def _tool_code_single_arg_name(
tools: list[dict[str, Any]] | None, forced_tool_name: str
) -> str | None:
@@ -199,11 +220,15 @@ def _tool_code_object_from_text(
single_arg_name: str | None = None,
) -> dict[str, Any] | None:
raw = text.strip()
if not raw.startswith("```tool_code") or not raw.endswith("```"):
if not raw.startswith("```") or not raw.endswith("```"):
return None
lines = raw.splitlines()
if len(lines) < 2:
return None
fence = lines[0].strip().lower()
language = fence[3:].strip()
if language and language not in {"tool_code", "python", "py"}:
return None
body = "\n".join(lines[1:-1]).strip()
try:
parsed = ast.parse(body, mode="eval")
@@ -239,7 +264,7 @@ def _forced_tool_event_from_text(
*,
single_arg_name: str | None = None,
) -> dict[str, Any] | None:
parsed = _json_object_from_text(text)
parsed = _json_tool_candidate_from_text(text)
if parsed is None:
parsed = _tool_code_object_from_text(
text, forced_tool_name, single_arg_name=single_arg_name