jsantangelo commited on
Commit
97b8dae
·
verified ·
1 Parent(s): 14a4d0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -183
app.py CHANGED
@@ -1,184 +1,121 @@
1
  import os
2
- import gradio as gr
3
- from llama_cloud import LlamaCloud
4
- from dotenv import load_dotenv
5
-
6
- # Load environment variables
7
- load_dotenv()
8
-
9
- # Initialize LlamaCloud client
10
- client = LlamaCloud(
11
- api_key=os.getenv("LLAMA_CLOUD_API_KEY")
12
- )
13
-
14
- class DocumentChatbot:
15
- def __init__(self):
16
- self.pipeline = None
17
- self.load_pipeline()
18
-
19
- def load_pipeline(self):
20
- """Load the pipeline from LlamaCloud"""
21
- try:
22
- # Replace with your actual pipeline ID from LlamaCloud
23
- pipeline_id = os.getenv("LLAMA_CLOUD_PIPELINE_ID")
24
-
25
- if not pipeline_id:
26
- raise ValueError("LLAMA_CLOUD_PIPELINE_ID not found in environment variables")
27
-
28
- # Get the pipeline from LlamaCloud
29
- self.pipeline = client.pipelines.get(pipeline_id)
30
-
31
- print("✅ Successfully connected to LlamaCloud pipeline")
32
-
33
- except Exception as e:
34
- print(f"❌ Error loading pipeline: {str(e)}")
35
- self.pipeline = None
36
-
37
- def chat(self, message, history):
38
- """Process chat message using LlamaCloud pipeline directly"""
39
- if not self.pipeline:
40
- return "❌ Error: Could not connect to LlamaCloud pipeline. Please check your configuration."
41
-
42
- try:
43
- # Query using LlamaCloud pipeline directly
44
- response = client.pipelines.run(
45
- pipeline_id=self.pipeline.id,
46
- input={"query": message}
47
- )
48
-
49
- # Extract the response text
50
- if hasattr(response, 'output') and 'response' in response.output:
51
- response_text = response.output['response']
52
- elif hasattr(response, 'response'):
53
- response_text = str(response.response)
54
- else:
55
- response_text = str(response)
56
-
57
- return response_text
58
-
59
- except Exception as e:
60
- return f"❌ Error processing your question: {str(e)}"
61
-
62
- # Initialize the chatbot
63
- chatbot = DocumentChatbot()
64
-
65
- # Create Gradio interface
66
- def create_interface():
67
- with gr.Blocks(
68
- title="Chat with Your Documents",
69
- theme=gr.themes.Soft(),
70
- css="""
71
- .gradio-container {
72
- max-width: 800px !important;
73
- margin: auto !important;
74
- }
75
- """
76
- ) as iface:
77
-
78
- gr.Markdown(
79
- """
80
- # 📚 Chat with Your Documents
81
-
82
- Ask questions about your uploaded documents. The AI will search through your document index and provide relevant answers with sources.
83
-
84
- **Example questions:**
85
- - "What are the main topics covered in the documents?"
86
- - "Summarize the key findings"
87
- - "What does the document say about [specific topic]?"
88
- """
89
- )
90
-
91
- # Chat interface
92
- chatbot_ui = gr.Chatbot(
93
- height=400,
94
- placeholder="Your conversation will appear here...",
95
- show_copy_button=True
96
- )
97
-
98
- msg = gr.Textbox(
99
- placeholder="Type your question here...",
100
- label="Your Question",
101
- lines=2
102
- )
103
-
104
- # Button row
105
- with gr.Row():
106
- submit_btn = gr.Button("Send", variant="primary", scale=2)
107
- clear_btn = gr.Button("Clear Chat", scale=1)
108
-
109
- # Example questions
110
- gr.Examples(
111
- examples=[
112
- ["What are the main topics discussed in the documents?"],
113
- ["Can you provide a summary of the key points?"],
114
- ["What are the most important findings?"],
115
- ["Tell me about the methodology used"],
116
- ["What conclusions were drawn?"]
117
- ],
118
- inputs=msg,
119
- label="Example Questions"
120
- )
121
-
122
- # Event handlers
123
- def respond(message, chat_history):
124
- if not message.strip():
125
- return chat_history, ""
126
-
127
- # Add user message to history
128
- chat_history.append([message, None])
129
-
130
- # Get bot response
131
- bot_response = chatbot.chat(message, chat_history)
132
-
133
- # Update history with bot response
134
- chat_history[-1][1] = bot_response
135
-
136
- return chat_history, ""
137
-
138
- def clear_chat():
139
- return [], ""
140
-
141
- # Wire up events
142
- submit_btn.click(
143
- respond,
144
- inputs=[msg, chatbot_ui],
145
- outputs=[chatbot_ui, msg]
146
- )
147
-
148
- msg.submit(
149
- respond,
150
- inputs=[msg, chatbot_ui],
151
- outputs=[chatbot_ui, msg]
152
- )
153
-
154
- clear_btn.click(clear_chat, outputs=[chatbot_ui, msg])
155
-
156
- # Status information
157
- with gr.Accordion("ℹ️ System Information", open=False):
158
- status_text = "✅ Connected to LlamaCloud pipeline" if chatbot.pipeline else "❌ Failed to connect to pipeline"
159
- gr.Markdown(f"**Status:** {status_text}")
160
-
161
- if chatbot.pipeline:
162
- gr.Markdown("**Configuration:** Using LlamaCloud pipeline directly (no external LLM needed)")
163
- else:
164
- gr.Markdown("**Error:** Please check your environment variables and LlamaCloud configuration")
165
-
166
- return iface
167
-
168
- # Launch the app
169
- if __name__ == "__main__":
170
- # Check required environment variables
171
- required_vars = ["LLAMA_CLOUD_API_KEY", "LLAMA_CLOUD_PIPELINE_ID"]
172
- missing_vars = [var for var in required_vars if not os.getenv(var)]
173
-
174
- if missing_vars:
175
- print(f"❌ Missing required environment variables: {', '.join(missing_vars)}")
176
- print("Please set them in your Hugging Face Space secrets or .env file")
177
-
178
- # Create and launch interface
179
- demo = create_interface()
180
- demo.launch(
181
- server_name="0.0.0.0",
182
- server_port=7860,
183
- share=False
184
- )
 
