Create OpenAI-compatible function schemas from python functions
Project description
Py2OpenAI
OpenAI Function Schema Generator
Convert Python functions to OpenAI-compatible function schemas automatically.
Installation
pip install openai-function-schema # not yet published
Basic Usage
from openai_function_schema import create_schema
from typing import Literal
def get_weather(
location: str,
unit: Literal["C", "F"] = "C",
detailed: bool = False,
) -> dict[str, str | float]:
"""Get the weather for a location.
Args:
location: City or address to get weather for
unit: Temperature unit (Celsius or Fahrenheit)
detailed: Include extended forecast
"""
return {"temp": 22.5, "conditions": "sunny"}
# Create schema
schema = create_schema(get_weather)
# Use with OpenAI
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "What's the weather in London?"}],
functions=[schema.model_dump_openai()],
function_call="auto"
)
Supported Types
Basic Types
def func(
text: str, # -> "type": "string"
number: int, # -> "type": "integer"
amount: float, # -> "type": "number"
enabled: bool, # -> "type": "boolean"
anything: Any, # -> "type": "string"
) -> None: ...
Container Types
def func(
items: list[str], # -> "type": "array", "items": {"type": "string"}
numbers: set[int], # -> same as list
mapping: dict[str, Any], # -> "type": "object", "additionalProperties": true
nested: list[dict[str, int]], # -> nested array/object types
sequence: Sequence[str], # -> "type": "array"
collection: Collection[int], # -> "type": "array"
) -> None: ...
Enums and Literals
class Color(Enum):
RED = "red"
BLUE = "blue"
def func(
color: Color, # -> "type": "string", "enum": ["red", "blue"]
mode: Literal["fast", "slow"], # -> "type": "string", "enum": ["fast", "slow"]
) -> None: ...
Optional and Union Types
def func(
opt1: str | None, # -> "type": "string"
opt2: int | None, # -> "type": "integer"
union: str | int, # -> "type": "string" (first type)
) -> None: ...
Custom Types
@dataclass
class User:
name: str
age: int
def func(
user: User, # -> "type": "object"
data: JsonDict, # -> "type": "object"
) -> None: ...
Type Aliases
JsonValue = dict[str, Any] | list[Any] | str | int | float | bool | None
JsonDict = dict[str, JsonValue]
def func(
data: JsonDict, # -> "type": "object"
values: list[JsonValue], # -> "type": "array"
) -> None: ...
Recursive Types
def func(
tree: dict[str, "dict[str, Any] | str"], # -> "type": "object"
nested: dict[str, list["dict[str, Any]"]], # -> "type": "object"
) -> None: ...
Generated Schema Example
{
"name": "get_weather",
"description": "Get the weather for a location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City or address to get weather for"
},
"unit": {
"type": "string",
"enum": ["C", "F"],
"description": "Temperature unit (Celsius or Fahrenheit)",
"default": "C"
},
"detailed": {
"type": "boolean",
"description": "Include extended forecast",
"default": false
}
},
"required": ["location"]
}
}
Schema Generators
Module Schemas
You can generate schemas for all public functions in a module using create_schemas_from_module:
from py2openai import create_schemas_from_module
import math
# Generate schemas for all public functions
schemas = create_schemas_from_module(math)
# Generate schemas for specific functions only
schemas = create_schemas_from_module(math, include_functions=['sin', 'cos'])
# Import module by string name
schemas = create_schemas_from_module('math')
Class Schemas
Generate schemas for all public methods in a class using create_schemas_from_class:
from py2openai import create_schemas_from_class
class Calculator:
def add(self, x: int, y: int) -> int:
"""Add two numbers.
Args:
x: First number
y: Second number
Returns:
Sum of x and y
"""
return x + y
@classmethod
def multiply(cls, x: int, y: int) -> int:
"""Multiply two numbers.
Args:
x: First number
y: Second number
Returns:
Product of x and y
"""
return x * y
@staticmethod
def divide(x: float, y: float) -> float:
"""Divide two numbers.
Args:
x: Numerator
y: Denominator
Returns:
Result of x divided by y
"""
return x / y
# Generate schemas for all public methods
schemas = create_schemas_from_class(Calculator)
# Access individual method schemas
add_schema = schemas['Calculator.add']
multiply_schema = schemas['Calculator.multiply']
divide_schema = schemas['Calculator.divide']
The schema generators support:
- Regular instance methods
- Class methods
- Static methods
- Async methods
- Property methods
- All supported type annotations
- Method docstrings for descriptions
- Default values
- Return type hints
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file py2openai-0.9.3.tar.gz.
File metadata
- Download URL: py2openai-0.9.3.tar.gz
- Upload date:
- Size: 22.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.5.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f70eda813c72f237f9bf68079e667987002172e647bc7ab7b3a4fe49a34f1312
|
|
| MD5 |
00c13249de54ddc6b9d8c1589e9116aa
|
|
| BLAKE2b-256 |
9e96a66ccf0be521d1410b8991282488e313849c53071c0cf2b7512d7c5259fb
|
File details
Details for the file py2openai-0.9.3-py3-none-any.whl.
File metadata
- Download URL: py2openai-0.9.3-py3-none-any.whl
- Upload date:
- Size: 13.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.5.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f2d07ac52a17cc0651cdf91dadbd1f610b5191d372d7a8e1a0151f3e780b5fae
|
|
| MD5 |
17310ef877f5f96df8c44de856f5f5d2
|
|
| BLAKE2b-256 |
38c757887b333a055149d017090ed208c2d1cbec5ed9d1bf9433216d41c1d4f8
|