atriumsample / app.py
jsantangelo's picture
Update app.py
f313c28 verified
Raw History Blame
6.05 kB
import os
import gradio as gr
from llama_cloud import LlamaCloud
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Initialize LlamaCloud client
client = LlamaCloud(
api_key=os.getenv("LLAMA_CLOUD_API_KEY")
)
class DocumentChatbot:
def __init__(self):
self.pipeline = None
self.load_pipeline()
def load_pipeline(self):
"""Load the pipeline from LlamaCloud"""
try:
# Replace with your actual pipeline ID from LlamaCloud
pipeline_id = os.getenv("LLAMA_CLOUD_PIPELINE_ID")
if not pipeline_id:
raise ValueError("LLAMA_CLOUD_PIPELINE_ID not found in environment variables")
# Get the pipeline from LlamaCloud
self.pipeline = client.pipelines.get(pipeline_id)
print("βœ… Successfully connected to LlamaCloud pipeline")
except Exception as e:
print(f"❌ Error loading pipeline: {str(e)}")
self.pipeline = None
def chat(self, message, history):
"""Process chat message using LlamaCloud pipeline directly"""
if not self.pipeline:
return "❌ Error: Could not connect to LlamaCloud pipeline. Please check your configuration."
try:
# Query using LlamaCloud pipeline directly
response = client.pipelines.run(
pipeline_id=self.pipeline.id,
input={"query": message}
)
# Extract the response text
if hasattr(response, 'output') and 'response' in response.output:
response_text = response.output['response']
elif hasattr(response, 'response'):
response_text = str(response.response)
else:
response_text = str(response)
return response_text
except Exception as e:
return f"❌ Error processing your question: {str(e)}"
# Initialize the chatbot
chatbot = DocumentChatbot()
# Create Gradio interface
def create_interface():
with gr.Blocks(
title="Chat with Your Documents",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 800px !important;
margin: auto !important;
}
"""
) as iface:
gr.Markdown(
"""
# πŸ“š Chat with Your Documents
Ask questions about your uploaded documents. The AI will search through your document index and provide relevant answers with sources.
**Example questions:**
- "What are the main topics covered in the documents?"
- "Summarize the key findings"
- "What does the document say about [specific topic]?"
"""
)
# Chat interface
chatbot_ui = gr.Chatbot(
height=400,
placeholder="Your conversation will appear here...",
show_copy_button=True
)
msg = gr.Textbox(
placeholder="Type your question here...",
label="Your Question",
lines=2
)
# Button row
with gr.Row():
submit_btn = gr.Button("Send", variant="primary", scale=2)
clear_btn = gr.Button("Clear Chat", scale=1)
# Example questions
gr.Examples(
examples=[
["What are the main topics discussed in the documents?"],
["Can you provide a summary of the key points?"],
["What are the most important findings?"],
["Tell me about the methodology used"],
["What conclusions were drawn?"]
],
inputs=msg,
label="Example Questions"
)
# Event handlers
def respond(message, chat_history):
if not message.strip():
return chat_history, ""
# Add user message to history
chat_history.append([message, None])
# Get bot response
bot_response = chatbot.chat(message, chat_history)
# Update history with bot response
chat_history[-1][1] = bot_response
return chat_history, ""
def clear_chat():
return [], ""
# Wire up events
submit_btn.click(
respond,
inputs=[msg, chatbot_ui],
outputs=[chatbot_ui, msg]
)
msg.submit(
respond,
inputs=[msg, chatbot_ui],
outputs=[chatbot_ui, msg]
)
clear_btn.click(clear_chat, outputs=[chatbot_ui, msg])
# Status information
with gr.Accordion("ℹ️ System Information", open=False):
status_text = "βœ… Connected to LlamaCloud pipeline" if chatbot.pipeline else "❌ Failed to connect to pipeline"
gr.Markdown(f"**Status:** {status_text}")
if chatbot.pipeline:
gr.Markdown("**Configuration:** Using LlamaCloud pipeline directly (no external LLM needed)")
else:
gr.Markdown("**Error:** Please check your environment variables and LlamaCloud configuration")
return iface
# Launch the app
if __name__ == "__main__":
# Check required environment variables
required_vars = ["LLAMA_CLOUD_API_KEY", "LLAMA_CLOUD_PIPELINE_ID"]
missing_vars = [var for var in required_vars if not os.getenv(var)]
if missing_vars:
print(f"❌ Missing required environment variables: {', '.join(missing_vars)}")
print("Please set them in your Hugging Face Space secrets or .env file")
# Create and launch interface
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
)