Types¶
alloy.types ¶
to_json_schema ¶
to_json_schema(tp, strict=True)
Best-effort JSON Schema generator for output types.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp
|
Any
|
The type to convert to JSON schema |
required |
strict
|
bool
|
If True (default), all fields are required (for structured outputs). If False, fields with defaults are optional (for tool parameters). |
True
|
Supports primitives, dataclasses (with postponed annotations), and nested lists/dicts. Falls back to None for complex generics/Unions so callers can avoid forcing a schema when not strictly necessary.
parse_output ¶
parse_output(tp, raw)
Parse model output into the requested type.
Attempts JSON decoding first, then recursively coerces to the requested type.
to_jsonable ¶
to_jsonable(value)
Convert a Python value to a JSON‑serializable structure.
Supports dataclasses (converted via asdict) and recursively normalizes dict, list, and tuple containers. Leaves primitives and strings as is.
flatten_property_paths ¶
flatten_property_paths(schema)
Return dotted property paths for all properties in an object schema.
Arrays of objects use the segment "[*]" to indicate any index.
Usage¶
from dataclasses import dataclass
from alloy import command
@dataclass
class Person:
name: str
email: str
@command(output=Person)
def extract_person(text: str) -> str:
return f"Extract name and email from: {text}"
print(extract_person("Ada, ada@example.com"))
TypedDict outputs
from typing import TypedDict
from alloy import command
class Product(TypedDict):
name: str
price: float
@command(output=Product)
def make() -> str:
return "Return a Product with name='Test' and price=9.99 (numeric literal)."
out = make()
assert isinstance(out, dict)
Validation errors
from alloy import CommandError
try:
extract_person("Incomplete data") # may raise if schema cannot be satisfied
except CommandError as e:
print("Parse failed:", e)
See also
- Guide → Structured Outputs: guide/structured-outputs.md