Thanks for the detailed code and explanation. I understand your goal is:
- When user submits custom prompts for analyze, summary, and detail in the dashboard, the whole pipeline uses the custom prompts and produces results accordingly.
- The topics from analysis show up properly in the sidebar.
- On clicking topics in sidebar, detail is generated correctly using custom prompts.
- The consolidated summary also uses the custom summary prompt you specify.
- This all should work in your Streamlit app with multiple agents (OverallAgent, TariffTradeAgent, SalesAgent, SupplyChainAgent) and also respect your custom prompts per agent.
Major issues & fixes based on your description & provided code
1. Passing Custom Prompt Correctly Through analyze_document, generate_consolidated_summary_from_topics and generate_topic_detail
Your BaseAgent methods expect prompt_system, prompt_user, and text inputs, but in your analyze_documents helper, you do:
topics = agent.analyze_document(text, custom_prompt)
But in BaseAgent.analyze_document method signature, third positional arg is text, and before that are your system and user prompt. You need to pass:
agent.analyze_document(prompt_system, prompt_user, text)
Fix: You should change the signature of analyze_document in agent subclasses so that when you call
agent.analyze_document(text, custom_prompt)
it internally uses the correct prompts and text.
Luckily, OverallAgent has helper methods:
def analyze_document_overall(self, text, custom_prompt=None):
prompt_analyze = custom_prompt if custom_prompt else self.prompt_analyze
return super().analyze_document(self.prompt_sys, prompt_analyze, text)
Same for summary and detail.
=> So your Streamlit code when calling agent.analyze_document must call these helper methods instead
2. Your analyze_documents function currently calls (simplified):
topics = agent.analyze_document(text, custom_prompt)
But should call e.g.
topics = agent.analyze_document_overall(text, custom_prompt)
or the respective function matching the agent type.
3. Similarly, for summary generation:
You call in your Streamlit:
summary = agent.generate_consolidated_summary_from_topics(processed_files, custom_prompt)
But your OverallAgent has:
def generate_consolidated_summary_from_topics_overall(self, processed_files, custom_prompt=None):
prompt_summary = custom_prompt if custom_prompt else self.prompt_summary
return super().generate_consolidated_summary_from_topics(self.prompt_sys, prompt_summary, processed_files)
=> You want to call this function to pass custom prompt properly.
4. For Detail generation:
Same logic applies, call generate_topic_detail_overall.
5. Setting the prompts on the agent directly like:
agent.prompt_summary = sess['custom_prompts'][mode]['summary']
agent.prompt_analyze = sess['custom_prompts'][mode]['analyze']
agent.prompt_detail = sess['custom_prompts'][mode]['detail']
only updates the local variables in agent instance, but the BaseAgent methods require explicit passing of these prompts.
You must use the helper wrapper function in OverallAgent/TariffTradeAgent etc that pull those prompt changes when you do the call.
Summary:
You need to update analyze_documents and summary generation calls in dashboard_page() to call the specialized methods (analyze_document_overall, generate_consolidated_summary_from_topics_overall, generate_topic_detail_overall) depending on agent type.
Below is a corrected and consolidated version of your relevant part of the Streamlit dashboard_page() and helper analyze_documents() reflecting your exact requirement:
- Incorporate custom prompts fully for analyze, summary, detail.
- Use correct methods with prompt_system and prompt_user.
- Maintain sidebar display with topics.
Full corrected code snippet for these functionalities (streamlit part):
NOTE: Only initialize_clients_and_agents(), analyze_documents() and dashboard_page() functions are shown here with corrections; you should keep your rest of main.py the same.
def initialize_clients_and_agents(provider_select: str, mode: str = None):
# ... Your existing same code ...
pass
def analyze_documents(mode, agent, processed_files, sess, custom_prompts=None):
"""
Analyze documents & generate consolidated summary using the proper agent methods.
:param mode: e.g. "overall", "tariff", "sales", "supplychain"
:param agent: Corresponding agent instance
:param processed_files: Dict of already processed files info (topics, text etc)
:param sess: Session dict for stored uploaded files etc
:param custom_prompts: dict with keys ['analyze', 'summary', 'detail'] for custom prompts or None to use default
"""
analyze_prompt = None
summary_prompt = None
detail_prompt = None
if custom_prompts:
analyze_prompt = custom_prompts.get('analyze')
summary_prompt = custom_prompts.get('summary')
detail_prompt = custom_prompts.get('detail')
# 1. Process individual files for analysis
for filename, file_bytes in sess['uploaded_files'].items():
if filename not in processed_files:
try:
file_obj = BytesIO(file_bytes)
file_obj.name = filename
text = extract_text(file_obj)
if text:
# Use appropriate method depending on agent type
if mode == "overall":
topics = agent.analyze_document_overall(text, analyze_prompt)
elif mode == "tariff" and hasattr(agent, 'analyze_document_tariff'):
topics = agent.analyze_document_tariff(text, analyze_prompt)
elif mode == "sales" and hasattr(agent, 'analyze_document_sales'):
topics = agent.analyze_document_sales(text, analyze_prompt)
elif mode == "supplychain" and hasattr(agent, 'analyze_document_supplychain'):
topics = agent.analyze_document_supplychain(text, analyze_prompt)
else:
# fallback to base analyze_document with given prompts or defaults
topics = agent.analyze_document(agent.prompt_sys, analyze_prompt or agent.prompt_analyze, text)
processed_files[filename] = {
"text": text,
"topics": topics,
"context": text,
}
st.toast(f"✅ Processed {filename}")
else:
st.error(f"❌ Failed to extract text for {filename}")
except Exception as e:
st.error(f"Error processing {filename}: {str(e)}")
# 2. Generate consolidated summary using custom summary prompt
if mode == "overall":
summary = agent.generate_consolidated_summary_from_topics_overall(processed_files, summary_prompt)
elif mode == "tariff" and hasattr(agent, 'generate_consolidated_summary_from_topics_tariff'):
summary = agent.generate_consolidated_summary_from_topics_tariff(processed_files, summary_prompt)
elif mode == "sales" and hasattr(agent, 'generate_consolidated_summary_from_topics_sales'):
summary = agent.generate_consolidated_summary_from_topics_sales(processed_files, summary_prompt)
elif mode == "supplychain" and hasattr(agent, 'generate_consolidated_summary_from_topics_supplychain'):
summary = agent.generate_consolidated_summary_from_topics_supplychain(processed_files, summary_prompt)
else:
# Fallback
summary = agent.generate_consolidated_summary_from_topics(agent.prompt_sys, summary_prompt or agent.prompt_summary, processed_files)
# Store summary in session state appropriately
if mode == "overall":
sess['consolidated_summary_overall'] = summary
elif mode == "tariff":
sess['consolidated_summary_tariff'] = summary
elif mode == "sales":
sess['consolidated_summary_sales'] = summary
elif mode == "supplychain":
sess['consolidated_summary_supplychain'] = summary
sess['last_analysis_mode'] = mode
sess['active_file'] = None
sess['active_topic'] = None
st.success(f"Analysis and summary generated for {mode.replace('supplychain', 'supply chain')}.")
def dashboard_page():
st.title("📊 Macy's Document Analysis Dashboard")
provider_select = st.radio("Select AI Provider", ["Azure GPT", "Google Gemini"])
# Initialize client and agents for dashboard
initialize_clients_and_agents(provider_select, mode="dashboard")
if "session" not in st.session_state:
st.session_state.session = {
'uploaded_files': {},
'processed_files_overall': {},
'processed_files_tariff': {},
'processed_files_sales': {},
'processed_files_supplychain': {},
'active_file': None,
'active_topic': None,
'topic_details_cache': {},
'chat_history': [],
'consolidated_summary_overall': None,
'consolidated_summary_tariff': None,
'consolidated_summary_sales': None,
'consolidated_summary_supplychain': None,
'last_analysis_mode': None,
'custom_prompt_enabled': {},
'custom_prompts': {
"overall": {
'summary': OverallAgent.prompt_summary,
'analyze': OverallAgent.prompt_analyze,
'detail': OverallAgent.prompt_detail
},
# Assuming these agents have similar prompt constants
'tariff': {
'summary': TariffTradeAgent.prompt_summary,
'analyze': TariffTradeAgent.prompt_analyze,
'detail': TariffTradeAgent.prompt_detail
},
'sales': {
'summary': SalesAgent.prompt_summary,
'analyze': SalesAgent.prompt_analyze,
'detail': SalesAgent.prompt_detail
},
'supplychain': {
'summary': SupplyChainAgent.prompt_summary,
'analyze': SupplyChainAgent.prompt_analyze,
'detail': SupplyChainAgent.prompt_detail
}
}
}
sess = st.session_state.session
# --- File Upload ---
st.subheader("1. Upload Documents")
uploaded_files = st.file_uploader(
"Upload PDF documents",
type=["pdf"],
accept_multiple_files=True,
key="file_uploader",
)
if uploaded_files:
new_files_added = False
for file in uploaded_files:
if file.name not in sess['uploaded_files']:
sess['uploaded_files'][file.name] = file.getvalue()
new_files_added = True
if new_files_added:
with st.spinner("🔍 Analyzing new documents with Overall Agent..."):
# Always run initial overall analysis for new files with default prompts
analyze_documents(
mode="overall",
agent=st.session_state.agent_overall,
processed_files=sess['processed_files_overall'],
sess=sess,
custom_prompts=None
)
# --- Custom Prompts & Analysis ---
st.subheader("2. Custom Prompts & Analysis")
# Select which tab
tab_overall, tab_tariff, tab_sales, tab_supply = st.tabs([
"📑 Overall", "🔍 Tariff", "📈 Sales", "🚚 Supply Chain"
])
# Prepare variable to track if generate clicked, and for which mode
generate_mode = None
generate_custom_prompts = None
with tab_overall:
st.subheader("Overall Prompts")
use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_overall")
if use_custom:
# Load existing prompts or defaults
overall_prompts = sess['custom_prompts']['overall']
overall_prompts['summary'] = st.text_area(
"Summary Prompt:",
value=overall_prompts['summary'],
height=150,
key="overall_prompt_summary"
)
overall_prompts['analyze'] = st.text_area(
"Analysis Prompt:",
value=overall_prompts['analyze'],
height=150,
key="overall_prompt_analyze"
)
overall_prompts['detail'] = st.text_area(
"Detail Prompt:",
value=overall_prompts['detail'],
height=150,
key="overall_prompt_detail"
)
if st.button("🔄 Generate with Custom Prompts", key="generate_overall"):
generate_mode = "overall"
generate_custom_prompts = overall_prompts
with tab_tariff:
st.subheader("Tariff Prompts")
use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_tariff")
if use_custom:
tariff_prompts = sess['custom_prompts']['tariff']
tariff_prompts['summary'] = st.text_area(
"Summary Prompt:",
value=tariff_prompts['summary'],
height=150,
key="tariff_prompt_summary"
)
tariff_prompts['analyze'] = st.text_area(
"Analysis Prompt:",
value=tariff_prompts['analyze'],
height=150,
key="tariff_prompt_analyze"
)
tariff_prompts['detail'] = st.text_area(
"Detail Prompt:",
value=tariff_prompts['detail'],
height=150,
key="tariff_prompt_detail"
)
if st.button("🔄 Generate with Custom Prompts", key="generate_tariff"):
generate_mode = "tariff"
generate_custom_prompts = tariff_prompts
with tab_sales:
st.subheader("Sales Prompts")
use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_sales")
if use_custom:
sales_prompts = sess['custom_prompts']['sales']
sales_prompts['summary'] = st.text_area(
"Summary Prompt:",
value=sales_prompts['summary'],
height=150,
key="sales_prompt_summary"
)
sales_prompts['analyze'] = st.text_area(
"Analysis Prompt:",
value=sales_prompts['analyze'],
height=150,
key="sales_prompt_analyze"
)
sales_prompts['detail'] = st.text_area(
"Detail Prompt:",
value=sales_prompts['detail'],
height=150,
key="sales_prompt_detail"
)
if st.button("🔄 Generate with Custom Prompts", key="generate_sales"):
generate_mode = "sales"
generate_custom_prompts = sales_prompts
with tab_supply:
st.subheader("Supply Chain Prompts")
use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_supply")
if use_custom:
supply_prompts = sess['custom_prompts']['supplychain']
supply_prompts['summary'] = st.text_area(
"Summary Prompt:",
value=supply_prompts['summary'],
height=150,
key="supply_prompt_summary"
)
supply_prompts['analyze'] = st.text_area(
"Analysis Prompt:",
value=supply_prompts['analyze'],
height=150,
key="supply_prompt_analyze"
)
supply_prompts['detail'] = st.text_area(
"Detail Prompt:",
value=supply_prompts['detail'],
height=150,
key="supply_prompt_detail"
)
if st.button("🔄 Generate with Custom Prompts", key="generate_supplychain"):
generate_mode = "supplychain"
generate_custom_prompts = supply_prompts
# --- Quick Analysis Buttons ---
st.subheader("Quick Analysis")
col0, col1, col2, col3 = st.columns(4)
analyze_overall = col0.button("📑 Overall Summary")
analyze_tariff = col1.button("🔍 Analyze Tariffs")
analyze_sales = col2.button("📈 Analyze Sales")
analyze_supplychain = col3.button("🚚 Supply Chain")
# Determine which mode to run
if not generate_mode:
if analyze_overall:
generate_mode = "overall"
elif analyze_tariff:
generate_mode = "tariff"
elif analyze_sales:
generate_mode = "sales"
elif analyze_supplychain:
generate_mode = "supplychain"
if generate_mode:
if not sess['uploaded_files']:
st.error("Please upload documents first.")
st.stop()
agent = None
processed_files = None
if generate_mode == "overall":
agent = st.session_state.agent_overall
processed_files = sess['processed_files_overall']
elif generate_mode == "tariff":
agent = st.session_state.agent_tariff
processed_files = sess['processed_files_tariff']
elif generate_mode == "sales":
agent = st.session_state.agent_sales
processed_files = sess['processed_files_sales']
elif generate_mode == "supplychain":
agent = st.session_state.agent_supplychain
processed_files = sess['processed_files_supplychain']
# Run analysis & summary with or without custom prompts
with st.spinner(f"🔍 Analyzing {generate_mode.replace('supplychain', 'supply chain')} documents..."):
analyze_documents(
mode=generate_mode,
agent=agent,
processed_files=processed_files,
sess=sess,
custom_prompts=generate_custom_prompts
)
# --- Sidebar Topics & Display, Topic Detail Generation ---
# (You can keep your existing sidebar and detail generation code here,
# but when generating detail use the custom detail prompts similarly)
# Example: when generating topic detail, do
# if current_mode = mode_config[last_mode]
# current_mode['agent'].generate_topic_detail_overall(...)
#
# Pass corresponding custom detail prompt from sess['custom_prompts'][mode]['detail']
# I won't duplicate all the sidebar UI code here since the biggest change is ensuring
# custom prompts are passed correctly in analyze_documents and also when generating topic details.
# You should update your code to modify detail generation similarly:
# e.g.,
# current_mode['agent'].generate_topic_detail_overall(context_text, topic, custom_prompt=custom_detail_prompt)
# To keep your existing UI functional, just propagate these prompt parameters accordingly.
# You already cache these results in sess['topic_details_cache'] for performance.
What you need to do in your agent classes:
- Ensure your subclasses (TariffTradeAgent, SalesAgent, SupplyChainAgent) also define their own
def analyze_document_tariff(self, text, custom_prompt=None):
prompt_analyze = custom_prompt if custom_prompt else self.prompt_analyze
return super().analyze_document(self.prompt_sys, prompt_analyze, text)
def generate_consolidated_summary_from_topics_tariff(self, processed_files, custom_prompt=None):
prompt_summary = custom_prompt if custom_prompt else self.prompt_summary
return super().generate_consolidated_summary_from_topics(self.prompt_sys, prompt_summary, processed_files)
def generate_topic_detail_tariff(self, text, topic, custom_prompt=None):
prompt_detail = custom_prompt if custom_prompt else self.prompt_detail
# similar streaming generator code...
(similar for sales and supply chain agents)
This makes your interface uniform and allows calling them cleanly.
Additional notes:
-
When you call .generate_topic_detail inside Streamlit on clicking a topic, pass the custom detail prompt stored in session state for the active mode.
-
Your custom prompts should be fully editable by users, so keep session state up-to-date with latest edits.
-
Clear cache for topic details when prompts change to avoid stale content.
TL;DR
- Adjust your Streamlit
analyze_documents to call agent.analyze_document_overall or agent-specific variants instead of base .analyze_document, passing custom prompt text.
- Use the corresponding helper methods for summary and detail with custom prompts.
- Update your agent classes with these helper methods.
- Pass or store your custom prompts safely in session state and use them in all three phases: analyze, summary and detail generation.
- Your sidebar should then show topics extracted with correct prompts and detail generation uses correct prompts too.
If you want, I can help you generate the fully detailed fixed OverallAgent and the others plus the full main.py with all fixes — just let me know!
Example: Updated OverallAgent methods
class OverallAgent(BaseAgent):
# ... your existing class and prompts ...
def analyze_document_overall(self, text, custom_prompt=None):
prompt_analyze = custom_prompt if custom_prompt else self.prompt_analyze
return super().analyze_document(self.prompt_sys, prompt_analyze, text)
def generate_consolidated_summary_from_topics_overall(self, processed_files, custom_prompt=None):
prompt_summary = custom_prompt if custom_prompt else self.prompt_summary
return super().generate_consolidated_summary_from_topics(self.prompt_sys, prompt_summary, processed_files)
def generate_topic_detail_overall(self, text, topic, custom_prompt=None):
prompt_detail = custom_prompt if custom_prompt else self.prompt_detail
return super().generate_topic_detail(self.prompt_sys, prompt_detail, text, topic)
Final offer:
If you provide your other agent classes (TariffTradeAgent, SalesAgent, SupplyChainAgent) with their prompt strings, I can write the precise corresponding helper functions for them too and integrate fully with your Streamlit.
Do you want me to provide an end-to-end fixed full working code including:
BaseAgent (your original, minimal changes)
OverallAgent (with helper wrappers)
main.py with fixed dashboard_page() and analyze_documents()
- Sample updated
TariffTradeAgent etc skeletons with helper methods?
Please send me your other agent classes TariffTradeAgent, SalesAgent, and SupplyChainAgent or confirm you want me to generate those helper methods assuming they have prompt strings like OverallAgent, then I will provide the full complete fixed code.