PHP code example of orhanerday / open-ai

1. Go to this page and download the library: Download orhanerday/open-ai 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/ */

    

orhanerday / open-ai example snippets




rhanerday\OpenAi\OpenAi;

$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key);

$chat = $open_ai->chat([
   'model' => 'gpt-3.5-turbo',
   'messages' => [
       [
           "role" => "system",
           "content" => "You are a helpful assistant."
       ],
       [
           "role" => "user",
           "content" => "Who won the world series in 2020?"
       ],
       [
           "role" => "assistant",
           "content" => "The Los Angeles Dodgers won the World Series in 2020."
       ],
       [
           "role" => "user",
           "content" => "Where was it played?"
       ],
   ],
   'temperature' => 1.0,
   'max_tokens' => 4000,
   'frequency_penalty' => 0,
   'presence_penalty' => 0,
]);


var_dump($chat);
echo "<br>";
echo "<br>";
echo "<br>";
// decode response
$d = json_decode($chat);
// Get Content
echo($d->choices[0]->message->content);



rhanerday\OpenAi\OpenAi;

$nvidia_ai_key = getenv('NVIDIA_AI_API_KEY');
error_log($open_ai_key);
$open_ai = new OpenAi($nvidia_ai_key);
$open_ai->setBaseURL("https://integrate.api.nvidia.com");
$chat = $open_ai->chat([
    'model' => 'mistralai/mixtral-8x7b-instruct-v0.1',
    'messages' => [["role" => "user", "content" => "Write a limmerick about the wonders of GPU computing."]],
    'temperature' => 0.5,
    'max_tokens' => 1024,
    'top_p' => 1,
]);

var_dump($chat);
echo "<br>";
echo "<br>";
echo "<br>";
// decode response
$d = json_decode($chat);
// Get Content
echo ($d->choices[0]->message->content);


use Orhanerday\OpenAi\OpenAi;

$open_ai = new OpenAi(env('OPEN_AI_API_KEY'));

$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key);
$open_ai->setORG("org-IKN2E1nI3kFYU8ywaqgFRKqi");

$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key,$originURL);
$open_ai->setBaseURL("https://ai.example.com/");

$open_ai->setProxy("http://127.0.0.1:1086");

$open_ai->setHeader(["Connection"=>"keep-alive"]);

$open_ai = new OpenAi($open_ai_key);
echo $open_ai->listModels(); // you should execute the request FIRST!
var_dump($open_ai->getCURLInfo()); // You can call the request

$complete = $open_ai->chat([
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "Who won the world series in 2020?"
        ],
        [
            "role" => "assistant",
            "content" => "The Los Angeles Dodgers won the World Series in 2020."
        ],
        [
            "role" => "user",
            "content" => "Where was it played?"
        ],
    ],
    'temperature' => 1.0,
    'max_tokens' => 4000,
    'frequency_penalty' => 0,
    'presence_penalty' => 0,
]);


// Dummy Response For Chat API
$j = '
{
   "id":"chatcmpl-*****",
   "object":"chat.completion",
   "created":1679748856,
   "model":"gpt-3.5-turbo-0301",
   "usage":{
      "prompt_tokens":9,
      "completion_tokens":10,
      "total_tokens":19
   },
   "choices":[
      {
         "message":{
            "role":"assistant",
            "content":"This is a test of the AI language model."
         },
         "finish_reason":"length",
         "index":0
      }
   ]
}
';

// decode response
$d = json_decode($j);

// Get Content
echo($d->choices[0]->message->content);

$complete = $open_ai->completion([
    'model' => 'gpt-3.5-turbo-instruct',
    'prompt' => 'Hello',
    'temperature' => 0.9,
    'max_tokens' => 150,
    'frequency_penalty' => 0,
    'presence_penalty' => 0.6,
]);

$open_ai = new OpenAi(env('OPEN_AI_API_KEY'));

