Skip to content

Instantly share code, notes, and snippets.

@johnroyer
Created June 6, 2023 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnroyer/e8b99d64a62b7f57abc4a1c5a859c1da to your computer and use it in GitHub Desktop.
Save johnroyer/e8b99d64a62b7f57abc4a1c5a859c1da to your computer and use it in GitHub Desktop.
OpenAI GPT-3 PHP example
{
"require": {
"openai-php/client": "^0.5.2",
"symfony/http-client": "^6.2",
"nyholm/psr7": "^1.8",
"guzzlehttp/guzzle": "^7.7"
},
"config": {
"allow-plugins": {
"php-http/discovery": true
}
}
}
<?php
require_once __DIR__ . '/vendor/autoload.php';
$apiKey = 'put-your-api-key-here';
$client = OpenAI::client($apiKey);
$totalTokens = 0;
function translate(string $countryName)
{
global $client, $totalTokens;
$flattend = implode("\n", $list);
while (1) {
try {
$response = null;
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
[
'role' => 'user',
'content' => "幫我翻譯成繁體中文,每行一個翻譯結果\n----\nTaiwan Taipei\nThailand Lop Buri"
],
[
'role' => 'assistant',
'content' => "台灣 台北\n泰國 華富里府",
],
[
'role' => 'user',
'content' => "幫我翻譯成繁體中文,每行一個翻譯結果\n----\n" . $countryName,
],
],
]);
} catch (\Exception $e) {
echo "exception: " . $e->getMessage() . "\n";
echo "\nretry again ... \n";
continue;
} catch (\Error $e) {
echo "exception: " . $e->getMessage() . "\n";
echo "\nretry again ... \n";
continue;
}
if (!property_exists($response, 'choices')) {
$totalTokens += $response->usage->totalTokens;
// might be error
echo "error occurs";
var_dump($response->toArray());
echo "\nRetrying ....\n";
} else {
break;
}
}
$totalTokens += $response->usage->totalTokens;
if (0 < count($response->choices)) {
return $response->choices[0]->message->content;
} else {
return null;
}
}
echo translate('taiwan taichung') . "\n";
echo "total tokens: $totalTokens \n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment