2024-10-31 12:09:06 -05:00
< ? php
2024-10-31 15:19:59 -05:00
use App\Models\AiChat ;
use Illuminate\Database\Eloquent\Model ;
use Livewire\Volt\Component ;
2025-09-26 17:41:28 -05:00
new class extends Component
{
2024-10-31 15:19:59 -05:00
// props
public Model $chatable ;
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
public string $system_prompt = 'You are an investment portfolio assistant providing advice to an investor. Use the following information to provide relevant recommendations. Use the words \'likely\' or \'may\' instead of concrete statements (except for obvious statements of fact or common sense). Use github style markdown for any formatting.' ;
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
public array $suggested_prompts = [];
public array $messages = [];
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
public ? string $prompt = null ;
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
public ? string $answer = null ;
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
public bool $streaming = false ;
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
// methods
public function mount ()
{
$this -> messages = $this -> chatable -> chats () -> orderByRaw ( 'created_at, id' ) -> limit ( 25 ) -> get ([ 'role' , 'content' ]) -> toArray ();
}
public function startCompletion ( $suggestedPrompt = null )
{
// prevent spam
if ( $this -> isRateLimited () || $this -> streaming ) {
array_push ( $this -> messages , [
2025-09-26 17:41:28 -05:00
'role' => 'assistant' ,
'content' => __ ( 'Hang on! You\'re doing that too much.' ),
2024-10-31 15:19:59 -05:00
]);
$this -> js ( 'scrollChatWindow(250)' );
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
return ;
2024-10-31 12:09:06 -05:00
}
2024-10-31 15:19:59 -05:00
if ( $suggestedPrompt ) {
$this -> prompt = $suggestedPrompt ;
}
2024-10-31 12:09:06 -05:00
2024-10-31 15:19:59 -05:00
if ( empty ( trim ( $this -> prompt ))) {
$this -> resetPrompt ();
2024-10-31 12:09:06 -05:00
2024-10-31 15:19:59 -05:00
array_push ( $this -> messages , [ 'role' => 'assistant' , 'content' => __ ( 'Feel free to ask me a question!' )]);
2024-10-31 12:09:06 -05:00
$this -> js ( 'scrollChatWindow(250)' );
2024-10-31 15:19:59 -05:00
return ;
2025-09-26 17:41:28 -05:00
}
2024-10-31 15:19:59 -05:00
$this -> chatable -> chats () -> save ( new AiChat ([ 'role' => 'user' , 'content' => $this -> prompt ]));
array_push ( $this -> messages , [ 'role' => 'user' , 'content' => $this -> prompt ]);
$this -> js ( 'scrollChatWindow(250)' );
$this -> resetPrompt ();
$this -> streaming = true ;
2024-11-01 23:18:22 -05:00
$this -> js ( '$wire.generateCompletion()' );
2024-10-31 15:19:59 -05:00
}
2024-11-01 23:18:22 -05:00
public function generateCompletion () : void
2024-10-31 15:19:59 -05:00
{
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
try {
2024-12-06 16:01:53 -06:00
$client = $this -> createOpenAiClient ();
2025-09-26 17:41:28 -05:00
2024-12-06 16:01:53 -06:00
$stream = $client -> chat () -> createStreamed ([
2024-10-31 15:19:59 -05:00
'model' => config ( 'openai.model' ),
'messages' => [
2024-11-01 23:18:22 -05:00
[ 'role' => 'system' , 'content' => " Today's date is "
2025-04-09 19:25:15 -05:00
. now () -> toDateString ()
2024-11-01 23:18:22 -05:00
. " . \n \n " . $this -> system_prompt ],
2025-09-26 17:41:28 -05:00
... array_slice ( $this -> messages , - 10 ),
2024-10-31 15:19:59 -05:00
],
]);
} catch ( \Exception $e ) {
$this -> chatable -> chats () -> save ( new AiChat ([ 'role' => 'assistant' , 'content' => $e -> getMessage ()]));
array_push ( $this -> messages , [ 'role' => 'assistant' , 'content' => $e -> getMessage ()]);
2024-10-31 12:09:06 -05:00
$this -> resetPrompt ();
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
return ;
2024-10-31 12:09:06 -05:00
}
2025-09-26 17:41:28 -05:00
$this -> stream ( to : 'answer' , content : '' , replace : true );
foreach ( $stream as $response ) {
if ( ! empty ( $response -> choices [ 0 ] -> delta -> content )) {
2024-10-31 15:19:59 -05:00
$this -> stream ( to : 'answer' , content : $response -> choices [ 0 ] -> delta -> content , replace : false );
$this -> answer .= $response -> choices [ 0 ] -> delta -> content ;
2024-10-31 12:09:06 -05:00
}
2024-10-31 15:19:59 -05:00
$this -> js ( 'scrollChatWindow()' );
2024-10-31 12:09:06 -05:00
}
2024-10-31 15:19:59 -05:00
$this -> chatable -> chats () -> save ( new AiChat ([ 'role' => 'assistant' , 'content' => $this -> answer ]));
array_push ( $this -> messages , [ 'role' => 'assistant' , 'content' => $this -> answer ]);
$this -> resetPrompt ();
2024-11-01 23:18:22 -05:00
$this -> js ( '$wire.generateSuggestedPrompts()' );
}
public function generateSuggestedPrompts () : void
{
try {
2024-12-06 16:01:53 -06:00
$client = $this -> createOpenAiClient ();
$suggested_prompts = $client -> chat () -> create ([
2024-11-01 23:18:22 -05:00
'model' => config ( 'openai.model' ),
'response_format' => [
'type' => 'json_schema' ,
'json_schema' => [
'name' => 'suggested_prompts_schema' ,
'strict' => true ,
'schema' => [
2025-09-26 17:41:28 -05:00
'type' => 'object' ,
'properties' => [
'suggested_prompts' => [
'type' => 'array' ,
'items' => [
'type' => 'object' ,
'properties' => [
'text' => [
'type' => 'string' ,
'description' => 'The suggested prompt question (no more than 5 words)' ,
],
'value' => [
'type' => 'string' ,
'description' => 'The detailed version of the question' ,
2024-11-01 23:18:22 -05:00
],
],
2025-09-26 17:41:28 -05:00
'required' => [ 'text' , 'value' ],
'additionalProperties' => false ,
],
],
2024-11-01 23:18:22 -05:00
],
2025-09-26 17:41:28 -05:00
'required' => [ 'suggested_prompts' ],
'additionalProperties' => false ,
],
],
2024-11-01 23:18:22 -05:00
],
'messages' => [
2025-09-26 17:41:28 -05:00
[ 'role' => 'system' , 'content' => '
2024-11-03 16:13:24 -06:00
Your role is to assist investors in asking thoughtful questions of their investment advisors.
2024-11-01 23:18:22 -05:00
2024-11-03 16:13:24 -06:00
When you help investors ask good questions, you should ensure the you questions you recommend
are based on the provided context. Be sure to keep the questions short!
2024-11-01 23:18:22 -05:00
The questions you recommend might be based on natural follow up from the given context, requests
2024-11-03 16:13:24 -06:00
to further refine a previous response, clarify undefined terms, common decision frameworks,
possible risks or benefits, or commonly understood investing concepts that may require additional
explanation.
2024-11-01 23:18:22 -05:00
Your response should only include valid JSON.
2025-09-26 17:41:28 -05:00
' ],
2024-11-01 23:18:22 -05:00
[ 'role' => 'user' , 'content' => "
2024-11-03 16:13:24 -06:00
Generate between 1 and 5 (no more than 5) follow up questions a savvy investor might ask their
advisor based on the following conversation:
2024-11-01 23:18:22 -05:00
\n \n
2025-09-26 17:41:28 -05:00
" . json_encode ( array_slice ( $this -> messages , - 4 )),
2024-11-01 23:18:22 -05:00
],
],
]);
$this -> suggested_prompts = json_decode ( $suggested_prompts -> choices [ 0 ] -> message -> content , true )[ 'suggested_prompts' ];
} catch ( \Exception $e ) {
$this -> suggested_prompts = [];
$this -> error ( $e -> getMessage ());
2025-09-26 17:41:28 -05:00
2024-11-01 23:18:22 -05:00
return ;
}
2024-10-31 15:19:59 -05:00
}
public function resetPrompt () : void
{
$this -> answer = null ;
$this -> prompt = null ;
$this -> streaming = false ;
}
public function isRateLimited () : bool
{
2025-09-26 17:41:28 -05:00
$rateLimitKey = auth () -> id () . '/' . $this -> chatable -> id ;
2024-10-31 15:19:59 -05:00
if ( RateLimiter :: tooManyAttempts ( $rateLimitKey , 20 )) {
2025-09-26 17:41:28 -05:00
2024-10-31 15:19:59 -05:00
return true ;
2024-10-31 12:09:06 -05:00
}
2024-10-31 15:19:59 -05:00
RateLimiter :: hit ( $rateLimitKey , 60 );
2024-10-31 12:09:06 -05:00
2024-10-31 15:19:59 -05:00
return false ;
}
2024-10-31 12:09:06 -05:00
2024-12-06 16:01:53 -06:00
private function createOpenAiClient ()
{
$apiKey = config ( 'openai.api_key' );
$organization = config ( 'openai.organization' );
$baseUri = config ( 'openai.base_uri' );
return OpenAI :: factory ()
-> withApiKey ( $apiKey )
-> withOrganization ( $organization )
-> withHttpHeader ( 'OpenAI-Beta' , 'assistants=v2' )
-> withHttpClient ( new \GuzzleHttp\Client ([ 'timeout' => config ( 'openai.request_timeout' , 30 )]))
-> withBaseUri ( $baseUri )
-> make ();
}
2024-10-31 15:19:59 -05:00
}; ?>
<div
x-data="{
open: false,
async scrollChatWindow(delay = 0) {
await new Promise(resolve => setTimeout(resolve, delay));
this.$refs.chatWindow.scrollBy({
top: this.$refs.chatWindow.scrollHeight,
behavior: 'smooth'
});
}
}"
2024-11-01 22:13:40 -05:00
class="fixed z-50 bottom-8 right-8"
2024-10-31 15:19:59 -05:00
>
2024-11-01 22:13:40 -05:00
{{-- toggle button --}}
2025-09-26 17:41:28 -05:00
<x-ui.button
2024-11-01 22:13:40 -05:00
x-show="!open"
2024-10-31 15:19:59 -05:00
@click="$dispatch('toggle-ai-chat')"
2025-09-26 17:41:28 -05:00
@keyup.escape.window="open = false"
2024-11-01 22:13:40 -05:00
class="flex btn btn-circle md:btn-lg btn-primary"
2024-10-31 15:19:59 -05:00
>
<x-slot:label>
2025-09-26 17:41:28 -05:00
<x-ui.icon name="o-sparkles" class="w-6 h-6 md:w-8 md:h-8"></x-ui.icon>
2024-10-31 15:19:59 -05:00
</x-slot:label>
2025-09-26 17:41:28 -05:00
</x-ui.button>
2024-10-31 12:09:06 -05:00
2024-11-01 22:13:40 -05:00
{{-- popup --}}
2024-10-31 12:09:06 -05:00
<div
2024-10-31 15:19:59 -05:00
x-on:toggle-ai-chat.window="open = !open"
x-show="open"
x-trap="open"
x-bind:inert="!open"
2024-11-01 22:13:40 -05:00
x-transition:enter="transition ease-out duration-300"
x-transition:enter-start="opacity-0 transform translate-y-full"
x-transition:enter-end="opacity-100 transform translate-y-0"
x-transition:leave="transition ease-in duration-200"
x-transition:leave-start="opacity-100 transform translate-y-0"
x-transition:leave-end="opacity-0 transform translate-y-full"
2024-10-31 15:19:59 -05:00
x-cloak
key="ai-chat"
2025-09-26 17:41:28 -05:00
class="fixed bg-base-300 shadow-2xl rounded-none md:rounded-lg
inset-0 h-screen w-full md:inset-auto md:right-6
md:bottom-6 md:w-[32rem] md:h-[46rem]"
2024-10-31 12:09:06 -05:00
>
2024-11-01 22:13:40 -05:00
<div
class="absolute inset-0 flex flex-col overflow-hidden p-4"
x-intersect="scrollChatWindow()"
>
<div class="flex grow-0 justify-between items-center pb-4 ">
2025-09-26 17:41:28 -05:00
<h2 class="text-lg text-bold select-none">{{ __('AI Chat') }}</h2>
<x-ui.button
2024-11-01 22:13:40 -05:00
icon="o-x-mark"
class="absolute top-5 right-4 btn-ghost btn-circle btn-sm"
title="{{ __('Close') }}"
@click="open = false"
/>
</div>
2024-10-31 15:19:59 -05:00
{{-- chat window --}}
2024-11-01 22:13:40 -05:00
<div class="grow overflow-hidden overflow-y-scroll ai-chat" x-ref="chatWindow">
2024-10-31 15:19:59 -05:00
<div class="flex gap-3 mb-5 flex-1">
<span class="
flex
rounded-full
w-10 h-10
border border-gray-600
dark:border-gray-400
text-gray-600
dark:text-gray-400
bg-slate-200
dark:bg-slate-800
">
2025-09-26 17:41:28 -05:00
<x-ui.icon name="o-sparkles" class="h-auto p-1 w-10" />
2024-10-31 15:19:59 -05:00
</span>
<p class="leading-relaxed w-full">
<span class="block font-bold">AI</span> {{ __('Hi, how can I help?') }}
</p>
</div>
2024-10-31 12:09:06 -05:00
2024-10-31 15:19:59 -05:00
@foreach($messages as $message)
@if ($message['role'] == 'user')
<div class="flex gap-3 mb-5 flex-1">
<span class="relative flex shrink-0 overflow-hidden rounded-full w-10 h-10">
2025-09-26 17:41:28 -05:00
<x-ui.avatar :image="auth()->user()->profile_photo_url" class="!w-10" />
2024-10-31 15:19:59 -05:00
</span>
<p class="leading-relaxed">
<span class="block font-bold ">{{ __('You') }} </span> {{ $message['content'] }}
</p>
</div>
@else
<div class="flex gap-3 mb-5 flex-1">
<span class="
flex
rounded-full
w-10 h-10
border border-gray-600
dark:border-gray-400
text-gray-600
dark:text-gray-400
bg-slate-200
dark:bg-slate-800
">
2025-09-26 17:41:28 -05:00
<x-ui.icon name="o-sparkles" class="h-auto p-1 w-10" />
2024-10-31 15:19:59 -05:00
</span>
<div class="leading-relaxed" >
<span class="block font-bold ">AI </span> {!! Str::markdown($message['content']) !!}
</div>
</div>
@endif
@endforeach
@if($streaming)
<div class="flex gap-3 mb-10 flex-1">
2024-10-31 12:09:06 -05:00
<span class="
flex
rounded-full
w-10 h-10
border border-gray-600
dark:border-gray-400
text-gray-600
dark:text-gray-400
bg-slate-200
dark:bg-slate-800
2024-10-31 15:19:59 -05:00
">
2025-09-26 17:41:28 -05:00
<x-ui.icon name="o-sparkles" class="h-auto p-1 w-10" />
2024-10-31 12:09:06 -05:00
</span>
2024-10-31 15:19:59 -05:00
<p class="leading-relaxed" >
<span class="block font-bold ">AI </span> <span wire:stream="answer">{{ $answer }}</span>
2024-10-31 12:09:06 -05:00
</p>
</div>
2024-10-31 15:19:59 -05:00
@endif
</div>
{{-- prompt input --}}
2024-11-01 22:13:40 -05:00
<div class="mt-3 grow-0">
2025-09-26 17:41:28 -05:00
<form submit="startCompletion">
2024-11-01 22:13:40 -05:00
<div class="">
@foreach($suggested_prompts as $prompt)
2025-09-26 17:41:28 -05:00
<x-ui.button
2024-11-01 22:13:40 -05:00
class="btn-xs btn-primary btn-outline mr-1 mb-2"
2024-11-01 23:18:22 -05:00
wire:click="startCompletion('{{ addslashes($prompt['value']) }}')"
2025-09-26 17:41:28 -05:00
>{{ $prompt['text'] }}</x-ui.button>
2024-11-01 22:13:40 -05:00
@endforeach
2024-10-31 12:09:06 -05:00
</div>
2024-10-31 15:19:59 -05:00
2024-11-01 22:13:40 -05:00
<div class="flex justify-between align-bottom space-x-2 mt-1">
2025-09-26 17:41:28 -05:00
<div class="w-full" >
2024-11-01 22:13:40 -05:00
2025-09-26 17:41:28 -05:00
<x-ui.textarea
2024-11-01 22:13:40 -05:00
wire:model="prompt"
2025-09-26 17:41:28 -05:00
class="h-18 resize-none bg-base-200"
2024-11-01 22:13:40 -05:00
placeholder="{{ __('Have a question? AI might be able to help...') }}"
wire:keydown.enter.prevent="startCompletion"
autofocus
2025-09-26 17:41:28 -05:00
@toggle-ai-chat.window="setTimeout(() => $el.focus(), 250)"
></x-ui.textarea>
{{-- --}}
2024-11-01 22:13:40 -05:00
</div>
2025-09-26 17:41:28 -05:00
<x-ui.button
2024-11-01 23:18:22 -05:00
spinner="generateCompletion"
2024-11-01 22:13:40 -05:00
wire:click="startCompletion"
2025-09-26 17:41:28 -05:00
class="btn btn-ghost h-32"
2024-11-01 22:13:40 -05:00
icon="o-paper-airplane"
2025-09-26 17:41:28 -05:00
></x-ui.button>
2024-11-01 22:13:40 -05:00
</div>
<div class="w-full mt-2">
2025-09-26 17:41:28 -05:00
<p class="text-xs text-secondary leading-tight select-none">{{ __('Advice generated by AI may contain errors. Use at your own risk. Always consult a licensed investment advisor.') }} </p>
2024-11-01 22:13:40 -05:00
</div>
</form>
</div>
</div>
2024-10-31 12:09:06 -05:00
</div>
2024-10-31 15:19:59 -05:00
</div>