API Reference
ChatGPT function calling based on function docstrings.
- class openai_functions.ArgSchemaParser(argtype: Type[T], rec_parsers: list[Type[openai_functions.parsers.abc.ArgSchemaParser]])
An abstract parser for a specific argument type
Both converts the argument definition to a JSON schema and parses the argument value from JSON.
- abstract property argument_schema: dict[str, JsonType]
Parse an argument of a specific type
- abstract classmethod can_parse(argtype: Any) TypeGuard[Type[T]]
Whether this parser can parse a specific arg type
- Parameters:
argtype (Any) – The type to check
- parse_rec(argtype: Type[S]) ArgSchemaParser[S]
Parse a type recursively
- Parameters:
argtype (Type[S]) – The type to parse
- Returns:
The parser for the type
- Return type:
- Raises:
CannotParseTypeError – If the type cannot be parsed
- abstract parse_value(value: JsonType) T
Parse a value of a specific type
- Parameters:
value (JsonType) – The value to parse
- Raises:
BrokenSchemaError – If the value does not match the schema
- class openai_functions.BasicFunctionSet(functions: list[openai_functions.functions.functions.OpenAIFunction] | None = None)
A skill set - a set of OpenAIFunction objects ready to be called. Inherited from MutableFunctionSet, therefore you can add and remove functions by using the @add_function and remove_function methods.
- Parameters:
functions (list[OpenAIFunction] | None) – The functions to initialize with.
- find_function(function_name: str) OpenAIFunction
Find a function in the skillset
- Parameters:
function_name (str) – The function name
- Returns:
The function of the given name
- Return type:
- Raises:
FunctionNotFoundError – If the function is not found
- property functions_schema: list[JsonType]
Get the functions schema, in the format OpenAI expects
- Returns:
The schema of all the available functions
- Return type:
JsonType
- get_function_result(function: OpenAIFunction, arguments: dict[str, JsonType]) RawFunctionResult | None
Get the result of a function’s execution
- Parameters:
function (OpenAIFunction) – The function to run
arguments (dict[str, JsonType]) – The arguments to run the function with
- Returns:
- The result of the function, or None if the
function does not save its return value
- Return type:
RawFunctionResult | None
- run_function(input_data: FunctionCall) FunctionResult
Run the function
- Parameters:
input_data (FunctionCall) – The function call
- Returns:
The function output
- Return type:
- Raises:
FunctionNotFoundError – If the function is not found
InvalidJsonError – If the arguments are not valid JSON
- exception openai_functions.BrokenSchemaError(response: JsonType, schema: JsonType)
The OpenAI response did not match the schema.
- response
The response that did not match the schema
- Type:
JsonType
- schema
The schema that the response did not match
- Type:
JsonType
- exception openai_functions.CannotParseTypeError(argtype: Any)
This type of the argument could not be parsed.
- argtype
The type that could not be parsed
- Type:
Any
- class openai_functions.Conversation(skills: list[FunctionSet] | None = None, model: str = 'gpt-3.5-turbo-0613', engine: str | None = None)
A class representing a single conversation with the AI
Contains the messages sent and received, and the skillset used.
- add_function(function: OpenAIFunction) OpenAIFunction
- add_function(function: Callable[[...], Any], *, name: str | None = None, description: str | None = None, save_return: bool = True, serialize: bool = True, remove_call: bool = False, interpret_as_response: bool = False) Callable[[...], Any]
- add_function(*, name: str | None = None, description: str | None = None, save_return: bool = True, serialize: bool = True, remove_call: bool = False, interpret_as_response: bool = False) Callable[[Callable[[...], Any]], Callable[[...], Any]]
Add a function to the functions available to the AI
- Parameters:
function (OpenAIFunction | Callable[..., Any]) – The function to add
name (str) – The name of the function. Defaults to the function’s name.
description (str) – The description of the function. Defaults to getting the short description from the function’s docstring.
save_return (bool) – Whether to send the return value of this function back to the AI. Defaults to True.
serialize (bool) – Whether to serialize the return value of this function. Otherwise, the return value must be a string.
remove_call (bool) – Whether to remove the function call itself from the chat history
interpret_as_response (bool) – Whether to interpret the return value of this function as the natural language response of the AI.
- Returns:
A decorator Callable[…, Any]: The original function
- Return type:
Callable[[Callable[…, Any]], Callable[…, Any]]
- add_function_result(function_result: FunctionResult) bool
Add a function execution result
If the function has a return value (save_return is True), it will be added to the chat. The function call will be removed depending on the remove_call attribute, and the function result will be interpreted as a response or a function call depending on the interpret_return_as_response attribute.
- Parameters:
function_result (FunctionResult) – The function result
- Returns:
Whether the function result was added
- Return type:
bool
- add_message(message: GenericMessage | MessageType | str) None
Add a message to the end of the conversation
- Parameters:
message (GenericMessage | MessageType | str) – The message
- add_messages(messages: list[GenericMessage | MessageType]) None
Add multiple messages to the end of the conversation
- Parameters:
messages (list[GenericMessage | MessageType]) – The messages
- add_skill(skill: FunctionSet) None
Add a skill to those available to the AI
- Parameters:
skill (FunctionSet) – The skill to add
- ask(question: str, retries: int | None = 1) str
Ask the AI a question, running until a response is generated
- Parameters:
question (str) – The question
retries (int | None) – The number of retries; if None, will retry indefinitely
- Returns:
The answer to the question
- Return type:
str
- clear_messages() None
Fully clear the messages, but keep the skillset
- property functions_schema: list[JsonType]
Get the functions schema for the conversation
- Returns:
The functions schema
- Return type:
list[JsonType]
- generate_message(function_call: OpenAiFunctionCallInput = 'auto', retries: int | None = 1) GenericMessage
Generate the next message. Will run a function if the last message was a function call and the function call is not being overridden; if the function does not save the return a message will still be generated.
- Parameters:
function_call (OpenAiFunctionCallInput) – The function call
retries (int | None) – The number of retries; if None, will retry indefinitely
- Returns:
The response
- Return type:
- pop_message(index: int = -1) GenericMessage
Pop a message
- Parameters:
index (int) – The index. Defaults to -1.
- Returns:
The message
- Return type:
- remove_function(function: str | OpenAIFunction | Callable[..., Any]) None
Remove a function
- Parameters:
function (str | OpenAIFunction | Callable[..., Any]) – The function
- remove_function_call(function_name: str) None
Remove a function call from the messages, if it is the last message
- Parameters:
function_name (str) – The function name
- run(function: str, prompt: str | None = None, retries: int | None = 1) Any
Run a specified function and return the raw function result
- Parameters:
function (str) – The function to run
prompt (str | None) – The prompt to use
retries (int | None) – The number of retries; if None, will retry indefinitely
- Returns:
The raw function result
- run_function_and_substitute(function_call: FunctionCall) bool
Run a function, replacing the last message with the result if needed
- Parameters:
function_call (FunctionCall) – The function call
- Raises:
TypeError – If the function returns a None value
- Returns:
- Whether the function result was added to the chat
(whether save_return was True)
- Return type:
bool
- run_function_if_needed() bool
Run a function if the last message was a function call
Might run the function over and over again if the function does not save the return.
- Returns:
Whether the function result was added
- Return type:
bool
- run_until_response(allow_function_calls: bool = True, retries: int | None = 1) FinalResponseMessage
Run functions query the AI until a response is generated
- Parameters:
allow_function_calls (bool) – Whether to allow the AI to call functions
retries (int | None) – The number of retries; if None, will retry indefinitely
- Returns:
- The final response, either from the AI or a function
that has interpret_as_response set to True
- Return type:
- class openai_functions.FinalResponseMessage(message: FinalResponseMessageType | UserMessageType | IntermediateResponseMessageType | FunctionMessageType)
- class openai_functions.FinalResponseMessage(message: str)
- class openai_functions.FinalResponseMessage(message: str, role: Literal['system', 'user', 'assistant'])
A container for OpenAI final response messages
Inherited from GenericMessage, acts the same, just restricts the message to have content and not be a function call
- property content: str
Get the content of the message
- property function_call: None
Get the function call
- property is_final_response: Literal[True]
Check if the message is a final response
- class openai_functions.FunctionCall
A container for OpenAI function calls
- name
The name of the function
- Type:
str
- arguments
The arguments of the function, in JSON format
- Type:
str
- exception openai_functions.FunctionNotFoundError(function_name: str)
The function was not found in the given skillset.
- function_name
The name of the function that was not found
- Type:
str
- class openai_functions.FunctionResult(name: str, raw_result: RawFunctionResult | None, remove_call: bool = False, interpret_return_as_response: bool = False)
A result of a function’s execution
- property content: str | None
Get the content of this result
- Returns:
The content
- Return type:
str | None
- property result: Any | None
Get the result of this function call
- Returns:
The raw result of the function call
- class openai_functions.FunctionSet
A skill set - a provider for a functions schema and a function runner
- abstract property functions_schema: list[JsonType]
Get the functions schema
- abstract run_function(input_data: FunctionCall) FunctionResult
Run the function
- Parameters:
input_data (FunctionCall) – The function call
- Raises:
FunctionNotFoundError – If the function is not found
- class openai_functions.FunctionWrapper(func: Callable[[...], Any], config: WrapperConfig | None = None, name: str | None = None, description: str | None = None)
Wraps a function for jsonschema io
Provides a function schema and a function runner - the function schema is generated from the function’s docstring and argument type annotations, and the function runner parses the arguments from JSON and runs the function. They are accessed via the schema property and a __call__ method respectively.
- Parameters:
func (Callable[..., Any]) – The function to wrap
config (WrapperConfig | None, optional) – The configuration for the wrapper.
- property arg_docs: dict[str, str]
Get the argument docs for this function
- Returns:
The argument docs
- Return type:
dict[str, str]
- property argument_parsers: OrderedDict[str, ArgSchemaParser]
Get the argument parsers for this function
- Returns:
The argument parsers
- Return type:
OrderedDict[str, ArgSchemaParser]
- property arguments_schema: JsonType
Get the arguments schema for this function
- Returns:
The arguments schema
- Return type:
JsonType
- property interpret_as_response: bool
Get whether to interpret the return value as an assistant response
- Returns:
Whether to interpret the return value as a response
- Return type:
bool
- property name: str
Get the name of this function
- Returns:
The name
- Return type:
str
- parse_argument(argument: Parameter) ArgSchemaParser
Parse an argument
- Parameters:
argument (inspect.Parameter) – The argument to parse
- Raises:
CannotParseTypeError – If the argument cannot be parsed
- Returns:
The parser for the argument
- Return type:
- parse_arguments(arguments: dict[str, JsonType]) OrderedDict[str, Any]
Parse arguments
- Parameters:
arguments (dict[str, JsonType]) – The arguments to parse
- Raises:
BrokenSchemaError – If the arguments do not match the schema
- Returns:
The parsed arguments
- Return type:
OrderedDict[str, Any]
- property parsed_docs: Docstring
Get the parsed docs for this function
- Returns:
The parsed docs
- Return type:
Docstring
- property parsers: list[Type[openai_functions.parsers.abc.ArgSchemaParser]]
Get the parsers for this function
- Returns:
The parsers
- Return type:
list[Type[ArgSchemaParser]]
- property remove_call: bool
Get whether to remove the call to this function from the chat history
- Returns:
Whether to remove the call to this function from the chat history
- Return type:
bool
- property required_arguments: JsonType
Get the required arguments for this function
- Returns:
The required arguments
- Return type:
JsonType
- property save_return: bool
Get whether to send the return value of this function to the AI
- Returns:
Whether to send the return value to the AI
- Return type:
bool
- property schema: dict[str, JsonType]
Get the schema for this function
- Returns:
The schema
- Return type:
dict[str, JsonType]
- property serialize: bool
Get whether to serialize the return value of this function
The function should return strictly a string if this is false.
- Returns:
Whether to serialize the return value
- Return type:
bool
- class openai_functions.GenericMessage(message: FinalResponseMessageType | UserMessageType | IntermediateResponseMessageType | FunctionMessageType)
- class openai_functions.GenericMessage(message: str)
- class openai_functions.GenericMessage(message: str, role: Literal['system', 'user', 'assistant'])
A container protocol for OpenAI messages
- as_dict() FinalResponseMessageType | UserMessageType | IntermediateResponseMessageType | FunctionMessageType
Get the message as a dictionary
- property content: str | None
Get the content of the message
- property function_call: FunctionCall | None
Get the function call
- property is_final_response: bool
Check if the message is a final response
- property is_function_call: bool
Check if the message is a function call
- property role: Literal['system', 'user', 'assistant', 'function']
Get the role of the message
- exception openai_functions.InvalidJsonError(response: str)
OpenAI returned invalid JSON for the arguments.
- response
The response that was not valid JSON
- Type:
str
- class openai_functions.Message(message: FinalResponseMessageType | UserMessageType | IntermediateResponseMessageType | FunctionMessageType)
- class openai_functions.Message(message: str)
- class openai_functions.Message(message: str, role: Literal['system', 'user', 'assistant'])
A container for OpenAI messages
- as_dict() FinalResponseMessageType | UserMessageType | IntermediateResponseMessageType | FunctionMessageType
Get the message as a dictionary
- Returns:
The message
- Return type:
MessageType
- property content: str | None
Get the content of the message
- Returns:
The content of the message
- Return type:
str | None
- property function_call: FunctionCall | None
Get the function call
- Returns:
The function call
- Return type:
FunctionCall | None
- property is_final_response: bool
Check if the message is a final response
- Returns:
Whether the message is a final response
- Return type:
bool
- property is_function_call: bool
Check if the message is a function call
- Returns:
Whether the message is a function call
- Return type:
bool
- property role: Literal['system', 'user', 'assistant', 'function']
Get the role of the message
- Returns:
The role of the message
- Return type:
Literal[“system”, “user”, “assistant”, “function”]
- class openai_functions.MutableFunctionSet
A skill set that can be modified - functions can be added and removed
- add_function(function: OpenAIFunction) OpenAIFunction
- add_function(function: Callable[[...], Any], *, name: str | None = None, description: str | None = None, save_return: bool = True, serialize: bool = True, remove_call: bool = False, interpret_as_response: bool = False) Callable[[...], Any]
- add_function(*, name: str | None = None, description: str | None = None, save_return: bool = True, serialize: bool = True, remove_call: bool = False, interpret_as_response: bool = False) Callable[[Callable[[...], Any]], Callable[[...], Any]]
Add a function
- Parameters:
function (OpenAIFunction | Callable[..., Any]) – The function
name (str) – The name of the function. Defaults to the function’s name.
description (str) – The description of the function. Defaults to getting the short description from the function’s docstring.
save_return (bool) – Whether to send the return value of this function to the AI. Defaults to True.
serialize (bool) – Whether to serialize the return value of this function. Defaults to True. Otherwise, the return value must be a string.
remove_call (bool) – Whether to remove the function call from the AI’s chat history. Defaults to False.
interpret_as_response (bool) – Whether to interpret the return value of this function as a response of the agent. Defaults to False.
- Returns:
A decorator Callable[…, Any]: The original function
- Return type:
Callable[[Callable[…, Any]], Callable[…, Any]]
- remove_function(function: str | OpenAIFunction | Callable[[...], Any]) None
Remove a function
- Parameters:
function (str | OpenAIFunction | Callable[..., Any]) – The function
- class openai_functions.NaturalLanguageAnnotated(function_result: T, annotation: str)
A natural language annotated function return value
- exception openai_functions.NonSerializableOutputError(result: Any)
The function returned a non-serializable output.
- result
The result that was not serializable
- Type:
Any
- class openai_functions.OpenAIFunction(*args, **kwargs)
A protocol for OpenAI functions.
Requires a __call__ method, a schema property, and a name property, as well as those that define the treatment of the return value.
- property interpret_as_response: bool
Get whether to interpret the return value of this function as a response
- property name: str
Get the name of this function
- property remove_call: bool
Get whether to remove the call to this function from the chat history
- property save_return: bool
Get whether to save the return value of this function
- property schema: JsonType
Get the schema for this function
- property serialize: bool
Get whether to continue running after this function
- exception openai_functions.OpenAIFunctionsError
The base exception for all OpenAI Functions errors.
- class openai_functions.RawFunctionResult(result: Any, serialize: bool = True)
A raw function result
- property serialized: str
Get the serialized result
- Raises:
NonSerializableOutputError – If the result cannot be serialized
- Returns:
The serialized result
- Return type:
str
- class openai_functions.TogglableSet(enable_function_name: str, enable_function_description: str | None = None, functions: list[openai_functions.functions.functions.OpenAIFunction] | None = None)
A function set that is disabled by default and can be enabled by the AI.
- Parameters:
enable_function_name (str) – The name of the function to enable the set
enable_function_description (str, optional) – The description of the enable function. By default no description is provided.
functions (list[OpenAIFunction], optional) – The functions in the set.
- enable() None
Enable the function set.
- property functions_schema: list[JsonType]
Get the functions schema, in the format OpenAI expects
- Returns:
The schema of all the available functions
- Return type:
JsonType
- run_function(input_data: FunctionCall) FunctionResult
Run the function, enabling the set if the enable function is called.
- Parameters:
input_data (FunctionCall) – The function call
- Returns:
The function output
- Return type:
- Raises:
FunctionNotFoundError – If the function is not found
- class openai_functions.UnionSkillSet(*sets: FunctionSet)
A function set that’s a union of other function sets.
- add_skill(skill: FunctionSet) None
Add a skill
- Parameters:
skill (FunctionSet) – The skill
- property functions_schema: list[JsonType]
Get the combined functions schema
- Returns:
The combined functions schema
- Return type:
list[JsonType]
- run_function(input_data: FunctionCall) FunctionResult
Run the function
- Parameters:
input_data (FunctionCall) – The function call
- Returns:
The function output
- Return type:
- Raises:
FunctionNotFoundError – If the function is not found
- class openai_functions.Wrapper(origin: Callable[[...], Return], config: NLPWrapperConfig)
A wrapper for a function that provides a natural language interface
- from_natural_language(prompt: str, retries: int | None = 1) Return
Run the function with the given natural language input
- Parameters:
prompt (str) – The prompt to use
retries (int | None) – The number of retries; if None, will retry indefinitely
- Returns:
The result of the original function
- natural_language_annotated(prompt: str, retries: int | None = 1) NaturalLanguageAnnotated[Return]
Run the function and respond to the user with natural language as well as the raw function result
- Parameters:
prompt (str) – The prompt to use
retries (int | None) – The number of retries; if None, will retry indefinitely
- Returns:
The response from the AI
- Return type:
- natural_language_response(prompt: str, retries: int | None = 1) str
Run the function and respond to the user with natural language
- Parameters:
prompt (str) – The prompt to use
retries (int | None) – The number of retries; if None, will retry indefinitely
- Returns:
The response from the AI
- Return type:
str
- class openai_functions.WrapperConfig(parsers: list[Type[openai_functions.parsers.abc.ArgSchemaParser]] | None = None, save_return: bool = True, serialize: bool = True, remove_call: bool = False, interpret_as_response: bool = False)
Configuration for a FunctionWrapper, one that specifies the parsers for the arguments and the treatment of the return value.
- Parameters:
parsers (list[Type[ArgSchemaParser]] | None) – The parsers for the arguments. defaults to defargparsers, which support all JSON types, as well as enums and dataclasses
save_return (bool) – Whether to send the return value back to the AI
serialize (bool) – Whether to serialize the return value; if False, the return value must be a string
remove_call (bool) – Whether to remove the call to this function from the chat history
interpret_as_response (bool) – Whether to interpret the return value as a response from the agent directly, or to base the response on the return value
- openai_functions.nlp(function: Callable[[Param], Return] | None = None, *, name: str | None = None, description: str | None = None, serialize: bool = True, system_prompt: str | None = None, model: str = 'gpt-3.5-turbo-0613', engine: str | None = None) Wrapper[Param, Return] | DecoratorProtocol
Add natural language input to a function
- Parameters:
function (Callable | None) – The function to add natural language input to
name (str | None) – The name override for the function, will be inferred from the function name if not provided.
description (str | None) – The description sent to OpenAI, defaults to the short description from the function docstring.
serialize (bool) – Whether to serialize the function result.
system_prompt (str | None) – The system prompt to use. Defaults to None.
model (str) – The model to use. Defaults to “gpt-3.5-turbo-0613”.
engine (str | None) – The engine to use, for example, for Azure deployments.
- Returns:
The function, with natural language input, or a decorator to add natural language input to a function
- Return type:
Wrapper | DecoratorProtocol