$opts = [
    'prompt' => "Hello",
    'temperature' => 0.9,
    "max_tokens" => 150,
    "frequency_penalty" => 0,
    "presence_penalty" => 0.6,
    "stream" => true,
];

header('Content-type: text/event-stream');
header('Cache-Control: no-cache');

$open_ai->completion($opts, function ($curl_info, $data) {
    echo $data . "<br><br>";
    echo PHP_EOL;
    ob_flush();
    flush();
    return strlen($data);
});



<div id="divID">Hello</div>
<script>
    var eventSource = new EventSource("/");
    var div = document.getElementById('divID');


    eventSource.onmessage = function (e) {
       if(e.data == "[DONE]")
       {
           div.innerHTML += "<br><br>Hello";
       }
        div.innerHTML += JSON.parse(e.data).choices[0].text;
    };
    eventSource.onerror = function (e) {
        console.log(e);
    };
</script>

    $result = $open_ai->createEdit([
        "model" => "text-davinci-edit-001",
        "input" => "What day of the wek is it?",
        "instruction" => "Fix the spelling mistakes",
    ]);

$complete = $open_ai->image([
    "prompt" => "A cat drinking milk",
    "n" => 1,
    "size" => "256x256",
    "response_format" => "url",
]);

$otter = curl_file_create(__DIR__ . './files/otter.png');
$mask = curl_file_create(__DIR__ . './files/mask.jpg');

$result = $open_ai->imageEdit([
    "image" => $otter,
    "mask" => $mask,
    "prompt" => "A cute baby sea otter wearing a beret",
    "n" => 2,
    "size" => "1024x1024",
]);

$otter = curl_file_create(__DIR__ . './files/otter.png');

$result = $open_ai->createImageVariation([
    "image" => $otter,
    "n" => 2,
    "size" => "256x256",
]);

$search = $open_ai->search([
    'engine' => 'ada',
    'documents' => ['White House', 'hospital', 'school'],
    'query' => 'the president',
]);

$result = $open_ai->embeddings([
    "model" => "text-similarity-babbage-001",
    "input" => "The food was delicious and the waiter..."
]);

$answer = $open_ai->answer([
    'documents' => ['Puppy A is happy.', 'Puppy B is sad.'],
    'question' => 'which puppy is happy?',
    'search_model' => 'ada',
    'model' => 'curie',
    'examples_context' => 'In 2017, U.S. life expectancy was 78.6 years.',
    'examples' => [['What is human life expectancy in the United States?', '78 years.']],
    'max_tokens' => 5,
    'stop' => ["\n", '<|endoftext|>'],
]);

$classification = $open_ai->classification([
    'examples' => [
        ['A happy moment', 'Positive'],
        ['I am sad.', 'Negative'],
        ['I am feeling awesome', 'Positive'],
    ],
    'labels' => ['Positive', 'Negative', 'Neutral'],
    'query' => 'It is a raining day =>(',
    'search_model' => 'ada',
    'model' => 'curie',
]);

$flags = $open_ai->moderation([
    'input' => 'I want to kill them.'
]);

$engines = $open_ai->engines();


$result = $open_ai->tts([
    "model" => "tts-1", // tts-1-hd
    "input" => "I'm going to use the stones again. Hey, we'd be going in short-handed, you know",
    "voice" => "alloy", // echo, fable, onyx, nova, and shimmer
]);

// Save audio file
file_put_contents('tts-result.mp3', $result);

$c_file = curl_file_create(__DIR__ . '/files/en-marvel-endgame.m4a');

$result = $open_ai->transcribe([
    "model" => "whisper-1",
    "file" => $c_file,
]);

$c_file = curl_file_create(__DIR__ . '/files/tr-baris-ozcan-youtuber.m4a');

$result = $open_ai->translate([
    "model" => "whisper-1",
    "file" => $c_file,
]);

...
    echo $open_ai->translate(
        [
            "purpose" => "answers",
            "file" => $c_file,
        ]
    );
