@@ -85,22 +85,37 @@ def get_history(
8585
8686def parse_output (output : list ) -> tuple [str , list [str ], list [str ]]:
8787 fail_msg = "Failed to get response"
88+ MIN_OUTPUT_LENGTH = 3
8889
89- if not isinstance (output , list ) or len (output ) < 3 :
90+ # Validate outputs
91+ if not isinstance (output , list ):
92+ logging .error (f"Output is not a list: { type (output )} " )
93+ return fail_msg , [], []
94+ if len (output ) < MIN_OUTPUT_LENGTH :
95+ logging .error (f"Output too short: { len (output )} elements (expected >= { MIN_OUTPUT_LENGTH } )" )
9096 return fail_msg , [], []
9197
98+ # Validate last element contains generation
9299 last = output [- 1 ]
93100 if not isinstance (last , dict ):
101+ logging .error (f"Last element is not a dict: { type (last )} " )
94102 return fail_msg , [], []
95103
104+ # Determine if RAG or agent mode
96105 is_rag = "rag_generate" in last
97106 key = "rag_generate" if is_rag else "generate"
98107
99- if key not in last or "messages" not in last [key ]:
108+ if key not in last :
109+ logging .error (f"Missing '{ key } ' key in final output. Available keys: { list (last .keys ())} " )
110+ return fail_msg , [], []
111+
112+ if "messages" not in last [key ]:
113+ logging .error (f"Missing 'messages' in { key } " )
100114 return fail_msg , [], []
101115
102116 msgs = last [key ]["messages" ]
103117 if not msgs :
118+ logging .error ("Empty messages list in generation output" )
104119 return fail_msg , [], []
105120
106121 response = str (msgs [0 ])
@@ -123,6 +138,7 @@ def parse_output(output: list) -> tuple[str, list[str], list[str]]:
123138 urls = tool_out .get ("urls" , [])
124139 sources .extend (urls )
125140
141+ # Deduplicate sources
126142 return response , list (set (sources )), tools
127143
128144
@@ -243,10 +259,20 @@ def main() -> None:
243259
244260 except KeyboardInterrupt :
245261 console .print ("\n [yellow]Interrupted. Goodbye![/yellow]" )
246- except Exception as e :
247- console .print (f"[bold red]Error:[/bold red] { str (e )} " )
262+ except ValueError as e :
263+ console .print (f"[bold red]Configuration Error:[/bold red] { str (e )} " )
264+ console .print ("[yellow]Check your environment variables and try again.[/yellow]" )
265+ if debug :
266+ logging .exception ("Configuration error" )
267+ except ConnectionError as e :
268+ console .print (f"[bold red]Connection Error:[/bold red] { str (e )} " )
269+ console .print ("[yellow]Check your network connection and database availability.[/yellow]" )
248270 if debug :
249- logging .exception ("Error in main loop" )
271+ logging .exception ("Connection error" )
272+ except Exception as e :
273+ console .print (f"[bold red]Unexpected Error:[/bold red] { str (e )} " )
274+ console .print ("[yellow]Please report this issue if it persists.[/yellow]" )
275+ logging .exception ("Unexpected error in main loop" )
250276 finally :
251277 # Clean up database session
252278 if db_generator is not None :
0 commit comments