Spaces:
Runtime error
Runtime error
File size: 15,329 Bytes
a006388 fb4483c 67d801e a006388 67d801e a006388 67d801e a006388 67d801e fb4483c a006388 67d801e a006388 67d801e a006388 67d801e a006388 67d801e a006388 67d801e | 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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | import gradio as gr
import time
import os
import base64
from typing import List, Tuple, Optional
from langchain_core.messages import HumanMessage
from agent import build_graph
class QnAChatbot:
"""A Q&A chatbot interface for the agent."""
def __init__(self):
print("๐ค QnAChatbot initializing...")
print("๐ง Building agent graph...")
self.graph = build_graph()
self.conversation_history = []
print("โ
QnAChatbot initialized successfully")
def process_question(self, question: str, history: List[Tuple[str, str]], uploaded_files: Optional[List] = None) -> Tuple[str, List[Tuple[str, str]]]:
"""Process a question and return the response with updated history."""
if not question.strip() and not uploaded_files:
print("โ ๏ธ No question or files provided")
return "", history
try:
print(f"\n{'='*60}")
print(f"๐ค Processing new question...")
print(f"๐ Question: {question[:100]}{'...' if len(question) > 100 else ''}")
print(f"๐ Files uploaded: {len(uploaded_files) if uploaded_files else 0}")
# Handle uploaded files
file_context = ""
if uploaded_files:
print(f"๐ Processing {len(uploaded_files)} uploaded file(s)...")
file_context = self._process_uploaded_files(uploaded_files)
if file_context:
original_question = question
question = f"{question}\n\n{file_context}" if question.strip() else file_context
print(f"๐ File context added to question (length: {len(file_context)} chars)")
# Wrap the question in a HumanMessage
messages = [HumanMessage(content=question)]
print(f"๐ Invoking agent graph...")
# Get response from the agent
result = self.graph.invoke({"messages": messages})
print(f"๐จ Received {len(result['messages'])} message(s) from agent")
# Print all messages for debugging
for i, msg in enumerate(result['messages']):
print(f"๐ง Message {i+1}: {type(msg).__name__}")
if hasattr(msg, 'content'):
content_preview = msg.content[:200] + "..." if len(msg.content) > 200 else msg.content
print(f" Content preview: {content_preview}")
answer = result['messages'][-1].content
# Clean up the answer if it starts with "Assistant: "
if answer.startswith("Assistant: "):
answer = answer[11:]
print("๐งน Cleaned 'Assistant: ' prefix from response")
# Update conversation history
history.append((question, answer))
print(f"โ
Question processed successfully")
print(f"๐ Response length: {len(answer)} characters")
print(f"๐ฌ Total conversation history: {len(history)} exchanges")
print(f"{'='*60}\n")
return "", history
except Exception as e:
error_msg = f"Error processing question: {str(e)}"
print(f"โ {error_msg}")
print(f"๐ Exception details: {type(e).__name__}: {str(e)}")
import traceback
print(f"๐ Traceback:\n{traceback.format_exc()}")
history.append((question, error_msg))
print(f"{'='*60}\n")
return "", history
def _process_uploaded_files(self, uploaded_files: List) -> str:
"""Process uploaded files and return context for the question."""
file_contexts = []
for file_path in uploaded_files:
if not file_path or not os.path.exists(file_path):
print(f"โ ๏ธ Skipping invalid file path: {file_path}")
continue
try:
file_name = os.path.basename(file_path)
file_ext = os.path.splitext(file_name)[1].lower()
file_size = os.path.getsize(file_path)
print(f"๐ Processing file: {file_name} ({file_size} bytes, {file_ext})")
# Handle different file types
if file_ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']:
# Image file - convert to base64
with open(file_path, 'rb') as f:
image_data = base64.b64encode(f.read()).decode('utf-8')
file_contexts.append(f"[UPLOADED IMAGE: {file_name}] - Base64 data: {image_data}")
print(f"๐ผ๏ธ Image converted to base64 ({len(image_data)} chars)")
elif file_ext in ['.txt', '.md', '.py', '.js', '.html', '.css', '.json', '.xml']:
# Text file - read content
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
file_contexts.append(f"[UPLOADED TEXT FILE: {file_name}]\nContent:\n{content}")
print(f"๐ Text file content read ({len(content)} chars)")
elif file_ext in ['.csv']:
# CSV file - provide file path for analysis
file_contexts.append(f"[UPLOADED CSV FILE: {file_name}] - File path: {file_path}")
print(f"๐ CSV file prepared for analysis")
elif file_ext in ['.xlsx', '.xls']:
# Excel file - provide file path for analysis
file_contexts.append(f"[UPLOADED EXCEL FILE: {file_name}] - File path: {file_path}")
print(f"๐ Excel file prepared for analysis")
elif file_ext in ['.pdf']:
# PDF file - mention it's available
file_contexts.append(f"[UPLOADED PDF FILE: {file_name}] - File path: {file_path}")
print(f"๐ PDF file prepared for processing")
else:
# Other file types - just mention the file
file_contexts.append(f"[UPLOADED FILE: {file_name}] - File path: {file_path}")
print(f"๐ Generic file prepared for processing")
except Exception as e:
error_msg = f"Error processing file {file_path}: {e}"
print(f"โ {error_msg}")
print(f"๐ File processing error details: {type(e).__name__}: {str(e)}")
file_contexts.append(f"[ERROR PROCESSING FILE: {os.path.basename(file_path)}] - {str(e)}")
total_context = "\n\n".join(file_contexts) if file_contexts else ""
if total_context:
print(f"๐ Total file context generated: {len(total_context)} characters")
return total_context
def clear_history(self):
"""Clear the conversation history."""
print("๐งน Clearing conversation history...")
self.conversation_history = []
print("โ
Conversation history cleared")
return []
def create_qna_interface():
"""Create the Q&A chatbot interface."""
print("๐ Creating Q&A interface...")
# Initialize the chatbot
chatbot = QnAChatbot()
print("๐จ Setting up UI components...")
# Custom CSS for better styling
custom_css = """
.gradio-container {
max-width: 1200px !important;
margin: auto !important;
}
.chat-message {
padding: 10px !important;
margin: 5px 0 !important;
border-radius: 10px !important;
}
.user-message {
background-color: #e3f2fd !important;
margin-left: 20% !important;
}
.bot-message {
background-color: #f5f5f5 !important;
margin-right: 20% !important;
}
"""
with gr.Blocks(css=custom_css, title="GAIA Agent - Q&A Chatbot") as demo:
gr.Markdown(
"""
# ๐ค GAIA Agent - Q&A Chatbot
Welcome to the GAIA Agent Q&A interface! Ask me anything and I'll help you find the answer using my various tools and capabilities.
**What I can do:**
- ๐ Search the web, Wikipedia, and academic papers
- ๐งฎ Perform mathematical calculations
- ๐ป Execute code in multiple languages (Python, Bash, SQL, C, Java)
- ๐ Analyze CSV and Excel files
- ๐ผ๏ธ Process and analyze images (JPG, PNG, GIF, etc.)
- ๐ Extract text from images (OCR)
- ๐ Handle file uploads and processing (PDF, DOC, TXT, etc.)
- ๐ Create visualizations and charts
- ๐ง Multi-file analysis and comparison
- And much more!
---
"""
)
# Chat interface
with gr.Row():
with gr.Column(scale=1):
chatbot_interface = gr.Chatbot(
label="Conversation",
height=500,
show_label=True,
container=True,
bubble_full_width=False
)
# File upload section
with gr.Row():
with gr.Column():
file_upload = gr.File(
label="๐ Upload Files (Images, Documents, CSV, Excel, etc.)",
file_count="multiple",
file_types=[
".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", # Images
".txt", ".md", ".py", ".js", ".html", ".css", ".json", ".xml", # Text files
".csv", ".xlsx", ".xls", # Data files
".pdf", ".doc", ".docx" # Documents
],
height=100
)
with gr.Row():
with gr.Column(scale=8):
question_input = gr.Textbox(
label="Ask a question",
placeholder="Type your question here or upload files above... (e.g., 'What is the capital of France?', 'Analyze this image', 'Summarize this document')",
lines=2,
max_lines=5
)
with gr.Column(scale=1, min_width=100):
submit_btn = gr.Button("Send", variant="primary", size="lg")
with gr.Row():
clear_btn = gr.Button("Clear History", variant="secondary")
clear_files_btn = gr.Button("Clear Files", variant="secondary")
# Example questions
with gr.Row():
gr.Markdown("### ๐ก Example Questions:")
with gr.Row():
with gr.Column():
gr.Examples(
examples=[
"What is the current population of Tokyo?",
"Calculate the square root of 144",
"Write a Python function to sort a list",
"What are the latest developments in AI?",
"Explain quantum computing in simple terms",
],
inputs=question_input,
label="General Questions"
)
with gr.Column():
gr.Examples(
examples=[
"Search for recent papers on machine learning",
"What is the weather like today?",
"Create a simple bar chart using Python",
"Convert 100 USD to EUR",
"What are the benefits of renewable energy?",
],
inputs=question_input,
label="Research & Analysis"
)
with gr.Column():
gr.Examples(
examples=[
"Analyze this image and describe what you see",
"Extract text from this image using OCR",
"Summarize the content of this document",
"Analyze the data in this CSV file",
"What insights can you find in this Excel file?",
],
inputs=question_input,
label="File Analysis"
)
# Event handlers
def submit_question(question, history, files):
print(f"๐ฏ UI: Submit button clicked")
print(f"๐ UI: Question length: {len(question) if question else 0}")
print(f"๐ UI: Files count: {len(files) if files else 0}")
result_question, result_history = chatbot.process_question(question, history, files)
print(f"๐ UI: Returning results and clearing files")
return result_question, result_history, None # Clear files after processing
def clear_conversation():
print("๐งน UI: Clear conversation button clicked")
return chatbot.clear_history()
def clear_files():
print("๐๏ธ UI: Clear files button clicked")
return None
# Connect the events
submit_btn.click(
fn=submit_question,
inputs=[question_input, chatbot_interface, file_upload],
outputs=[question_input, chatbot_interface, file_upload],
show_progress=True
)
question_input.submit(
fn=submit_question,
inputs=[question_input, chatbot_interface, file_upload],
outputs=[question_input, chatbot_interface, file_upload],
show_progress=True
)
clear_btn.click(
fn=clear_conversation,
outputs=[chatbot_interface],
show_progress=False
)
clear_files_btn.click(
fn=clear_files,
outputs=[file_upload],
show_progress=False
)
# Footer
gr.Markdown(
"""
---
**Note:** This agent uses various tools and APIs to provide comprehensive answers.
Processing complex questions and file analysis may take some time. Please be patient!
**Supported file types:**
- **Images:** JPG, PNG, GIF, BMP, WebP
- **Documents:** PDF, DOC, DOCX, TXT, MD
- **Data files:** CSV, Excel (XLS, XLSX)
- **Code files:** Python, JavaScript, HTML, CSS, JSON, XML
**Powered by:** LangGraph, Groq, and various specialized tools
"""
)
return demo
if __name__ == "__main__":
print("\n" + "-"*50)
print("๐ Starting GAIA Agent Q&A Chatbot...")
print("-"*50 + "\n")
# Create and launch the interface
demo = create_qna_interface()
demo.launch(
debug=True,
share=False,
server_name="0.0.0.0",
server_port=7860,
show_error=True
) |