Last active
November 24, 2023 20:14
-
-
Save narenaryan/e8a5aac3825b0e752cf70daa69abb65a to your computer and use it in GitHub Desktop.
This gist shows an example to use OpenAI function calling with Python. See full article here: https://medium.com/dev-bits/a-clear-guide-to-openai-function-calling-with-python-dcbc200c5d70
This file contains 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 | |
import os | |
import json | |
from typing import List | |
from pydantic import BaseModel | |
# set Open AI API Key | |
api_key = os.getenv("OPENAI_API_KEY") | |
assert api_key is not None, "API Key not set in environment" | |
openai.api_key = api_key | |
# create a PyDantic schema for output | |
class StepByStepAIResponse(BaseModel): | |
title: str | |
steps: List[str] | |
# make a call to open ai | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-0613", | |
messages=[ | |
{"role": "user", "content": "Explain how to assemble a PC"} | |
], | |
functions=[ | |
{ | |
"name": "get_answer_for_user_query", | |
"description": "Get user answer in series of steps", | |
"parameters": StepByStepAIResponse.schema() | |
} | |
], | |
function_call={"name": "get_answer_for_user_query"} | |
) | |
# parse JSON output from AI model | |
output = json.loads(response.choices[0]["message"]["function_call"]["arguments"]) | |
# load JSON optionally into PyDantic model (or) use it directly | |
sbs = StepByStepAIResponse(**output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment