import streamlit as st
from io import BytesIO
from datetime import datetime
Assuming these are correctly defined and accessible
from utils.pdf_utils import extract_text
from clients.azure_client import AzureClient
from clients.gemini_client import GeminiClient
from agents.tariff_agent import TariffTradeAgent
from agents.sales_agent import SalesAgent
from agents.supply_chain_agent import SupplyChainAgent
from agents.overall_agent import OverallAgent
from agents.enhanced_chat_agent import EnhancedChatAgent
from agents.qa_agent import QAAgent
def initialize_clients_and_agents(provider_select: str, mode: str = None):
"""
Ensure 'client' and agents are initialized in st.session_state.
If mode is 'dashboard', initialize dashboard agents.
If mode is 'qa', initialize QA agent.
If mode is None, initialize all.
"""
code
Assistant
need_reinit = (
"client" not in st.session_state
or st.session_state.get("provider") != provider_select
)
if need_reinit:
if provider_select == "Azure GPT":
st.session_state.client = AzureClient()
is_azure = True
else:
st.session_state.client = GeminiClient()
is_azure = False
st.session_state.provider = provider_select
# For dashboard agents
st.session_state.agent_overall = OverallAgent(st.session_state.client, is_azure)
st.session_state.agent_tariff = TariffTradeAgent(st.session_state.client, is_azure)
st.session_state.agent_sales = SalesAgent(st.session_state.client, is_azure)
st.session_state.agent_supplychain = SupplyChainAgent(st.session_state.client, is_azure)
# Chat agent (used on both pages)
st.session_state.chat_agent = EnhancedChatAgent(st.session_state.client, is_azure)
# QA agent only if mode is 'qa' or None (default to initialize all)
if mode == "qa" or mode is None:
st.session_state.agent_qa = QAAgent(st.session_state.client, is_azure)
else:
# If client/provider the same, still validate agents are present and initialize if missing
if mode in [None, "dashboard"]:
if "agent_overall" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_overall = OverallAgent(st.session_state.client, is_azure)
if "agent_tariff" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_tariff = TariffTradeAgent(st.session_state.client, is_azure)
if "agent_sales" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_sales = SalesAgent(st.session_state.client, is_azure)
if "agent_supplychain" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_supplychain = SupplyChainAgent(st.session_state.client, is_azure)
if "chat_agent" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.chat_agent = EnhancedChatAgent(st.session_state.client, is_azure)
if mode in [None, "qa"]:
if "agent_qa" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_qa = QAAgent(st.session_state.client, is_azure)
def analyze_documents(mode, agent, processed_files, sess, custom_prompt=None):
# Process individual files
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:
topics = agent.analyze_document(text, custom_prompt)
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)}")
if 'qa_page' not in st.session_state:
st.session_state.qa_page = {
'uploaded_files': {},
'processed_files': {},
'active_file': None,
'active_topic': None,
'chat_history': [],
'selected_files': []
}
qa_state = st.session_state.qa_page
provider_select = st.sidebar.radio("Select AI Provider", ["Azure GPT", "Google Gemini"])
# Initialize client and QA agents
initialize_clients_and_agents(provider_select, mode="qa")
# --- File Upload ---
st.subheader("Upload Documents")
uploaded_files = st.file_uploader(
"Upload PDF documents for Q&A extraction",
type=["pdf"],
accept_multiple_files=True,
key="qa_file_uploader"
)
if uploaded_files:
new_files_added = False
for file in uploaded_files:
if file.name not in qa_state['uploaded_files']:
qa_state['uploaded_files'][file.name] = file.getvalue()
new_files_added = True
if new_files_added:
with st.spinner("🔍 Extracting Q&A from new documents..."):
for filename in qa_state['uploaded_files']:
if filename not in qa_state['processed_files']:
try:
file_bytes = qa_state['uploaded_files'][filename]
file_obj = BytesIO(file_bytes)
file_obj.name = filename
text = extract_text(file_obj)
if text:
# Use the QA Agent to generate structured Q&A content
qa_data = st.session_state.agent_qa.analyze_question(text)
# Store the structured data
qa_state['processed_files'][filename] = {
'text': text,
'qa_data': qa_data
}
st.toast(f"✅ Processed {filename}")
# Automatically select the first topic
if not qa_state.get('error') and qa_data.get('topics'):
qa_state['active_topic'] = qa_data['topics'][0]
else:
st.error(f"❌ Failed to extract text for {filename}")
except Exception as e:
st.error(f"Error processing {filename}: {str(e)}")
# Auto-select the first file if none is selected
if not qa_state['active_file'] and qa_state['processed_files']:
qa_state['active_file'] = next(iter(qa_state['processed_files'].keys()))
# --- Document Selection ---
st.sidebar.header("📄 Processed Documents")
for filename in qa_state['processed_files']:
if st.sidebar.button(
f"📄 {filename}",
key=f"qa_file_{filename}",
use_container_width=True,
):
qa_state['active_file'] = filename
# Automatically select the first topic for this document
file_data = qa_state['processed_files'][filename]
qa_data = file_data['qa_data']
if not qa_data.get('error') and qa_data.get('topics'):
qa_state['active_topic'] = qa_data['topics'][0]
# --- Topic Sidebar ---
if qa_state['active_file']:
file_data = qa_state['processed_files'][qa_state['active_file']]
qa_data = file_data['qa_data']
st.sidebar.header("📌 Topics")
# Handle error case
if "error" in qa_data:
st.sidebar.error("Error in document processing")
elif 'topics' in qa_data:
topics = qa_data['topics']
# Display each topic in the sidebar
for topic in topics:
btn_label = f"{topic['topic']} ({topic['mention_count']} mentions)"
if st.sidebar.button(
btn_label,
key=f"topic_{topic['topic']}_{qa_state['active_file']}",
use_container_width=True,
):
qa_state['active_topic'] = topic
else:
st.sidebar.info("No topics found in this document")
# --- Q&A Display ---
st.subheader("📝 Extracted Q&A Content")
if qa_state['active_file']:
file_data = qa_state['processed_files'][qa_state['active_file']]
qa_data = file_data['qa_data']
st.markdown(f"**Document:** {qa_state['active_file']}")
# Handle error case
if "error" in qa_data:
st.error(f"Error processing document: {qa_data['error']}")
if "raw_response" in qa_data:
st.text_area("Raw AI Response", qa_data["raw_response"], height=300)
# Display key takeaways
elif 'key_takeaways' in qa_data and qa_data['key_takeaways']:
st.subheader("Key Takeaways")
for takeaway in qa_data['key_takeaways']:
st.markdown(f"- {takeaway}")
# Display selected topic
if qa_state['active_topic']:
topic = qa_state['active_topic']
st.divider()
st.subheader(topic['topic'])
st.markdown(f"**Mentioned:** {topic['mention_count']} times")
st.divider()
# Display questions for this topic
if 'questions' in topic and topic['questions']:
for idx, question in enumerate(topic['questions']):
firm = question.get('firm', 'Unknown Firm')
st.markdown(f"**Firm:** {firm}")
st.markdown(f"**Question {idx+1}:** {question['question']}")
st.write("---")
else:
st.info("No questions found for this topic")
elif 'topics' in qa_data and qa_data['topics']:
# If no topic selected but topics exist, show the first one
qa_state['active_topic'] = qa_data['topics'][0]
st.rerun()
else:
st.info("No Q&A content found for this document")
else:
st.info("Upload documents to see extracted Q&A content")
st.divider()
# --- Chat Interface ---
st.subheader("💬 Chat with Documents")
available_files = list(qa_state['processed_files'].keys())
selected_files = st.multiselect(
"Select documents to include in chat context:",
available_files,
default=available_files[:min(3, len(available_files))],
key="qa_chat_selector"
)
qa_state['selected_files'] = selected_files
for msg in qa_state['chat_history']:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
question = st.chat_input("Ask about the documents...")
if question:
if not selected_files:
st.error("Please select at least one document for context")
st.stop()
qa_state['chat_history'].append({
"role": "user",
"content": question,
"timestamp": datetime.utcnow().isoformat(),
})
try:
context = "\n\n".join([
f"=== {filename} ===\n{qa_state['processed_files'][filename]['text']}"
for filename in selected_files
])
with st.chat_message("assistant"):
response_placeholder = st.empty()
full_response = ""
for chunk, _ in st.session_state.chat_agent.generate_answer(question, context):
full_response = chunk
response_placeholder.markdown(full_response + " ▌")
response_placeholder.markdown(full_response)
qa_state['chat_history'].append({
"role": "assistant",
"content": full_response,
"timestamp": datetime.utcnow().isoformat(),
})
except Exception as e:
st.error(f"Chat error: {str(e)}")
qa_state['chat_history'].append({
"role": "assistant",
"content": f"Error: {str(e)}",
"timestamp": datetime.utcnow().isoformat(),
})
# Reset button for QA page
if st.button("🔄 Reset Q&A Session", key="reset_qa_page"):
qa_state.clear()
qa_state.update({
'uploaded_files': {},
'processed_files': {},
'active_file': None,
'active_topic': None,
'chat_history': [],
'selected_files': []
})
st.rerun()
if name == "main":
main()
why only summarise custom prompt is working if we done any changes in analyze and detail nothing is working
please correct this and give me full code back
The issue you're facing arises because when doing custom prompt generation, only in the summarization step the custom summary prompt is used, but during the actual analyze_document call, the custom analyze (and possibly the detail) prompt isn't used effectively or passed correctly to downstream methods.
Looking at your code, the primary place the custom prompts are assigned is here:
python
if generate_mode:
agent.prompt_summary = sess['custom_prompts'][mode]['summary']
agent.prompt_analyze = sess['custom_prompts'][mode]['analyze']
agent.prompt_detail = sess['custom_prompts'][mode]['detail']
st.toast(f"Using custom prompts for {mode} analysis")
else:
# Reset to default prompts
...
But then in your analyze_documents function, you call:
During the call, you pass custom_prompt which is usually None. So if the custom analyze prompt is set on the agent class attribute (prompt_analyze), it should be internally used in analyze_document.
However, if your agent classes (OverallAgent, TariffTradeAgent, etc.) do not internally use the updated prompt attributes when calling analyze_document, but rather rely on passed custom_prompt, or some internal logic that ignores the updated prompt, then only changing the prompt_summary has effect, but analyze and detail don't.
Likely cause:
Your agent's analyze_document method ignores the self.prompt_analyze attribute and uses only passed custom_prompt or their own fixed prompt internally.
Or you do not pass the custom prompts properly as a parameter, so the custom analyze prompt is never actually used.
Summary works because the summary generation explicitly uses agent.prompt_summary.
How to fix:
Pass the relevant custom prompts explicitly during analyze_document calls.
Modify the analyze_documents function to explicitly pass the custom analyze prompt.
Make sure generate_consolidated_summary_from_topics receives the correct custom summary prompt.
If generate_topic_detail or other generators use the detail prompt, ensure to update the prompt correctly as well.
My approach:
Introduce explicit parameters for all the prompts to the analyze methods.
Pass custom prompts as needed.
Ensure defaults fall back to agent.prompt_analyze, agent.prompt_summary, etc.
Assign these custom prompt values right inside the agent instance so all calls use them internally.
Here is the corrected full code focusing on these fixes added to your original code:
python
Summary of what I changed:
analyze_documents(...) now takes a custom_prompts dict and explicitly passes the analyze prompt into agent.analyze_document.
When generating consolidated summary, the custom summary prompt is passed explicitly.
When setting custom prompts on the agent (agent.prompt_summary, agent.prompt_analyze, agent.prompt_detail), this is preserved and used during generation of topic detail.
The chat agents remain unchanged (assuming they handle prompts internally).
Changed st.rerun() to st.experimental_rerun() as the formerly recommended method (adjust if needed depending on your Streamlit version).
Ensured custom prompts textareas update the sess['custom_prompts'][mode] dict for summary, analyze, and detail prompts properly.
When user triggers generation (custom or quick analysis), analyze_documents receives the proper custom prompts dict or None.
This approach guarantees that all parts of the pipeline honor the custom prompts instead of just summary prompts.
Please ensure your agent code (analyze_document, generate_consolidated_summary_from_topics, generate_topic_detail) are written to use those prompts (via either parameter or instance variables) properly. If they ignore the prompts, you'll want to update them accordingly.
If you want me to help confirm or fix your Agent code accordingly, please share their relevant parts.
Let me know if you face issues with this or want help updating your agent code as well.