Crackershoot commited on
Commit
a26d789
Β·
verified Β·
1 Parent(s): a303f94

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +319 -136
app.py CHANGED
@@ -1,211 +1,394 @@
 
1
  import logging
2
  import sys
3
  import os
 
 
4
  from agno.agent import Agent
5
  from agno.models.openai import OpenAIChat
6
  from agno.knowledge.embedder.openai import OpenAIEmbedder
7
  from agno.tools.duckduckgo import DuckDuckGoTools
8
  from agno.knowledge.knowledge import Knowledge
9
  from agno.vectordb.lancedb import LanceDb, SearchType
 
 
10
  import gradio as gr
11
- import fitz
12
- from PIL import Image
13
- import io
14
- import requests
15
- import re
16
-
 
 
 
17
  logging.basicConfig(stream=sys.stdout, level=logging.INFO)
 
18
  logger = logging.getLogger(__name__)
19
-
 
20
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
 
21
  if not OPENAI_API_KEY:
22
  raise ValueError("Missing OPENAI_API_KEY")
23
-
24
- # ===================== KNOWLEDGE BASE =====================
25
  knowledge = Knowledge(
 
26
  vector_db=LanceDb(
27
- uri="tmp/lancedb",
28
- table_name="pdf_documents",
29
- search_type=SearchType.vector,
 
30
  embedder=OpenAIEmbedder(id="text-embedding-3-small"),
31
  )
32
  )
33
-
 
34
  pdf_urls = [
35
  "https://media.datacamp.com/cms/working-with-hugging-face.pdf",
36
  "https://media.datacamp.com/cms/ai-agents-cheat-sheet.pdf",
37
  "https://media.datacamp.com/cms/introduction-to-sql-with-ai-1.pdf",
38
  "https://media.datacamp.com/legacy/image/upload/v1719844709/Marketing/Blog/Azure_CLI_Cheat_Sheet.pdf"
39
  ]
40
-
 
41
  def download_if_needed(url, filename):
 
42
  if not os.path.exists(filename):
 
 
43
  response = requests.get(url)
 
44
  with open(filename, "wb") as f:
 
45
  f.write(response.content)
46
-
 
 
 
47
  os.makedirs("pdf_cache", exist_ok=True)
48
-
 
49
  def add_pdfs_to_knowledge():
 
 
50
  contents_to_add = []
 
 
51
  for i, url in enumerate(pdf_urls):
 
52
  filename = f"pdf_cache/file_{i}.pdf"
53
- download_if_needed(url, filename)
54
- contents_to_add.append({"path": filename, "metadata": {"source": url}})
55
-
56
- if hasattr(knowledge, 'add_contents'):
57
- knowledge.add_contents(contents_to_add)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  else:
59
- for item in contents_to_add:
60
- knowledge.add_content(**item)
61
-
 
62
  add_pdfs_to_knowledge()
63
-
64
- # ===================== AGENT =====================
65
  agent = Agent(
 
66
  model=OpenAIChat(id="gpt-4.1-mini", temperature=0.2),
 
67
  description="You are Dox a data expert!",
68
- instructions="""(UNCHANGED PROMPT)""",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  knowledge=knowledge,
 
70
  add_datetime_to_context=True,
 
71
  add_location_to_context=True,
 
72
  search_knowledge=True,
 
73
  tools=[DuckDuckGoTools()],
 
74
  markdown=True
75
  )
76
-
 
77
  logger.info("🟒 Agent initialized successfully!")
78
-
79
- # ===================== CORE FUNCTIONS =====================
80
  def ask_agent(question):
81
- try:
82
- response = agent.run(question, use_knowledge=True)
83
- full_content = response.get_content_as_string()
84
-
85
- match = re.search(r'https?://[^\s]+\.pdf', full_content, re.IGNORECASE)
86
- link = match.group(0) if match else None
87
-
88
- # Add suggestions
89
- full_content += "\n\n---\n**πŸ” Try asking:**\n- Give me a real example\n- Explain step by step\n- Compare with alternatives"
90
-
91
- return full_content, link
92
- except Exception as e:
93
- logger.error(str(e))
94
- return "❌ Something went wrong. Please try again.", None
95
-
96
-
 
 
97
  def download_pdf_from_url(url):
 
