PHP code example of muhammetsafak / openai-client

1. Go to this page and download the library: Download muhammetsafak/openai-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

muhammetsafak / openai-client example snippets


use MuhammetSafak\OpenAI\OpenAI;
use MuhammetSafak\OpenAI\Services\Completions;
const SECRET_KEY = "";

$openai = new OpenAI(SECRET_KEY);
$openai->setPrompt($_GET['prompt'])
    ->setTemperature(0.7);

$res = (new Completions($openai))->get();

echo $res['response']['choices'][0]['text'];

[
    'status'        => true,
    'message'       => '',
    'response'      => [
        "id" => "cmpl-8WlS2x6looAGlj8Z182D3M...",
        "object" => "text_completion",
        "created" => 1702819590,
        "model" => "davinci-002",
        "choices" => [
            0 => [
                "text" => "...",
                "index" => 0,
                "logprobs" => null,
                "finish_reason" => "stop",
            ],
        ],
        "usage" => [
                "prompt_tokens" => 1,
                "completion_tokens" => 81,
                "total_tokens" => 32,
        ],
    ]
]

use MuhammetSafak\OpenAI\OpenAI;
use MuhammetSafak\OpenAI\Services\Chat;
const SECRET_KEY = "";

$openai = new OpenAI(SECRET_KEY);
$openai->setPrompt($systemMessage)
    ->setTemperature(0.7);
    
$res = (new Chat($openai))
    ->setUserMessage($userMessage)
    ->get();

echo $res['response']['choices'][0]['message']['content'];

[
    'status'        => true,
    'message'       => '',
    'response'      => [
        "id" => "chatcmpl-8WmzZ2uCDqBZ83BFWbAaifeDNHmlG",
        "object" => "chat.completion",
        "created" => 1702825513,
        "model" => "gpt-3.5-turbo-0613",
        "choices" => [
            0 => [
                "index" => 0,
                "message" => [
                    "role" => "assistant",
                    "content" => "",
                ],
                "logprobs" => null,
                "finish_reason" => "stop",
            ],
        ],
        "usage" => [
                "prompt_tokens" => 121,
                "completion_tokens" => 8,
                "total_tokens" => 129,
        ],
        "system_fingerprint" => null,
    ]
]