Pular para o conteúdo

PHP

Requer PHP 8.4 ou superior, allow_url_fopen e OpenSSL habilitados. O exemplo usa streams HTTP sem dependências Composer. Configure as três variáveis dos primeiros passos.

chat.php
<?php
// PHP 8.4+ com allow_url_fopen e OpenSSL. Execute: php examples/chat.php
function requiredEnv(string $name): string {
$value = getenv($name);
if ($value === false || $value === '') {
fwrite(STDERR, "Configure $name\n");
exit(1);
}
return $value;
}
$baseUrl = rtrim(requiredEnv('NEXVRA_BASE_URL'), '/');
$key = requiredEnv('NEXVRA_API_KEY');
$model = requiredEnv('NEXVRA_MODEL');
$body = json_encode([
'model' => $model,
'messages' => [['role' => 'user', 'content' => 'Olá! Responda em uma frase.']],
'max_tokens' => 128,
], JSON_THROW_ON_ERROR);
$context = stream_context_create(['http' => [
'method' => 'POST',
'header' => "Authorization: Bearer $key\r\nContent-Type: application/json\r\n",
'content' => $body,
'timeout' => 60,
'ignore_errors' => true,
'follow_location' => 0,
], 'ssl' => ['verify_peer' => true, 'verify_peer_name' => true]]);
$response = @file_get_contents($baseUrl . '/chat/completions', false, $context);
if ($response === false) {
fwrite(STDERR, "Falha de transporte HTTP\n");
exit(1);
}
$headers = http_get_last_response_headers();
$status = 0;
$requestId = '';
foreach ($headers ?? [] as $line) {
if (preg_match('/^HTTP\/\S+\s+(\d{3})/', $line, $matches)) {
$status = (int) $matches[1];
}
if (stripos($line, 'x-nexvra-request-id:') === 0) {
$requestId = trim(substr($line, strlen('x-nexvra-request-id:')));
}
}
if ($status !== 200) {
fwrite(STDERR, "HTTP $status; request-id=$requestId\n$response\n");
exit(1);
}
$result = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
echo $result['choices'][0]['message']['content'], PHP_EOL;

Execute com php chat.php. Para produção, também é possível usar um cliente HTTP como o adotado pelo seu framework; preserve HTTPS, timeout e tratamento de status, sem retries automáticos da geração.