98
  response = requests.get(url, timeout=30)
 
99
  response.raise_for_status()
 
100
  return response.content
101
-
102
-
 
 
 
 
 
 
 
 
103
  def display_pdf(pdf_url):
 
104
  if not pdf_url:
105
- return gr.update(value=None, visible=False)
106
-
 
 
107
  try:
 
108
  pdf_bytes = download_pdf_from_url(pdf_url)
 
109
  doc = fitz.open(stream=pdf_bytes, filetype="pdf")
 
110
  page = doc[0]
111
- pix = page.get_pixmap(matrix=fitz.Matrix(4, 4))
 
 
 
 
112
  img = Image.open(io.BytesIO(pix.tobytes("png")))
 
113
  doc.close()
114
- return gr.update(value=img, visible=True)
115
- except:
116
- return gr.update(value=None, visible=False)
117
-
118
-
119
- def show_pdf_link(link):
120
- if link:
121
- return f"[πŸ“₯ Open Full PDF]({link})"
122
- return ""
123
-
124
-
125
- # ===================== UI =====================
126
- theme = gr.themes.Ocean()
127
-
128
- with gr.Blocks(title="# πŸ€– Dox the Data Professional's Advisor πŸ€–", theme=theme) as demo:
129
-
 
 
 
 
 
 
 
 
 
130
  gr.Markdown("# πŸ€– Dox the Data Professional's Advisor πŸ€–")
131
- gr.Markdown("🟒 Mode: Knowledge Base + Web Enabled")
132
-
 
133
  with gr.Row():
 
134
  with gr.Column(scale=3):
135
-
136
- chatbot = gr.Chatbot(height=450)
137
-
 
 
138
  question = gr.Textbox(
139
- placeholder="Ask about SQL, AI agents, Hugging Face...",
140
- lines=1,
141
- autofocus=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  )
143
-
144
- with gr.Row():
145
- ask_btn = gr.Button("Submit πŸ“€", variant="primary")
146
- clear_btn = gr.Button("🧹 Clear")
147
-
148
- # Feedback
149
- with gr.Row():
150
- thumbs_up = gr.Button("πŸ‘")
151
- thumbs_down = gr.Button("πŸ‘Ž")
152
-
153
- feedback_box = gr.Textbox(visible=False, placeholder="Tell us what went wrong...")
154
- submit_feedback_btn = gr.Button("Submit Feedback", visible=False)
155
- feedback_status = gr.Markdown()
156
-
157
  with gr.Column(scale=2):
158
- output_image = gr.Image(visible=False)
159
- pdf_link_btn = gr.Markdown()
160
-
161
- link_state = gr.State()
162
-
163
- # ===================== CHAT LOGIC =====================
 
 
 
 
 
 
164
  def chat_ui(user_message, chat_history):
 
165
  if chat_history is None:
166
  chat_history = []
167
-
168
- chat_history.append({"role": "user", "content": user_message})
169
- chat_history.append({"role": "assistant", "content": "πŸ€” Thinking...\n⏳ Searching knowledge base..."})
170
-
171
- yield chat_history, None, gr.update(value=None, visible=False), ""
172
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  response_text, link = ask_agent(user_message)
174
-
175
- chat_history[-1] = {"role": "assistant", "content": response_text}
176
-
177
- yield chat_history, link, gr.update(value=None, visible=False), ""
178
-
 
 
 
 
 
 
 
 
 
 
 
179
  def submit_chain():
