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.7.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

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

Uploaded Python 2 Python 3

File details

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

File metadata

  • Download URL: funcmodels-0.0.7.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.7.tar.gz
Algorithm Hash digest
SHA256 6cc90131fd962a8207600cfead92e55206213fcb2d02401f25aeec83ff1af715
MD5 c6fe7dffe4b41f62cfc25da21c5fc1d3
BLAKE2b-256 d053d547368a9a49ffd64dec32cb5aa865dd8386963f6c9d4be53328d1b89124

See more details on using hashes here.

File details

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

File metadata

  • Download URL: funcmodels-0.0.7-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.7-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 f51c259efbaa0ffcf35057766fe9c9815430f6cacaf1605ac04b1096d5f3b94a
MD5 ec235a8917e8c9ea36cd54c983c8c004
BLAKE2b-256 70d11bd520bf3e531a9480c00cafb5734587aa7cdc5ed48ad6b5fe557a69d4c6

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