​call_me_maybe /
src / io_utils.py
52 commits
12-08-2026
133 lines 4.0 kB
  1"""Reading the two input files and writing the results file.
  2
  3A problem with a whole file is fatal and raises. A problem with one entry is
  4not: it is reported on stderr and the entry is skipped.
  5"""
  6
  7import json
  8import sys
  9from pathlib import Path
 10from typing import Any, List, Sequence
 11
 12from pydantic import ValidationError
 13
 14from .models import FunctionCall, FunctionDefinition, PromptEntry
 15
 16
 17class InputError(Exception):
 18    """Raised when an input file cannot be read or is not a JSON array."""
 19
 20
 21class OutputError(Exception):
 22    """Raised when the results file cannot be written."""
 23
 24
 25def warn(message: str) -> None:
 26    """Report a non-fatal problem on stderr.
 27
 28    Args:
 29        message: The text to show.
 30    """
 31    print(f"warning: {message}", file=sys.stderr)
 32
 33
 34def load_json_array(path: Path, kind: str) -> List[Any]:
 35    """Read a file that must hold a JSON array.
 36
 37    Args:
 38        path: The file to read.
 39        kind: How to name the file in error messages.
 40
 41    Returns:
 42        The entries of the array.
 43
 44    Raises:
 45        InputError: If the file cannot be read, is not JSON, or is not an array.
 46    """
 47    try:
 48        payload = json.loads(path.read_text(encoding="utf-8"))
 49    except OSError as error:
 50        raise InputError(f"{kind} file could not be read: {path} ({error})") from None
 51    except (json.JSONDecodeError, UnicodeDecodeError) as error:
 52        raise InputError(f"{kind} file is not valid JSON: {path} ({error})") from None
 53
 54    if not isinstance(payload, list):
 55        raise InputError(f"{kind} file must hold a JSON array: {path}")
 56    return payload
 57
 58
 59def load_function_definitions(path: Path) -> List[FunctionDefinition]:
 60    """Load the functions the model may choose from.
 61
 62    Args:
 63        path: The functions definition file.
 64
 65    Returns:
 66        The usable definitions, in file order.
 67
 68    Raises:
 69        InputError: If the file holds no usable definition.
 70    """
 71    definitions: List[FunctionDefinition] = []
 72    for index, entry in enumerate(load_json_array(path, "functions definition")):
 73        try:
 74            definitions.append(FunctionDefinition.model_validate(entry))
 75        except ValidationError as error:
 76            warn(f"skipping function definition {index} in {path}: {_first_problem(error)}")
 77
 78    if not definitions:
 79        raise InputError(f"no usable function definition in {path}")
 80    return definitions
 81
 82
 83def load_prompts(path: Path) -> List[str]:
 84    """Load the requests to answer.
 85
 86    Args:
 87        path: The prompts file.
 88
 89    Returns:
 90        The prompts, in file order.
 91
 92    Raises:
 93        InputError: If the file cannot be read.
 94    """
 95    prompts: List[str] = []
 96    for index, entry in enumerate(load_json_array(path, "prompts")):
 97        try:
 98            prompts.append(PromptEntry.model_validate(entry).prompt)
 99        except ValidationError as error:
100            warn(f"skipping prompt {index} in {path}: {_first_problem(error)}")
101    return prompts
102
103
104def write_results(path: Path, results: Sequence[FunctionCall]) -> None:
105    """Write every answer as one JSON array, creating the directory if needed.
106
107    Args:
108        path: The results file to write.
109        results: One call per prompt.
110
111    Raises:
112        OutputError: If the file cannot be written.
113    """
114    try:
115        path.parent.mkdir(parents=True, exist_ok=True)
116        payload = json.dumps([result.model_dump() for result in results], indent=2, ensure_ascii=False)
117        path.write_text(payload + "\n", encoding="utf-8")
118    except OSError as error:
119        raise OutputError(f"results file could not be written: {path} ({error})") from None
120
121
122def _first_problem(error: ValidationError) -> str:
123    """Condense a validation error into one line.
124
125    Args:
126        error: The error raised while validating one entry.
127
128    Returns:
129        A short "field: message" description of the first problem.
130    """
131    first = error.errors()[0]
132    field = ".".join(str(part) for part in first["loc"]) or "entry"
133    return f"{field}: {first['msg']}"