Sample code for "Function calling

I found a mistake in the sample code.

Since message.get("location") returns None, the argument is not set to the expected value.
This is because location is a child of arguments, not message.
However, since this parameter is not used, the code can be executed without problems.

        # Step 3, call the function
        # Note: the JSON response from the model may not be valid JSON
        function_response = get_current_weather(
            location=message.get("location"),
            unit=message.get("unit"),
        )
1 Like

Hello together,

I can also confirm that message.get(“location”) is None.
The return value of the function is then as follows:

‘{“location”: null, “temperature”: “50”, “unit”: null, “forecast”: [“sunny”, “windy”]}’

I have also tested whether so the answer of the AI also mentions Boston and indeed the following answer comes:

‘The current weather in Boston is sunny and windy with a temperature of 50 degrees.’

This apparently results from the question of what the weather is like in Boston. Although the return value for the location is None, Boston is assumed.

It seems difficult to access the arguments.

{
  "content": null,
  "function_call": {
    "arguments": "{\n  \"location\": \"Boston, MA\"\n}",
    "name": "get_current_weather"
  },
  "role": "assistant"
}

message.function_call.arguments is a string so I can’t use .get method.

Kind regards,
Michele

1 Like

I can also confirm. Therefore it’s not clear how to call the functions with arguments.

1 Like

Looks like no one debugged the sample or API is being changed already :slight_smile: Anyway this should work fine:

arguments=message[“function_call”][“arguments”]
arg_dict = json.loads(arguments)

location=arg_dict[“location”] if “location” in arg_dict else None,
unit=arg_dict[“unit”] if “unit” in arg_dict else None,

2 Likes
args = json.loads(message[“arguments”])
function(**args)

Not ideal, but it works…

1 Like

for java code e.g:

Oh wow. So message["arguments"] is not a valid json object, it’s a python object. It must be eval’d :frowning:

From this file:

query = eval(message["function_call"]["arguments"])["query"]

This seems incredibly unsafe. Why would an API return such object instead of a json parsable string?

Here’s a safer way to do it:

import ast
...
query = ast.literal_eval(message["function_call"]["arguments"])["query"]

What would this code for a function call look like in Python?