Package: openai-function-call
Instructor (openai_function_call)Structured extraction in Python, powered by OpenAI's function calling api, designed for simplicity, transparency, and control.This library is built to interact with openai's function call api from python code, with python structs / objects. It's designed to be intuitive, easy to use, but give great visibily in how we call openai.RequirementsThis library depends onPydanticandOpenAIthat's all.InstallationTo get started with OpenAI Function Call, you need to install it usingpip. Run the following command in your terminal:$pipinstallinstructorQuick Start with Patching ChatCompletionTo simplify your work with OpenAI models and streamline the extraction of Pydantic objects from prompts, we offer a patching mechanism for the `ChatCompletion`` class. Here's a step-by-step guide:Step 1: Import and Patch the ModuleFirst, import the required libraries and apply the patch function to the OpenAI module. This exposes new functionality with the response_model parameter.importopenaifrompydanticimportBaseModelfrominstructorimportpatchpatch()Step 2: Define the Pydantic ModelCreate a Pydantic model to define the structure of the data you want to extract. This model will map directly to the information in the prompt.classUserDetail(BaseModel):name:strage:intStep 3: Extract Data with ChatCompletionUse the openai.ChatCompletion.create method to send a prompt and extract the data into the Pydantic object. The response_model parameter specifies the Pydantic model to use for extraction.user:UserDetail=openai.ChatCompletion.create(model="gpt-3.5-turbo",response_model=UserDetail,messages=[{"role":"user","content":"Extract Jason is 25 years old"},])Step 4: Validate the Extracted DataYou can then validate the extracted data by asserting the expected values. By adding the type things you also get a bunch of nice benefits with your IDE like spell check and auto complete!assertuser.name=="Jason"assertuser.age==25Introduction toOpenAISchemaIf you want more control than just passing a single class we can use theOpenAISchemawhich extendsBaseModel.This quick start guide contains the follow sections:Defining a schemaAdding Additional PromptingCalling the ChatCompletionDeserializing back to the instanceOpenAI Function Call allows you to leverage OpenAI's powerful language models for function calls and schema extraction. This guide provides a quick start for using OpenAI Function Call.Section 1: Defining a SchemaTo begin, let's define a schema using OpenAI Function Call. A schema describes the structure of the input and output data for a function. In this example, we'll define a simple schema for aUserobject:frominstructorimportOpenAISchemaclassUserDetails(OpenAISchema):name:strage:intIn this schema, we define aUserDetailsclass that extendsOpenAISchema. We declare two fields,nameandage, of typestrandintrespectively.Section 2: Adding Additional PromptingTo enhance the performance of the OpenAI language model, you can add additional prompting in the form of docstrings and field descriptions. They can provide context and guide the model on how to process the data.!!! note Usingpatchthese docstrings and fields descriptions are powered bypydantic.BaseModelso they'll work via the patching approach as well.frominstructorimportOpenAISchemafrompydanticimportFieldclassUserDetails(OpenAISchema):"Correctly extracted user information"name:str=Field(...,description="User's full name")age:intIn this updated schema, we use theFieldclass frompydanticto add descriptions to thenamefield. The description provides information about the field, giving even more context to the language model.!!! note "Code, schema, and prompt"
We can runopenai_schemato see exactly what the API will see, notice how the docstrings, attributes, types, and field descriptions are now part of the schema. This describes on this library's core philosophies.classUserDetails(OpenAISchema):"Correctly extracted user information"name:str=Field(...,description="User's full name")age:intUserDetails.openai_schema{"name":"UserDetails","description":"Correctly extracted user information","parameters":{"type":"object","properties":{"name":{"description":"User's full name","type":"string"},"age":{"type":"integer"}},"required":["age","name"]}}Section 3: Calling the ChatCompletionWith the schema defined, let's proceed with calling theChatCompletionAPI using the defined schema and messages.frominstructorimportOpenAISchemafrompydanticimportFieldclassUserDetails(OpenAISchema):"Correctly extracted user information"name:str=Field(...,description="User's full name")age:intcompletion=openai.ChatCompletion.create(model="gpt-3.5-turbo-0613",functions=[UserDetails.openai_schema],function_call={"name":UserDetails.openai_schema["name"]},messages=[{"role":"system","content":"Extract user details from my requests"},{"role":"user","content":"My name is John Doe and I'm 30 years old."},],)In this example, we make a call to theChatCompletionAPI by providing the model name (gpt-3.5-turbo-0613) and a list of messages. The messages consist of a system message and a user message. The system message sets the context by requesting user details, while the user message provides the input with the user's name and age.Note that we have omitted the additional parameters that can be included in the API request, such astemperature,max_tokens, andn. These parameters can be customized according to your requirements.Section 4: Deserializing Back to the InstanceTo deserialize the response from theChatCompletionAPI back into an instance of theUserDetailsclass, we can use thefrom_responsemethod.user=UserDetails.from_response(completion)print(user.name)# Output: John Doeprint(user.age)# Output: 30By callingUserDetails.from_response, we create an instance of theUserDetailsclass using the response from the API call. Subsequently, we can access the extracted user details through thenameandageattributes of theuserobject.IDE SupportEverything is designed for you to get the best developer experience possible, with the best editor support.Includingautocompletion:And eveninline errorsOpenAI Schema and PydanticThis quick start guide provided you with a basic understanding of how to use OpenAI Function Call for schema extraction and function calls. You can now explore more advanced use cases and creative applications of this library.SinceUserDetailsis aOpenAISchemsand apydantic.BaseModelyou can use inheritance and nesting to create more complex emails while avoiding code duplicationclassUserDetails(OpenAISchema):name:str=Field(...,description="User's full name")age:intclassUserWithAddress(UserDetails):address:strclassUserWithFriends(UserDetails):best_friend:UserDetailsfriends:List[UserDetails]If you have any questions, feel free to leave an issue or reach out to the library's author onTwitter. For a more comprehensive solution with additional features, consider checking outMarvinAI.To see more examples of how we can create interesting models check out someexamples.LicenseThis project is licensed under the terms of the MIT License.