"""Extract tool calls from raw model output. Models emit calls in many shapes: Qwen-native XML, OpenAI JSON, prose-wrapped JSON in a code fence, plain-text `TOOL name | k=v`, or a bare argument object. Extractors are tried in priority order and the first that yields calls wins. """ from __future__ import annotations import json import re from typing import Any, Callable, Iterable, Mapping, Sequence from .schema import ParseResult, ToolCall from .tools import REGISTRY, canonical_name _THINK_BLOCK = re.compile(r"<(think|thinking|reasoning|analysis)>.*?", re.S | re.I) _THINK_OPEN = re.compile(r"<\|?(think|thinking|reasoning|analysis)\|?>.*?(?=" _FENCE = re.compile(r"```(?:json|python|xml|yaml|tool_code)?\s*(.*?)```", re.S | re.I) _XML_CALL = re.compile(r"(.*?)", re.S | re.I) _XML_FUNCTION = re.compile(r"(.*?)(?:|(?=)|$)", re.S | re.I) _XML_PARAM = re.compile(r"(.*?)(?:|(?= str: if _THINK_END_MARKER in text: text = text.rsplit(_THINK_END_MARKER, 1)[-1] text = _THINK_BLOCK.sub(" ", text) text = _THINK_OPEN.sub(" ", text) return re.sub(r"", " ", text, flags=re.I) def _coerce(value: Any) -> Any: if not isinstance(value, str): return value text = value.strip() if not text: return "" stripped = text.strip("`") if stripped in ("true", "false"): return stripped == "true" if stripped in ("null", "none"): return None try: return json.loads(stripped) except (ValueError, TypeError): pass if re.fullmatch(r"[-+]?\d+", stripped): return int(stripped) if re.fullmatch(r"[-+]?\d*\.\d+([eE][-+]?\d+)?", stripped): return float(stripped) return text def _pair_args(raw: Mapping[str, Any] | str | None) -> dict[str, Any]: if raw is None: return {} if isinstance(raw, str): try: raw = json.loads(raw) except ValueError: return {} if not isinstance(raw, Mapping): return {} return {str(key): _coerce(value) for key, value in raw.items()} def _call_from_object(obj: Any) -> list[ToolCall]: calls: list[ToolCall] = [] if isinstance(obj, list): for item in obj: calls.extend(_call_from_object(item)) return calls if not isinstance(obj, Mapping): return calls if isinstance(obj.get("tool_calls"), list): for item in obj["tool_calls"]: calls.extend(_call_from_object(item)) return calls function = obj.get("function") if isinstance(function, Mapping): name = function.get("name") if isinstance(name, str): args = _pair_args(function.get("arguments")) if not args and isinstance(function.get("parameters"), (Mapping, str)): args = _pair_args(function["parameters"]) return [ToolCall(name=canonical_name(name), args=args)] if isinstance(function, str) and obj.get("arguments") is not None: return [ToolCall(name=canonical_name(function), args=_pair_args(obj.get("arguments")))] name = obj.get("name") or obj.get("tool") or obj.get("tool_name") or obj.get("function_name") if isinstance(name, str) and canonical_name(name) in REGISTRY: args_source = None for key in ("arguments", "args", "parameters", "input", "parameter", "params"): if key in obj: args_source = obj[key] break args = _pair_args(args_source) if args_source is not None else { key: _coerce(value) for key, value in obj.items() if key not in ("name", "tool", "tool_name", "function_name", "arguments", "args", "parameters", "input", "parameter", "params", "id", "type") } return [ToolCall(name=canonical_name(name), args=args)] return calls def _extract_json(text: str) -> list[ToolCall]: calls: list[ToolCall] = [] for match in _JSON_BLOB.finditer(text): try: obj = json.loads(match.group(0)) except ValueError: continue calls.extend(_call_from_object(obj)) return calls def _extract_xml(text: str) -> list[ToolCall]: calls: list[ToolCall] = [] for block in _XML_CALL.findall(text): inner = block.strip() if inner.startswith("{"): try: calls.extend(_call_from_object(json.loads(inner))) continue except ValueError: pass for name, body in _XML_FUNCTION.findall(inner or text): args = {key: _coerce(value) for key, value in _XML_PARAM.findall(body)} calls.append(ToolCall(name=canonical_name(name), args=args)) if not calls and " list[ToolCall]: calls: list[ToolCall] = [] for name, tail in _PLAIN_CALL.findall(text): args: dict[str, Any] = {} for chunk in (tail or "").split("|")[1:]: if "=" in chunk: key, value = chunk.split("=", 1) args[key.strip().strip("`\"'")] = _coerce(value.strip().strip("`\"'")) elif chunk.strip(): args.setdefault("value", _coerce(chunk.strip())) calls.append(ToolCall(name=canonical_name(name), args=args)) return calls def _extract_bare_json_args(text: str) -> list[ToolCall]: """A model may answer with arguments only, e.g. {"expression": "45+12"}.""" out: list[ToolCall] = [] for match in _JSON_BLOB.finditer(text): try: obj = json.loads(match.group(0)) except ValueError: continue if not isinstance(obj, Mapping) or not obj: continue keys = {str(key) for key in obj} matches = [ spec.name for spec in REGISTRY.values() if set(spec.required) <= keys and keys <= set(spec.parameters) ] if len(matches) == 1: out.append(ToolCall(name=matches[0], args={str(k): _coerce(v) for k, v in obj.items()})) return out _STRATEGIES: tuple[tuple[str, Callable[[str], list[ToolCall]]], ...] = ( ("xml", _extract_xml), ("json", _extract_json), ("plain", _extract_plain), ("bare_args", _extract_bare_json_args), ) def parse_output(raw: str) -> ParseResult: text = strip_thinking(raw or "") searched: Sequence[str] = (text, *[m.group(1) for m in _FENCE.finditer(text)]) for source, extractor in _STRATEGIES: for candidate in searched: found = extractor(candidate) if found: return ParseResult(calls=tuple(found), source=source) markers = (" str: """Model output with thinking blocks and call payloads removed.""" text = strip_thinking(raw or "") text = _XML_CALL.sub(" ", text) text = re.sub(r"|$)", " ", text, flags=re.S | re.I) text = _PLAIN_CALL_ANY.sub(" ", text) text = _FENCE.sub(lambda m: m.group(1) if not m.group(1).strip().startswith("{") else " ", text) for match in list(_JSON_BLOB.finditer(text)): try: obj = json.loads(match.group(0)) except ValueError: continue if isinstance(obj, Mapping) and ({"name", "tool_calls", "function"} & set(obj)) : text = text[: match.start()] + " " + text[match.end() :] return re.sub(r"\s+", " ", text).strip() def iter_call_signatures(calls: Iterable[ToolCall]) -> list[str]: return [call.canonical() for call in calls]