Skip to main content

Pydantic model validation and argument handling, for your functions!

Project description

OpenAI Functions

pip install funcmodels
from funcmodels import openai_function

@openai_function

Highlights

This documentation assumes you're already familiar with OpenAI function calling, and Pydantic BaseModel.

from typing import Literal

@openai_function
def get_stock_price(ticker: str, currency: Literal["USD", "EUR"] = "USD"):
    """
    Get the stock price of a company, by ticker symbol

    Parameters
    ----------
    ticker
        The ticker symbol of the company
    currency
        The currency to use
    """
    return f"182.41 {currency}, -0.48 (0.26%) today"


get_stock_price
OpenaiFunction({
    "name": "get_stock_price",
    "description": "Get the stock price of a company, by ticker symbol",
    "parameters": {
        "properties": {
            "ticker": {
                "type": "string",
                "description": "The ticker symbol of the company"
            },
            "currency": {
                "default": "USD",
                "enum": [
                    "USD",
                    "EUR"
                ],
                "type": "string",
                "description": "The currency to use"
            }
        },
        "required": [
            "ticker"
        ],
        "type": "object"
    }
})

@openai_function dynamically creates a custom pydantic.BaseModel class with:

  • Your function's parameters as attributes, for validation
  • Class attribute, schema, with an OpenAI Function object for your function
    • Parses docstring for description, and parameter descriptions, if present.
    • Type structure based on pydantic's .model_json_schema()
  • Class method, .from_json() to easily instantiate your model from raw JSON arguments received from OpenAI
  • A .__call__() method to easily call your original function, using the model's validated attributes.

Get our OpenAI function definition dictionary

get_stock_price.schema
{'name': 'get_stock_price', 'description': 'Get the stock price of a company, by ticker symbol', 'parameters': {'properties': {'ticker': {'type': 'string', 'description': 'The ticker symbol of the company'}, 'currency': {'default': 'USD', 'enum': ['USD', 'EUR'], 'type': 'string', 'description': 'The currency to use'}}, 'required': ['ticker'], 'type': 'object'}}

Instantiate our pydantic model, validating arguments

model = get_stock_price(ticker="AAPL")

Or, go directly from raw json arguments from OpenAI

raw_arguments_from_openai = '{"ticker": "AAPL"}'
model = get_stock_price.from_json(raw_arguments_from_openai)
model.currency
'USD'

Call our function, with already-validated arguments

model()
'182.41 USD, -0.48 (0.26%) today'

If you prefer Pydantic syntax, we can achieve the same thing using Fields

from pydantic import Field

@openai_function
def get_stock_price(
    ticker: str = Field(description="The ticker symbol of the company"),
    currency: Literal["USD", "EUR"] = Field("USD", description="The currency to use."),
):
    "Get the stock price of a company, by ticker symbol"
    return f"182.41 {currency}, -0.48 (0.26%) today"

Here, the field descriptions are defined in the parameters themselves, rather than the docstring.

The result is the exact same function definition as before:

get_stock_price
OpenaiFunction({
    "name": "get_stock_price",
    "description": "Get the stock price of a company, by ticker symbol",
    "parameters": {
        "properties": {
            "ticker": {
                "type": "string",
                "description": "The ticker symbol of the company"
            },
            "currency": {
                "default": "USD",
                "enum": [
                    "USD",
                    "EUR"
                ],
                "type": "string",
                "description": "The currency to use"
            }
        },
        "required": [
            "ticker"
        ],
        "type": "object"
    }
})

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

funcmodels-0.0.6.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

funcmodels-0.0.6-py2.py3-none-any.whl (6.3 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file funcmodels-0.0.6.tar.gz.

File metadata

  • Download URL: funcmodels-0.0.6.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.11.6

File hashes

Hashes for funcmodels-0.0.6.tar.gz
Algorithm Hash digest
SHA256 0a188f30cf6c715d9521df0995512c591736b6ed55eb2698c4827818ba8d41dc
MD5 2d5e8d10f68f90b9c1d63c0a352a8a20
BLAKE2b-256 014951376473bc661f8ff7ea66b9bfc6e78b787db2eb59d6b94b0742a6faacba

See more details on using hashes here.

File details

Details for the file funcmodels-0.0.6-py2.py3-none-any.whl.

File metadata

  • Download URL: funcmodels-0.0.6-py2.py3-none-any.whl
  • Upload date:
  • Size: 6.3 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.11.6

File hashes

Hashes for funcmodels-0.0.6-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 8efc679caf240d4fa9a7a2a32d74b80ca88a66e356dff4785b5069419136c226
MD5 979fc20ba6a5268f450a58d16eb81be3
BLAKE2b-256 f70f1cdedc8a5146d87fbdcb5b91e5205b3b63964e750af7992b15860ce80054

See more details on using hashes here.

Supported by

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