...
// OR
...
    echo $open_ai->transcribe(
        [
            "purpose" => "answers",
            "file" => $c_file,
        ]
    );
...

$files = $open_ai->listFiles();

$c_file = curl_file_create(__DIR__ . 'files/sample_file_1.jsonl');
$result = $open_ai->uploadFile([
            "purpose" => "answers",
            "file" => $c_file,
]);

<form action="index.php" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

ileToUpload']['name']);
    $c_file = curl_file_create($tmp_file, $_FILES['fileToUpload']['type'], $file_name);

    echo "[";
    echo $open_ai->uploadFile(
        [
            "purpose" => "answers",
            "file" => $c_file,
        ]
    );
    echo ",";
    echo $open_ai->listFiles();
    echo "]";

}


$result = $open_ai->deleteFile('file-xxxxxxxx');

$file = $open_ai->retrieveFile('file-xxxxxxxx');

$file = $open_ai->retrieveFileContent('file-xxxxxxxx');

$result = $open_ai->createFineTune([
        "model" => "gpt-3.5-turbo-1106",
        "training_file" => "file-U3KoAAtGsjUKSPXwEUDdtw86",
]);

$fine_tunes = $open_ai->listFineTunes();

$fine_tune = $open_ai->retrieveFineTune('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

$result = $open_ai->cancelFineTune('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

$fine_tune_events = $open_ai->listFineTuneEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

$result = $open_ai->deleteFineTune('curie:ft-acmeco-2021-03-03-21-44-20');

$engine = $open_ai->engine('davinci');

$result = $open_ai->listModels();

$result = $open_ai->retrieveModel("text-ada-001");

echo $search;

$data = [
    'model' => 'gpt-3.5-turbo',
    'name' => 'my assistant',
    'description' => 'my assistant description',
    'instructions' => 'you should cordially help me',
    'tools' => [],
    'file_ids' => [],
];

$assistant = $open_ai->createAssistant($data);

$assistantId = 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz';

$assistant = $open_ai->retrieveAssistant($assistantId);

$assistantId = 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz';
$data = [
    'name' => 'my modified assistant',
    'instructions' => 'you should cordially help me again',
];

$assistant = $open_ai->modifyAssistant($assistantId, $data);

$assistantId = 'asst_DgiOnXK7nRfyvqoXWpFlwESc';

$assistant = $open_ai->deleteAssistant($assistantId);

$query = ['limit' => 10];

$assistants = $open_ai->listAssistants($query);

$assistantId = 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz';
$fileId = 'file-jrNZZZBAPGnhYUKma7CblGoR';

$file = $open_ai->createAssistantFile($assistantId, $fileId);

$assistantId = 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz';
$fileId = 'file-jrNZZZBAPGnhYUKma7CblGoR';

$file = $open_ai->retrieveAssistantFile($assistantId, $fileId);

$assistantId = 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz';
$fileId = 'file-jrNZZZBAPGnhYUKma7CblGoR';

$file = $open_ai->deleteAssistantFile($assistantId, $fileId);

$assistantId = 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz';
$query = ['limit' => 10];

$files = $open_ai->listAssistantFiles($assistantId, $query);

$data = [
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Hello, what is AI?',
            'file_ids' => [],
        ],
    ],
];

$thread = $open_ai->createThread($data);

$threadId = 'thread_YKDArENVWFDO2Xz3POifFYlp';

$thread = $open_ai->retrieveThread($threadId);

$threadId = 'thread_YKDArENVWFDO2Xz3POifFYlp';
$data = [
    'metadata' => ['test' => '1234abcd'],
];

$thread = $open_ai->modifyThread($threadId, $data);

$threadId = 'thread_YKDArENVWFDO2Xz3POifFYlp';

$thread = $open_ai->deleteThread($threadId);

$threadId = 'thread_YKDArENVWFDO2Xz3POifFYlp';
$data = [
    'role' => 'user',
    'content' => 'How does AI work? Explain it in simple terms.',
];

