-
-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathAIChatRequestHandler.php
More file actions
154 lines (136 loc) · 5.63 KB
/
AIChatRequestHandler.php
File metadata and controls
154 lines (136 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Domain\Integration\AI\Chat\AddChatMessage\AddChatMessage;
use App\Domain\Integration\AI\Chat\ChatCommands;
use App\Domain\Integration\AI\Chat\ChatRepository;
use App\Infrastructure\Config\AppConfig;
use App\Infrastructure\CQRS\Command\Bus\CommandBus;
use App\Infrastructure\Http\ServerSentEvent;
use App\Infrastructure\Serialization\Json;
use GuzzleHttp\Exception\ClientException;
use League\Flysystem\FilesystemOperator;
use NeuronAI\Agent\AgentInterface;
use NeuronAI\Chat\Enums\MessageRole;
use NeuronAI\Chat\Messages\Stream\Chunks\TextChunk;
use NeuronAI\Chat\Messages\UserMessage;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\EventStreamResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;
use Twig\Environment;
#[AsController]
final readonly class AIChatRequestHandler
{
public function __construct(
private FilesystemOperator $buildStorage,
private AgentInterface $neuronAIAgent,
private ChatCommands $chatCommands,
private ChatRepository $chatRepository,
private CommandBus $commandBus,
private FormFactoryInterface $formFactory,
private Environment $twig,
) {
}
#[Route(path: '/ai/chat', methods: ['GET'], priority: 2)]
public function handle(): Response
{
if (!$this->buildStorage->fileExists('index.html')) {
return new RedirectResponse('/', Response::HTTP_FOUND);
}
if (!AppConfig::isAIIntegrationWithUIEnabled()) {
return new Response('UI for AI not enabled', Response::HTTP_OK);
}
$formBuilder = $this->formFactory->createBuilder();
$form = $formBuilder
->setAction('/ai/chat/user-message')
->add('message', TextType::class, [
'label' => 'Message',
'required' => true,
])
->add('submit', SubmitType::class)
->getForm();
return new Response($this->twig->render('html/chat/chat.html.twig', [
'chatHistory' => $this->chatRepository->findAll(),
'form' => $form->createView(),
'chatCommands' => Json::encode($this->chatCommands),
]), Response::HTTP_OK);
}
#[Route(path: '/chat/clear', methods: ['POST'], priority: 2)]
public function clearChat(): Response
{
$this->chatRepository->clear();
return new Response(status: Response::HTTP_NO_CONTENT);
}
#[Route('/chat/sse', methods: ['GET'], priority: 2)]
public function chatSse(Request $request): EventStreamResponse
{
return new EventStreamResponse(function (EventStreamResponse $response) use ($request): void {
$message = $request->query->get('message');
assert(is_string($message));
$response->sendEvent(new ServerSentEvent(
data: $this->twig->render('html/chat/message.html.twig', [
'chatMessage' => $this->chatRepository->buildMessage(
message: $message,
messageRole: MessageRole::USER,
),
'isThinking' => false,
]),
type: 'fullMessage'
));
$response->sendEvent(new ServerSentEvent(
data: $this->twig->render('html/chat/message.html.twig', [
'chatMessage' => $this->chatRepository->buildMessage(
message: '__PLACEHOLDER__',
messageRole: MessageRole::ASSISTANT,
),
'isThinking' => true,
]),
type: 'fullMessage'
));
try {
$handler = $this->neuronAIAgent->stream(new UserMessage($message));
foreach ($handler->events() as $chunk) {
if (!$chunk instanceof TextChunk) {
continue; // @codeCoverageIgnore
}
$response->sendEvent(new ServerSentEvent(
data: '',
type: 'removeThinking'
));
$response->sendEvent(new ServerSentEvent(
data: $chunk->content,
type: 'agentResponse'
));
}
} catch (\Throwable $e) {
$response->sendEvent(new ServerSentEvent(
data: '',
type: 'removeThinking'
));
$message = $e->getMessage().': '.$e->getTraceAsString();
if ($e instanceof ClientException) {
$message = $e->getResponse()->getBody()->getContents(); // @codeCoverageIgnore
}
$fullMessage = 'Oh no, I made a booboo... <br />'.preg_replace('/\s+/', ' ', $message);
$response->sendEvent(new ServerSentEvent(
data: $fullMessage,
type: 'agentResponse'
));
$this->commandBus->dispatch(new AddChatMessage(
message: $fullMessage,
messageRole: MessageRole::ASSISTANT,
));
}
$response->sendEvent(new ServerSentEvent(
data: 'done',
type: 'done'
));
});
}
}