gurunath93 commited on
Commit
afba6de
Β·
verified Β·
1 Parent(s): b2fff7e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +557 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,559 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import base64
3
+ import io
4
+ import json
5
+ import requests
6
+ import os
7
+
8
+ # --- Configuration ---
9
+ # Read from environment variables with fallback defaults
10
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
11
+ OPENAI_API_BASE_URL = os.environ.get("OPENAI_API_BASE_URL", "https://api.openai.com/v1")
12
+ OPENAI_CHAT_COMPLETIONS_ENDPOINT = f"{OPENAI_API_BASE_URL}/chat/completions"
13
+
14
+ TEXT_MODEL = os.environ.get("TEXT_MODEL", "gpt-3.5-turbo")
15
+
16
+ # MCP Server's direct image query endpoint
17
+ MCP_IMAGE_QUERY_ENDPOINT = os.environ.get("MCP_IMAGE_QUERY_ENDPOINT", "http://localhost:3339/image_query")
18
+
19
+ # --- Tool Definitions for Supervisor Agent's LLM ---
20
+ GENERAL_CHAT_TOOL = {
21
+ "type": "function",
22
+ "function": {
23
+ "name": "general_chat",
24
+ "description": "Engage in general conversation and answer questions that do not require specific document or image analysis.",
25
+ "parameters": {
26
+ "type": "object",
27
+ "properties": {
28
+ "query": {
29
+ "type": "string",
30
+ "description": "The user's query for general conversation."
31
+ }
32
+ },
33
+ "required": ["query"]
34
+ }
35
+ }
36
+ }
37
+
38
+ DOCUMENT_ANALYSIS_TOOL = {
39
+ "type": "function",
40
+ "function": {
41
+ "name": "document_analysis",
42
+ "description": "Analyze and summarize uploaded text documents based on the user's query.",
43
+ "parameters": {
44
+ "type": "object",
45
+ "properties": {
46
+ "query": {
47
+ "type": "string",
48
+ "description": "The query related to the document analysis."
49
+ }
50
+ },
51
+ "required": ["query"]
52
+ }
53
+ }
54
+ }
55
+
56
+ IMAGE_ANALYSIS_TOOL = {
57
+ "type": "function",
58
+ "function": {
59
+ "name": "image_analysis",
60
+ "description": "Process and analyze uploaded images based on the user's query. This tool delegates image processing to an external Model Context Protocol (MCP) that handles vision models.",
61
+ "parameters": {
62
+ "type": "object",
63
+ "properties": {
64
+ "query": {
65
+ "type": "string",
66
+ "description": "The query related to the image analysis, to be sent to the MCP's vision capabilities."
67
+ }
68
+ },
69
+ "required": ["query"]
70
+ }
71
+ }
72
+ }
73
+
74
+ # List of all tools available to the Supervisor Agent's LLM
75
+ SUPERVISOR_TOOLS = [GENERAL_CHAT_TOOL, DOCUMENT_ANALYSIS_TOOL, IMAGE_ANALYSIS_TOOL]
76
+
77
+
78
+ # --- Helper Functions for OpenAI Compatible API Calls ---
79
+
80
+ def call_openai_api(messages, model, tools=None, tool_choice=None, generation_config=None):
81
+ """
82
+ Makes a call to an OpenAI-compatible API with the given messages, supporting tool calls.
83
+ Returns content or tool_calls.
84
+ """
85
+ if not OPENAI_API_KEY:
86
+ st.error("OpenAI Compatible API Key is not set. Please provide it in your environment variables.")
87
+ return None, None
88
+
89
+ headers = {
90
+ "Content-Type": "application/json",
91
+ "Authorization": f"Bearer {OPENAI_API_KEY}"
92
+ }
93
+ payload = {
94
+ "model": model,
95
+ "messages": messages,
96
+ "temperature": 0.7, # Default temperature
97
+ }
98
+ if tools:
99
+ payload["tools"] = tools
100
+ if tool_choice:
101
+ payload["tool_choice"] = tool_choice
102
+ if generation_config:
103
+ payload.update(generation_config)
104
+
105
+ try:
106
+ with st.spinner(f"Agent ({model}) thinking..."):
107
+ response = requests.post(OPENAI_CHAT_COMPLETIONS_ENDPOINT, headers=headers, json=payload)
108
+ response.raise_for_status() # Raise an exception for HTTP errors
109
+ result = response.json()
110
+
111
+ if result and result.get("choices") and result["choices"][0].get("message"):
112
+ message = result["choices"][0]["message"]
113
+ if message.get("content"):
114
+ return message["content"], None
115
+ elif message.get("tool_calls"):
116
+ return None, message["tool_calls"]
117
+ # If the LLM returns an empty message object or no choices/message,
118
+ # return a specific string instead of None to prevent 'None' in UI.
119
+ return "No response from agent.", None
120
+ except requests.exceptions.RequestException as e:
121
+ st.error(f"Error communicating with OpenAI Compatible API: {e}")
122
+ return None, None
123
+ except json.JSONDecodeError:
124
+ st.error("Failed to decode JSON response from OpenAI Compatible API.")
125
+ return None, None
126
+ except Exception as e:
127
+ st.error(f"An unexpected error occurred: {e}")
128
+ return None, None
129
+
130
+ def _call_text_model_for_content(messages, model):
131
+ """
132
+ Internal helper to call the text model for content, without managing chat history.
133
+ Used by tools to get a response.
134
+ """
135
+ content, _ = call_openai_api(messages, model)
136
+ return content
137
+
138
+
139
+ def get_openai_response(user_message, chat_history=None):
140
+ """
141
+ Gets a response from the OpenAI compatible text model for general chat.
142
+ This function specifically handles the 'General Chat Agent' mode.
143
+ """
144
+ if chat_history is None:
145
+ chat_history = []
146
+
147
+ messages = []
148
+ for msg in chat_history[-4:]: # Use last 4 messages for context
149
+ messages.append({"role": msg["role"], "content": msg["content"]})
150
+ messages.append({"role": "user", "content": user_message})
151
+
152
+ # This function is now responsible for getting the content and returning it.
153
+ # The calling context (General Chat Agent mode) will append it to chat_history.
154
+ content = _call_text_model_for_content(messages, TEXT_MODEL)
155
+ return content
156
+
157
+ def get_openai_document_analysis(prompt, document_content):
158
+ """
159
+ Gets document analysis/summarization from the OpenAI compatible text model.
160
+ """
161
+ if not document_content:
162
+ return "Error: Document analysis requested but no document uploaded."
163
+
164
+ full_prompt = f"Analyze the following document content and respond to the query:\n\nDocument:\n{document_content}\n\nQuery: {prompt}"
165
+ messages = [{"role": "user", "content": full_prompt}]
166
+ content = _call_text_model_for_content(messages, TEXT_MODEL)
167
+ return content
168
+
169
+ def call_mcp_image_tool(question_for_image: str, image_data_base64: str):
170
+ if not image_data_base64:
171
+ return "Error: Image processing requested but no image uploaded."
172
+ if not MCP_IMAGE_QUERY_ENDPOINT:
173
+ return "Error: MCP_IMAGE_QUERY_ENDPOINT is not configured in your environment variables."
174
+
175
+ payload = {
176
+ "image_base64": image_data_base64,
177
+ "question": question_for_image
178
+ }
179
+
180
+ headers = {
181
+ "Content-Type": "application/json",
182
+ "Accept": "application/json"
183
+ }
184
+
185
+ try:
186
+ print(f"DEBUG: Value of question_for_image: '{question_for_image}'")
187
+ print(f"DEBUG: Type of question_for_image: {type(question_for_image)}")
188
+ print(f"DEBUG: Length of image_data_base64: {len(image_data_base64) if image_data_base64 else 0}")
189
+ print(f"DEBUG: Type of image_data_base64: {type(image_data_base64)}")
190
+ print(f"DEBUG: Full payload being sent to MCP:\n{json.dumps(payload, indent=2)}")
191
+
192
+ with st.spinner("Delegating to MCP for image processing..."):
193
+ response = requests.post(MCP_IMAGE_QUERY_ENDPOINT, json=payload, headers=headers, timeout=180)
194
+ response.raise_for_status()
195
+
196
+ mcp_result = response.json()
197
+ print(f"Received response from MCP: {json.dumps(mcp_result, indent=2)}")
198
+
199
+ if isinstance(mcp_result, dict) and "result" in mcp_result:
200
+ return mcp_result["result"]
201
+ else:
202
+ return f"Unexpected response format from MCP. Raw response: {mcp_result}"
203
+
204
+ except requests.exceptions.RequestException as e:
205
+ if e.response is not None:
206
+ error_details = e.response.json() if e.response.text else "No response body."
207
+ st.error(f"Error communicating with MCP: {e}. FastAPI validation details: {error_details}")
208
+ print(f"DEBUG: Full FastAPI 422 response text: {e.response.text}")
209
+ else:
210
+ st.error(f"Error communicating with MCP: {e}.")
211
+ return f"Error: Failed to get response from MCP."
212
+ except json.JSONDecodeError:
213
+ st.error(f"Error: Failed to decode JSON response from MCP. Is the MCP server responding with valid JSON? Raw response: {response.text}")
214
+ return f"Error: Invalid JSON response from MCP."
215
+ except Exception as e:
216
+ st.error(f"An unexpected error occurred during MCP delegation: {e}")
217
+ return f"An unexpected error occurred: {e}"
218
+
219
+
220
+ # --- Streamlit App Layout ---
221
+
222
+ st.set_page_config(
223
+ page_title="Shopping Floor Safety Monitor",
224
+ page_icon="πŸ€–",
225
+ layout="wide"
226
+ )
227
+
228
+ st.title("πŸ€– Shopping Floor Safety Monitor")
229
+ st.markdown("""
230
+ **AI-Powered Document and Image Analysis**
231
+
232
+ This application uses a **Supervisor Agent** that intelligently orchestrates specialized agents to analyze documents,
233
+ process images, and provide comprehensive answers to your queries.
234
+ """)
235
+
236
+ # Initialize session state for chat history and uploaded files
237
+ if "chat_history" not in st.session_state:
238
+ st.session_state.chat_history = []
239
+ if "uploaded_doc_content" not in st.session_state:
240
+ st.session_state.uploaded_doc_content = None
241
+ if "uploaded_image_data" not in st.session_state:
242
+ st.session_state.uploaded_image_data = None
243
+ if "uploaded_image_base64" not in st.session_state:
244
+ st.session_state.uploaded_image_base64 = None
245
+ if "input_text_value" not in st.session_state:
246
+ st.session_state.input_text_value = ""
247
+ # Initialize a counter for the input widget key
248
+ if "input_key_counter" not in st.session_state:
249
+ st.session_state.input_key_counter = 0
250
+ # Initialize session state for showing traces
251
+ if "show_traces" not in st.session_state:
252
+ st.session_state.show_traces = False
253
+
254
+
255
+ # --- Callback to clear state when clear conversation button is clicked ---
256
+ def clear_state_on_change():
257
+ st.session_state.chat_history = []
258
+ st.session_state.uploaded_doc_content = None
259
+ st.session_state.uploaded_image_data = None
260
+ st.session_state.uploaded_image_base64 = None
261
+ st.session_state.input_text_value = ""
262
+ st.session_state.input_key_counter += 1 # Increment to force re-creation of text_area
263
+
264
+ # --- Callback for the "Show Traces" toggle ---
265
+ def update_show_traces_state():
266
+ # This function is called when the toggle is clicked.
267
+ # The value of the toggle is automatically updated in st.session_state
268
+ # under the key specified by the 'key' argument of st.toggle.
269
+ # We explicitly update our 'show_traces' state variable based on the toggle's new value.
270
+ st.session_state.show_traces = st.session_state.show_traces_toggle_internal
271
+
272
+
273
+ # --- Sidebar for Agent Architecture and Settings ---
274
+ st.sidebar.header("πŸ€– Multi-Agent System")
275
+
276
+ # Compact Agent Architecture Visualization
277
+ st.sidebar.markdown(f"""
278
+ <div style='background-color: rgba(0, 102, 204, 0.1); padding: 10px; border-radius: 8px; margin-bottom: 15px; border: 1px solid rgba(0, 102, 204, 0.3);'>
279
+ <div style='text-align: center; margin-bottom: 8px;'>
280
+ <strong style='color: #0066cc;'>🎯 Supervisor</strong>
281
+ <div style='font-size: 10px; opacity: 0.7;'>orchestrates ↓</div>
282
+ </div>
283
+ <div style='font-size: 11px; line-height: 1.6;'>
284
+ πŸ’¬ <strong>Chat</strong> β€’ πŸ“„ <strong>Document</strong> β€’ πŸ–ΌοΈ <strong>Image (MCP)</strong>
285
+ </div>
286
+ <div style='margin-top: 8px; padding-top: 8px; border-top: 1px solid rgba(0, 102, 204, 0.2); text-align: center;'>
287
+ <span style='font-size: 10px; opacity: 0.7;'>Model: <strong>{TEXT_MODEL}</strong></span>
288
+ </div>
289
+ </div>
290
+ """, unsafe_allow_html=True)
291
+
292
+ st.sidebar.header("πŸ“€ Upload Your Data")
293
+
294
+ uploaded_document = st.sidebar.file_uploader(
295
+ "πŸ“‹ Text Document",
296
+ type=["txt", "md"],
297
+ key="doc_uploader",
298
+ help="Upload any text document for analysis (.txt or .md)"
299
+ )
300
+
301
+ if uploaded_document is not None:
302
+ try:
303
+ string_data = uploaded_document.read().decode("utf-8")
304
+ st.session_state.uploaded_doc_content = string_data
305
+ st.sidebar.success("βœ… Document uploaded successfully!")
306
+ with st.sidebar.expander("πŸ“– View Document Preview"):
307
+ st.code(string_data[:500] + "..." if len(string_data) > 500 else string_data)
308
+ except Exception as e:
309
+ st.sidebar.error(f"❌ Error reading document: {e}")
310
+ st.session_state.uploaded_doc_content = None
311
+ else:
312
+ st.session_state.uploaded_doc_content = None
313
+
314
+ uploaded_image = st.sidebar.file_uploader(
315
+ "πŸ“Έ Image File",
316
+ type=["jpg", "jpeg", "png"],
317
+ key="image_uploader",
318
+ help="Upload any image for visual analysis"
319
+ )
320
+
321
+ if uploaded_image is not None:
322
+ try:
323
+ image_bytes = uploaded_image.read()
324
+ st.session_state.uploaded_image_data = image_bytes
325
+ st.session_state.uploaded_image_base64 = base64.b64encode(image_bytes).decode("utf-8")
326
+ st.sidebar.success("βœ… Image uploaded successfully!")
327
+ st.sidebar.image(uploaded_image, caption="Uploaded Image", use_container_width=True)
328
+ except Exception as e:
329
+ st.sidebar.error(f"❌ Error reading image: {e}")
330
+ st.session_state.uploaded_image_data = None
331
+ st.session_state.uploaded_image_base64 = None
332
+ else:
333
+ st.session_state.uploaded_image_data = None
334
+ st.session_state.uploaded_image_base64 = None
335
+
336
+ st.sidebar.markdown("---")
337
+ st.sidebar.markdown("""
338
+ <div style='background-color: rgba(33, 150, 243, 0.1); padding: 10px; border-radius: 8px; font-size: 11px; border: 1px solid rgba(33, 150, 243, 0.3);'>
339
+ <strong style='color: inherit;'>ℹ️ How it works:</strong><br/>
340
+ Upload files β†’ Ask question β†’ Get AI analysis
341
+ </div>
342
+ """, unsafe_allow_html=True)
343
+
344
+ # --- Main Chat Interface ---
345
+ st.subheader("πŸ’¬ Analysis Console")
346
+
347
+ # --- Compact status indicator showing uploaded files ---
348
+ status_parts = []
349
+ if st.session_state.uploaded_doc_content:
350
+ status_parts.append("πŸ“„ Document")
351
+ if st.session_state.uploaded_image_base64:
352
+ status_parts.append("πŸ–ΌοΈ Image")
353
+
354
+ if status_parts:
355
+ st.success(f"βœ… Ready: {' β€’ '.join(status_parts)}")
356
+ else:
357
+ st.info("ℹ️ No files uploaded - You can still chat or upload files from the sidebar")
358
+
359
+ st.markdown("---")
360
+
361
+ # Use a form for automatic submission on Enter
362
+ with st.form(key="chat_form"):
363
+ # Set default prompt if input_text_value is empty
364
+ default_value = st.session_state.input_text_value if st.session_state.input_text_value else "Analyze the given image for any safety hazard. If you find any, draft an email to John who is responsible for floor safety. Describe the exact safety issue."
365
+
366
+ user_input_from_widget = st.text_area(
367
+ "✍️ Your Question or Request:",
368
+ key=f"user_input_widget_{st.session_state.input_key_counter}",
369
+ value=default_value,
370
+ height=120,
371
+ placeholder="Ask me anything about your uploaded documents or images, or just chat with me..."
372
+ )
373
+
374
+ col_btn1, col_btn2 = st.columns([0.85, 0.15])
375
+ with col_btn1:
376
+ send_button_clicked = st.form_submit_button("πŸš€ Analyze", use_container_width=True, type="primary")
377
+ with col_btn2:
378
+ st.form_submit_button("πŸ—‘οΈ Clear", on_click=clear_state_on_change, use_container_width=True)
379
+
380
+ if send_button_clicked:
381
+ current_user_message = user_input_from_widget
382
+
383
+ if current_user_message:
384
+ st.session_state.chat_history.append({"role": "user", "content": current_user_message})
385
+
386
+ # Prepare messages for supervisor, including context about uploaded files
387
+ initial_system_prompt = (
388
+ "You are a highly capable Supervisor Agent responsible for fulfilling user requests. "
389
+ "You have access to specialized tools: 'general_chat' for conversational queries, "
390
+ "'document_analysis' for extracting insights from text documents, and 'image_analysis' for processing images. "
391
+ "Your task is to select and execute the most appropriate tool(s) based on the user's query "
392
+ "and any available uploaded data. "
393
+ "\n\n"
394
+ "IMPORTANT INSTRUCTIONS:\n"
395
+ "1. If the user's request requires analysis of uploaded files, call the appropriate tool(s) (document_analysis and/or image_analysis).\n"
396
+ "2. After receiving tool outputs, you MUST synthesize the information into a comprehensive, direct answer to the user.\n"
397
+ "3. DO NOT just describe what tools were called or what they returned.\n"
398
+ "4. DO NOT generate meta-commentary about the process.\n"
399
+ "5. Provide the actual final answer, report, email draft, or analysis that the user requested.\n"
400
+ "6. If multiple tools were used, combine their outputs into one coherent response.\n"
401
+ "7. Be direct and answer the user's question fully using the information from the tools.\n"
402
+ )
403
+
404
+ user_message_content = current_user_message
405
+ if st.session_state.uploaded_doc_content:
406
+ user_message_content += "\n\n[CONTEXT: A text document is available for analysis. Use the `document_analysis` tool if relevant to the query.]"
407
+ if st.session_state.uploaded_image_base64:
408
+ user_message_content += "\n\n[CONTEXT: An image file is available for analysis. Use the `image_analysis` tool if relevant to the query.]"
409
+
410
+ messages_for_supervisor = [
411
+ {"role": "system", "content": initial_system_prompt},
412
+ {"role": "user", "content": user_message_content} # Use the modified user message
413
+ ]
414
+
415
+ # final_agent_response will store the last, definitive content from the agent
416
+ final_agent_response = ""
417
+ orchestration_finished = False # Flag to indicate if orchestration resulted in a final answer
418
+
419
+ # Loop for potential multi-turn tool use by Supervisor Agent
420
+ MAX_TURNS = 5
421
+ for turn_count in range(MAX_TURNS):
422
+ # Call the Supervisor LLM to decide on actions (content or tool calls)
423
+ content, tool_calls = call_openai_api(messages_for_supervisor, TEXT_MODEL, tools=SUPERVISOR_TOOLS)
424
+
425
+ if tool_calls:
426
+ # Log tool execution (always add to history, display controlled by toggle)
427
+ st.session_state.chat_history.append({"role": "model", "content": f"*(Supervisor decided to use {len(tool_calls)} tool(s) - Turn {turn_count + 1})*"})
428
+
429
+ tool_output_messages = []
430
+ any_tool_error = False
431
+
432
+ for tool_call in tool_calls:
433
+ function_name = tool_call['function']['name']
434
+ function_args = json.loads(tool_call['function']['arguments'])
435
+ tool_call_id = tool_call['id']
436
+
437
+ st.session_state.chat_history.append({"role": "model", "content": f"*(Executing tool: {function_name})*"})
438
+
439
+ tool_output = ""
440
+ # Handle cases where tool is called but no relevant file is uploaded
441
+ if function_name == "image_analysis" and not st.session_state.uploaded_image_base64:
442
+ tool_output = "Error: Image analysis tool selected by Supervisor, but no image was uploaded. Please upload an image if you want image analysis."
443
+ st.warning(tool_output)
444
+ any_tool_error = True
445
+ elif function_name == "document_analysis" and not st.session_state.uploaded_doc_content:
446
+ tool_output = "Error: Document analysis tool selected by Supervisor, but no document was uploaded. Please upload a document if you want document analysis."
447
+ st.warning(tool_output)
448
+ any_tool_error = True
449
+ elif function_name == "general_chat":
450
+ # For general_chat tool, we directly call the text model for content
451
+ tool_output = _call_text_model_for_content([{"role": "user", "content": function_args["query"]}], TEXT_MODEL)
452
+ elif function_name == "document_analysis":
453
+ tool_output = get_openai_document_analysis(function_args["query"], st.session_state.uploaded_doc_content)
454
+ elif function_name == "image_analysis":
455
+ tool_output = call_mcp_image_tool(function_args["query"], st.session_state.uploaded_image_base64)
456
+ else:
457
+ tool_output = f"Error: Unknown tool '{function_name}' called by Supervisor."
458
+ any_tool_error = True
459
+
460
+ # Ensure tool_output is a string, even if the tool function returns None or empty
461
+ if tool_output is None:
462
+ tool_output = "No output from tool."
463
+
464
+ # Store the tool call (assistant message) and its output (tool message)
465
+ tool_output_messages.append({"role": "assistant", "tool_calls": [tool_call]})
466
+ tool_output_messages.append({"role": "tool", "tool_call_id": tool_call_id, "content": tool_output})
467
+
468
+ # Always add to history (display controlled by toggle)
469
+ st.session_state.chat_history.append({"role": "model", "content": f"*(Tool output for {function_name}: {tool_output[:100]}...)*" if len(tool_output) > 100 else f"*(Tool output for {function_name}: {tool_output})*"})
470
+
471
+ # Add all tool outputs to the messages for the next LLM call
472
+ messages_for_supervisor.extend(tool_output_messages)
473
+
474
+ # Add explicit instruction to synthesize the final answer
475
+ messages_for_supervisor.append({
476
+ "role": "system",
477
+ "content": "Now provide your final comprehensive answer to the user based on the tool outputs above. Do NOT describe what tools were used or provide meta-commentary. Directly answer the user's question with the actual content they requested (e.g., if they asked for an email draft, provide the complete email)."
478
+ })
479
+
480
+ # If there were errors in tool execution, break loop to prevent further LLM calls with bad context
481
+ if any_tool_error:
482
+ final_agent_response = "Supervisor encountered issues executing some tools. Please review the warnings above."
483
+ orchestration_finished = True
484
+ break # Exit the loop if errors occurred
485
+
486
+ # If LLM returned tool calls, we continue the loop for the next turn
487
+ # to allow it to process the tool outputs and generate a final answer.
488
+ # No 'break' here - continue to next iteration
489
+
490
+ elif content:
491
+ # If LLM returns content directly (no tool call), this is the final answer
492
+ final_agent_response = content
493
+ orchestration_finished = True
494
+ break # Exit the loop as we have a final response
495
+ else:
496
+ # If no content and no tool calls, it's an ambiguous state, break.
497
+ final_agent_response = "Supervisor did not provide a direct response or tool calls in this turn. Halting orchestration."
498
+ orchestration_finished = True
499
+ break
500
+
501
+ # After the orchestration loop, ensure a final response is set
502
+ if not final_agent_response: # Checks if it's still empty after the loop
503
+ st.session_state.chat_history.append({"role": "model", "content": f"*(Supervisor synthesizing final response...)*"})
504
+
505
+ synthesized_response, _ = call_openai_api(messages_for_supervisor, TEXT_MODEL)
506
+
507
+ if synthesized_response:
508
+ final_agent_response = synthesized_response
509
+ else:
510
+ final_agent_response = "Supervisor completed its process but could not generate a clear final response. Please rephrase your query or provide more context."
511
+
512
+ # ONLY APPEND THE FINAL RESPONSE HERE
513
+ st.session_state.chat_history.append({"role": "model", "content": final_agent_response})
514
+
515
+ st.session_state.input_text_value = ""
516
+ st.rerun()
517
+
518
+
519
+ # --- Display Chat History ---
520
+ st.markdown("---")
521
+
522
+ # --- Header with Toggle ---
523
+ col_header1, col_header2, col_header3 = st.columns([0.6, 0.2, 0.2])
524
+ with col_header1:
525
+ st.subheader("πŸ“‹ Conversation History")
526
+ with col_header2:
527
+ st.button("πŸ—‘οΈ Clear All", on_click=clear_state_on_change, use_container_width=True, key="clear_history_btn")
528
+ with col_header3:
529
+ # Toggle button for showing/hiding traces
530
+ st.toggle(
531
+ "πŸ” Traces",
532
+ value=st.session_state.show_traces,
533
+ key="show_traces_toggle_internal",
534
+ on_change=update_show_traces_state,
535
+ help="Show/hide agent thinking traces"
536
+ )
537
+
538
+ chat_container = st.container(height=500, border=True)
539
+
540
+ # Display messages in chronological order (oldest first)
541
+ with chat_container:
542
+ for message in st.session_state.chat_history:
543
+ if message["role"] == "user":
544
+ st.markdown(f"**πŸ‘€ You:** {message['content']}")
545
+ st.markdown("---")
546
+ else: # role is "model"
547
+ # Check if it's a trace message (starts with *( and ends with )*)
548
+ is_trace_message = isinstance(message["content"], str) and message["content"].startswith("*(") and message["content"].endswith(")*")
549
+
550
+ if st.session_state.show_traces or not is_trace_message:
551
+ # Apply different styling for trace vs final messages
552
+ if is_trace_message:
553
+ # Trace messages in a muted style
554
+ st.markdown(f"<div style='opacity: 0.6; font-style: italic; font-size: 0.9em;'>πŸ” {message['content']}</div>", unsafe_allow_html=True)
555
+ else:
556
+ # Final answer in normal style
557
+ st.markdown(f"**πŸ€– Agent:** {message['content']}")
558
+ st.markdown("---")
559