$message = $open_ai->createThreadMessage($threadId, $data);

$threadId = 'thread_d86alfR2rfF7rASyV4V7hicz';
$messageId = 'msg_d37P5XgREsm6BItOcppnBO1b';

$message = $open_ai->retrieveThreadMessage($threadId, $messageId);

$threadId = 'thread_d86alfR2rfF7rASyV4V7hicz';
$messageId = 'msg_d37P5XgREsm6BItOcppnBO1b';
$data = [
    'metadata' => ['test' => '1234abcd'],
];

$message = $open_ai->modifyThreadMessage($threadId, $messageId, $data);

$threadId = 'thread_d86alfR2rfF7rASyV4V7hicz';
$query = ['limit' => 10];

$messages = $open_ai->listThreadMessages($threadId, $query);

$threadId = 'thread_d86alfR2rfF7rASyV4V7hicz';
$messageId = 'msg_CZ47kAGZugAfeHMX6bmJIukP';
$fileId = 'file-CRLcY63DiHphWuBrmDWZVCgA';

$file = $open_ai->retrieveMessageFile($threadId, $messageId, $fileId);

$threadId = 'thread_d86alfR2rfF7rASyV4V7hicz';
$messageId = 'msg_CZ47kAGZugAfeHMX6bmJIukP';
$query = ['limit' => 10];

$files = $open_ai->listMessageFiles($threadId, $messageId, $query);

$threadId = 'thread_d86alfR2rfF7rASyV4V7hicz';
$data = ['assistant_id' => 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz'];

$run = $open_ai->createRun($threadId, $data);

$threadId = 'thread_JZbzCYpYgpNb79FNeneO3cGI';
$runId = 'run_xBKYFcD2Jg3gnfrje6fhiyXj';

$run = $open_ai->retrieveRun($threadId, $runId);

$threadId = 'thread_JZbzCYpYgpNb79FNeneO3cGI';
$runId = 'run_xBKYFcD2Jg3gnfrje6fhiyXj';
$data = [
    'metadata' => ['test' => 'abcd1234'],
];

$run = $open_ai->modifyRun($threadId, $runId, $data);

$threadId = 'thread_JZbzCYpYgpNb79FNeneO3cGI';
$query = ['limit' => 10];

$runs = $open_ai->listRuns($threadId, $query);

$threadId = 'thread_JZbzCYpYgpNb79FNeneO3cGI';
$runId = 'run_xBKYFcD2Jg3gnfrje6fhiyXj';
$outputs = [
    'tool_outputs' => [
        ['tool_call_id' => 'call_abc123', 'output' => '28C'],
    ],
];

$run = $open_ai->submitToolOutputs($threadId, $runId, $outputs);

$threadId = 'thread_JZbzCYpYgpNb79FNeneO3cGI';
$runId = 'run_xBKYFcD2Jg3gnfrje6fhiyXj';

$run = $open_ai->cancelRun($threadId, $runId);

$data = [
    'assistant_id' => 'asst_zT1LLZ8dWnuFCrMFzqxFOhzz',
    'thread' => [
        'messages' => [
            [
                'role' => 'user',
                'content' => 'Hello, what is AI?',
                'file_ids' => [],
            ],
        ],
    ],
];

$run = $open_ai->createThreadAndRun($data);

$threadId = 'thread_JZbzCYpYgpNb79FNeneO3cGI';
$runId = 'run_xBKYFcD2Jg3gnfrje6fhiyXj';
$stepId = 'step_kwLG0vPQjqVyQHVoL7GVK3aG';

$step = $open_ai->retrieveRunStep($threadId, $runId, $stepId);

$threadId = 'thread_JZbzCYpYgpNb79FNeneO3cGI';
$runId = 'run_xBKYFcD2Jg3gnfrje6fhiyXj';
$query = ['limit' => 10];

$steps = $open_ai->listRunSteps($threadId, $runId, $query);