Skip to main content

Python function signatures to OpenAI-compatible JSON Schema

Project description

matrix-fn-schema

Convert Python function signatures (type annotations + docstrings) into OpenAI-compatible JSON Schema (tool call format).

from dataclasses import dataclass
from enum import Enum
from typing import Annotated, List, Optional, Literal
from uuid import UUID
from matrix_fn_schema import build_json_schema


class Priority(int, Enum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3


@dataclass
class Attachment:
    filename: str
    url: str


def create_task(
    title: Annotated[str, "Max 200 chars"],
    priority: Priority,
    assignee_id: UUID,
    attachments: List[Attachment],
    deadline: Optional[str] = None,
) -> dict:
    """Create a new task."""
    ...


schema = build_json_schema(create_task)

Result:

{
  "type": "function",
  "name": "create_task",
  "description": "Create a new task.",
  "strict": true,
  "parameters": {
    "type": "object",
    "properties": {
      "title":         {"type": "string"},
      "priority":      {"type": "integer", "enum": [1, 2, 3]},
      "assignee_id":   {"type": "string", "format": "uuid"},
      "attachments":   {"type": "array", "items": {"type": "object", "properties": {
                          "filename": {"type": "string"},
                          "url": {"type": "string"}
                        }, "required": ["filename", "url"], "additionalProperties": false}},
      "deadline":      {"anyOf": [{"type": "string"}, {"type": "null"}]}
    },
    "additionalProperties": false,
    "required": ["title", "priority", "assignee_id", "attachments", "deadline"]
  }
}

Supported types

Python JSON Schema
int {"type": "integer"}
float {"type": "number"}
str {"type": "string"}
bool {"type": "boolean"}
None {"type": "null"}
Literal["a", "b"] {"enum": ["a", "b"]}
list[X] {"type": "array", "items": <X>}
tuple[X, Y] {"type": "array", "prefixItems": [...], "minItems": N, "maxItems": N}
tuple[X, ...] {"type": "array", "items": <X>}
dict[K, V] {"type": "object", "additionalProperties": <V>}
Optional[X] / X | None {"anyOf": [<X>, {"type": "null"}]}
Union[X, Y, Z] / X | Y | Z {"anyOf": [<X>, <Y>, <Z>]}
Annotated[T, ...] unwrapped to T
Final[T] unwrapped to T
enum.Enum (str values) {"type": "string", "enum": [...]}
enum.IntEnum {"type": "integer", "enum": [...]}
uuid.UUID {"type": "string", "format": "uuid"}
datetime.datetime {"type": "string", "format": "date-time"}
datetime.date {"type": "string", "format": "date"}
datetime.time {"type": "string", "format": "time"}
@dataclass recursive {"type": "object", "properties": {...}}
TypedDict recursive {"type": "object"} with Required/NotRequired
Self / recursive types cycle-safe (breaks at the self-reference)
pydantic.BaseModel delegated to .model_json_schema() (optional dep)

Requirements

Python 3.10+. Dependencies: docstring-parser>=0.16.

Optional: pydantic>=2 for BaseModel support.

Written with love by dotmatrix.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

matrix_fn_schema-0.1.3.tar.gz (9.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

matrix_fn_schema-0.1.3-py3-none-any.whl (6.4 kB view details)

Uploaded Python 3

File details

Details for the file matrix_fn_schema-0.1.3.tar.gz.

File metadata

  • Download URL: matrix_fn_schema-0.1.3.tar.gz
  • Upload date:
  • Size: 9.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for matrix_fn_schema-0.1.3.tar.gz
Algorithm Hash digest
SHA256 660e84932896e5d2742193aa3d4d462dd825aa833450af3fdbd13cd37f5c9db8
MD5 31a739f70f82163ead38eb1a6e3fbb20
BLAKE2b-256 2db1563bfff0b002b2b48230b7351b31897e6e6c85ce5c8b681da79b190b6c46

See more details on using hashes here.

File details

Details for the file matrix_fn_schema-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for matrix_fn_schema-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 8ab71f53d9808be95dbb93c14adb54e73103aee779802d2836bda2c672e0bb1d
MD5 932b3399fbfe37f8bfcb546793a2aa8c
BLAKE2b-256 b78f845d66a985619bc992d17fc42f9d622d2d7dc615d9772e677f28998845ab

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page