-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathAIAgentChatConsoleCommand.php
More file actions
100 lines (85 loc) · 3.2 KB
/
AIAgentChatConsoleCommand.php
File metadata and controls
100 lines (85 loc) · 3.2 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
<?php
declare(strict_types=1);
namespace App\Console;
use App\Infrastructure\Config\AppConfig;
use GuzzleHttp\Exception\ClientException;
use NeuronAI\Agent\AgentInterface;
use NeuronAI\Chat\Messages\Stream\Chunks\TextChunk;
use NeuronAI\Chat\Messages\UserMessage;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* @codeCoverageIgnore
*/
#[AsCommand(name: 'app:ai:agent-chat', description: 'Start a new AI agent chat')]
final class AIAgentChatConsoleCommand extends Command
{
public function __construct(
private readonly AgentInterface $agent,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
if (!AppConfig::isAIIntegrationEnabled()) {
$io->error('The AI feature is not enabled.');
return Command::SUCCESS;
}
$helper = $this->getHelper('question');
assert($helper instanceof QuestionHelper);
$io->block(
messages: [
"Hi 👋, I'm Mark, your personal workout assistant.".PHP_EOL.
'Feel free to ask me anything—whether it’s about your training history or tips to improve!',
'Type "exit" to close the conversation.',
],
style: 'fg=black;bg=green',
padding: true
);
while (true) {
$question = new Question('<info><You></info> ');
$userInput = $helper->ask($input, $output, $question);
if (null === $userInput) {
continue; // if the user just presses Enter
}
if ('exit' === $userInput) {
$output->writeln('<comment><Mark></comment> Mkey, bye 👋');
break;
}
try {
$handler = $this->agent->stream(new UserMessage($userInput));
$first = true;
foreach ($handler->events() as $chunk) {
if (!$chunk instanceof TextChunk) {
continue;
}
if ($first) {
$output->write('<comment><Mark></comment> ');
$first = false;
}
$output->write($chunk->content);
}
$output->writeln('');
} catch (\Exception $e) {
$message = $e->getMessage();
if ($e instanceof ClientException) {
$message = $e->getResponse()->getBody()->getContents();
}
$output->writeln('');
$output->writeln('<comment><Mark></comment> Oh no, I made a booboo...');
$output->writeln(sprintf(
'<error>%s</error>',
$message
));
break;
}
}
return Command::SUCCESS;
}
}