You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.3 KiB
44 lines
1.3 KiB
<?php |
|
|
|
namespace App\Services; |
|
|
|
use Illuminate\Support\Facades\Http; |
|
use RuntimeException; |
|
|
|
class OllamaService |
|
{ |
|
public function isConfigured(): bool |
|
{ |
|
return (string) config('ollama.base_url') !== ''; |
|
} |
|
|
|
/** |
|
* @param array<int, array{role: string, content: string}> $messages |
|
*/ |
|
public function chat(array $messages, ?string $model = null): string |
|
{ |
|
$baseUrl = rtrim((string) config('ollama.base_url'), '/'); |
|
if ($baseUrl === '') { |
|
throw new RuntimeException('OLLAMA_BASE_URL belum dikonfigurasi.'); |
|
} |
|
|
|
$response = Http::timeout((int) config('ollama.timeout', 120)) |
|
->acceptJson() |
|
->post($baseUrl.'/api/chat', [ |
|
'model' => $model ?: (string) config('ollama.chat_model'), |
|
'messages' => $messages, |
|
'stream' => false, |
|
]); |
|
|
|
if (! $response->successful()) { |
|
throw new RuntimeException('Ollama chat gagal: HTTP '.$response->status()); |
|
} |
|
|
|
$content = data_get($response->json(), 'message.content'); |
|
if (! is_string($content) || trim($content) === '') { |
|
throw new RuntimeException('Ollama mengembalikan respons kosong.'); |
|
} |
|
|
|
return trim($content); |
|
} |
|
}
|
|
|