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.2.tar.gz (9.4 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.2-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: matrix_fn_schema-0.1.2.tar.gz
  • Upload date:
  • Size: 9.4 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.2.tar.gz
Algorithm Hash digest
SHA256 7f96b9d6a1e445ac3ab2de3adc264894b7220b58e4d7ef94506f68b84090fb47
MD5 94c843418aea9b12bd7788ef83f07cec
BLAKE2b-256 fb0b27a91ba9b8e640899c1c96dd455f7a752c31da457c1929fc948e3446fdcd

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for matrix_fn_schema-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 8b938056c6da095184e13bec19a67be3ee652a45232c01601b72ce6859b0a393
MD5 be45c12472dba2fe04b117b942dd264e
BLAKE2b-256 3a17c6bf11188909caf8e8478a2fb74e11da6dc522cf42a4ea8fd672f82ad866

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