Created
December 1, 2023 23:27
-
-
Save raphael2692/c21f5688042ace96f1ec557efc996e32 to your computer and use it in GitHub Desktop.
"Hello world" of OpenAI function_calling
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
# main.py | |
import openai | |
import json | |
# Load OPENA_API_KEY from .env | |
from dotenv import load_dotenv | |
load_dotenv() | |
# Define a custom function you want your chatbot to use | |
def greet_someone(name:str) -> str: | |
return f"Hello {name}" | |
# Define the name, description and parameters of your function | |
function_specs = [ | |
{ | |
"name": "greet_someone", | |
"description" : "Say a funny insult to a given name", | |
"parameters" : { | |
"type" : "object", | |
"properties" : { | |
"name" : {"type" : "string", "description": "The name of the person to greet."} | |
} | |
}, | |
"required" : ["name"] | |
} | |
] | |
# Setup the chatbot | |
def chat_response(message:str) -> None: | |
# Setup a dict to store function and call them later | |
available_functions = { | |
"greet_someone" : greet_someone | |
} | |
# Setup conversation. Setting up the system message can be useful | |
messages = [{"role": "user", "content": message }] | |
response = openai.OpenAI().chat.completions.create( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
functions = function_specs, | |
function_call = 'auto' | |
) | |
# Check if the client understood which function could call to answer user message | |
if response.choices[0].message.function_call: | |
# Get the invoked function name | |
function_name = response.choices[0].message.function_call.name | |
# Get the invoked function args as a dictionary | |
function_args = json.loads(response.choices[0].message.function_call.arguments) | |
# Call the appropriate function with its args | |
function_response = available_functions[function_name](**function_args) | |
print(function_response) | |
else: | |
print("Unable to process request.") | |
# Process the conversation on the first user message | |
message = "Greet Mario please" | |
chat_response(message) | |
# >>> python main.py | |
# >>> Hello Mario |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment