Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,99 +1,209 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# Load
|
| 8 |
-
|
| 9 |
-
PIPELINE_ID = os.environ.get("PIPELINE_ID", "")
|
| 10 |
-
API_URL = f"https://api.cloud.llamaindex.ai/api/v1/pipelines/{PIPELINE_ID}/chat"
|
| 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 |
-
body = r.text.strip()
|
| 69 |
-
|
| 70 |
-
# Handle multi-JSON response
|
| 71 |
-
json_blobs = re.findall(r'\{.*?\}(?=\s*[{[]|\s*$)', body, re.DOTALL)
|
| 72 |
-
frames = [json.loads(blob) for blob in json_blobs if blob.strip().startswith("{")]
|
| 73 |
-
|
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from llama_index.core import VectorStoreIndex
|
| 4 |
+
from llama_index.llms.openai import OpenAI
|
| 5 |
+
from llama_index.core import Settings
|
| 6 |
+
from llama_cloud import LlamaCloud
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
|
| 9 |
+
# Load environment variables
|
| 10 |
+
load_dotenv()
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# Initialize LlamaCloud client
|
| 13 |
+
client = LlamaCloud(
|
| 14 |
+
api_key=os.getenv("LLAMA_CLOUD_API_KEY")
|
| 15 |
+
)
|
| 16 |
|
| 17 |
+
# Configure settings
|
| 18 |
+
Settings.llm = OpenAI(
|
| 19 |
+
model="gpt-3.5-turbo",
|
| 20 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 21 |
+
temperature=0.1
|
| 22 |
+
)
|
| 23 |
|
| 24 |
+
class DocumentChatbot:
|
| 25 |
+
def __init__(self):
|
| 26 |
+
self.index = None
|
| 27 |
+
self.query_engine = None
|
| 28 |
+
self.load_index()
|
| 29 |
+
|
| 30 |
+
def load_index(self):
|
| 31 |
+
"""Load the index from LlamaCloud"""
|
| 32 |
+
try:
|
| 33 |
+
# Replace with your actual index ID from LlamaCloud
|
| 34 |
+
index_id = os.getenv("LLAMA_CLOUD_INDEX_ID")
|
| 35 |
+
|
| 36 |
+
if not index_id:
|
| 37 |
+
raise ValueError("LLAMA_CLOUD_INDEX_ID not found in environment variables")
|
| 38 |
+
|
| 39 |
+
# Connect to your existing LlamaCloud index
|
| 40 |
+
self.index = VectorStoreIndex.from_cloud(
|
| 41 |
+
cloud_id=index_id,
|
| 42 |
+
api_key=os.getenv("LLAMA_CLOUD_API_KEY")
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# Create query engine
|
| 46 |
+
self.query_engine = self.index.as_query_engine(
|
| 47 |
+
similarity_top_k=3,
|
| 48 |
+
response_mode="compact"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
print("β
Successfully connected to LlamaCloud index")
|
| 52 |
+
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f"β Error loading index: {str(e)}")
|
| 55 |
+
self.index = None
|
| 56 |
+
self.query_engine = None
|
| 57 |
+
|
| 58 |
+
def chat(self, message, history):
|
| 59 |
+
"""Process chat message and return response"""
|
| 60 |
+
if not self.query_engine:
|
| 61 |
+
return "β Error: Could not connect to document index. Please check your configuration."
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
# Query the documents
|
| 65 |
+
response = self.query_engine.query(message)
|
| 66 |
+
|
| 67 |
+
# Format response with sources if available
|
| 68 |
+
response_text = str(response)
|
| 69 |
+
|
| 70 |
+
# Add source information if available
|
| 71 |
+
if hasattr(response, 'source_nodes') and response.source_nodes:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
sources = []
|
| 73 |
+
for i, node in enumerate(response.source_nodes[:3]): # Show top 3 sources
|
| 74 |
+
if hasattr(node, 'metadata') and 'file_name' in node.metadata:
|
| 75 |
+
sources.append(f"π {node.metadata['file_name']}")
|
| 76 |
+
else:
|
| 77 |
+
sources.append(f"π Source {i+1}")
|
| 78 |
+
|
| 79 |
+
if sources:
|
| 80 |
+
response_text += f"\n\n**Sources:**\n" + "\n".join(sources)
|
| 81 |
+
|
| 82 |
+
return response_text
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
return f"β Error processing your question: {str(e)}"
|
|
|
|
| 86 |
|
| 87 |
+
# Initialize the chatbot
|
| 88 |
+
chatbot = DocumentChatbot()
|
|
|
|
| 89 |
|
| 90 |
+
# Create Gradio interface
|
| 91 |
+
def create_interface():
|
| 92 |
+
with gr.Blocks(
|
| 93 |
+
title="Chat with Your Documents",
|
| 94 |
+
theme=gr.themes.Soft(),
|
| 95 |
+
css="""
|
| 96 |
+
.gradio-container {
|
| 97 |
+
max-width: 800px !important;
|
| 98 |
+
margin: auto !important;
|
| 99 |
+
}
|
| 100 |
+
"""
|
| 101 |
+
) as iface:
|
| 102 |
+
|
| 103 |
+
gr.Markdown(
|
| 104 |
+
"""
|
| 105 |
+
# π Chat with Your Documents
|
| 106 |
+
|
| 107 |
+
Ask questions about your uploaded documents. The AI will search through your document index and provide relevant answers with sources.
|
| 108 |
+
|
| 109 |
+
**Example questions:**
|
| 110 |
+
- "What are the main topics covered in the documents?"
|
| 111 |
+
- "Summarize the key findings"
|
| 112 |
+
- "What does the document say about [specific topic]?"
|
| 113 |
+
"""
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Chat interface
|
| 117 |
+
chatbot_ui = gr.Chatbot(
|
| 118 |
+
height=400,
|
| 119 |
+
placeholder="Your conversation will appear here...",
|
| 120 |
+
show_copy_button=True
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
msg = gr.Textbox(
|
| 124 |
+
placeholder="Type your question here...",
|
| 125 |
+
label="Your Question",
|
| 126 |
+
lines=2
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Button row
|
| 130 |
+
with gr.Row():
|
| 131 |
+
submit_btn = gr.Button("Send", variant="primary", scale=2)
|
| 132 |
+
clear_btn = gr.Button("Clear Chat", scale=1)
|
| 133 |
+
|
| 134 |
+
# Example questions
|
| 135 |
+
gr.Examples(
|
| 136 |
+
examples=[
|
| 137 |
+
["What are the main topics discussed in the documents?"],
|
| 138 |
+
["Can you provide a summary of the key points?"],
|
| 139 |
+
["What are the most important findings?"],
|
| 140 |
+
["Tell me about the methodology used"],
|
| 141 |
+
["What conclusions were drawn?"]
|
| 142 |
+
],
|
| 143 |
+
inputs=msg,
|
| 144 |
+
label="Example Questions"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# Event handlers
|
| 148 |
+
def respond(message, chat_history):
|
| 149 |
+
if not message.strip():
|
| 150 |
+
return chat_history, ""
|
| 151 |
+
|
| 152 |
+
# Add user message to history
|
| 153 |
+
chat_history.append([message, None])
|
| 154 |
+
|
| 155 |
+
# Get bot response
|
| 156 |
+
bot_response = chatbot.chat(message, chat_history)
|
| 157 |
+
|
| 158 |
+
# Update history with bot response
|
| 159 |
+
chat_history[-1][1] = bot_response
|
| 160 |
+
|
| 161 |
+
return chat_history, ""
|
| 162 |
+
|
| 163 |
+
def clear_chat():
|
| 164 |
+
return [], ""
|
| 165 |
+
|
| 166 |
+
# Wire up events
|
| 167 |
+
submit_btn.click(
|
| 168 |
+
respond,
|
| 169 |
+
inputs=[msg, chatbot_ui],
|
| 170 |
+
outputs=[chatbot_ui, msg]
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
msg.submit(
|
| 174 |
+
respond,
|
| 175 |
+
inputs=[msg, chatbot_ui],
|
| 176 |
+
outputs=[chatbot_ui, msg]
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
clear_btn.click(clear_chat, outputs=[chatbot_ui, msg])
|
| 180 |
+
|
| 181 |
+
# Status information
|
| 182 |
+
with gr.Accordion("βΉοΈ System Information", open=False):
|
| 183 |
+
status_text = "β
Connected to LlamaCloud index" if chatbot.query_engine else "β Failed to connect to index"
|
| 184 |
+
gr.Markdown(f"**Status:** {status_text}")
|
| 185 |
+
|
| 186 |
+
if chatbot.index:
|
| 187 |
+
gr.Markdown("**Configuration:** Using LlamaCloud with OpenAI GPT-3.5-turbo")
|
| 188 |
+
else:
|
| 189 |
+
gr.Markdown("**Error:** Please check your environment variables and LlamaCloud configuration")
|
| 190 |
+
|
| 191 |
+
return iface
|
| 192 |
|
| 193 |
+
# Launch the app
|
| 194 |
+
if __name__ == "__main__":
|
| 195 |
+
# Check required environment variables
|
| 196 |
+
required_vars = ["LLAMA_CLOUD_API_KEY", "LLAMA_CLOUD_INDEX_ID", "OPENAI_API_KEY"]
|
| 197 |
+
missing_vars = [var for var in required_vars if not os.getenv(var)]
|
| 198 |
+
|
| 199 |
+
if missing_vars:
|
| 200 |
+
print(f"β Missing required environment variables: {', '.join(missing_vars)}")
|
| 201 |
+
print("Please set them in your Hugging Face Space secrets or .env file")
|
| 202 |
+
|
| 203 |
+
# Create and launch interface
|
| 204 |
+
demo = create_interface()
|
| 205 |
+
demo.launch(
|
| 206 |
+
server_name="0.0.0.0",
|
| 207 |
+
server_port=7860,
|
| 208 |
+
share=False
|
| 209 |
+
)
|