Files
2026-09-01 09:22:30 -03:00

87 lines
2.6 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace App\Services\Ai;
use App\Models\AiProvider;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
class StepFunService implements AiServiceInterface
{
/**
* @param AiProvider $provider
*/
public function __construct(private AiProvider $provider)
{
$this->client = new Client([
'base_uri' => rtrim((string) $provider->base_url, '/') . '/',
'timeout' => 120,
]);
}
public function chat(array $messages, array $data = []): array
{
$apiKey = $data['api_key'] ?? $this->provider->api_key;
if (empty($apiKey)) {
throw new \InvalidArgumentException('StepFun API key is not configured.');
}
try {
$payload = [
'model' => (string) ($data['model'] ?? ''),
'messages' => $messages,
];
if (isset($data['temperature'])) {
$payload['temperature'] = (float) $data['temperature'];
}
if (isset($data['max_tokens'])) {
$payload['max_tokens'] = (int) $data['max_tokens'];
}
if (!empty($data['reasoning_effort'])) {
$payload['reasoning_effort'] = (string) $data['reasoning_effort'];
}
$response = $this->client->post('chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
$body = json_decode($response->getBody()->getContents(), true);
if (!isset($body['choices'][0]['message']['content'])) {
throw new \RuntimeException('Invalid response structure from StepFun.');
}
return [
'content' => $body['choices'][0]['message']['content'],
'tokens_used' => $body['usage']['total_tokens'] ?? null,
'model' => $body['model'] ?? (string) ($data['model'] ?? ''),
];
} catch (GuzzleException $e) {
Log::error('StepFun API error: ' . $e->getMessage());
throw new \RuntimeException('Failed to generate prompt with StepFun: ' . $e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* {@inheritdoc}
*/
public function generatePrompt(array $data): array
{
return $this->chat(
[['role' => 'user', 'content' => (string) ($data['prompt'] ?? '')]],
$data
);
}
}