PHP code example of mathsgod / openai-client
1. Go to this page and download the library: Download mathsgod/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/ */
mathsgod / openai-client example snippets
use OpenAI\Client;
$client=new Client("OPEN_API_KEY");
$data = $client->chatCompletions()->create([
"model" => "gpt-4o-mini",
"messages" => [
["role" => "user", "content" => "Hi"]
]
]);
print_r($data);
$data=$client->chatCompletions()->create([
"model" => "gpt-4o-mini",
"messages" => [
["role" => "user", "content" => "What is the price of iphone14?"]
],
"functions" =>[
[
"name" => "get_iphone_price",
"description" => "Get the price of iphone",
"parameters" => [
"type" => "object",
"properties" => [
"model" => [
"type" => "string",
"description" => "The model of the iphone"
]
],
"
print_r($client->images()->generations([
"model" => "dall-e-3",
"prompt" => "a white siamese cat",
"n" => 1,
"size" => "1024x1024"
]));
print_r($client->embeddings()->create([
"model" => "text-embedding-3-small",
"input"=>"I feel great",
]));
print_r($client->audio()->speech([
"model"=>"tts-1",
"input"=>"Hello, how are you?",
"voice"=>"alloy"
]));
print_r($client->audio()->transcriptions([
"model"=>"whisper-1",
"file"=>fopen('/path/to/audio.mp3', 'r')
]));
print_r($client->audio()->translation([
"model"=>"whisper-1",
"file"=>fopen('/path/to/audio.mp3', 'r')
]));
$client->assistants()->create([
"model" => "gpt-4o-mini",
]);
$client->assistants()->list();
$client->assistants()->retrieve("asst_1234");
$client->assistant("asst_1234")->delete();
$client->threads()->create(); //return Thread object
$client->thread("thread_1234")->messages()->create([
"role" => "user",
"content" => "Hello"
]);
$stream = $thread->runs()->createStream([
"assistant_id" => "asst_1234",
]);
$stream->on("thread.message.delta", function ($data) {
echo $data;
echo "\n";
});
$stream->on("thread.message.completed", function ($data) {
echo $data;
echo "\n";
});
$stream->on("done", function () use (&$thread) {
echo "End\n";
});
$thread = $client->threads()->create([
"messages" => [
[
"role" => "user",
"content" => "Hi"
]
]
]);
$data=$thread->runs()->create([
"assistant_id" => "asst_1234", //assistant_id
]);
print_r($data);