Skip to content

Instantly share code, notes, and snippets.

@vedovelli
Created June 2, 2025 17:52
Show Gist options
  • Save vedovelli/36458a3978c205d56b8e33a828723bdc to your computer and use it in GitHub Desktop.
Save vedovelli/36458a3978c205d56b8e33a828723bdc to your computer and use it in GitHub Desktop.
<?php
use Prism\Prism\Prism;
use Prism\Prism\Facades\Tool;
use Prism\Prism\ValueObjects\Messages\AssistantMessage;
use Prism\Prism\ValueObjects\Messages\SystemMessage;
use Prism\Prism\ValueObjects\Messages\UserMessage;
use Carbon\Carbon;
use Exception;
Route::post('/chat', function () {
return response()->stream(function () {
$messages = [new SystemMessage(view('prompts/charges-prompt')->render())];
foreach (request('messages') as $messageObj) {
if ($messageObj['sender'] === 'user') {
$messages[] = new UserMessage($messageObj['text']);
} else {
$messages[] = new AssistantMessage($messageObj['text']);
}
}
$tool = Tool::as('chargesList')
->for('Responder perguntas sobre as cobranças da entidade pai do usuário logado')
->withStringParameter('startDate', 'Data de início no formato YYYY-MM-DD (ex: 2024-01-15)')
->withStringParameter('endDate', 'Data de fim no formato YYYY-MM-DD (ex: 2024-01-31)')
->using(function (string $startDate, string $endDate) {
$user = auth()->user()->parent;
try {
$start = Carbon::createFromFormat('Y-m-d', $startDate)->startOfDay();
$end = Carbon::createFromFormat('Y-m-d', $endDate)->endOfDay();
} catch (Exception $e) {
return json_encode([
'error' => 'Formato de data inválido. Use o formato YYYY-MM-DD (ex: 2024-01-15)',
]);
}
if ($start->gt($end)) {
return json_encode([
'error' => 'A data de início deve ser anterior à data de fim.',
]);
}
if ($start->diffInDays($end) > 90) {
return json_encode([
'error' => 'O período máximo permitido é de 3 meses (90 dias).',
]);
}
return $user->charges()
->with('supplier:id,name')
->whereNotNull('document_code')
->whereBetween('due_at', [$start, $end])
->select('id', 'supplier_id', 'status', 'description', 'amount', 'due_at', 'paid_at')
->orderBy('due_at', 'desc')
->get()
->toJson();
});
$response = Prism::text()
->using('openai', 'gpt-4o-mini')
->withMessages($messages)
->withTools([$tool])
->withMaxSteps(2)
->asStream();
foreach ($response as $chunk) {
echo $chunk->text;
ob_flush();
flush();
}
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'X-Accel-Buffering' => 'no',
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment