orhanerday / open-ai

OpenAI PHP SDK : Most downloaded, forked, contributed, huge community supported, and used PHP (Laravel , Symfony, Yii, Cake PHP or any PHP framework) SDK for OpenAI GPT-3 and DALL-E. It also supports chatGPT-like streaming. (ChatGPT AI is supported)
https://orhanerday.gitbook.io/openai-php-api-1/
MIT License
2.23k stars 286 forks source link

json_object #126

Open MwSpaceLLC opened 9 months ago

MwSpaceLLC commented 9 months ago

Describe the feature or improvement you're requesting

Please, see at: https://platform.openai.com/docs/guides/text-generation/json-mode

            $chat = json_decode(
                $open_ai->completion([
                    'model' => 'gpt-4-1106-preview',
                    'prompt' => $prompt,
                    'temperature' => 0.7,
                    'max_tokens' => 1024,
                    "top_p" => 1,
                    'frequency_penalty' => 0,
                    'presence_penalty' => 0,
                    'response_format ' => [
                        'type' => "json_object"
                    ]
                ])
            );

Additional context

No response

jamesmalin commented 9 months ago

Yes, it works great! I've been using this in all of my projects. Was super easy to use out of the box with this package.

Although it's straight forward, might be worth adding an example to the README.md for others searching for the feature across PHP GitHub projects.

Created a pull request: https://github.com/orhanerday/open-ai/pull/128

Adding PR here:

$complete = $open_ai->chat([
    'model' => 'gpt-3.5-turbo-1106',
    'messages' => [
            [
                'role' => 'system',
                'content' => 'You are a zoologist.'
            ],
            [
                'role' => 'system',
                'content' => 'Respond with JSON. Use this structure: [{"animal":"","description":""}]'
            ],
            [
                'role' => 'user',
                'content' => 'Supply a list of the most common animals you would see in a zoo.'
            ],
    ],
    'temperature' => 1,
    'max_tokens' => 3500,
    'response_format' => [ 'type' => 'json_object' ]
]);
christoph-werker commented 4 months ago

Just a quick note for everyone whoe stumpled over this issue.

$open_ai->completion([…]); won't work due to error Unrecognized request argument supplied: response_format.

But $open_ai->->chat works:

$result = json_decode($open_ai->chat([
    'model' => 'gpt-3.5-turbo-1106',
    'messages' => [
        [
            'role' => 'system',
            'content' => 'Respond with JSON. Use the provided keys to answer the question.',
        ],
        [
            'role' => 'user',
            'content' => $prompt
        ],
    ],
    'temperature' => 1,
    'max_tokens' => 3500,
    'response_format' => ['type' => 'json_object']
]), false, 512, JSON_THROW_ON_ERROR);

Have fun.