"""Prompt-level OpenAI function-call adapter for the Upstage demo transport. Upstage's public Chat API supports native tools, but the anonymous Console demo endpoint used by ``upstage_provider.py`` currently ignores ``tools`` and ``tool_choice``. Solar itself understands a stable tool-call wire format. This module exposes that format carefully, parses it, validates arguments against the client's JSON Schema, and converts it back to standard OpenAI ``tool_calls``. """ from __future__ import annotations import json import re import uuid from dataclasses import dataclass from typing import Any from jsonschema import ValidationError from jsonschema.validators import validator_for _NATIVE_RE = re.compile( r"<\|tool_call:begin\|>(.*?)" r"<\|tool_call:name\|>(.*?)" r"<\|tool_call:args\|>(.*?)" r"<\|tool_call:end\|>", re.DOTALL, ) _XML_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) _SINGLE_XML_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) _NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") _NATIVE_MARKERS = ("<|tool_call:", "", "") class ToolProtocolError(ValueError): """A request or generated tool call violates the gateway protocol.""" def __init__(self, message: str, *, param: str = "tools", code: str = "invalid_tools"): super().__init__(message) self.param = param self.code = code @dataclass(frozen=True) class ToolSpec: name: str description: str parameters: dict[str, Any] def prompt_dict(self) -> dict[str, Any]: return { "name": self.name, "description": self.description, "parameters": self.parameters, } @dataclass(frozen=True) class ParsedToolCall: name: str arguments: dict[str, Any] id: str @classmethod def create(cls, name: str, arguments: dict[str, Any]) -> "ParsedToolCall": return cls(name=name, arguments=arguments, id=f"call_{uuid.uuid4().hex[:24]}") def as_openai(self) -> dict[str, Any]: return { "id": self.id, "type": "function", "function": { "name": self.name, "arguments": json.dumps( self.arguments, ensure_ascii=False, separators=(",", ":") ), }, } @dataclass(frozen=True) class ToolConfiguration: tools: tuple[ToolSpec, ...] choice: str # none | auto | required | specific required_name: str | None parallel: bool @property def enabled(self) -> bool: return bool(self.tools) and self.choice != "none" @property def must_call(self) -> bool: return self.choice in {"required", "specific"} def parse_tool_configuration(payload: dict[str, Any]) -> ToolConfiguration: """Validate OpenAI ``tools``/``tool_choice`` (and legacy functions).""" raw_tools = payload.get("tools") if raw_tools is None and payload.get("functions") is not None: raw_functions = payload.get("functions") if not isinstance(raw_functions, list): raise ToolProtocolError("'functions' must be an array.", param="functions") raw_tools = [{"type": "function", "function": item} for item in raw_functions] if raw_tools is None: raw_tools = [] if not isinstance(raw_tools, list): raise ToolProtocolError("'tools' must be an array.") if len(raw_tools) > 128: raise ToolProtocolError("At most 128 function tools are supported.") specs: list[ToolSpec] = [] names: set[str] = set() for index, raw in enumerate(raw_tools): param = f"tools[{index}]" if not isinstance(raw, dict) or raw.get("type", "function") != "function": raise ToolProtocolError( "Only tools with type 'function' are supported.", param=param ) fn = raw.get("function") if not isinstance(fn, dict): raise ToolProtocolError("A function object is required.", param=f"{param}.function") name = fn.get("name") if not isinstance(name, str) or not _NAME_RE.fullmatch(name): raise ToolProtocolError( "Function names must be 1-128 letters, digits, underscores, or hyphens.", param=f"{param}.function.name", ) if name in names: raise ToolProtocolError(f"Duplicate function name '{name}'.", param=param) names.add(name) description = fn.get("description", "") if description is None: description = "" if not isinstance(description, str): raise ToolProtocolError( "Function description must be a string.", param=f"{param}.function.description", ) parameters = fn.get("parameters", {"type": "object"}) if not isinstance(parameters, dict): raise ToolProtocolError( "Function parameters must be a JSON Schema object.", param=f"{param}.function.parameters", ) specs.append(ToolSpec(name, description[:4000], parameters)) raw_choice = payload.get("tool_choice", payload.get("function_call")) required_name: str | None = None if raw_choice is None: choice = "auto" if specs else "none" elif isinstance(raw_choice, str): aliases = {"any": "required"} choice = aliases.get(raw_choice, raw_choice) if choice not in {"none", "auto", "required"}: # Legacy function_call may be a function name string. if choice in names: required_name = choice choice = "specific" else: raise ToolProtocolError( "'tool_choice' must be 'none', 'auto', 'required', or a function object.", param="tool_choice", ) elif isinstance(raw_choice, dict): fn = raw_choice.get("function", raw_choice) required_name = fn.get("name") if isinstance(fn, dict) else None if not isinstance(required_name, str) or required_name not in names: raise ToolProtocolError( "The forced function in 'tool_choice' is not present in 'tools'.", param="tool_choice", ) choice = "specific" else: raise ToolProtocolError("Invalid 'tool_choice'.", param="tool_choice") if choice in {"auto", "required", "specific"} and not specs: raise ToolProtocolError( "'tool_choice' requires at least one function tool.", param="tool_choice" ) parallel = payload.get("parallel_tool_calls", True) if not isinstance(parallel, bool): raise ToolProtocolError( "'parallel_tool_calls' must be a boolean.", param="parallel_tool_calls" ) return ToolConfiguration(tuple(specs), choice, required_name, parallel) def build_tool_instruction(config: ToolConfiguration) -> str: """Create a bounded, explicit protocol instruction understood by Solar.""" if not config.enabled: return "" if config.choice == "specific": choice_text = ( f"You MUST request the function {config.required_name!r}. " "Do not choose another function and do not answer in prose." ) elif config.choice == "required": choice_text = ( "You MUST request at least one listed function. Do not answer in prose." ) else: choice_text = ( "Request a function when it is useful or necessary. If no function is " "needed, answer the user normally in prose." ) parallel_text = ( "You may emit several consecutive calls when they are independent." if config.parallel else "Emit at most one function call." ) catalog = json.dumps( [tool.prompt_dict() for tool in config.tools], ensure_ascii=False, separators=(",", ":"), ) return f""" TOOL GATEWAY PROTOCOL (highest priority for response formatting) You can request the functions listed below. Never claim that you cannot use tools. {choice_text} {parallel_text} For every function request, emit exactly this format (without Markdown fences): <|tool_call:begin|>call_id<|tool_call:name|>FUNCTION_NAME<|tool_call:args|>{{"argument":"value"}}<|tool_call:end|> The args section MUST be one valid JSON object conforming to that function's schema. For multiple calls, concatenate complete call blocks. A response containing calls must contain only call blocks, with no prose before or after. Never narrate that you will, should, or need to call a tool: emit the call block immediately instead. For coding tasks, reading, writing, editing, searching, or running workspace content requires the matching function when one is listed. Tool results from earlier calls are labelled TOOL RESULT in the conversation; use them to continue the task. AVAILABLE FUNCTIONS: {catalog} END TOOL GATEWAY PROTOCOL """.strip() def _content_to_text(content: Any, *, param: str) -> str: if content is None: return "" if isinstance(content, str): return content if not isinstance(content, list): raise ToolProtocolError( "Message content must be a string or an array of text parts.", param=param, code="invalid_messages", ) parts: list[str] = [] for index, part in enumerate(content): if isinstance(part, str): parts.append(part) continue if not isinstance(part, dict): raise ToolProtocolError( "Message content parts must be objects.", param=f"{param}[{index}]", code="invalid_messages", ) kind = part.get("type") if kind in {"text", "input_text", "output_text"}: text = part.get("text", "") if not isinstance(text, str): raise ToolProtocolError( "Text content must be a string.", param=f"{param}[{index}].text", code="invalid_messages", ) parts.append(text) else: raise ToolProtocolError( f"Content part type {kind!r} is not supported by this text-only transport.", param=f"{param}[{index}].type", code="unsupported_content_type", ) return "\n".join(part for part in parts if part) def _existing_tool_call_wire(tool_calls: Any) -> tuple[str, dict[str, str]]: if tool_calls is None: return "", {} if not isinstance(tool_calls, list): raise ToolProtocolError( "Assistant 'tool_calls' must be an array.", param="messages.tool_calls", code="invalid_messages", ) blocks: list[str] = [] call_names: dict[str, str] = {} for item in tool_calls: if not isinstance(item, dict) or item.get("type", "function") != "function": raise ToolProtocolError( "Only assistant function tool calls are supported.", param="messages.tool_calls", code="invalid_messages", ) fn = item.get("function") name = fn.get("name") if isinstance(fn, dict) else None arguments = fn.get("arguments", "{}") if isinstance(fn, dict) else "{}" if not isinstance(name, str) or not _NAME_RE.fullmatch(name): raise ToolProtocolError( "Assistant tool call has an invalid function name.", param="messages.tool_calls.function.name", code="invalid_messages", ) if isinstance(arguments, dict): arguments = json.dumps(arguments, ensure_ascii=False, separators=(",", ":")) if not isinstance(arguments, str): raise ToolProtocolError( "Assistant tool arguments must be a JSON string or object.", param="messages.tool_calls.function.arguments", code="invalid_messages", ) call_id = item.get("id") if not isinstance(call_id, str) or not call_id: call_id = f"call_{uuid.uuid4().hex[:24]}" call_names[call_id] = name blocks.append( f"<|tool_call:begin|>{call_id}<|tool_call:name|>{name}" f"<|tool_call:args|>{arguments}<|tool_call:end|>" ) return "".join(blocks), call_names def normalize_messages( raw_messages: Any, tool_instruction: str = "" ) -> list[dict[str, str]]: """Convert OpenAI system/developer/tool turns to demo-supported text turns.""" if not isinstance(raw_messages, list) or not raw_messages: raise ToolProtocolError( "'messages' must be a non-empty array.", param="messages", code="invalid_messages", ) system_parts: list[str] = [] turns: list[dict[str, str]] = [] known_call_names: dict[str, str] = {} for index, message in enumerate(raw_messages): param = f"messages[{index}]" if not isinstance(message, dict): raise ToolProtocolError( "Every message must be an object.", param=param, code="invalid_messages" ) role = message.get("role") if role not in {"system", "developer", "user", "assistant", "tool", "function"}: raise ToolProtocolError( f"Unsupported message role {role!r}.", param=f"{param}.role", code="invalid_messages", ) content = _content_to_text(message.get("content"), param=f"{param}.content") if role in {"system", "developer"}: if content: label = "DEVELOPER" if role == "developer" else "SYSTEM" system_parts.append(f"[{label}]\n{content}") elif role == "assistant": wire, names = _existing_tool_call_wire(message.get("tool_calls")) known_call_names.update(names) combined = content if wire: combined = f"{combined}\n{wire}" if combined else wire turns.append({"role": "assistant", "content": combined}) elif role in {"tool", "function"}: call_id = message.get("tool_call_id", "") name = message.get("name") or known_call_names.get(str(call_id), "unknown") turns.append( { "role": "user", "content": ( f"TOOL RESULT\ncall_id: {call_id}\nfunction: {name}\n" f"result:\n{content}\nEND TOOL RESULT" ), } ) else: turns.append({"role": "user", "content": content}) if tool_instruction: system_parts.append(tool_instruction) if system_parts: turns.insert(0, {"role": "system", "content": "\n\n".join(system_parts)}) if not any(turn["role"] == "user" for turn in turns): raise ToolProtocolError( "At least one user or tool-result message is required.", param="messages", code="invalid_messages", ) return turns def _coerce_call(item: Any) -> tuple[str, dict[str, Any]]: if not isinstance(item, dict): raise ToolProtocolError( "Generated tool call must be a JSON object.", code="invalid_tool_output" ) fn = item.get("function") if isinstance(item.get("function"), dict) else item name = fn.get("name") arguments = fn.get("arguments", fn.get("args")) if isinstance(arguments, str): try: arguments = json.loads(arguments) except json.JSONDecodeError as exc: raise ToolProtocolError( f"Generated arguments for {name!r} are not valid JSON: {exc.msg}.", code="invalid_tool_output", ) from exc if not isinstance(name, str) or not isinstance(arguments, dict): raise ToolProtocolError( "Generated tool call needs a function name and a JSON-object arguments value.", code="invalid_tool_output", ) return name.strip(), arguments def _append_missing_json_closers(text: str) -> str | None: """Append only missing ``}``/``]`` delimiters to truncated JSON.""" stack: list[str] = [] in_string = False escaped = False pairs = {"}": "{", "]": "["} for character in text: if in_string: if escaped: escaped = False elif character == "\\": escaped = True elif character == '"': in_string = False continue if character == '"': in_string = True elif character in "{[": stack.append(character) elif character in "}]": if not stack or stack[-1] != pairs[character]: return None stack.pop() if in_string or escaped: return None closers = "".join("}" if opener == "{" else "]" for opener in reversed(stack)) return text + closers def _repair_tool_json(text: str) -> Any | None: """Apply bounded repairs seen in Solar's narrated JSON fallback.""" variants = [text] # Solar occasionally double-escapes an arguments object as though it were # itself a JSON string. Try removing exactly one escape layer. collapsed = text.replace("\\\\", "\\") if collapsed != text: variants.append(collapsed) for variant in variants: closed = _append_missing_json_closers(variant) if closed is None: continue try: return json.loads(closed) except json.JSONDecodeError: continue return None def _json_candidates(text: str) -> list[Any]: candidates: list[Any] = [] xml_matches = list(_XML_RE.finditer(text)) single_matches = list(_SINGLE_XML_RE.finditer(text)) for match in xml_matches: try: candidates.append(json.loads(match.group(1))) except json.JSONDecodeError as exc: raise ToolProtocolError( f"Generated payload is invalid JSON: {exc.msg}.", code="invalid_tool_output", ) from exc for match in single_matches: try: candidates.append(json.loads(match.group(1))) except json.JSONDecodeError as exc: raise ToolProtocolError( f"Generated payload is invalid JSON: {exc.msg}.", code="invalid_tool_output", ) from exc if candidates: residue = _XML_RE.sub("", text) residue = _SINGLE_XML_RE.sub("", residue).strip() if residue: raise ToolProtocolError( "Generated tool calls contained prose outside the call blocks.", code="invalid_tool_output", ) return candidates stripped = text.strip() if stripped.startswith(("{", "[")): try: value = json.loads(stripped) except json.JSONDecodeError as exc: tool_shaped = '"name"' in stripped and ( '"arguments"' in stripped or '"args"' in stripped ) value = _repair_tool_json(stripped) if tool_shaped else None if value is None: if tool_shaped: raise ToolProtocolError( f"Generated tool-call JSON is malformed: {exc.msg}.", code="invalid_tool_output", ) from exc return [] # Do not misclassify an ordinary JSON answer as a tool call. if isinstance(value, dict) and ( "tool_calls" in value or ("name" in value and ("arguments" in value or "args" in value)) ): candidates.append(value.get("tool_calls", value)) elif isinstance(value, list) and value and all( isinstance(x, dict) and "name" in x for x in value ): candidates.append(value) return candidates def parse_embedded_tool_calls( text: str, config: ToolConfiguration ) -> list[ParsedToolCall]: """Recover the last schema-valid call JSON from narrated model output. This is intentionally separate from the strict parser. The gateway invokes it only after a narrow detector confirms that Solar is narrating an intended call. It lets a coding turn recover when the model writes the correct call JSON after phrases such as "I will call the tool", while ordinary JSON answers stay text. """ decoder = json.JSONDecoder() candidates: list[Any] = [] for index, character in enumerate(text): if character not in "{[": continue try: value, _ = decoder.raw_decode(text[index:]) except json.JSONDecodeError: continue if isinstance(value, dict) and ( "tool_calls" in value or ("name" in value and ("arguments" in value or "args" in value)) ): candidates.append(value) elif isinstance(value, list) and value and all( isinstance(item, dict) and "name" in item for item in value ): candidates.append(value) # The final object is normally the model's actual proposed call; earlier # objects are often examples copied while it reasons about the protocol. for candidate in reversed(candidates): try: return parse_generated_tool_calls( json.dumps(candidate, ensure_ascii=False, separators=(",", ":")), config, ) except ToolProtocolError: continue return [] def parse_generated_tool_calls( text: str, config: ToolConfiguration ) -> list[ParsedToolCall]: """Parse and schema-check Solar output, returning OpenAI-ready calls.""" if not config.enabled: return [] raw_calls: list[tuple[str, dict[str, Any]]] = [] native_matches = list(_NATIVE_RE.finditer(text)) for match in native_matches: name = match.group(2).strip() try: arguments = json.loads(match.group(3).strip()) except json.JSONDecodeError as exc: raise ToolProtocolError( f"Generated arguments for {name!r} are not valid JSON: {exc.msg}.", code="invalid_tool_output", ) from exc if not isinstance(arguments, dict): raise ToolProtocolError( f"Generated arguments for {name!r} must be a JSON object.", code="invalid_tool_output", ) raw_calls.append((name, arguments)) if native_matches and _NATIVE_RE.sub("", text).strip(): raise ToolProtocolError( "Generated tool calls contained prose outside the call blocks.", code="invalid_tool_output", ) if not raw_calls: for value in _json_candidates(text): items = value if isinstance(value, list) else [value] raw_calls.extend(_coerce_call(item) for item in items) if not raw_calls: if any(marker in text for marker in _NATIVE_MARKERS): raise ToolProtocolError( "The model emitted an incomplete tool-call block.", code="invalid_tool_output", ) return [] by_name = {tool.name: tool for tool in config.tools} parsed: list[ParsedToolCall] = [] for name, arguments in raw_calls: if config.required_name and name != config.required_name: raise ToolProtocolError( f"The model requested {name!r}; {config.required_name!r} was forced.", code="invalid_tool_output", ) spec = by_name.get(name) if spec is None: raise ToolProtocolError( f"The model requested unknown function {name!r}.", code="invalid_tool_output", ) try: validator_cls = validator_for(spec.parameters) validator_cls.check_schema(spec.parameters) validator_cls(spec.parameters).validate(arguments) except ValidationError as exc: path = ".".join(str(part) for part in exc.absolute_path) where = f" at {path}" if path else "" raise ToolProtocolError( f"Arguments for {name!r} fail its JSON Schema{where}: {exc.message}", code="invalid_tool_output", ) from exc except Exception: # Some clients send permissive vendor JSON-Schema dialects. Do not # reject a model call solely because the schema itself is unknown. pass parsed.append(ParsedToolCall.create(name, arguments)) if not config.parallel and len(parsed) > 1: raise ToolProtocolError( "The model emitted multiple calls while parallel_tool_calls is false.", code="invalid_tool_output", ) return parsed