Really struggling to figure out function calling. When attempting to build a function in the Playground assistants, the example looks like this:
{ "name": "get_weather", "description": "Determine weather in my location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": [ "c", "f" ] } }, "required": [ "location" ] } }
But there’s no actual code or API reference here. How do I specify what the function should call?
Hi @mikea
This is just a json schema describing the function, it’s not the function definition. The schema helps model know before hand what function(s) is/are available to the model and how to call them, should it need to.
Here’s the sample response for function call, now a subset of tools, from the API reference:
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1699896916,
"model": "gpt-3.5-turbo-0613",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": "{\n\"location\": \"Boston, MA\"\n}"
}
}
]
},
"logprobs": null,
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 82,
"completion_tokens": 17,
"total_tokens": 99
}
}
This example from the OpenAI Cookbook should help you get to speed with function calling.
Thanks @sps - I did read that doc too, which also makes reference to a ‘hypothetical’ weather function, but nowhere in the documentation do I see a call to a weather API actually specified. Maybe I’m misunderstanding how this works, but presumably it also needs a (python in my case) function that defines get_current_weather as an API call to weatherapi.com or similar?
Yes the json schema has to be of a function that you can call, once you receive the API response.
Once you have the response, you can validate and form the function call.
e.g
def my_function():
print("Hello, World!")
function_name = "my_function"
f = globals()[function_name]
f() # This will call my_function
In this example, globals()
is used to access the global namespace where my_function
is defined. If you’re dealing with a class or module, you would use getattr
instead.
In case you need to call a function with arguments, you can simply pass them when calling the function:
def greet(name):
print(f"Hello, {name}!")
function_name = "greet"
f = globals()[function_name]
f("Alice") # This will call greet("Alice")