schemez
Class info¶
Re-exported classes¶
| Class | Module | Description |
|---|---|---|
| ConfigSchema | schemez.schema | Schema for configuration objects that may declare required packages. |
| ExecutableFunction | schemez.functionschema.executable | Wrapper for executing functions with different calling patterns. |
| FunctionSchema | schemez.functionschema.functionschema | Schema representing an OpenAI function definition and metadata. |
| ImportedSchemaDef | schemez.schemadef.schemadef | Response definition that imports an existing Pydantic model. |
| InlineSchemaDef | schemez.schemadef.schemadef | Inline definition of schema. |
| JSONCode | schemez.code | JSON with syntax validation. |
| ModelStore | schemez.storage.model_store | Type-safe async SQLite storage for Pydantic models. |
| OpenAIFunctionDefinition | schemez.functionschema.typedefs | Schema for the function definition part of an OpenAI tool. |
| OpenAIFunctionTool | schemez.functionschema.typedefs | Complete OpenAI tool definition for function calling. |
| PythonCode | schemez.code | Python with syntax validation. |
| Schema | schemez.schema | Base class for configuration models. |
| SchemaField | schemez.schemadef.schemadef | Field definition for inline response types. |
| TOMLCode | schemez.code | TOML with syntax validation. |
| ToolCodeGenerator | schemez.code_generation.tool_code_generator | Generates code artifacts for a single tool. |
| ToolsetCodeGenerator | schemez.code_generation.toolset_code_generator | Generates code artifacts for multiple tools. |
| YAMLCode | schemez.code | YAML with syntax validation. |
🛈 DocStrings¶
Schemez: main package.
Pydantic shim for config stuff.
ConfigSchema
¶
ExecutableFunction
¶
Wrapper for executing functions with different calling patterns.
Source code in src/schemez/functionschema/executable.py
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 | |
__init__
¶
__init__(
schema: FunctionSchema,
func: (
Callable[..., T_co]
| Callable[..., Generator[T_co]]
| Callable[..., AsyncGenerator[T_co]]
| Callable[..., AsyncIterator[T_co]]
),
) -> None
Initialize with schema and function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
FunctionSchema
|
OpenAI function schema |
required |
func
|
Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]] | Callable[..., AsyncIterator[T_co]]
|
The actual function to execute |
required |
Source code in src/schemez/functionschema/executable.py
arun
async
¶
Run the function asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional arguments to pass to the function |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Returns:
| Type | Description |
|---|---|
T_co | list[T_co]
|
Function result or list of results for generators |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the function type is unknown |
Source code in src/schemez/functionschema/executable.py
astream
async
¶
Stream results from the function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional arguments to pass to the function |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[T_co]
|
Individual results as they become available |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the function type is unknown |
Source code in src/schemez/functionschema/executable.py
run
¶
Run the function synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional arguments to pass to the function |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Returns:
| Type | Description |
|---|---|
T_co | list[T_co]
|
Either a single result or list of results for generators |
Inside a running event loop, coroutines run on a worker thread's own loop
(blocking the caller); use arun from async code.
Source code in src/schemez/functionschema/executable.py
FunctionSchema
¶
Bases: BaseModel
Schema representing an OpenAI function definition and metadata.
This class encapsulates all the necessary information to describe a function to the OpenAI API, including its name, description, parameters, return type, and execution characteristics. It follows the OpenAI function calling format while adding additional metadata useful for Python function handling.
Source code in src/schemez/functionschema/functionschema.py
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 | |
description
class-attribute
instance-attribute
¶
Optional description of what the function does.
name
instance-attribute
¶
The name of the function as it will be presented to the OpenAI API.
parameters
class-attribute
instance-attribute
¶
parameters: ToolParameters = pydantic.Field(
default_factory=lambda: ToolParameters(type="object", properties={}, required=[])
)
JSON Schema object describing the function's parameters.
required
class-attribute
instance-attribute
¶
List of parameter names that are required (do not have default values).
returns
class-attribute
instance-attribute
¶
JSON Schema object describing the function's return type.
create_parameter_model
¶
Create a Pydantic model from the schema parameters.
Source code in src/schemez/functionschema/functionschema.py
from_dict
classmethod
¶
from_dict(schema: Mapping[str, Any], output_schema: dict[str, Any] | None = None) -> FunctionSchema
Create a FunctionSchema from a raw schema dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
Mapping[str, Any]
|
OpenAI function schema dictionary (also an |
required |
output_schema
|
dict[str, Any] | None
|
Optional dictionary specifying the return type. If not provided, an object type will be set. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If schema format is invalid or missing required fields |
Source code in src/schemez/functionschema/functionschema.py
get_annotations
¶
Get a dictionary of parameter names to their Python types.
This can be used directly for annotations assignment.
Returns:
| Type | Description |
|---|---|
dict[str, type[Any]]
|
Dictionary mapping parameter names to their Python types. |
Source code in src/schemez/functionschema/functionschema.py
model_dump_openai
¶
model_dump_openai() -> OpenAIFunctionTool
Convert the schema to OpenAI's function calling format.
Returns:
| Type | Description |
|---|---|
OpenAIFunctionTool
|
A dictionary matching OpenAI's complete function tool definition format. |
OpenAIFunctionTool
|
{"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}} |
Source code in src/schemez/functionschema/functionschema.py
to_parameter_model_code
¶
Generate Pydantic model code for parameters using datamodel-codegen.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
class_name
|
str | None
|
Name for the generated class (default: {name}Params) |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Generated Python code string |
Source code in src/schemez/functionschema/functionschema.py
to_python_signature
¶
Convert the schema back to a Python function signature.
This method creates a Python function signature from the OpenAI schema, mapping JSON schema types back to their Python equivalents.
Source code in src/schemez/functionschema/functionschema.py
to_return_model_code
¶
Generate Pydantic model code for return type using datamodel-codegen.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
class_name
|
str | None
|
Name for the generated class (default: {name}Response) |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Generated Python code string |
Source code in src/schemez/functionschema/functionschema.py
ImportedSchemaDef
¶
Bases: BaseSchemaDef
Response definition that imports an existing Pydantic model.
Allows using externally defined Pydantic models as response types. Benefits: - Reuse existing model definitions - Full Python type support - Complex validation logic - IDE support for imported types
Example
responses: AnalysisResult: type: import import_path: myapp.models.AnalysisResult
Source code in src/schemez/schemadef/schemadef.py
import_path
class-attribute
instance-attribute
¶
import_path: str = Field(
title="Import path",
examples=["myapp.models.User", "schemas.api:ResponseModel", "models.core.BaseResponse"],
)
The path to the pydantic model to use as the response type.
type
class-attribute
instance-attribute
¶
Import-path based response definition.
get_schema
¶
get_schema() -> type[BaseModel]
Import and return the model class.
Source code in src/schemez/schemadef/schemadef.py
InlineSchemaDef
¶
Bases: BaseSchemaDef
Inline definition of schema.
Allows defining response types directly in the configuration using: - Field definitions with types and descriptions - Optional validation constraints - Custom field descriptions - Field dependencies and relationships
Example
type: inline fields: success: {type: bool, description: "Operation success"} message: {type: str, description: "Result details"} payment_method: {type: str, description: "Payment method used"} card_number: { type: str, description: "Credit card number", dependent_required: { "payment_method": ["card_expiry", "card_cvc"] } }
Source code in src/schemez/schemadef/schemadef.py
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 | |
fields
class-attribute
instance-attribute
¶
fields: dict[str, SchemaField] = Field(
title="Schema fields",
examples=[
{
"name": {"type": "str", "description": "User name"},
"age": {"type": "int", "description": "User age", "ge": 0},
}
],
)
A dictionary containing all fields.
type
class-attribute
instance-attribute
¶
Inline response definition.
add_field_dependency
¶
Add a dependency between fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
The field where to add the dependency |
required |
dependent_on
|
str
|
The field that triggers the dependency |
required |
required_fields
|
list[str]
|
Fields that become required when the dependency is triggered |
required |
Source code in src/schemez/schemadef/schemadef.py
add_schema_dependency
¶
Add a schema dependency between fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
The field where to add the dependency |
required |
dependent_on
|
str
|
The field that triggers the dependency |
required |
schema
|
dict[str, Any]
|
JSON Schema to apply when dependent_on exists |
required |
Source code in src/schemez/schemadef/schemadef.py
get_schema
¶
get_schema() -> type[BaseModel]
Create Pydantic model from inline definition.
Source code in src/schemez/schemadef/schemadef.py
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 | |
JSONCode
¶
Bases: BaseCode
JSON with syntax validation.
Source code in src/schemez/code.py
ModelStore
¶
Type-safe async SQLite storage for Pydantic models.
Can be initialized with a model type, or opened from an existing database that has the schema stored.
Example
class User(BaseModel):
name: str
age: int
email: str | None = None
# Create new database with known type
async with ModelStore(User, "users.db") as store:
user_id = await store.insert(User(name="Alice", age=30))
user = await store.get(user_id)
all_users = await store.all()
# Open existing database, reconstruct type from stored schema
async with await ModelStore.open("users.db") as store:
users = await store.all() # Returns reconstructed model instances
Source code in src/schemez/storage/model_store.py
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 | |
import_path
property
¶
Get the import path for the stored model, if available.
__aenter__
async
¶
Open connection and create/load table.
Source code in src/schemez/storage/model_store.py
__aexit__
async
¶
__aexit__(
exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: object
) -> None
Close connection.
Source code in src/schemez/storage/model_store.py
__init__
¶
__init__(
model_type: type[T] | None = None,
path: str | Path = ":memory:",
table_name: str | None = None,
) -> None
Initialize the model store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
|
type[T] | None
|
The Pydantic model class to store (required for new DBs) |
None
|
path
|
str | Path
|
SQLite database path (":memory:" for in-memory) |
':memory:'
|
table_name
|
str | None
|
Custom table name (defaults to lowercase model name) |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If model_type is None and path doesn't exist or is :memory: |
Source code in src/schemez/storage/model_store.py
all
async
¶
Fetch all model instances.
Returns:
| Type | Description |
|---|---|
list[T]
|
List of all model instances |
Source code in src/schemez/storage/model_store.py
count
async
¶
Count total rows in the table.
Returns:
| Type | Description |
|---|---|
int
|
Number of rows |
Source code in src/schemez/storage/model_store.py
delete
async
¶
Delete a model instance by id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row_id
|
int
|
The row id to delete |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if a row was deleted, False otherwise |
Source code in src/schemez/storage/model_store.py
get
async
¶
Fetch a model instance by id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row_id
|
int
|
The row id to fetch |
required |
Returns:
| Type | Description |
|---|---|
T | None
|
The model instance, or None if not found |
Source code in src/schemez/storage/model_store.py
insert
async
¶
Insert a model instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
The model instance to insert |
required |
Returns:
| Type | Description |
|---|---|
int
|
The inserted row's id |
Source code in src/schemez/storage/model_store.py
insert_many
async
¶
Insert multiple model instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instances
|
Sequence[T]
|
The model instances to insert |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
List of inserted row ids |
Source code in src/schemez/storage/model_store.py
open
async
classmethod
¶
open(path: str | Path) -> ModelStore[BaseModel]
Open an existing database and reconstruct the model from stored schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to existing SQLite database |
required |
Returns:
| Type | Description |
|---|---|
ModelStore[BaseModel]
|
ModelStore with reconstructed model type |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If database doesn't exist |
ValueError
|
If database has no stored schema |
Source code in src/schemez/storage/model_store.py
query
async
¶
Query instances with simple equality filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**filters
|
Any
|
Field-value pairs for WHERE clause (equality only) |
{}
|
Returns:
| Type | Description |
|---|---|
list[T]
|
List of matching model instances |
Source code in src/schemez/storage/model_store.py
OpenAIFunctionDefinition
¶
Bases: TypedDict
Schema for the function definition part of an OpenAI tool.
This represents the inner "function" object that contains the actual function metadata and parameters.
Source code in src/schemez/functionschema/typedefs.py
OpenAIFunctionTool
¶
Bases: TypedDict
Complete OpenAI tool definition for function calling.
This represents the top-level tool object that wraps a function definition and identifies it as a function tool type.
Source code in src/schemez/functionschema/typedefs.py
Schema
¶
Bases: BaseModel
Base class for configuration models.
Provides:
- Common Pydantic settings (extra="forbid", attribute docstrings as descriptions)
- YAML loading and dumping (optionally with field descriptions as comments)
- Markdown documentation, Python code and test data generation
- Model creation from functions, class constructors and JSON Schema
- Merging and sub-model iteration
Dumps (model_dump(), model_dump_json(), YAML) put the fields of the most derived
class first, then those of its bases. Pydantic itself orders base fields first, so a
wrap serializer reorders the keys of every dump, nested Schema instances included.
That makes dumps about 3x slower than a plain BaseModel (around 1.8 µs instead of
0.6 µs for a three-field model). This is deliberate: the order is what users read in
dumped configs; the key order per class is cached, the remaining cost is the Python-level
serializer call.
Source code in src/schemez/schema.py
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 | |
dump_markdown_schema
classmethod
¶
dump_markdown_schema(
*,
template: str | None = None,
header_level: int = 1,
include_defaults: bool = True,
include_examples: bool = True,
include_constraints: bool = True,
display_mode: Literal["table", "python_code", "yaml"] = "table",
mode: Literal["minimal", "maximal", "default"] = "default",
exclude_none: bool = True,
exclude_defaults: bool = False,
exclude_unset: bool = False,
indent: int = 2,
header_style: Literal["default", "pymdownx"] = "default",
serialization_mode: Literal["json", "python"] = "json"
) -> str
Dump model class schema to Markdown documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str | None
|
Custom Jinja2 template string (uses default if None) |
None
|
header_level
|
int
|
Starting header level (1 = h1, 2 = h2, etc.) |
1
|
include_defaults
|
bool
|
Include default values in the table |
True
|
include_examples
|
bool
|
Include examples section |
True
|
include_constraints
|
bool
|
Include constraints section |
True
|
display_mode
|
Literal['table', 'python_code', 'yaml']
|
Output format - "table", "python_code", or "yaml" |
'table'
|
mode
|
Literal['minimal', 'maximal', 'default']
|
Generation mode for YAML examples |
'default'
|
exclude_none
|
bool
|
Exclude None values from YAML |
True
|
exclude_defaults
|
bool
|
Exclude default values from YAML |
False
|
exclude_unset
|
bool
|
Exclude unset values from YAML |
False
|
indent
|
int
|
YAML indentation |
2
|
header_style
|
Literal['default', 'pymdownx']
|
Code block header style - "default" or "pymdownx" |
'default'
|
serialization_mode
|
Literal['json', 'python']
|
Pydantic serialization mode - "json" (default) or "python" |
'json'
|
Returns:
| Type | Description |
|---|---|
str
|
Markdown string documenting the model schema |
Source code in src/schemez/schema.py
for_class_ctor
classmethod
¶
for_class_ctor(target_cls: type) -> type[Schema]
Create a schema model from a class constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_cls
|
type
|
The class whose constructor to convert |
required |
Returns:
| Type | Description |
|---|---|
type[Schema]
|
A new schema model class based on the constructor parameters |
Source code in src/schemez/schema.py
for_function
classmethod
¶
for_function(func: Callable[..., Any], *, name: str | None = None) -> type[Schema]
Create a schema model from a function's signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
The function to create a schema from |
required |
name
|
str | None
|
Optional name for the model |
None
|
Returns:
| Type | Description |
|---|---|
type[Schema]
|
A new schema model class based on the function parameters |
Source code in src/schemez/schema.py
from_json_schema
classmethod
¶
from_json_schema(json_schema: dict[str, Any]) -> type[Schema]
Create a schema model from a JSON schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_schema
|
dict[str, Any]
|
The JSON schema to create a schema from |
required |
Returns:
| Type | Description |
|---|---|
type[Schema]
|
A new schema model class based on the JSON schema |
Source code in src/schemez/schema.py
from_llm
async
classmethod
¶
from_llm(
*prompts: JoinablePathLike | str | UserContent,
model: str = "google-gla:gemini-2.0-flash",
system_prompt: str = DEFAULT_SYSTEM_PROMPT,
user_prompt: str = DEFAULT_USER_PROMPT
) -> Self
Create a schema model from a text snippet using AI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompts
|
JoinablePathLike | str | UserContent
|
The text to create a schema from |
()
|
model
|
str
|
The AI model to use for schema extraction |
'google-gla:gemini-2.0-flash'
|
system_prompt
|
str
|
The system prompt to use for schema extraction |
DEFAULT_SYSTEM_PROMPT
|
user_prompt
|
str
|
The user prompt to use for schema extraction |
DEFAULT_USER_PROMPT
|
Returns:
| Type | Description |
|---|---|
Self
|
A new schema model class based on the document |
Source code in src/schemez/schema.py
from_yaml
classmethod
¶
Create from YAML string.
Source code in src/schemez/schema.py
generate_test_data
classmethod
¶
generate_test_data(
*,
seed: int = 0,
mode: Literal["minimal", "maximal", "default"] = "default",
validate: bool = True
) -> Self
Generate test data that conforms to this schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Seed for deterministic generation (default: 0) |
0
|
mode
|
Literal['minimal', 'maximal', 'default']
|
Generation mode: - "minimal": Only required fields, minimum values - "maximal": All fields, maximum reasonable values - "default": Balanced generation (default) |
'default'
|
validate
|
bool
|
Whether to validate the generated data (default: True) |
True
|
Returns:
| Type | Description |
|---|---|
Self
|
An instance of this schema populated with generated test data |
Example
class PersonSchema(Schema):
name: str
age: int = 25
email: str | None = None
# Generate test data
person = PersonSchema.generate_test_data(seed=42)
# Result: PersonSchema(name="abc", age=42, email=None)
# Generate minimal data (required fields only)
minimal = PersonSchema.generate_test_data(mode="minimal")
# Result: PersonSchema(name="a", age=0, email=None)
# Generate maximal data (all fields populated)
maximal = PersonSchema.generate_test_data(mode="maximal")
# Result: PersonSchema(name="abcdefghij", age=1000, email="user0@example.com")
Source code in src/schemez/schema.py
iter_submodel_types
classmethod
¶
iter_submodel_types(
*, recursive: bool = True, include_union_members: bool = True
) -> Iterator[tuple[str, type[BaseModel]]]
Iterate through all nested BaseModel types in field annotations.
Supports field types: - BaseModel (direct type) - list[BaseModel] - dict[str, BaseModel] - BaseModel | OtherModel (unions, when include_union_members=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recursive
|
bool
|
If True, also iterate through submodel types of submodels |
True
|
include_union_members
|
bool
|
If True, yield each union member separately |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, type[BaseModel]]
|
Tuples of (path, model_type) where path is like "field", "field[]", "field{}" |
Source code in src/schemez/schema.py
iter_submodels
¶
Iterate through all nested BaseModel instances in fields.
Supports fields of type: - BaseModel (direct instance) - list[BaseModel] - dict[str, BaseModel]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recursive
|
bool
|
If True, also iterate through submodels of submodels |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, BaseModel]
|
Tuples of (path, submodel) where path is like "field", "field[0]", "field['key']" |
Source code in src/schemez/schema.py
merge
¶
model_dump_markdown
¶
model_dump_markdown(
*,
template: str | None = None,
header_level: int = 1,
include_defaults: bool = True,
include_examples: bool = True,
include_constraints: bool = True,
include_values: bool = True,
display_mode: Literal["table", "python_code", "yaml"] = "table",
exclude_none: bool = True,
exclude_defaults_yaml: bool = False,
exclude_unset: bool = False,
indent: int = 2,
header_style: Literal["default", "pymdownx"] = "default",
serialization_mode: Literal["json", "python"] = "json"
) -> str
Dump model instance to Markdown documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str | None
|
Custom Jinja2 template string (uses default if None) |
None
|
header_level
|
int
|
Starting header level (1 = h1, 2 = h2, etc.) |
1
|
include_defaults
|
bool
|
Include default values in the table |
True
|
include_examples
|
bool
|
Include examples section |
True
|
include_constraints
|
bool
|
Include constraints section |
True
|
include_values
|
bool
|
Include current instance values |
True
|
display_mode
|
Literal['table', 'python_code', 'yaml']
|
Output format - "table", "python_code", or "yaml" |
'table'
|
exclude_none
|
bool
|
Exclude None values from YAML |
True
|
exclude_defaults_yaml
|
bool
|
Exclude default values from YAML |
False
|
exclude_unset
|
bool
|
Exclude unset values from YAML |
False
|
indent
|
int
|
YAML indentation |
2
|
header_style
|
Literal['default', 'pymdownx']
|
Code block header style - "default" or "pymdownx" |
'default'
|
serialization_mode
|
Literal['json', 'python']
|
Pydantic serialization mode - "json" (default) or "python" |
'json'
|
Returns:
| Type | Description |
|---|---|
str
|
Markdown string documenting the model |
Source code in src/schemez/schema.py
model_dump_yaml
¶
model_dump_yaml(
exclude_none: bool = True,
exclude_defaults: bool = False,
exclude_unset: bool = False,
indent: int = 2,
default_flow_style: bool | None = None,
allow_unicode: bool = True,
comments: bool = False,
sort_keys: bool = True,
mode: Literal["json", "python"] = "python",
) -> str
Dump configuration to YAML string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_none
|
bool
|
Exclude fields with None values |
True
|
exclude_defaults
|
bool
|
Exclude fields with default values |
False
|
exclude_unset
|
bool
|
Exclude fields that are not set |
False
|
indent
|
int
|
Indentation level for YAML output |
2
|
default_flow_style
|
bool | None
|
Default flow style for YAML output |
None
|
allow_unicode
|
bool
|
Allow unicode characters in YAML output |
True
|
comments
|
bool
|
Include descriptions as comments in the YAML output |
False
|
sort_keys
|
bool
|
Sort keys in the YAML output |
True
|
mode
|
Literal['json', 'python']
|
Output mode, either "json" or "python" |
'python'
|
Returns:
| Type | Description |
|---|---|
str
|
YAML string representation of the model |
Source code in src/schemez/schema.py
save
¶
Save configuration to a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
JoinablePathLike
|
Path to save the configuration to |
required |
overwrite
|
bool
|
Whether to overwrite an existing file |
False
|
Raises:
| Type | Description |
|---|---|
OSError
|
If file cannot be written |
ValueError
|
If path is invalid |
Source code in src/schemez/schema.py
to_python_code
classmethod
¶
to_python_code(
*,
class_name: str | None = None,
target_python_version: PythonVersionStr | None = None,
model_type: str = "pydantic.BaseModel"
) -> str
Convert this model to Python code asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
class_name
|
str | None
|
Optional custom class name for the generated code |
None
|
target_python_version
|
PythonVersionStr | None
|
Target Python version for code generation |
None
|
model_type
|
str
|
Type of model to generate |
'pydantic.BaseModel'
|
Returns:
| Type | Description |
|---|---|
str
|
Generated Python code as string |
Source code in src/schemez/schema.py
SchemaField
¶
Bases: Schema
Field definition for inline response types.
Defines a single field in an inline response definition, including: - Data type specification - Optional description - Validation constraints - Enum values (when type is 'enum') - Field dependencies and relationships
Used by InlineSchemaDef to structure response fields.
Source code in src/schemez/schemadef/schemadef.py
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 | |
constraints
class-attribute
instance-attribute
¶
constraints: dict[ConstraintType | str, Any] = Field(
default_factory=dict,
title="Constraints",
examples=[
{"min_length": 3, "max_length": 50},
{"ge": 0, "le": 100},
{"strict": True, "frozen": False},
],
)
Additional Pydantic Field constraints not covered by explicit fields
default
class-attribute
instance-attribute
¶
default: Any | None = Field(
default=None, title="Default value", examples=["localhost", 8080, True, []]
)
Default value for the field
dependent_required
class-attribute
instance-attribute
¶
dependent_required: dict[str, list[str]] = Field(
default_factory=dict,
title="Required field dependencies",
examples=[
{"payment_method": ["card_number", "expiry_date"]},
{"auth_enabled": ["username", "password"]},
],
)
Field dependencies - when this field exists, dependent fields are required
dependent_schema
class-attribute
instance-attribute
¶
dependent_schema: dict[str, dict[str, Any]] = Field(
default_factory=dict,
title="Schema dependencies",
examples=[
{"ssl_enabled": {"properties": {"ssl_cert": {"type": "string"}}}},
{"debug": {"properties": {"log_level": {"enum": ["debug", "trace"]}}}},
],
)
Schema dependencies - when this field exists, dependent fields must match schema
description
class-attribute
instance-attribute
¶
description: str | None = Field(
default=None,
title="Field description",
examples=["User name", "Port number", "Enable debug mode"],
)
Optional description of what this field represents
examples
class-attribute
instance-attribute
¶
examples: list[Any] | None = Field(
default=None,
title="Field examples",
examples=[["localhost", "example.com"], [8080, 3000, 443], [True, False]],
)
Examples for this field in JSON Schema
field_config
class-attribute
instance-attribute
¶
field_config: dict[str, Any] | None = Field(
default=None, title="Pydantic field config", examples=[{"alias": "userName"}, {"exclude": True}]
)
Configuration for Pydantic model fields
ge
class-attribute
instance-attribute
¶
Greater than or equal (inclusive) validation for numbers
gt
class-attribute
instance-attribute
¶
Greater than (exclusive) validation for numbers
json_schema_extra
class-attribute
instance-attribute
¶
json_schema_extra: dict[str, Any] | None = Field(
default=None,
title="JSON Schema extras",
examples=[{"format": "email"}, {"contentMediaType": "application/json"}],
)
Additional JSON Schema information
le
class-attribute
instance-attribute
¶
Less than or equal (inclusive) validation for numbers
literal_value
class-attribute
instance-attribute
¶
literal_value: Any | None = Field(
default=None, title="Literal value", examples=["production", 42, True]
)
Value for Literal type constraint, makes field accept only this specific value
lt
class-attribute
instance-attribute
¶
Less than (exclusive) validation for numbers
max_length
class-attribute
instance-attribute
¶
max_length: Annotated[int | None, Field(ge=0)] = Field(
default=None, title="Maximum length", examples=[50, 255, 1000]
)
Maximum length for collections
min_length
class-attribute
instance-attribute
¶
min_length: Annotated[int | None, Field(ge=0)] = Field(
default=None, title="Minimum length", examples=[1, 3, 8]
)
Minimum length for collections
multiple_of
class-attribute
instance-attribute
¶
multiple_of: Annotated[float | None, Field(gt=0)] = Field(
default=None, title="Multiple of", examples=[2, 5, 10, 0.5]
)
Number must be a multiple of this value
optional
class-attribute
instance-attribute
¶
Whether this field is optional (None value allowed)
pattern
class-attribute
instance-attribute
¶
pattern: str | None = Field(
default=None,
title="Regex pattern",
examples=["^[A-Za-z]+$", "\\d{3}-\\d{3}-\\d{4}", "^[a-z0-9_]+$"],
)
Regex pattern for string validation
title
class-attribute
instance-attribute
¶
title: str | None = Field(
default=None, title="Field title", examples=["Server Name", "Port Number", "Debug Mode"]
)
Title for the field in generated JSON Schema
type
class-attribute
instance-attribute
¶
type: FieldType | str = Field(
title="Field type", examples=["str", "int", "list[str]", "dict[str, Any]", "enum"]
)
Data type of the response field
values
class-attribute
instance-attribute
¶
values: list[Any] | None = Field(
default=None,
title="Enum values",
examples=[["active", "inactive", "pending"], ["small", "medium", "large"]],
)
Values for enum type fields
add_required_dependency
¶
Add a dependency requiring other fields when this field exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
The field that triggers the dependency |
required |
required_fields
|
list[str]
|
Fields that become required when field_name exists |
required |
Source code in src/schemez/schemadef/schemadef.py
add_schema_dependency
¶
Add a schema dependency when this field exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
The field that triggers the dependency |
required |
schema
|
dict[str, Any]
|
JSON Schema to apply when field_name exists |
required |
Source code in src/schemez/schemadef/schemadef.py
TOMLCode
¶
Bases: BaseCode
TOML with syntax validation.
Source code in src/schemez/code.py
ToolCodeGenerator
dataclass
¶
Generates code artifacts for a single tool.
Source code in src/schemez/code_generation/tool_code_generator.py
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 | |
callable
class-attribute
instance-attribute
¶
Optional callable for actual execution. Required only for FastAPI route generation and Python namespace execution. All other operations (client code generation, signatures, models) work purely from the schema.
name_override
class-attribute
instance-attribute
¶
Name override for the function to generate code for.
add_route_to_app
¶
Add this tool's route to FastAPI app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
FastAPI
|
FastAPI application instance |
required |
path_prefix
|
str
|
Path prefix for the route |
'/tools'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If callable is not provided |
Source code in src/schemez/code_generation/tool_code_generator.py
from_callable
classmethod
¶
from_callable(
fn: Callable[..., Any],
exclude_types: list[type] | None = None,
schema_type: SchemaType = "simple",
) -> ToolCodeGenerator
Create a ToolCodeGenerator from a callable.
Source code in src/schemez/code_generation/tool_code_generator.py
from_schema
classmethod
¶
from_schema(schema: FunctionSchema, name_override: str | None = None) -> ToolCodeGenerator
Create a ToolCodeGenerator from a schema only (no execution capability).
Source code in src/schemez/code_generation/tool_code_generator.py
generate_parameter_model
¶
Generate Pydantic model code for the tool's parameters.
Source code in src/schemez/code_generation/tool_code_generator.py
generate_return_model
¶
Generate Pydantic model code for the tool's return type.
Source code in src/schemez/code_generation/tool_code_generator.py
generate_route_handler
¶
Generate FastAPI route handler for this tool.
Returns:
| Type | Description |
|---|---|
Callable[..., Awaitable[dict[str, Any]]]
|
Async route handler function |
Raises:
| Type | Description |
|---|---|
ValueError
|
If callable is not provided |
Source code in src/schemez/code_generation/tool_code_generator.py
get_function_definition
¶
Extract function definition using FunctionSchema.
Source code in src/schemez/code_generation/tool_code_generator.py
get_function_signature
¶
Assembles a signature for given generator, excluding (async) def.
ToolsetCodeGenerator
dataclass
¶
Generates code artifacts for multiple tools.
Source code in src/schemez/code_generation/toolset_code_generator.py
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 | |
generators
instance-attribute
¶
generators: Sequence[ToolCodeGenerator]
ToolCodeGenerator instances for each tool.
include_docstrings
class-attribute
instance-attribute
¶
Include function docstrings in documentation.
add_all_routes
¶
Add FastAPI routes for all tools.
from_callables
classmethod
¶
from_callables(
callables: Sequence[Callable[..., Any]],
include_docstrings: bool = True,
exclude_types: list[type] | None = None,
) -> ToolsetCodeGenerator
Create a ToolsetCodeGenerator from a sequence of callables.
Source code in src/schemez/code_generation/toolset_code_generator.py
from_schemas
classmethod
¶
from_schemas(
schemas: Sequence[FunctionSchema], include_docstrings: bool = True
) -> ToolsetCodeGenerator
Create a ToolsetCodeGenerator from schemas only (no execution capability).
Source code in src/schemez/code_generation/toolset_code_generator.py
generate_code
¶
generate_code(
base_url: str = "http://localhost:8000",
path_prefix: str = "/tools",
args_format: ArgsFormat = "explicit",
output_type: OutputType = "implementation",
) -> str
Generate HTTP client code with specified format and type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Base URL of the tool server |
'http://localhost:8000'
|
path_prefix
|
str
|
Path prefix for routes |
'/tools'
|
args_format
|
ArgsFormat
|
Format for function arguments |
'explicit'
|
output_type
|
OutputType
|
Type of output to generate |
'implementation'
|
Returns:
| Type | Description |
|---|---|
str
|
Generated client code |
Source code in src/schemez/code_generation/toolset_code_generator.py
generate_execution_namespace
¶
Build Python namespace with tool functions and generated models.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any generator lacks a callable |
Source code in src/schemez/code_generation/toolset_code_generator.py
generate_mcp_code
¶
generate_mcp_code(
server_configs: dict[str, str],
args_format: ArgsFormat = "explicit",
output_type: OutputType = "implementation",
) -> str
Generate complete FastMCP client code with tools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_configs
|
dict[str, str]
|
FastMCP server configurations mapping server names to transport URLs e.g., {"github": "sse://localhost:8080/github"} |
required |
args_format
|
ArgsFormat
|
Format for function arguments |
'explicit'
|
output_type
|
OutputType
|
Type of output to generate |
'implementation'
|
Returns:
| Type | Description |
|---|---|
str
|
Complete FastMCP client code |
Source code in src/schemez/code_generation/toolset_code_generator.py
generate_return_models
¶
Generate Pydantic models for tool return types.
Source code in src/schemez/code_generation/toolset_code_generator.py
generate_structured_code
¶
generate_structured_code(
base_url: str = "http://localhost:8000",
path_prefix: str = "/tools",
client_type: ClientType = "http",
) -> GeneratedCode
Generate structured code with all components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Base URL of the tool server (HTTP) or server name (FastMCP) |
'http://localhost:8000'
|
path_prefix
|
str
|
Path prefix for routes (HTTP only) |
'/tools'
|
client_type
|
ClientType
|
Type of client to generate ("http" or "fastmcp") |
'http'
|
Returns:
| Type | Description |
|---|---|
GeneratedCode
|
GeneratedCode with all components separated |
Source code in src/schemez/code_generation/toolset_code_generator.py
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 | |
generate_tool_description
¶
Generate comprehensive tool description with available functions.
Source code in src/schemez/code_generation/toolset_code_generator.py
get_fastmcp_client_code
¶
Generate FastMCP client code with connection management.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_configs
|
dict[str, str]
|
Dict mapping server names to their transport URLs e.g., {"github": "sse://localhost:8080/github"} |
required |
Returns:
| Type | Description |
|---|---|
str
|
FastMCP client code as string |
Source code in src/schemez/code_generation/toolset_code_generator.py
YAMLCode
¶
Bases: BaseCode
YAML with syntax validation.
Source code in src/schemez/code.py
create_constructor_schema
¶
create_constructor_schema(cls: type) -> FunctionSchema
Create OpenAI function schema from class constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
Class to create schema for |
required |
Returns:
| Type | Description |
|---|---|
FunctionSchema
|
OpenAI function schema for class constructor |
Source code in src/schemez/functionschema/schema_generators.py
create_executable
¶
create_executable(func: Callable[..., Generator[T_co]]) -> ExecutableFunction[T_co]
create_executable(func: Callable[..., AsyncGenerator[T_co]]) -> ExecutableFunction[T_co]
create_executable(func: Callable[..., T_co]) -> ExecutableFunction[T_co]
create_executable(
func: (
Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]]
),
) -> ExecutableFunction[T_co]
Create an executable function wrapper with schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]]
|
Function to wrap |
required |
Returns:
| Type | Description |
|---|---|
ExecutableFunction[T_co]
|
Executable wrapper with schema |
Source code in src/schemez/functionschema/executable.py
create_schema
¶
create_schema(
func: Callable[..., Any],
name_override: str | None = None,
description_override: str | None = None,
exclude_types: list[type] | None = None,
mode: SchemaType = "simple",
) -> FunctionSchema
Create an OpenAI function schema from a Python function.
If an iterator is passed, the schema return type is a list of the iterator's element type. Variable arguments (*args) and keyword arguments (**kwargs) are not supported in OpenAI function schemas and will be ignored with a warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Function to create schema for |
required |
name_override
|
str | None
|
Optional name override (otherwise the function name) |
None
|
description_override
|
str | None
|
Optional description override (otherwise the function docstring) |
None
|
exclude_types
|
list[type] | None
|
Types to exclude from parameters (e.g., context types) |
None
|
mode
|
SchemaType
|
Schema generation mode - simple" (default) uses custom simple implementation, - "openai" for OpenAI function calling via Pydantic, - "jsonschema" for standard JSON schema via Pydantic |
'simple'
|
Source code in src/schemez/functionschema/functionschema.py
create_schemas_from_callables
¶
create_schemas_from_callables(
callables: dict[str, Callable[..., Any]],
prefix: str | Literal[False] | None = None,
exclude_private: bool = True,
) -> dict[str, FunctionSchema]
Generate OpenAI function schemas from a dictionary of callables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callables
|
dict[str, Callable[..., Any]]
|
Dictionary mapping names to callable objects |
required |
prefix
|
str | Literal[False] | None
|
Schema name prefix to prepend to function names. If None, no prefix. If False, use raw name. If string, uses that prefix. |
None
|
exclude_private
|
bool
|
Whether to exclude callables starting with underscore |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, FunctionSchema]
|
Dictionary mapping qualified names to FunctionSchema objects |
Example
def foo(x: int) -> str: ... def bar(y: float) -> int: ... callables = {'foo': foo, 'bar': bar} schemas = create_schemas_from_callables(callables, prefix='math') print(schemas['math.foo'])
Source code in src/schemez/functionschema/schema_generators.py
create_schemas_from_class
¶
create_schemas_from_class(
cls: type, prefix: str | Literal[False] | None = None
) -> dict[str, FunctionSchema]
Generate OpenAI function schemas for all public methods in a class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The class to generate schemas from |
required |
prefix
|
str | Literal[False] | None
|
Schema name prefix. If None, uses class name. If False, no prefix. If string, uses that prefix. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, FunctionSchema]
|
Dictionary mapping qualified method names to FunctionSchema objects |
Example
class MyClass: ... def my_method(self, x: int) -> str: ... return str(x) schemas = create_schemas_from_class(MyClass) print(schemas['MyClass.my_method'])
Source code in src/schemez/functionschema/schema_generators.py
create_schemas_from_module
¶
create_schemas_from_module(
module: ModuleType | str,
include_functions: list[str] | None = None,
prefix: str | Literal[False] | None = None,
) -> dict[str, FunctionSchema]
Generate OpenAI function schemas from a Python module's functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
ModuleType | str
|
Either a ModuleType object or string name of module to analyze |
required |
include_functions
|
list[str] | None
|
Optional list of function names to specifically include |
None
|
prefix
|
str | Literal[False] | None
|
Schema name prefix. If None, uses module name. If False, no prefix. If string, uses that prefix. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, FunctionSchema]
|
Dictionary mapping function names to FunctionSchema objects |
Raises:
| Type | Description |
|---|---|
ImportError
|
If module string name cannot be imported |
Example
import math schemas = create_schemas_from_module(math, ['sin', 'cos']) print(schemas['math.sin'])
Source code in src/schemez/functionschema/schema_generators.py
jsonschema_to_code
¶
jsonschema_to_code(
schema_json: str, class_name: str | None = None, input_path: str | None = None
) -> str
Generate Pydantic model code from a JSON schema.
Source code in src/schemez/helpers.py
models_to_markdown_docs
¶
models_to_markdown_docs(
*models: type[BaseModel],
header_level: int = 2,
expand_mode: Literal["minimal", "maximal", "default"] = "default",
seed: int = 0,
validate: bool = False,
exclude_none: bool = True,
exclude_defaults: bool = False,
exclude_unset: bool = False,
indent: int = 2,
sort_keys: bool = True
) -> str
Generate markdown documentation with commented YAML examples for BaseModel classes.
Creates markdown chapters for each model with: - Model name as header - Model docstring - Commented YAML example with test data
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
type[BaseModel]
|
One or more BaseModel classes to document |
()
|
header_level
|
int
|
Starting header level (2 = h2, 3 = h3, etc.) |
2
|
expand_mode
|
Literal['minimal', 'maximal', 'default']
|
YAML generation mode - "minimal", "maximal", or "default" |
'default'
|
seed
|
int
|
Seed for deterministic YAML generation |
0
|
validate
|
bool
|
Whether to validate the generated test data |
False
|
exclude_none
|
bool
|
Exclude fields with None values in YAML |
True
|
exclude_defaults
|
bool
|
Exclude fields with default values in YAML |
False
|
exclude_unset
|
bool
|
Exclude fields that are not set in YAML |
False
|
indent
|
int
|
Indentation level for YAML output |
2
|
sort_keys
|
bool
|
Sort keys in the YAML output |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Markdown string with chapters for each model |
Example
from pydantic import BaseModel, Field
class Person(BaseModel):
'''A person with basic information.'''
name: str = Field(description='Full name')
age: int = Field(description='Age in years')
email: str | None = Field(default=None, description='Email address')
class Company(BaseModel):
'''A company entity.'''
name: str = Field(description='Company name')
founded: int = Field(description='Year founded')
# Generate documentation
docs = models_to_markdown_docs(Person, Company)
print(docs)
Output:
Company¶
A company entity.
```Source code in src/schemez/helpers.py
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 | |
openapi_to_code
¶
Generate Pydantic model code from an OpenAPI specification URL.