Skip to main content

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"
    }
})

Metadata

Release files for funcmodels 0.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for funcmodels 0.0.7
File Size Uploaded
funcmodels-0.0.7.tar.gz 5.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for funcmodels 0.0.7
File Interpreter ABI Platform
funcmodels-0.0.7-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 11.3 kB

Release files / funcmodels-0.0.7.tar.gz

Download URL funcmodels-0.0.7.tar.gz
Size 5.0 kB
Tags Source
SHA-256 checksum
How to use checksums
6cc90131fd962a8207600cfead92e55206213fcb2d02401f25aeec83ff1af715
BLAKE2b-256 checksum
How to use checksums
d053d547368a9a49ffd64dec32cb5aa865dd8386963f6c9d4be53328d1b89124
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.11.6

Release files / funcmodels-0.0.7-py2.py3-none-any.whl

Download URL funcmodels-0.0.7-py2.py3-none-any.whl
Size 6.3 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
f51c259efbaa0ffcf35057766fe9c9815430f6cacaf1605ac04b1096d5f3b94a
BLAKE2b-256 checksum
How to use checksums
70d11bd520bf3e531a9480c00cafb5734587aa7cdc5ed48ad6b5fe557a69d4c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.11.6

Release history Release notifications | RSS feed

This release

0.0.7 This release

2 release files

0.0.6

2 release files

0.0.5

2 release files

0.0.4

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page