Spaces:
Running on Zero

checkjson / checkjson /common.py
himanshu5trpth's picture
Upload 38 files
664563f verified
Raw History Blame Contribute Delete
5.79 kB
"""Shared JSON and schema helpers: strict parsing, tool-schema validation, $ref inlining."""
import json
from functools import lru_cache
from jsonschema import Draft7Validator, FormatChecker
def dumps(value):
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False, sort_keys=True)
def strict_loads(text):
def constant(value):
raise ValueError(f"Non-JSON constant: {value}")
def unique_keys(pairs):
obj = {}
for key, value in pairs:
if key in obj:
raise ValueError(f"Duplicate JSON key: {key}")
obj[key] = value
return obj
return json.loads(text, parse_constant=constant, object_pairs_hook=unique_keys)
@lru_cache(maxsize=8192)
def validator(schema_text):
schema = strict_loads(schema_text)
Draft7Validator.check_schema(schema)
return Draft7Validator(schema, format_checker=FormatChecker())
def escape(part):
return str(part).replace("~", "~0").replace("/", "~1")
def validate_payload(payload, tools):
errors = []
registry = {t["name"]: t for t in tools}
if len(registry) != len(tools):
raise ValueError("duplicate_tool_names")
if not isinstance(payload, dict) or not isinstance(payload.get("turns"), list):
return [{"code": "invalid_call", "path": ""}]
for ti, turn in enumerate(payload["turns"]):
if not isinstance(turn, dict) or not isinstance(turn.get("calls"), list):
errors.append({"code": "invalid_call", "path": f"/turns/{ti}"})
continue
for ci, call in enumerate(turn["calls"]):
prefix = f"/turns/{ti}/calls/{ci}"
if not isinstance(call, dict) or not isinstance(call.get("name"), str) or "arguments" not in call:
errors.append({"code": "invalid_call", "path": prefix})
continue
if call["name"] not in registry:
errors.append({"code": "unknown_func", "path": prefix + "/name"})
continue
if not isinstance(call["arguments"], dict):
errors.append({"code": "invalid_call", "path": prefix + "/arguments"})
continue
schema = registry[call["name"]]["parameters"]
for error in validator(dumps(schema)).iter_errors(call["arguments"]):
code = {"required": "missing_args", "additionalProperties": "unexpected_args",
"type": "invalid_arg_type"}.get(error.validator, "invalid_arg_value")
errors.append({"code": code, "path": prefix + "/arguments" + "".join("/" + escape(x) for x in error.absolute_path),
"rule": error.validator, "reason": error.message[:250]})
return errors
ENVELOPE = Draft7Validator({"type": "object", "required": ["turns"], "additionalProperties": False,
"properties": {"turns": {"type": "array", "minItems": 1, "items": {
"type": "object", "required": ["calls"], "additionalProperties": False,
"properties": {"calls": {"type": "array", "items": {
"type": "object", "required": ["name", "arguments"], "additionalProperties": False,
"properties": {"name": {"type": "string"}, "arguments": {"type": "object"}}}}}}}}})
def check_payload(payload, tools):
"""Every envelope and schema error in a payload; an empty list means the calls are valid."""
errors = [{"code": "invalid_envelope", "path": "/" + "/".join(map(str, e.absolute_path)),
"reason": e.message[:250]} for e in ENVELOPE.iter_errors(payload)]
return errors + validate_payload(payload, tools)
def inline_refs(schema):
"""The schema with its local references ("#/$defs/X", "#/definitions/X") written out in place.
A reference it cannot resolve, or one that points back into itself, becomes an unconstrained value."""
if not isinstance(schema, dict):
return schema
defs = {**(schema.get("definitions") or {}), **(schema.get("$defs") or {})}
def walk(node, seen):
if isinstance(node, list):
return [walk(n, seen) for n in node]
if not isinstance(node, dict):
return node
ref = node.get("$ref")
rest = {k: walk(v, seen) for k, v in node.items() if k != "$ref"}
if not isinstance(ref, str):
return rest
name = ref.rsplit("/", 1)[-1]
if ref.startswith("#/") and name in defs and name not in seen:
return {**walk(defs[name], seen | {name}), **rest}
return rest
return walk({k: v for k, v in schema.items() if k not in ("$defs", "definitions")}, frozenset())
def with_inlined_refs(tool):
params = tool.get("parameters")
if isinstance(params, dict) and ("$defs" in params or "definitions" in params or '"$ref"' in json.dumps(params)):
return {**tool, "parameters": inline_refs(params)}
return tool
def messages_from_input(data):
"""The context and the request as an ordered list of messages."""
messages = []
def visit(value, origin):
if isinstance(value, list):
for part in value:
visit(part, origin)
elif value:
if isinstance(value, dict) and isinstance(value.get("content"), str):
messages.append({"message_id": f"m{len(messages)}", "origin": origin,
"text": value["content"],
"metadata": {k: v for k, v in value.items() if k != "content"}})
else:
messages.append({"message_id": f"m{len(messages)}", "origin": origin,
"text": value if isinstance(value, str) else dumps(value)})
visit(data.get("context"), "context")
visit(data.get("request"), "request")
return messages