1
  import os
2
+ import streamlit as st
3
+
4
+ # Official LlamaIndex SDK
5
+ from llama_index.indices.managed.llama_cloud import LlamaCloudIndex
6
+
7
+ # ---------- Config & Secrets ----------
8
+ LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
9
+ DEFAULT_PIPELINE_ID = os.environ.get("PIPELINE_ID", "")
10
+
11
+ st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬")
12
+ st.title("💬 Chat with Your Documents (LlamaIndex SDK)")
13
+
14
+ if not LLAMA_KEY:
15
+ st.error("Missing LLAMA_CLOUD_API_KEY (add it in Space Settings → Secrets).")
16
+ st.stop()
17
+
18
+ # ---------- Sidebar ----------
19
+ with st.sidebar:
20
+ st.subheader("Settings")
21
+ pipeline_id = st.text_input(
22
+ "Pipeline (Index) ID",
23
+ value=DEFAULT_PIPELINE_ID,
24
+ help="Copy the UUID from your pipeline URL in cloud.llamaindex.ai",
25
+ )
26
+ top_k = st.slider("Top-K retrieval", 1, 10, 4)
27
+ st.caption(
28
+ f"API key: {'✅' if bool(LLAMA_KEY) else '❌'} · "
29
+ f"Pipeline ID: {'✅' if bool(pipeline_id) else '❌'}"
30
+ )
31
+ if st.button("Clear conversation"):
32
+ st.session_state.pop("chat_engine_keyed", None)
33
+ st.session_state.pop("messages", None)
34
+ st.rerun()
35
+
36
+ # ---------- Cached loader ----------
37
+ @st.cache_resource(show_spinner=True)
38
+ def get_chat_engine(index_id: str, api_key: str, k: int):
39
+ """
40
+ Create a LlamaCloudIndex and return its chat engine.
41
+ Cached by (index_id, api_key, k) for this Streamlit session.
42
+ """
43
+ # Build the managed index wrapper (no raw HTTP)
44
+ index = LlamaCloudIndex(index_id=index_id, api_key=api_key)
45
+ # Let the SDK handle retrieval+generation; you can pass knobs here if desired
46
+ chat_engine = index.as_chat_engine(similarity_top_k=k)
47
+ return chat_engine
48
+
49
+ # Ensure we have a pipeline to talk to
50
+ if not pipeline_id:
51
+ st.info("Enter your Pipeline (Index) ID in the sidebar to begin.")
52
+ st.stop()
53
+
54
+ # Instantiate chat engine (cached)
55
+ try:
56
+ chat_engine = get_chat_engine(pipeline_id, LLAMA_KEY, top_k)
57
+ except Exception as e:
58
+ st.error(f"Failed to initialize chat engine. Check Pipeline ID and API key.\n\n{e}")
59
+ st.stop()
60
+
61
+ # ---------- Chat History ----------
62
+ if "messages" not in st.session_state:
63
+ st.session_state.messages = []
64
+
65
+ # Render previous turns
66
+ for m in st.session_state.messages:
67
+ with st.chat_message(m["role"]):
68
+ st.markdown(m["content"])
69
+
70
+ # ---------- Ask ----------
71
+ q = st.chat_input("Ask a question about your documents…")
72
+
73
+ if q:
74
+ # Show user turn
75
+ st.session_state.messages.append({"role": "user", "content": q})
76
+ with st.chat_message("user"):
77
+ st.markdown(q)
78
+
79
+ # Assistant turn
80
+ with st.chat_message("assistant"):
81
+ with st.spinner("Thinking…"):
82
+ try:
83
+ # This handles retrieval + generation server-side using your pipeline’s config
84
+ resp = chat_engine.chat(q)
85
+
86
+ # Final text
87
+ answer = getattr(resp, "response", None) or "No answer."
88
+ st.markdown(answer)
89
+
90
+ # Sources (resp.source_nodes is a list of NodeWithScore)
91
+ source_nodes = getattr(resp, "source_nodes", []) or []
92
+ if source_nodes:
93
+ st.markdown("#### 📚 Sources")
94
+ for i, sn in enumerate(source_nodes, start=1):
95
+ try:
96
+ text = sn.get_text() if hasattr(sn, "get_text") else (sn.text if hasattr(sn, "text") else "")
97
+ meta = getattr(sn, "metadata", {}) or {}
98
+ except Exception:
99
+ # Fallback if object shape differs
100
+ text = ""
101
+ meta = {}
102
+ title = (
103
+ meta.get("file_name")
104
+ or meta.get("source")
105
+ or meta.get("file_path")
106
+ or meta.get("filename")
107
+ or f"Source {i}"
108
+ )
109
+ page = meta.get("page") or meta.get("page_number") or meta.get("page_label")
110
+ header = f"[{i}] {title}" + (f" • p.{page}" if page else "")
111
+ with st.expander(header):
112
+ snippet = (text or "").strip()
113
+ st.write(snippet[:1200] + ("…" if len(snippet) > 1200 else ""))
114
+ if meta:
115
+ st.code(meta, language="json")
116
+
117
+ # Save assistant turn to local chat history (for the UI only)
118
+ st.session_state.messages.append({"role": "assistant", "content": answer})
119
+
120
+ except Exception as e:
121
+ st.error(f"Chat failed: {e}")