Spaces:
Sleeping
Sleeping
File size: 25,036 Bytes
f45a595 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 | """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"<tool_calls>\s*(.*?)\s*</tool_calls>", re.DOTALL)
_SINGLE_XML_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
_NATIVE_MARKERS = ("<|tool_call:", "<tool_calls>", "<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 <tool_calls> 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 <tool_call> 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
|