180
- return chat_ui, [question, chatbot], [chatbot, link_state, output_image, question]
181
-
182
- ask_btn.click(*submit_chain())\
183
- .then(display_pdf, link_state, output_image)\
184
- .then(show_pdf_link, link_state, pdf_link_btn)
185
-
186
- question.submit(*submit_chain())\
187
- .then(display_pdf, link_state, output_image)\
188
- .then(show_pdf_link, link_state, pdf_link_btn)
189
-
190
- # ===================== CLEAR =====================
191
- def clear_chat():
192
- return [], None, gr.update(value=None, visible=False)
193
-
194
- clear_btn.click(clear_chat, outputs=[chatbot, link_state, output_image])
195
-
196
- # ===================== FEEDBACK =====================
197
- def show_feedback_box():
198
- return gr.update(visible=True), gr.update(visible=True)
199
-
200
- thumbs_down.click(show_feedback_box, outputs=[feedback_box, submit_feedback_btn])
201
-
202
- def handle_feedback(text):
203
- logger.info(f"Feedback: {text}")
204
- return "βœ… Feedback submitted!"
205
-
206
- submit_feedback_btn.click(handle_feedback, feedback_box, feedback_status)
207
-
208
-
209
- # ===================== RUN =====================
 
 
 
 
 
 
 
 
 
210
  if __name__ == "__main__":
 
211
  demo.launch()
 
1
+ # Import necessary libraries for logging, system operations, and file handling.
2
  import logging
3
  import sys
4
  import os
5
+
6
+ # Import core components from the 'agno' library for building the agent.
7
  from agno.agent import Agent
8
  from agno.models.openai import OpenAIChat
9
  from agno.knowledge.embedder.openai import OpenAIEmbedder
10
  from agno.tools.duckduckgo import DuckDuckGoTools
11
  from agno.knowledge.knowledge import Knowledge
12
  from agno.vectordb.lancedb import LanceDb, SearchType
13
+
14
+ # Import Gradio for creating the web user interface.
15
  import gradio as gr
16
+
17
+ # Import libraries for handling PDFs and images.
18
+ import fitz # PyMuPDF, used for PDF processing.
19
+ from PIL import Image # Pillow library for image manipulation.
20
+ import io # Used to handle in-memory binary streams.
21
+ import requests # For making HTTP requests to download files.
22
+ import re # Regular expressions for searching text patterns.
23
+
24
+ # Configure basic logging to output messages to the console.
25
  logging.basicConfig(stream=sys.stdout, level=logging.INFO)
26
+ # Get a logger instance for this script.
27
  logger = logging.getLogger(__name__)
28
+
29
+ # Retrieve the OpenAI API key from environment variables.
30
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
31
+ # If the API key is not found, raise an error.
32
  if not OPENAI_API_KEY:
33
  raise ValueError("Missing OPENAI_API_KEY")
34
+
35
+ # Initialize the Knowledge Base for the agent.
36
  knowledge = Knowledge(
37
+ # Use LanceDB as the vector database to store and search document embeddings.
38
  vector_db=LanceDb(
39
+ uri="tmp/lancedb", # Directory to store the database.
40
+ table_name="pdf_documents", # Name of the table within the database.
41
+ search_type=SearchType.vector, # Use vector search for finding relevant documents.
42
+ # Use OpenAI's embedding model to convert text into numerical vectors.
43
  embedder=OpenAIEmbedder(id="text-embedding-3-small"),
44
  )
45
  )
46
+
47
+ # A list of URLs pointing to PDF documents that will be added to the knowledge base.
48
  pdf_urls = [
49
  "https://media.datacamp.com/cms/working-with-hugging-face.pdf",
50
  "https://media.datacamp.com/cms/ai-agents-cheat-sheet.pdf",
51
  "https://media.datacamp.com/cms/introduction-to-sql-with-ai-1.pdf",
52
  "https://media.datacamp.com/legacy/image/upload/v1719844709/Marketing/Blog/Azure_CLI_Cheat_Sheet.pdf"
53
  ]
54
+
55
+ # Defines a function to download a file from a URL if it doesn't already exist locally.
56
  def download_if_needed(url, filename):
57
+ # Check if the file path does not exist.
58
  if not os.path.exists(filename):
59
+ logger.info(f"Downloading {url}...")
60
+ # Send an HTTP GET request to the URL.
61
  response = requests.get(url)
62
+ # Open the local file in write-binary mode.
63
  with open(filename, "wb") as f:
