openai-php / client

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
MIT License
4.82k stars 499 forks source link

Error when request contains function without parameters #262

Closed vadimpronin closed 10 months ago

vadimpronin commented 10 months ago

When calling chat completions endpoint with "tools" parameter which contains a function without parameters the following error is thrown:

Invalid schema for function 'myFunctionName': [] is not of type 'object'

Example request:

$request = [
    "model" => "gpt-4",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant",
        ],
        [
            "role" => "user",
            "content" => "hello",
        ],
    ],
    "max_tokens" => 300,
    "tools" => [
        [
            "type" => "function",
            "function" => [
                "name" => "myFunctionName",
                "description" => "My dummy function",
                "parameters" => [
                    "type" => "object",
                    "properties" => [], // Error is here
                ],
            ],
        ],
    ],
];

$client = OpenAI::client($yourApiKey);
$client->chat()->create($request);

This happens because empty array $request['tools'][0]['function']['parameters'] is json encoded into [] instead of {} as required by OpenAI API:

https://platform.openai.com/docs/api-reference/chat/create

To describe a function that accepts no parameters, provide the value {"type": "object", "properties": {}}.
gehrisandro commented 10 months ago

@vadimpronin Thank you for raising the issue. You should be able work around this by using "properties" => (object) [],.

But I haven't tested it. Would love to hear if this solves your problem.

The other option would be to use JSON_FORCE_OBJECT when we do json_encode in the client. But I am currently not sure if this would break other stuff.

vadimpronin commented 10 months ago

"properties" => (object) [] did help, thank you!