Categories
Projects

Function Calling Example with OpenAi Chat Completions API


I’m working on some stuff using function calling with the chat completions API from OpenAI, so I thought I would write a quick example of how to do this, for anyone who needs the help. Personally I haven’t found a lot of examples online of how to do this, so I imagine this simple example might be helpful to some.

I may expand on this with more detailed instructions later but I’m just providing this basic example in python for now.

import openai

# the 'prompt' for the chat completions API is a list of messages
chat_completions_prompt = [
  {'role': 'ai', 'message': 'what foods do you like/dislike?'},
  {'role': 'user', 'message': 'My favorite foods are apples, bananas, and carrots, but I don't like fish'}
]

# define the response data structure using jsonschema 
# https://json-schema.org/
user_preferences_function_json_schema = {
  "type": "object",
  "properties": {
    "likes": {"type": "array", "items": {"type": "string"}}
    "dislikes": {"type": "array", "items": {"type": "string"}}
  },
  "required": ["likes", "dislikes"]
}

# this is how you define a function to send to the API
get_user_preferences_open_ai_api_function = {
  name: 'get_user_preferences',
  description: 'organize user preferences into the correct categories',
  parameters: user_preferences_function_json_schema
}

# here is the actual completions call
# https://platform.openai.com/docs/api-reference/completions for reference
chat_completion = openai.ChatCompletion.create(
    model='gpt-3.5-turbo-0613',
    temperature=0,
    messages=chat_completions_prompt,
    functions=[get_user_preferences_open_ai_api_function],
    function_call={'name': 'get_user_preferences'}, # this can be 'none' or 'auto' but passing this object will ensure the function is called every time
)

# unless specified by the 'n' property in the api call, you'll only get one choice in the response
# the arguments property of function_call should be a data structure as defined in the json schema you provided
user_preferences = completion_response["choices"][0]["message"]["function_call"]["arguments"] 

print(user_preferences)

# expected output:
#
# {
#   "likes": ["apples", "bananas", "carrots"],
#   "dislikes": ["fish"]
# }
#

2 replies on “Function Calling Example with OpenAi Chat Completions API”

Leave a Reply

Your email address will not be published.