64
+ # Write the content of the response to the file.
65
  f.write(response.content)
66
+ logger.info(f"Downloaded {filename} ({len(response.content)} bytes)")
67
+
68
+ # Create a directory named 'pdf_cache' to store downloaded PDF files.
69
+ # 'exist_ok=True' prevents an error if the directory already exists.
70
  os.makedirs("pdf_cache", exist_ok=True)
71
+
72
+ # Defines a function to add the specified PDFs to the agent's knowledge base.
73
  def add_pdfs_to_knowledge():
74
+ """Add PDFs to knowledge base using the correct method for the installed agno version"""
75
+ # Create an empty list to hold information about the content to be added.
76
  contents_to_add = []
77
+
78
+ # Loop through the list of PDF URLs with their index.
79
  for i, url in enumerate(pdf_urls):
80
+ # Define a local filename for the cached PDF.
81
  filename = f"pdf_cache/file_{i}.pdf"
82
+ try:
83
+ # Download the PDF if it's not already in the cache.
84
+ download_if_needed(url, filename)
85
+ # Prepare a dictionary with the file path and metadata (source URL).
86
+ contents_to_add.append({
87
+ "path": filename,
88
+ "metadata": {"source": url}
89
+ })
90
+ logger.info(f"Prepared PDF {i+1}: {url}")
91
+ except Exception as e:
92
+ # Log an error if the PDF preparation fails.
93
+ logger.error(f"Failed to prepare PDF {i+1}: {str(e)}")
94
+
95
+ # Proceed only if there are PDFs to add.
96
+ if contents_to_add:
97
+ try:
98
+ # This block checks for the correct method to add documents based on the 'agno' library version.
99
+ # Check if the 'add_contents' method (for batch processing) exists.
100
+ if hasattr(knowledge, 'add_contents'):
101
+ knowledge.add_contents(contents_to_add)
102
+ logger.info(f"βœ… Successfully added {len(contents_to_add)} PDFs using add_contents")
103
+ # Else, check if the 'add_content' method (for single item processing) exists.
104
+ elif hasattr(knowledge, 'add_content'):
105
+ for item in contents_to_add:
106
+ knowledge.add_content(**item)
107
+ logger.info(f"βœ… Successfully added {len(contents_to_add)} PDFs using add_content")
108
+ # As a fallback for older versions, manually read and insert the documents.
109
+ else:
110
+ from agno.document.reader.pdf_reader import PDFReader
111
+ reader = PDFReader()
112
+ all_docs = []
113
+ for item in contents_to_add:
114
+ docs = reader.read(item["path"])
115
+ for doc in docs:
116
+ doc.metadata = item["metadata"]
117
+ all_docs.append(doc)
118
+ knowledge.vector_db.insert(documents=all_docs)
119
+ logger.info(f"βœ… Successfully added {len(all_docs)} document chunks from {len(contents_to_add)} PDFs")
120
+ except Exception as e:
121
+ # Log and re-raise any exception that occurs during the addition process.
122
+ logger.error(f"Failed to add PDFs: {str(e)}")
123
+ raise
124
  else:
125
+ # Warn if no PDFs were prepared.
126
+ logger.warning("No PDFs were prepared to add")
127
+
128
+ # Call the function to load the PDFs into the knowledge base.
129
  add_pdfs_to_knowledge()
