PHP code example of magenable / openai-php-client
1. Go to this page and download the library: Download magenable/openai-php-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' );
magenable / openai-php-client example snippets
$yourApiKey = getenv('YOUR_API_KEY' );
$client = OpenAI::client($yourApiKey);
$result = $client->chat()->create([
'model' => 'gpt-4' ,
'messages' => [
['role' => 'user' , 'content' => 'Hello!' ],
],
]);
echo $result->choices[0 ]->message->content;
$yourApiKey = getenv('YOUR_API_KEY' );
$client = OpenAI::factory()
->withApiKey($yourApiKey)
->withOrganization('your-organization' )
->withProject('Your Project' )
->withBaseUri('openai.example.com/v1' )
->withHttpClient($client = new \GuzzleHttp\Client([]))
->withHttpHeader('X-My-Header' , 'foo' )
->withQueryParam('my-param' , 'bar' )
->withStreamHandler(fn (RequestInterface $request): ResponseInterface => $client->send($request, [
'stream' => true
]))
->make();
$response = $client->models()->list();
$response->object;
foreach ($response->data as $result) {
$result->id;
$result->object;
}
$response->toArray();
$response = $client->models()->retrieve('gpt-3.5-turbo-instruct' );
$response->id;
$response->object;
$response->created;
$response->ownedBy;
$response->toArray();
$response = $client->models()->delete('curie:ft-acmeco-2021-03-03-21-44-20' );
$response->id;
$response->object;
$response->deleted;
$response->toArray();
$response = $client->completions()->create([
'model' => 'gpt-3.5-turbo-instruct' ,
'prompt' => 'Say this is a test' ,
'max_tokens' => 6 ,
'temperature' => 0
]);
$response->id;
$response->object;
$response->created;
$response->model;
foreach ($response->choices as $result) {
$result->text;
$result->index;
$result->logprobs;
$result->finishReason;
}
$response->usage->promptTokens;
$response->usage->completionTokens;
$response->usage->totalTokens;
$response->toArray();
$stream = $client->completions()->createStreamed([
'model' => 'gpt-3.5-turbo-instruct' ,
'prompt' => 'Hi' ,
'max_tokens' => 10 ,
]);
foreach ($stream as $response){
$response->choices[0 ]->text;
}
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo' ,
'messages' => [
['role' => 'user' , 'content' => 'Hello!' ],
],
]);
$response->id;
$response->object;
$response->created;
$response->model;
foreach ($response->choices as $result) {
$result->index;
$result->message->role;
$result->message->content;
$result->finishReason;
}
$response->usage->promptTokens;
$response->usage->completionTokens;
$response->usage->totalTokens;
$response->toArray();
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo-0613' ,
'messages' => [
['role' => 'user' , 'content' => 'What\'s the weather like in Boston?' ],
],
'tools' => [
[
'type' => 'function' ,
'function' => [
'name' => 'get_current_weather' ,
'description' => 'Get the current weather in a given location' ,
'parameters' => [
'type' => 'object' ,
'properties' => [
'location' => [
'type' => 'string' ,
'description' => 'The city and state, e.g. San Francisco, CA' ,
],
'unit' => [
'type' => 'string' ,
'enum' => ['celsius' , 'fahrenheit' ]
],
],
'
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo-0613' ,
'messages' => [
['role' => 'user' , 'content' => 'What\'s the weather like in Boston?' ],
],
'functions' => [
[
'name' => 'get_current_weather' ,
'description' => 'Get the current weather in a given location' ,
'parameters' => [
'type' => 'object' ,
'properties' => [
'location' => [
'type' => 'string' ,
'description' => 'The city and state, e.g. San Francisco, CA' ,
],
'unit' => [
'type' => 'string' ,
'enum' => ['celsius' , 'fahrenheit' ]
],
],
'
$stream = $client->chat()->createStreamed([
'model' => 'gpt-4' ,
'messages' => [
['role' => 'user' , 'content' => 'Hello!' ],
],
]);
foreach ($stream as $response){
$response->choices[0 ]->toArray();
}
$stream = $client->chat()->createStreamed([
'model' => 'gpt-4' ,
'messages' => [
['role' => 'user' , 'content' => 'Hello!' ],
],
'stream_options' =>[
' $response->usage->totalTokens; // 21
}
}
$client->audio()->speech([
'model' => 'tts-1' ,
'input' => 'The quick brown fox jumped over the lazy dog.' ,
'voice' => 'alloy' ,
]);
$stream = $client->audio()->speechStreamed([
'model' => 'tts-1' ,
'input' => 'The quick brown fox jumped over the lazy dog.' ,
'voice' => 'alloy' ,
]);
foreach ($stream as $chunk){
$chunk;
}
$response = $client->audio()->transcribe([
'model' => 'whisper-1' ,
'file' => fopen('audio.mp3' , 'r' ),
'response_format' => 'verbose_json' ,
'timestamp_granularities' => ['segment' , 'word' ]
]);
$response->task;
$response->language;
$response->duration;
$response->text;
foreach ($response->segments as $segment) {
$segment->index;
$segment->seek;
$segment->start;
$segment->end;
$segment->text;
$segment->tokens;
$segment->temperature;
$segment->avgLogprob;
$segment->compressionRatio;
$segment->noSpeechProb;
$segment->transient;
}
foreach ($response->words as $word) {
$word->word;
$word->start;
$word->end;
}
$response->toArray();
$response = $client->audio()->translate([
'model' => 'whisper-1' ,
'file' => fopen('german.mp3' , 'r' ),
'response_format' => 'verbose_json' ,
]);
$response->task;
$response->language;
$response->duration;
$response->text;
foreach ($response->segments as $segment) {
$segment->index;
$segment->seek;
$segment->start;
$segment->end;
$segment->text;
$segment->tokens;
$segment->temperature;
$segment->avgLogprob;
$segment->compressionRatio;
$segment->noSpeechProb;
$segment->transient;
}
$response->toArray();
$response = $client->embeddings()->create([
'model' => 'text-similarity-babbage-001' ,
'input' => 'The food was delicious and the waiter...' ,
]);
$response->object;
foreach ($response->embeddings as $embedding) {
$embedding->object;
$embedding->embedding;
$embedding->index;
}
$response->usage->promptTokens;
$response->usage->totalTokens;
$response->toArray();
$response = $client->files()->list();
$response->object;
foreach ($response->data as $result) {
$result->id;
$result->object;
}
$response->toArray();
$response = $client->files()->delete($file);
$response->id;
$response->object;
$response->deleted;
$response->toArray();
$response = $client->files()->retrieve('file-XjGxS3KTG0uNmNOK362iJua3' );
$response->id;
$response->object;
$response->bytes;
$response->createdAt;
$response->filename;
$response->purpose;
$response->status;
$response->status_details;
$response->toArray();
$response = $client->files()->upload([
'purpose' => 'fine-tune' ,
'file' => fopen('my-file.jsonl' , 'r' ),
]);
$response->id;
$response->object;
$response->bytes;
$response->createdAt;
$response->filename;
$response->purpose;
$response->status;
$response->status_details;
$response->toArray();
$client->files()->download($file);
$response = $client->fineTuning()->createJob([
'training_file' => 'file-abc123' ,
'validation_file' => null ,
'model' => 'gpt-3.5-turbo' ,
'hyperparameters' => [
'n_epochs' => 4 ,
],
'suffix' => null ,
]);
$response->id;
$response->object;
$response->model;
$response->fineTunedModel;
$response->toArray();
$response = $client->fineTuning()->listJobs();
$response->object;
foreach ($response->data as $result) {
$result->id;
$result->object;
}
$response->toArray();
$response = $client->fineTuning()->listJobs([
'limit' => 3 ,
'after' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F' ,
]);
$response = $client->fineTuning()->retrieveJob('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F' );
$response->id;
$response->object;
$response->model;
$response->createdAt;
$response->finishedAt;
$response->fineTunedModel;
$response->organizationId;
$response->resultFiles[0 ];
$response->status;
$response->validationFile;
$response->trainingFile;
$response->trainedTokens;
$response->hyperparameters->nEpochs;
$response->toArray();
$response = $client->fineTuning()->cancelJob('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F' );
$response->id;
$response->object;
$response->status;
$response->toArray();
$response = $client->fineTuning()->listJobEvents('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F' );
$response->object;
foreach ($response->data as $result) {
$result->object;
$result->createdAt;
}
$response->toArray();
$response = $client->fineTuning()->listJobEvents('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F' , [
'limit' => 3 ,
'after' => 'ftevent-kLPSMIcsqshEUEJVOVBVcHlP' ,
]);
$response = $client->fineTunes()->create([
'training_file' => 'file-ajSREls59WBbvgSzJSVWxMCB' ,
'validation_file' => 'file-XjSREls59WBbvgSzJSVWxMCa' ,
'model' => 'curie' ,
'n_epochs' => 4 ,
'batch_size' => null ,
'learning_rate_multiplier' => null ,
'prompt_loss_weight' => 0.01 ,
'compute_classification_metrics' => false ,
'classification_n_classes' => null ,
'classification_positive_class' => null ,
'classification_betas' => [],
'suffix' => null ,
]);
$response->id;
$response->object;
$response->toArray();
$response = $client->fineTunes()->list();
$response->object;
foreach ($response->data as $result) {
$result->id;
$result->object;
}
$response->toArray();
$response = $client->fineTunes()->retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F' );
$response->id;
$response->object;
$response->model;
$response->createdAt;
$response->fineTunedModel;
$response->organizationId;
$response->resultFiles;
$response->status;
$response->validationFiles;
$response->trainingFiles;
$response->updatedAt;
foreach ($response->events as $result) {
$result->object;
$result->createdAt;
$result->level;
$result->message;
}
$response->hyperparams->batchSize;
$response->hyperparams->learningRateMultiplier;
$response->hyperparams->nEpochs;
$response->hyperparams->promptLossWeight;
foreach ($response->resultFiles as $result) {
$result->id;
$result->object;
$result->bytes;
$result->createdAt;
$result->filename;
$result->purpose;
$result->status;
$result->status_details;
}
foreach ($response->validationFiles as $result) {
$result->id;
}
foreach ($response->trainingFiles as $result) {
$result->id;
}
$response->toArray();
$response = $client->fineTunes()->cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F' );
$response->id;
$response->object;
$response->status;
$response->toArray();
$response = $client->fineTunes()->listEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F' );
$response->object;
foreach ($response->data as $result) {
$result->object;
$result->createdAt;
}
$response->toArray();
$stream = $client->fineTunes()->listEventsStreamed('ft-y3OpNlc8B5qBVGCCVsLZsDST' );
foreach ($stream as $response){
$response->message;
}
$response = $client->moderations()->create([
'model' => 'text-moderation-latest' ,
'input' => 'I want to k*** them.' ,
]);
$response->id;
$response->model;
foreach ($response->results as $result) {
$result->flagged;
foreach ($result->categories as $category) {
$category->category->value;
$category->violated;
$category->score;
}
}
$response->toArray();
$response = $client->images()->create([
'model' => 'dall-e-3' ,
'prompt' => 'A cute baby sea otter' ,
'n' => 1 ,
'size' => '1024x1024' ,
'response_format' => 'url' ,
]);
$response->created;
foreach ($response->data as $data) {
$data->url;
$data->b64_json;
}
$response->toArray();
$response = $client->images()->edit([
'image' => fopen('image_edit_original.png' , 'r' ),
'mask' => fopen('image_edit_mask.png' , 'r' ),
'prompt' => 'A sunlit indoor lounge area with a pool containing a flamingo' ,
'n' => 1 ,
'size' => '256x256' ,
'response_format' => 'url' ,
]);
$response->created;
foreach ($response->data as $data) {
$data->url;
$data->b64_json;
}
$response->toArray();
$response = $client->images()->variation([
'image' => fopen('image_edit_original.png' , 'r' ),
'n' => 1 ,
'size' => '256x256' ,
'response_format' => 'url' ,
]);
$response->created;
foreach ($response->data as $data) {
$data->url;
$data->b64_json;
}
$response->toArray();
> $factory->withHttpHeader('OpenAI-Beta' , 'assistants=v2' )
>
$response = $client->assistants()->create([
'instructions' => 'You are a personal math tutor. When asked a question, write and run Python code to answer the question.' ,
'name' => 'Math Tutor' ,
'tools' => [
[
'type' => 'code_interpreter' ,
],
],
'model' => 'gpt-4' ,
]);
$response->id;
$response->object;
$response->createdAt;
$response->name;
$response->instructions;
$response->model;
$response->description;
$response->tools[0 ]->type;
$response->toolResources;
$response->metadata;
$response->temperature:
$response->topP:
$response->format:
$response->toArray();
$response = $client->assistants()->retrieve('asst_gxzBkD1wkKEloYqZ410pT5pd' );
$response->id;
$response->object;
$response->createdAt;
$response->name;
$response->instructions;
$response->model;
$response->description;
$response->tools[0 ]->type;
$response->toolResources;
$response->metadata;
$response->temperature:
$response->topP:
$response->format:
$response->toArray();
$response = $client->assistants()->modify('asst_gxzBkD1wkKEloYqZ410pT5pd' , [
'name' => 'New Math Tutor' ,
]);
$response->id;
$response->object;
$response->createdAt;
$response->name;
$response->instructions;
$response->model;
$response->description;
$response->tools[0 ]->type;
$response->toolResources;
$response->metadata;
$response->temperature:
$response->topP:
$response->format:
$response->toArray();
$response = $client->assistants()->delete('asst_gxzBkD1wkKEloYqZ410pT5pd' );
$response->id;
$response->object;
$response->deleted;
$response->toArray();
$response = $client->assistants()->list([
'limit' => 10 ,
]);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$response = $client->threads()->create([]);
$response->id;
$response->object;
$response->createdAt;
$response->toolResources;
$response->metadata;
$response->toArray();
$response = $client->threads()->createAndRun(
[
'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd' ,
'thread' => [
'messages' =>
[
[
'role' => 'user' ,
'content' => 'Explain deep learning to a 5 year old.' ,
],
],
],
],
);
$response->id;
$response->object;
$response->createdAt;
$response->assistantId;
$response->threadId;
$response->status;
$response->esponse->toArray();
$response = $client->threads()->retrieve('thread_tKFLqzRN9n7MnyKKvc1Q7868' );
$response->id;
$response->object;
$response->createdAt;
$response->toolResources;
$response->metadata;
$response->toArray();
$response = $client->threads()->modify('thread_tKFLqzRN9n7MnyKKvc1Q7868' , [
'metadata' => [
'name' => 'My new thread name' ,
],
]);
$response->id;
$response->object;
$response->createdAt;
$response->toolResources;
$response->metadata;
$response->toArray();
$response = $client->threads()->delete('thread_tKFLqzRN9n7MnyKKvc1Q7868' );
$response->id;
$response->object;
$response->deleted;
$response->toArray();
$response = $client->threads()->messages()->create('thread_tKFLqzRN9n7MnyKKvc1Q7868' , [
'role' => 'user' ,
'content' => 'What is the sum of 5 and 7?' ,
]);
$response->id;
$response->object;
$response->createdAt;
$response->threadId;
$response->status;
$response->incompleteDetails;
$response->completedAt;
$response->incompleteAt;
$response->role;
$response->content[0 ]->type;
$response->content[0 ]->text->value;
$response->content[0 ]->text->annotations;
$response->assistantId;
$response->runId;
$response->attachments;
$response->metadata;
$response->toArray();
$response = $client->threads()->messages()->retrieve(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
messageId: 'msg_SKYwvF3zcigxthfn6F4hnpdU' ,
);
$response->id;
$response->object;
$response->createdAt;
$response->threadId;
$response->status;
$response->incompleteDetails;
$response->completedAt;
$response->incompleteAt;
$response->role;
$response->content[0 ]->type;
$response->content[0 ]->text->value;
$response->content[0 ]->text->annotations;
$response->assistantId;
$response->runId;
$response->attachments;
$response->metadata;
$response->toArray();
$response = $client->threads()->messages()->modify(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
messageId: 'msg_SKYwvF3zcigxthfn6F4hnpdU' ,
parameters: [
'metadata' => [
'name' => 'My new message name' ,
],
],
);
$response->id;
$response->object;
$response->createdAt;
$response->threadId;
$response->status;
$response->incompleteDetails;
$response->completedAt;
$response->incompleteAt;
$response->role;
$response->content[0 ]->type;
$response->content[0 ]->text->value;
$response->content[0 ]->text->annotations;
$response->assistantId;
$response->runId;
$response->attachments;
$response->metadata;
$response->toArray();
$response = $client->threads()->messages()->delete(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
messageId: 'msg_SKYwvF3zcigxthfn6F4hnpdU'
);
$response->id;
$response->object;
$response->deleted;
$response->toArray();
$response = $client->threads()->messages()->list('thread_tKFLqzRN9n7MnyKKvc1Q7868' , [
'limit' => 10 ,
]);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$response = $client->threads()->runs()->create(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
parameters: [
'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd' ,
],
);
$response->id;
$response->object;
$response->createdAt;
$response->assistantId;
$response->threadId;
$response->status;
$response->startedAt;
$response->expiresAt;
$response->cancelledAt;
$response->failedAt;
$response->completedAt;
$response->incompleteDetails;
$response->lastError;
$response->model;
$response->instructions;
$response->tools;
$response->metadata;
$response->usage->total_tokens;
$response->temperature;
$response->topP;
$response->maxPromptTokens;
$response->maxCompletionTokens;
$response->truncationStrategy->type;
$response->toolChoice;
$response->responseFormat;
$response->toArray();
$stream = $client->threads()->runs()->createStreamed(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
parameters: [
'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd' ,
],
);
foreach ($stream as $response){
$response->event
$response->response
}
$stream = $client->threads()->runs()->createStreamed(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
parameters: [
'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd' ,
],
);
do {
foreach ($stream as $response){
$response->event
$response->response
switch ($response->event){
case 'thread.run.created' :
case 'thread.run.queued' :
case 'thread.run.completed' :
case 'thread.run.cancelling' :
$run = $response->response;
break ;
case 'thread.run.expired' :
case 'thread.run.cancelled' :
case 'thread.run.failed' :
$run = $response->response;
break 3 ;
case 'thread.run.
$response = $client->threads()->runs()->retrieve(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
runId: 'run_4RCYyYzX9m41WQicoJtUQAb8' ,
);
$response->id;
$response->object;
$response->createdAt;
$response->assistantId;
$response->threadId;
$response->status;
$response->startedAt;
$response->expiresAt;
$response->cancelledAt;
$response->failedAt;
$response->completedAt;
$response->incompleteDetails;
$response->lastError;
$response->model;
$response->instructions;
$response->tools;
$response->metadata;
$response->usage->promptTokens;
$response->usage->completionTokens;
$response->usage->totalTokens;
$response->temperature;
$response->topP;
$response->maxPromptTokens;
$response->maxCompletionTokens;
$response->truncationStrategy->type;
$response->toolChoice;
$response->responseFormat;
$response->toArray();
$response = $client->threads()->runs()->modify(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
runId: 'run_4RCYyYzX9m41WQicoJtUQAb8' ,
parameters: [
'metadata' => [
'name' => 'My new run name' ,
],
],
);
$response->id;
$response->object;
$response->createdAt;
$response->assistantId;
$response->threadId;
$response->status;
$response->startedAt;
$response->expiresAt;
$response->cancelledAt;
$response->failedAt;
$response->completedAt;
$response->incompleteDetails;
$response->lastError;
$response->model;
$response->instructions;
$response->tools;
$response->usage->total_tokens;
$response->temperature;
$response->topP;
$response->maxPromptTokens;
$response->maxCompletionTokens;
$response->truncationStrategy->type;
$response->toolChoice;
$response->responseFormat;
$response->metadata;
$response->toArray();
$response = $client->threads()->runs()->cancel(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
runId: 'run_4RCYyYzX9m41WQicoJtUQAb8' ,
);
$response->id;
$response->object;
$response->createdAt;
$response->assistantId;
$response->threadId;
$response->status;
$response->startedAt;
$response->expiresAt;
$response->cancelledAt;
$response->failedAt;
$response->completedAt;
$response->incompleteDetails;
$response->lastError;
$response->model;
$response->instructions;
$response->tools;
$response->usage?->total_tokens;
$response->temperature;
$response->topP;
$response->maxPromptTokens;
$response->maxCompletionTokens;
$response->truncationStrategy->type;
$response->toolChoice;
$response->responseFormat;
$response->metadata;
$response->toArray();
$response = $client->threads()->runs()->submitToolOutputs(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
runId: 'run_4RCYyYzX9m41WQicoJtUQAb8' ,
parameters: [
'tool_outputs' => [
[
'tool_call_id' => 'call_KSg14X7kZF2WDzlPhpQ168Mj' ,
'output' => '12' ,
],
],
]
);
$response->id;
$response->object;
$response->createdAt;
$response->assistantId;
$response->threadId;
$response->status;
$response->startedAt;
$response->expiresAt;
$response->cancelledAt;
$response->failedAt;
$response->completedAt;
$response->incompleteDetails;
$response->lastError;
$response->model;
$response->instructions;
$response->usage->total_tokens;
$response->temperature;
$response->topP;
$response->maxPromptTokens;
$response->maxCompletionTokens;
$response->truncationStrategy->type;
$response->responseFormat;
$response->tools[0 ]->type;
$response->toolChoice;
$response->metadata;
$response->toArray();
$response = $client->threads()->runs()->list(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
parameters: [
'limit' => 10 ,
],
);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$response = $client->threads()->runs()->steps()->retrieve(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
runId: 'run_4RCYyYzX9m41WQicoJtUQAb8' ,
stepId: 'step_1spQXgbAabXFm1YXrwiGIMUz' ,
);
$response->id;
$response->object;
$response->createdAt;
$response->runId;
$response->assistantId;
$response->threadId;
$response->type;
$response->status;
$response->cancelledAt;
$response->completedAt;
$response->expiresAt;
$response->failedAt;
$response->lastError;
$response->stepDetails->type;
$response->stepDetails->messageCreation->messageId;
$response->toArray();
$response = $client->threads()->runs()->steps()->list(
threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868' ,
runId: 'run_4RCYyYzX9m41WQicoJtUQAb8' ,
parameters: [
'limit' => 10 ,
],
);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$fileResponse = $client->files()->upload(
parameters: [
'purpose' => 'batch' ,
'file' => fopen('commands.jsonl' , 'r' ),
]
);
$fileId = $fileResponse->id;
$response = $client->batches()->create(
parameters: [
'input_file_id' => $fileId,
'endpoint' => '/v1/chat/completions' ,
'completion_window' => '24h'
]
);
$response->id;
$response->object;
$response->endpoint;
$response->errors;
$response->completionWindow;
$response->status;
$response->outputFileId;
$response->errorFileId;
$response->createdAt;
$response->inProgressAt;
$response->expiresAt;
$response->completedAt;
$response->failedAt;
$response->expiredAt;
$response->requestCounts;
$response->metadata;
$response->toArray();
$response = $client->batches()->retrieve(id: 'batch_abc123' );
$response->id;
$response->object;
$response->endpoint;
$response->errors;
$response->completionWindow;
$response->status;
$response->outputFileId;
$response->errorFileId;
$response->createdAt;
$response->inProgressAt;
$response->expiresAt;
$response->completedAt;
$response->failedAt;
$response->expiredAt;
$response->requestCounts->total;
$response->requestCounts->completed;
$response->requestCounts->failed;
$response->metadata;
$response->toArray();
$response = $client->batches()->cancel(id: 'batch_abc123' );
$response->id;
$response->object;
$response->endpoint;
$response->errors;
$response->completionWindow;
$response->status;
$response->outputFileId;
$response->errorFileId;
$response->createdAt;
$response->inProgressAt;
$response->expiresAt;
$response->cancellingAt;
$response->cancelledAt;
$response->requestCounts->total;
$response->requestCounts->completed;
$response->requestCounts->failed;
$response->metadata;
$response->toArray();
$response = $client->batches()->list(
parameters: [
'limit' => 10 ,
],
);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$response = $client->vectorStores()->create([
'file_ids' => [
'file-fUU0hFRuQ1GzhOweTNeJlCXG' ,
],
'name' => 'My first Vector Store' ,
]);
$response->id;
$response->object;
$response->createdAt;
$response->name;
$response->usageBytes;
$response->fileCounts->inProgress;
$response->fileCounts->completed;
$response->fileCounts->failed;
$response->fileCounts->cancelled;
$response->fileCounts->total;
$response->status;
$response->expiresAfter;
$response->expiresAt;
$response->lastActiveAt;
$response->toArray();
$response = $client->vectorStores()->retrieve(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
);
$response->id;
$response->object;
$response->createdAt;
$response->name;
$response->usageBytes;
$response->fileCounts->inProgress;
$response->fileCounts->completed;
$response->fileCounts->failed;
$response->fileCounts->cancelled;
$response->fileCounts->total;
$response->status;
$response->expiresAfter;
$response->expiresAt;
$response->lastActiveAt;
$response->toArray();
$response = $client->vectorStores()->modify(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
parameters: [
'name' => 'New name' ,
],
);
$response->id;
$response->object;
$response->createdAt;
$response->name;
$response->usageBytes;
$response->fileCounts->inProgress;
$response->fileCounts->completed;
$response->fileCounts->failed;
$response->fileCounts->cancelled;
$response->fileCounts->total;
$response->status;
$response->expiresAfter;
$response->expiresAt;
$response->lastActiveAt;
$response->toArray();
$response = $client->vectorStores()->delete(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
);
$response->id;
$response->object;
$response->deleted;
$response->toArray();
$response = $client->vectorStores()->list(
parameters: [
'limit' => 10 ,
],
);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$response = $client->vectorStores()->files()->create(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
parameters: [
'file_id' => 'file-fUU0hFRuQ1GzhOweTNeJlCXG' ,
]
);
$response->id;
$response->object;
$response->usageBytes;
$response->createdAt;
$response->vectorStoreId;
$response->status;
$response->lastError;
$response->chunkingStrategy->type;
$response->chunkingStrategy->maxChunkSizeTokens;
$response->chunkingStrategy->chunkOverlapTokens;
$response->toArray();
$response = $client->vectorStores()->files()->retrieve(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
fileId: 'file-fUU0hFRuQ1GzhOweTNeJlCXG' ,
);
$response->id;
$response->object;
$response->usageBytes;
$response->createdAt;
$response->vectorStoreId;
$response->status;
$response->lastError;
$response->chunkingStrategy->type;
$response->chunkingStrategy->maxChunkSizeTokens;
$response->chunkingStrategy->chunkOverlapTokens;
$response->toArray();
$response = $client->vectorStores()->files()->delete(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
fileId: 'file-fUU0hFRuQ1GzhOweTNeJlCXG' ,
);
$response->id;
$response->object;
$response->deleted;
$response->toArray();
$response = $client->vectorStores()->files()->list(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
parameters: [
'limit' => 10 ,
],
);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$response = $client->vectorStores()->batches()->create(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
parameters: [
'file_ids' => [
'file-fUU0hFRuQ1GzhOweTNeJlCXG' ,
],
]
);
$response->id;
$response->object;
$response->createdAt;
$response->vectorStoreId;
$response->status;
$response->fileCounts->inProgress;
$response->fileCounts->completed;
$response->fileCounts->failed;
$response->fileCounts->cancelled;
$response->fileCounts->total;
$response->toArray();
$response = $client->vectorStores()->batches()->retrieve(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
fileBatchId: 'vsfb_123' ,
);
$response->id;
$response->object;
$response->createdAt;
$response->vectorStoreId;
$response->status;
$response->fileCounts->inProgress;
$response->fileCounts->completed;
$response->fileCounts->failed;
$response->fileCounts->cancelled;
$response->fileCounts->total;
$response->toArray();
$response = $client->vectorStores()->batches()->cancel(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
fileBatchId: 'vsfb_123' ,
);
$response->id;
$response->object;
$response->createdAt;
$response->vectorStoreId;
$response->status;
$response->fileCounts->inProgress;
$response->fileCounts->completed;
$response->fileCounts->failed;
$response->fileCounts->cancelled;
$response->fileCounts->total;
$response->toArray();
$response = $client->vectorStores()->batches()->listFiles(
vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF' ,
fileBatchId: 'vsfb_123' ,
parameters: [
'limit' => 10 ,
],
);
$response->object;
$response->firstId;
$response->lastId;
$response->hasMore;
foreach ($response->data as $result) {
$result->id;
}
$response->toArray();
$response = $client->edits()->create([
'model' => 'text-davinci-edit-001' ,
'input' => 'What day of the wek is it?' ,
'instruction' => 'Fix the spelling mistakes' ,
]);
$response->object;
$response->created;
foreach ($response->choices as $result) {
$result->text;
$result->index;
}
$response->usage->promptTokens;
$response->usage->completionTokens;
$response->usage->totalTokens;
$response->toArray();
$response = $client->completions()->create([
'model' => 'gpt-3.5-turbo-instruct' ,
'prompt' => 'Say this is a test' ,
]);
$meta = $response->meta();
$meta->requestId;
$meta->openai->model;
$meta->openai->organization;
$meta->openai->version;
$meta->openai->processingMs;
$meta->requestLimit->limit;
$meta->requestLimit->remaining;
$meta->requestLimit->reset;
$meta->tokenLimit->limit;
$meta->tokenLimit->remaining;
$meta->tokenLimit->reset;
$meta->toArray();
$stream = $client->completions()->createStreamed([
'model' => 'gpt-3.5-turbo-instruct' ,
'prompt' => 'Say this is a test' ,
]);
$stream->meta();
OpenAI::factory()
->withApiKey($apiKey)
->withOrganization($organization)
->withHttpClient(new \GuzzleHttp\Client(['timeout' => $timeout]))
->make();
use OpenAI \Testing \ClientFake ;
use OpenAI \Responses \Completions \CreateResponse ;
$client = new ClientFake([
CreateResponse::fake([
'choices' => [
[
'text' => 'awesome!' ,
],
],
]),
]);
$completion = $client->completions()->create([
'model' => 'gpt-3.5-turbo-instruct' ,
'prompt' => 'PHP is ' ,
]);
expect($completion['choices' ][0 ]['text' ])->toBe('awesome!' );
use OpenAI \Testing \ClientFake ;
use OpenAI \Responses \Chat \CreateStreamedResponse ;
$client = new ClientFake([
CreateStreamedResponse::fake(fopen('file.txt' , 'r' ););
]);
$completion = $client->chat()->createStreamed([
'model' => 'gpt-3.5-turbo' ,
'messages' => [
['role' => 'user' , 'content' => 'Hello!' ],
],
]);
expect($response->getIterator()->current())
->id->toBe('chatcmpl-6yo21W6LVo8Tw2yBf7aGf2g17IeIl' );
$client->assertSent(Completions::class, function (string $method, array $parameters) : bool {
return $method === 'create' &&
$parameters['model' ] === 'gpt-3.5-turbo-instruct' &&
$parameters['prompt' ] === 'PHP is ' ;
});
$client->completions()->assertSent(function (string $method, array $parameters) : bool {
});
$client->assertSent(Completions::class, 2 );
$client->assertNotSent(Completions::class);
$client->completions()->assertNotSent();
$client->assertNothingSent();
$client = new ClientFake([
new \OpenAI\Exceptions\ErrorException([
'message' => 'The model `gpt-1` does not exist' ,
'type' => 'invalid_request_error' ,
'code' => null ,
])
]);
$completion = $client->completions()->create([
'model' => 'gpt-3.5-turbo-instruct' ,
'prompt' => 'PHP is ' ,
]);
$client = OpenAI::factory()
->withBaseUri('{your-resource-name}.openai.azure.com/openai/deployments/{deployment-id}' )
->withHttpHeader('api-key' , '{your-api-key}' )
->withQueryParam('api-version' , '{version}' )
->make();
$result = $client->completions()->create([
'prompt' => 'PHP is'
]);
bash
composer