tl;dr
How to properly type hint function calls?
The problem
There is a plethora of different classes that can be found under openai.types and it’s not always clear how they relate to one another or what the differences are. More specifically, I would like to properly type hint my function calls. I can find the following relevant types:
Both of these have the exact same attributes: name
, description
, and parameters
. But it is not clear to me when to use one over the other.
An example
The following function is correctly defined. Pyright (my type checker of choice) sees no problem with this, and I can pass it as an argument to the chat completions API without issues.
from openai.types.chat.completion_create_params import Function
function_definition_extract_number: Function = {
"name": "extract_number",
"description": "Extract the first number from the user message.",
"parameters": {
"type": "object",
"properties": {
"first_number": {"type": "array", "description": "The first number that appears in the user input."},
},
"required": ["first_number"],
},
}
However, when I change the type hint to FunctionDefinition
, my type checker complains about incorrect types:
from openai.types.shared.function_definition import FunctionDefinition
function_definition_extract_number: FunctionDefinition = {
...
} # <-- type checker complains
On the other hand, when I want to use a FunctionTool – necessary to do function calling with the assistant API – The type checker tells me that I cannot use a Function
where I need a FunctionDefinition
…
Any clarification on how/when to use these is appreciated!