130
+
131
+ # Initialize the AI agent with its configuration.
132
  agent = Agent(
133
+ # Set the underlying language model to OpenAI's GPT-4.1-mini with low temperature for more predictable responses.
134
  model=OpenAIChat(id="gpt-4.1-mini", temperature=0.2),
135
+ # Give the agent a name/description.
136
  description="You are Dox a data expert!",
137
+ # Provide detailed instructions (the "system prompt") that govern the agent's behavior.
138
+ instructions="""
139
+ You are a data professional's assistant named Dox.
140
+ Your primary goal is to answer questions about data, programming, cloud computing, AI/ML, and technology topics.
141
+ Here are your operating procedures:
142
+ 1. **Information Gathering Strategy**:
143
+ * **Prioritize Knowledge Base**: First, search your internal knowledge base for the answer.
144
+ * **Supplement with Web Search**: If the knowledge base information is outdated, insufficient, or the question is better suited for current web information, use the DuckDuckGo tool to perform web searches to fill in gaps or find the most up-to-date data.
145
+ * For general technology questions not in your knowledge base, use web search to provide accurate answers.
146
+ * If the question is asking for the "latest" or "most recent" of a data-related topic, always use web search and datetime to context.
147
+ * If the question is NOT data-related, you MUST respond with: "Please ask relevant data questions only." and terminate.
148
+ 2. **Response Length Guidelines**:
149
+ * For basic questions, keep your answer to a maximum of 300 words.
150
+ * For complex questions, extend your answer to a maximum of 500 words.
151
+ 3. **Citation Rules (CRITICAL)**:
152
+ * **Knowledge Base Citation**: For any information sourced from your internal knowledge base, you MUST include a citation on a NEW LINE after the answer, starting with "Source: ", followed by the metadata field 'source' to get the hyperlink.
153
+ * **Web Search Citation**: For any information obtained from the web using the DuckDuckGo tool, you MUST include a citation on a NEW LINE after the answer, starting with "Online Source: ", followed by the full hyperlink.
154
+ * **Final Rule for Citations**: Always end your answers with the appropriate citations, ensuring they are on separate lines as specified. Do NOT mix or combine citation types on a single line.
155
+ * ALWAYS cite with links NOT text like "from internal knowledge base"
156
+ 4. **Accuracy and Non-Hallucination**:
157
+ * Provide factual and relevant answers based ONLY on the information found in your knowledge base or through web searches.
158
+ * NEVER invent or hallucinate information. If an answer cannot be found, state that directly.
159
+ Make sure to follow these instructions precisely.
160
+ """,
161
+ # Link the agent to the knowledge base created earlier.
162
  knowledge=knowledge,
163
+ # Automatically add the current date and time to the agent's context.
164
  add_datetime_to_context=True,
165
+ # Automatically add the user's location to the context (if available).
166
  add_location_to_context=True,
167
+ # Enable the agent to search its knowledge base by default.
168
  search_knowledge=True,
169
+ # Equip the agent with tools, in this case, the ability to search the web using DuckDuckGo.
170
  tools=[DuckDuckGoTools()],
171
+ # Enable markdown formatting in the agent's output.
172
  markdown=True
173
  )
174
+
175
+ # Log a success message indicating the agent is ready.
176
  logger.info("🟒 Agent initialized successfully!")
177
+
178
+ # Defines a function to process a user's question.
179
  def ask_agent(question):
180
+ logger.info(f"Question asked: {question[:100]}...")
181
+ # Run the agent with the user's question, ensuring it uses its knowledge base.
182
+ response = agent.run(question, use_knowledge=True)
183
+ # Get the agent's response as a single string.
184
+ full_content = response.get_content_as_string()
185
+ # Use a regular expression to find the first URL ending in '.pdf' in the response.
186
+ match = re.search(r'https?://[^\s]+\.pdf', full_content, re.IGNORECASE)
187
+ # Extract the link if a match is found, otherwise set it to None.
188
+ link = match.group(0) if match else None
189
+
190
+ if link:
191
+ logger.info(f"PDF link found: {link}")
192
+ else:
193
+ logger.info("πŸ”΄ No PDF link found in response")
194
+ # Return the full text response and the extracted PDF link.
195
+ return full_content, link
196
+
197
+ # Defines a function to download the raw content of a PDF from a URL.
198
  def download_pdf_from_url(url):
199
+ # Make an HTTP GET request with a timeout.
200
  response = requests.get(url, timeout=30)
201
+ # Raise an exception if the request was not successful (e.g., 404 error).
202
  response.raise_for_status()
203
+ # Return the binary content of the PDF.
204
  return response.content
