Last active
June 14, 2023 09:19
-
-
Save jxnl/e3a6ab36b586eca4706f405b5548eea4 to your computer and use it in GitHub Desktop.
Creating objects using Pydantic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import openai | |
from pydantic import BaseModel, Field | |
class OpenAISchema(BaseModel): | |
@classmethod | |
@property | |
def openai_schema(cls): | |
schema = cls.schema() | |
return { | |
"name": schema["title"], | |
"description": schema["description"], | |
"parameters": schema | |
} | |
@classmethod | |
def from_response(cls, completion, throw_error=True): | |
message = completion.choices[0].message | |
if throw_error: | |
assert "function_call" in message, "No function call detected" | |
assert message["function_call"]["name"] == cls.openai_schema["name"], "Function name does not match" | |
function_call = message["function_call"] | |
arguments = json.loads(function_call["arguments"]) | |
return cls(**arguments) | |
# Note: The docstring and the description are used as part of the prompt, detailed desc and docs | |
# can be used to provide more information about the function | |
class Arguments(OpenAISchema): | |
"""Arguments to add""" | |
a: int = Field(..., description="First argument") | |
b: int = Field(..., description="Second argument") | |
completion = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-0613", | |
temperature=0, | |
functions=[Arguments.openai_schema], | |
messages=[ | |
{ | |
"role": "system", | |
"content": "You must use the `arguments` function instead of adding yourself.", | |
}, | |
{ | |
"role": "user", | |
"content": "What is 6+3, use the arguments", | |
}, | |
], | |
) | |
Arguments.from_response(completion) | |
# Arguments(a=6, b=3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment