jsantangelo commited on
Commit
3cb7919
Β·
verified Β·
1 Parent(s): 67c96de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -90
app.py CHANGED
@@ -1,99 +1,209 @@
1
  import os
2
- import streamlit as st
3
- import requests
4
- import json
5
- import re
 
 
6
 
7
- # Load secrets
8
- LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
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
- st.set_page_config(page_title="LlamaIndex Chat", page_icon="πŸ’¬")
13
- st.title("πŸ’¬ Chat with Your Documents")
 
 
14
 
15
- # Check secrets
16
- if not LLAMA_KEY or not PIPELINE_ID:
17
- st.error("Missing API key or pipeline ID. Set these in your Space's Secrets tab.")
18
- st.stop()
 
 
19
 
20
- # Set up history
21
- if "messages" not in st.session_state:
22
- st.session_state.messages = []
23
-
24
- # Show prior messages
25
- for msg in st.session_state.messages:
26
- with st.chat_message(msg["role"]):
27
- st.markdown(msg["content"])
28
-
29
- # Helper to display sources
30
- def render_sources(sources: list[dict]):
31
- if not sources:
32
- return
33
- st.markdown("#### πŸ“š Sources")
34
- for i, src in enumerate(sources, 1):
35
- meta = src.get("metadata", {}) or {}
36
- title = meta.get("file_name") or meta.get("source") or meta.get("file_path") or f"Source {i}"
37
- content = src.get("text") or src.get("content") or ""
38
- with st.expander(f"[{i}] {title}"):
39
- st.write(content.strip()[:1000] + ("..." if len(content.strip()) > 1000 else ""))
40
-
41
- # Chat input
42
- question = st.chat_input("Ask a question...")
43
-
44
- if question:
45
- st.session_state.messages.append({"role": "user", "content": question})
46
- with st.chat_message("user"):
47
- st.markdown(question)
48
-
49
- with st.chat_message("assistant"):
50
- with st.spinner("Thinking..."):
51
- try:
52
- # Send to LlamaIndex Cloud
53
- r = requests.post(
54
- API_URL,
55
- headers={
56
- "Authorization": f"Bearer {LLAMA_KEY}",
57
- "Content-Type": "application/json",
58
- "Accept": "application/json",
59
- },
60
- json={
61
- "messages": [{"role": "user", "content": question}],
62
- "stream": False,
63
- },
64
- timeout=60
65
- )
66
-
67
- r.raise_for_status()
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
-
74
- # Extract answer + sources
75
- answer = None
76
  sources = []
77
- for fr in frames:
78
- if fr.get("type") in ("final_message", "assistant_message"):
79
- answer = (
80
- fr.get("data", {}).get("message", {}).get("content") or
81
- fr.get("message") or
82
- fr.get("answer")
83
- )
84
- if fr.get("type") == "sources":
85
- nodes = fr.get("data", {}).get("nodes", [])
86
- for n in nodes:
87
- sources.append({
88
- "text": n.get("text") or n.get("content"),
89
- "metadata": n.get("metadata") or {}
90
- })
91
 
92
- answer = answer or "No answer."
93
- st.markdown(answer)
94
- render_sources(sources)
95
 
96
- st.session_state.messages.append({"role": "assistant", "content": answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- except Exception as e:
99
- st.error(f"Chat failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import gradio as gr
3
+ 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
+ )