205
+
206
+ # A Gradio helper function to update the UI while a PDF is being prepared for display.
207
+ def prepare_pdf_loading(link):
208
+ # If a link exists, show a "Loading..." message.
209
+ if link:
210
+ return gr.update(value="πŸ“„ Loading PDF preview...", visible=True)
211
+ # Otherwise, hide the message.
212
+ return gr.update(value="", visible=False)
213
+
214
+ # Defines a function to display the first page of a PDF as an image.
215
  def display_pdf(pdf_url):
216
+ # If no URL is provided, hide the image and status components in the UI.
217
  if not pdf_url:
218
+ return (
219
+ gr.update(value=None, visible=False),
220
+ gr.update(value="", visible=False)
221
+ )
222
  try:
223
+ # Download the PDF content from the URL.
224
  pdf_bytes = download_pdf_from_url(pdf_url)
225
+ # Open the PDF from the in-memory bytes.
226
  doc = fitz.open(stream=pdf_bytes, filetype="pdf")
227
+ # Get the first page of the document.
228
  page = doc[0]
229
+ # Create a transformation matrix to render the page at a higher resolution (5x zoom).
230
+ mat = fitz.Matrix(5, 5)
231
+ # Get a pixmap (a raster image) of the page.
232
+ pix = page.get_pixmap(matrix=mat)
233
+ # Convert the pixmap to a PNG image using PIL.
234
  img = Image.open(io.BytesIO(pix.tobytes("png")))
235
+ # Close the PDF document to free up resources.
236
  doc.close()
237
+ # Return the image to be displayed in the UI and hide any status messages.
238
+ return (
239
+ gr.update(value=img, visible=True),
240
+ gr.update(value="", visible=False)
241
+ )
242
+ except Exception as e:
243
+ # If an error occurs, log it and display a failure message in the UI.
244
+ logger.error(f"PDF error: {e}")
245
+ return (
246
+ gr.update(value=None, visible=False),
247
+ gr.update(value="❌ Failed to load PDF", visible=True)
248
+ )
249
+
250
+ # Define a custom theme for the Gradio interface.
251
+ theme = gr.themes.Ocean(
252
+ font=[gr.themes.GoogleFont("Quicksand"), "sans-serif"],
253
+ font_mono=[gr.themes.GoogleFont("Fira Code"), "monospace"],
254
+ )
255
+
256
+ # Create the Gradio interface using `gr.Blocks` for a custom layout.
257
+ with gr.Blocks(
258
+ title="# πŸ€– Dox the Data Professional's Advisor πŸ€–",
259
+ theme=theme
260
+ ) as demo:
261
+ # Add titles and descriptions using Markdown.
262
  gr.Markdown("# πŸ€– Dox the Data Professional's Advisor πŸ€–")
263
+ gr.Markdown("### 🧠 Dox knows about 4 DataCamp cheat sheets: (1️⃣ Hugging Face | 2️⃣ AI Agents | 3️⃣ SQL with AI | 4️⃣ Azure CLI):")
264
+
265
+ # Create a main row for the layout.
266
  with gr.Row():
267
+ # LEFT-SIDE COLUMN: for the chat interface.
268
  with gr.Column(scale=3):
269
+ # The chatbot display window.
270
+ chatbot = gr.Chatbot(label="πŸ’¬ Conversation", elem_classes="chatbot", height=450)
271
+ # A text area for status messages (used for PDF loading status).
272
+ status_text = gr.Markdown("")
273
+ # The textbox where the user types their question.
274
  question = gr.Textbox(
275
+ label="πŸ™‹ Ask Dox a question:",
276
+ placeholder="πŸ€” Type your question here...",
277
+ lines=1
278
+ )
279
+ # The submit button.
280
+ ask_btn = gr.Button("Submit πŸ“€", variant="primary")
281
+ # A section for example questions.
282
+ gr.Markdown("### πŸ’‘ Example Questions")
283
+ gr.Examples(
284
+ examples=[
285
+ "How do you log into Azure using device code authentication?",
286
+ "What are the three main components of an AI agent?",
287
+ "What are the \"core four\" Hugging Face libraries?",
288
+ "What SQL clause is used to filter data after grouping?",
289
+ "How to use \"HAVING\" clause in SQL?",
290
+ "What is the latest GPT model?"
291
+ ],
292
+ inputs=question,
293
  )
