|
|
|
@ -0,0 +1,78 @@ |
|
|
|
<?php |
|
|
|
|
|
|
|
namespace plugin\piadmin\app\utils\openai; |
|
|
|
|
|
|
|
use OpenAI; |
|
|
|
use plugin\piadmin\app\exception\ApiException; |
|
|
|
|
|
|
|
/** |
|
|
|
* openAi 客户端 |
|
|
|
*/ |
|
|
|
class OpenAiClient |
|
|
|
{ |
|
|
|
public static function getCurrentConfig(): array |
|
|
|
{ |
|
|
|
$defaultPlatform = config('openai.default'); |
|
|
|
$platform = config('openai.platforms.' . $defaultPlatform, []); |
|
|
|
if (empty($platform)) { |
|
|
|
throw new ApiException("默认的AI平台: {$defaultPlatform} 未配置", '', '', []); |
|
|
|
} |
|
|
|
if (empty($platform['base_url'])) { |
|
|
|
throw new ApiException("默认的AI平台: {$defaultPlatform} 未配置base_url", '', '', []); |
|
|
|
} |
|
|
|
if (empty($platform['api_key'])) { |
|
|
|
throw new ApiException("默认的AI平台: {$defaultPlatform} 未配置api_key", '', '', []); |
|
|
|
} |
|
|
|
if (empty($platform['model'])) { |
|
|
|
throw new ApiException("默认的AI平台: {$defaultPlatform} 未配置model", '', '', []); |
|
|
|
} |
|
|
|
return $platform; |
|
|
|
} |
|
|
|
|
|
|
|
public static function chat(string $prompt, bool $jsonResult = true): array |
|
|
|
{ |
|
|
|
$platformConfig = self::getCurrentConfig(); |
|
|
|
$client = self::getClient(); |
|
|
|
$promptContent = $prompt; |
|
|
|
$chatData = [ |
|
|
|
'model' => $platformConfig['model'], |
|
|
|
'messages' => [ |
|
|
|
[ |
|
|
|
'role' => 'user', |
|
|
|
'content' => $promptContent |
|
|
|
] |
|
|
|
] |
|
|
|
]; |
|
|
|
if ($jsonResult) { |
|
|
|
$chatData['response_format'] = [ |
|
|
|
'type' => 'json_object' |
|
|
|
]; |
|
|
|
} |
|
|
|
$openaiResult = $client->chat()->create($chatData); |
|
|
|
$resultContent = $openaiResult->choices[0]->message->content; |
|
|
|
$jsonResultContent = json_decode($resultContent, true); |
|
|
|
|
|
|
|
$result = []; |
|
|
|
if (!empty($jsonResultContent)) { |
|
|
|
$result['content'] = $jsonResultContent; |
|
|
|
} else { |
|
|
|
$result['content'] = $resultContent; |
|
|
|
} |
|
|
|
$result['usage'] = $openaiResult->usage; |
|
|
|
$result['prompt'] = $prompt; |
|
|
|
$result['platform'] = $platformConfig; |
|
|
|
return $result; |
|
|
|
} |
|
|
|
|
|
|
|
public static function getClient(): OpenAI\Client |
|
|
|
{ |
|
|
|
$platformConfig = self::getCurrentConfig(); |
|
|
|
return OpenAI::factory() |
|
|
|
->withApiKey($platformConfig['api_key']) |
|
|
|
->withBaseUri($platformConfig['base_url']) |
|
|
|
->withHttpClient(new \GuzzleHttp\Client([ |
|
|
|
'verify' => false |
|
|
|
])) |
|
|
|
->make(); |
|
|
|
} |
|
|
|
} |