@@ -35,26 +35,13 @@ class AgentChat extends Command
3535 */
3636 public function handle (): int
3737 {
38- $ agentName = $ this ->argument ('agent ' );
39-
40- try {
41- $ agent = Cortex::agent ($ agentName );
42- } catch (InvalidArgumentException $ e ) {
43- $ this ->error (sprintf ("Agent '%s' not found in registry. " , $ agentName ));
44-
45- $ availableAgents = AgentRegistry::names ();
46-
47- if (! empty ($ availableAgents )) {
48- $ this ->info ('Available agents: ' );
49- foreach ($ availableAgents as $ name ) {
50- $ this ->line (' - ' . $ name );
51- }
52- }
38+ $ agent = $ this ->getAgent ();
5339
40+ if ($ agent === null ) {
5441 return self ::FAILURE ;
5542 }
5643
57- $ this ->info ('Chatting with agent: ' . $ agentName );
44+ $ this ->info ('Chatting with agent: ' . $ agent -> getName () );
5845 $ this ->line ("Type 'exit' or 'quit' to end the conversation. \n" );
5946
6047 while (true ) {
@@ -69,16 +56,14 @@ public function handle(): int
6956 continue ;
7057 }
7158
72- // Create user message and pass it to stream
73- $ userMessage = new UserMessage ($ userInput );
74-
7559 try {
7660 $ this ->line ("\nAgent: " );
77- $ this ->streamAgentResponse ($ agent , $ userMessage );
61+ $ this ->streamAgentResponse ($ agent , new UserMessage ( $ userInput ) );
7862 $ this ->newLine ();
7963 } catch (Throwable $ e ) {
80- $ this ->error ('Error: ' . $ e ->getMessage ());
81- $ this ->newLine ();
64+ $ this ->renderErrorMessage ($ e ->getMessage ());
65+
66+ return self ::FAILURE ;
8267 }
8368 }
8469
@@ -229,8 +214,34 @@ protected function handleRunEnd(): void
229214 */
230215 protected function handleError (ChatGenerationChunk $ chunk ): void
231216 {
232- $ errorMessage = $ chunk ->exception ?->getMessage() ?? 'An error occurred ' ;
217+ $ this ->renderErrorMessage ($ chunk ->exception ?->getMessage() ?? 'An error occurred ' );
218+ }
219+
220+ protected function renderErrorMessage (string $ message ): void
221+ {
233222 $ this ->newLine ();
234- $ this ->error ('Error: ' . $ errorMessage );
223+ $ this ->error ('Error: ' . $ message );
224+ }
225+
226+ protected function getAgent (): ?Agent
227+ {
228+ $ agentName = $ this ->argument ('agent ' );
229+
230+ try {
231+ return Cortex::agent ($ agentName );
232+ } catch (InvalidArgumentException $ e ) {
233+ $ this ->error (sprintf ("Agent '%s' not found in registry. " , $ agentName ));
234+
235+ $ availableAgents = AgentRegistry::names ();
236+
237+ if (! empty ($ availableAgents )) {
238+ $ this ->info ('Available agents: ' );
239+ foreach ($ availableAgents as $ name ) {
240+ $ this ->line (' - ' . $ name );
241+ }
242+ }
243+
244+ return null ;
245+ }
235246 }
236247}
0 commit comments