294
+ # RIGHT-SIDE COLUMN: for the PDF preview.
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  with gr.Column(scale=2):
296
+ gr.Markdown("### πŸ“„ Referenced PDF Document")
297
+ # A hidden state to store the PDF link found in the agent's response.
298
+ link_state = gr.State()
299
+ # A markdown component to show PDF loading status.
300
+ pdf_status = gr.Markdown(visible=False)
301
+ # An image component to display the PDF preview.
302
+ output_image = gr.Image(
303
+ label="⬇️ Cheat Sheet Preview",
304
+ visible=False
305
+ )
306
+
307
+ # Defines the main chat logic as a generator function for streaming output.
308
  def chat_ui(user_message, chat_history):
309
+ # Initialize chat history if it's the first turn.
310
  if chat_history is None:
311
  chat_history = []
312
+
313
+ # Append the user's message to the chat history.
314
+ chat_history.append({
315
+ "role": "user",
316
+ "content": user_message
317
+ })
318
+
319
+ # Append a temporary "Thinking..." message from the assistant.
320
+ chat_history.append({
321
+ "role": "assistant",
322
+ "content": "πŸ€” Thinking..."
323
+ })
324
+
325
+ # `yield` immediately updates the UI with the user's message and "Thinking...".
326
+ # It also clears the user's input textbox.
327
+ yield (
328
+ chat_history,
329
+ None, # No link yet.
330
+ gr.update(value=None, visible=False), # Hide image preview.
331
+ "" # Clear textbox.
332
+ )
333
+
334
+ # Call the agent to get the actual response and PDF link.
335
  response_text, link = ask_agent(user_message)
336
+
337
+ # Replace the "Thinking..." message with the final response from the agent.
338
+ chat_history[-1] = {
339
+ "role": "assistant",
340
+ "content": response_text
341
+ }
342
+
343
+ # `yield` again to update the UI with the final response.
344
+ yield (
345
+ chat_history,
346
+ link, # Pass the extracted link to the link_state.
347
+ gr.update(value=None, visible=False), # Keep image preview hidden for now.
348
+ "" # Keep textbox clear.
349
+ )
350
+
351
+ # This is a helper function to avoid repeating the event handler chain.
352
  def submit_chain():
353
+ # It specifies that `chat_ui` is the function to run.
354
+ # It maps the `question` textbox and `chatbot` history as inputs.
355
+ # It maps the outputs to `chatbot` history, `link_state`, `output_image`, and clears the `question` textbox.
356
+ return (
357
+ chat_ui,
358
+ [question, chatbot],
359
+ [chatbot, link_state, output_image, question]
360
+ )
361
+
362
+ # Set up the event handler for the "Submit" button click.
363
+ ask_btn.click(
364
+ *submit_chain()
365
+ # `.then()` chains subsequent actions after the first one completes.
366
+ ).then(
367
+ # After chat_ui, call `prepare_pdf_loading` to show the "loading" message.
368
+ prepare_pdf_loading,
369
+ inputs=link_state, # Use the link from chat_ui's output.
370
+ outputs=pdf_status # Update the pdf_status text.
371
+ ).then(
372
+ # Finally, call `display_pdf` to render the PDF page.
373
+ display_pdf,
374
+ inputs=link_state, # Use the same link.
375
+ outputs=[output_image, pdf_status] # Update the image and hide the status text.
376
+ )
377
+
378
+ # Set up the same event handler for when the user presses Enter in the textbox.
379
+ question.submit(
380
+ *submit_chain()
381
+ ).then(
382
+ prepare_pdf_loading,
383
+ inputs=link_state,
384
+ outputs=pdf_status
385
+ ).then(
386
+ display_pdf,
387
+ inputs=link_state,
388
+ outputs=[output_image, pdf_status]
389
+ )
390
+
391
+ # This block ensures the code inside only runs when the script is executed directly.
392
  if __name__ == "__main__":
393
+ # Launch the Gradio web server.
394
  demo.launch()