Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

import streamlit as st from io import BytesIO from datetime import datetime from…

  1. User

    import streamlit as st from io import BytesIO from datetime import datetime from markdown import markdown from bs4 import BeautifulSoup from docx import Document

    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 markdown_to_word(markdown_content, output_file = 'output.docx'): # Convert Markdown to HTML html_content = markdown(markdown_content)

    # Parse HTML using BeautifulSoup
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # Create a Word document
    doc = Document()
    
    # Add content to the Word document
    for element in soup.descendants:
        if element.name == 'h1':
            doc.add_heading(element.text, level=1)
        elif element.name == 'h2':
            doc.add_heading(element.text, level=2)
        elif element.name == 'p':
            doc.add_paragraph(element.text)
        elif element.name == 'li':
            doc.add_paragraph(f"- {element.text}")
    
    # Save the Word document
    doc.save(output_file)
    

    def initialize_clients_and_agents(provider_select: str, mode: str = None): 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
    
        # 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
        st.session_state.chat_agent = EnhancedChatAgent(st.session_state.client, is_azure)
    
        # QA agent if required
        if mode == "qa" or mode is None:
            st.session_state.agent_qa = QAAgent(st.session_state.client, is_azure)
    
    else:
        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: # *** CHANGE: explicitly pass agent.prompt_analyze to ensure custom prompt used *** topics = agent.analyze_document( text, custom_prompt=agent.prompt_analyze if hasattr(agent, 'prompt_analyze') else None )

                    # *** DEBUG Prints to verify topics extracted - can remove later ***
                    # print(f"\n[DEBUG] Topics extracted from file '{filename}':")
                    # print(topics)
    
                    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)}")
    
    # Generate consolidated summary
    summary = agent.generate_consolidated_summary_from_topics(processed_files, custom_prompt)
    
    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 main(): st.set_page_config(page_title="Macy's Document Analysis Pro", layout="wide")

    st.sidebar.title("InsightHub")
    page = st.sidebar.radio("Select Any", ["Analysis Dashboard", "Question Assistant"])
    
    if page == "Analysis Dashboard":
        dashboard_page()
    elif page == "Question Assistant":
        qa_page()
    

    def dashboard_page(): st.title("📊 Macy's Document Analysis Dashboard")

    provider_select = st.radio("Select AI Provider", ["Azure GPT", "Google Gemini"])
    
    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_prompt_text': {}
        }
    
    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..."):
                analyze_documents(
                    mode="overall",
                    agent=st.session_state.agent_overall,
                    processed_files=sess['processed_files_overall'],
                    sess=sess
                )
    
    # --- Custom Prompts & Analysis ---
    st.subheader("2. Custom Prompts & Analysis")
    
    if 'custom_prompts' not in sess:
        sess['custom_prompts'] = {
            'overall': {
                'summary': OverallAgent.prompt_summary,
                'analyze': OverallAgent.prompt_analyze,
                'detail': OverallAgent.prompt_detail
            },
            '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
            }
        }
    
    tab_overall, tab_tariff, tab_sales, tab_supply = st.tabs([
        "📑 Overall", "🔍 Tariff", "📈 Sales", "🚚 Supply Chain"
    ])
    
    generate_mode = None
    
    with tab_overall:
        st.subheader("Overall Prompts")
        use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_overall")
    
        if use_custom:
            sess['custom_prompts']['overall']['summary'] = st.text_area(
                "Summary Prompt:",
                value=sess['custom_prompts']['overall']['summary'],
                height=150,
                key="overall_prompt_summary"
            )
            sess['custom_prompts']['overall']['analyze'] = st.text_area(
                "Analysis Prompt:",
                value=sess['custom_prompts']['overall']['analyze'],
                height=150,
                key="overall_prompt_analyze"
            )
            sess['custom_prompts']['overall']['detail'] = st.text_area(
                "Detail Prompt:",
                value=sess['custom_prompts']['overall']['detail'],
                height=150,
                key="overall_prompt_detail"
            )
    
            if st.button("🔄 Generate with Custom Prompts", key="generate_overall"):
                generate_mode = "overall"
    
    with tab_tariff:
        st.subheader("Tariff Prompts")
        use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_tariff")
    
        if use_custom:
            sess['custom_prompts']['tariff']['summary'] = st.text_area(
                "Summary Prompt:",
                value=sess['custom_prompts']['tariff']['summary'],
                height=150,
                key="tariff_prompt_summary"
            )
            sess['custom_prompts']['tariff']['analyze'] = st.text_area(
                "Analysis Prompt:",
                value=sess['custom_prompts']['tariff']['analyze'],
                height=150,
                key="tariff_prompt_analyze"
            )
            sess['custom_prompts']['tariff']['detail'] = st.text_area(
                "Detail Prompt:",
                value=sess['custom_prompts']['tariff']['detail'],
                height=150,
                key="tariff_prompt_detail"
            )
    
            if st.button("🔄 Generate with Custom Prompts", key="generate_tariff"):
                generate_mode = "tariff"
    
    with tab_sales:
        st.subheader("Sales Prompts")
        use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_sales")
    
        if use_custom:
            sess['custom_prompts']['sales']['summary'] = st.text_area(
                "Summary Prompt:",
                value=sess['custom_prompts']['sales']['summary'],
                height=150,
                key="sales_prompt_summary"
            )
            sess['custom_prompts']['sales']['analyze'] = st.text_area(
                "Analysis Prompt:",
                value=sess['custom_prompts']['sales']['analyze'],
                height=150,
                key="sales_prompt_analyze"
            )
            sess['custom_prompts']['sales']['detail'] = st.text_area(
                "Detail Prompt:",
                value=sess['custom_prompts']['sales']['detail'],
                height=150,
                key="sales_prompt_detail"
            )
    
            if st.button("🔄 Generate with Custom Prompts", key="generate_sales"):
                generate_mode = "sales"
    
    with tab_supply:
        st.subheader("Supply Chain Prompts")
        use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_supply")
    
        if use_custom:
            sess['custom_prompts']['supplychain']['summary'] = st.text_area(
                "Summary Prompt:",
                value=sess['custom_prompts']['supplychain']['summary'],
                height=150,
                key="supply_prompt_summary"
            )
            sess['custom_prompts']['supplychain']['analyze'] = st.text_area(
                "Analysis Prompt:",
                value=sess['custom_prompts']['supplychain']['analyze'],
                height=150,
                key="supply_prompt_analyze"
            )
            sess['custom_prompts']['supplychain']['detail'] = st.text_area(
                "Detail Prompt:",
                value=sess['custom_prompts']['supplychain']['detail'],
                height=150,
                key="supply_prompt_detail"
            )
    
            if st.button("🔄 Generate with Custom Prompts", key="generate_supplychain"):
                generate_mode = "supplychain"
    
    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")
    
    # *** CHANGE: Clear processed files on custom generation to force re-analysis ***
    if generate_mode or analyze_overall or analyze_tariff or analyze_sales or analyze_supplychain:
        if not sess['uploaded_files']:
            st.error("Please upload documents first.")
            st.stop()
    
        mode = generate_mode or (
            "overall" if analyze_overall else
            "tariff" if analyze_tariff else
            "sales" if analyze_sales else
            "supplychain" if analyze_supplychain else None
        )
    
        agent = None
    
        if mode == "overall":
            agent = st.session_state.agent_overall
        elif mode == "tariff":
            agent = st.session_state.agent_tariff
        elif mode == "sales":
            agent = st.session_state.agent_sales
        elif mode == "supplychain":
            agent = st.session_state.agent_supplychain
    
        # Clear processed files for fresh analysis on prompt change
        sess[f'processed_files_{mode}'] = {}
        processed_files = sess[f'processed_files_{mode}']
    
        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:
            if mode == "overall":
                agent.prompt_summary = OverallAgent.prompt_summary
                agent.prompt_analyze = OverallAgent.prompt_analyze
                agent.prompt_detail = OverallAgent.prompt_detail
            elif mode == "tariff":
                agent.prompt_summary = TariffTradeAgent.prompt_summary
                agent.prompt_analyze = TariffTradeAgent.prompt_analyze
                agent.prompt_detail = TariffTradeAgent.prompt_detail
            elif mode == "sales":
                agent.prompt_summary = SalesAgent.prompt_summary
                agent.prompt_analyze = SalesAgent.prompt_analyze
                agent.prompt_detail = SalesAgent.prompt_detail
            elif mode == "supplychain":
                agent.prompt_summary = SupplyChainAgent.prompt_summary
                agent.prompt_analyze = SupplyChainAgent.prompt_analyze
                agent.prompt_detail = SupplyChainAgent.prompt_detail
    
        with st.spinner(f"🔍 Analyzing {mode.replace('supplychain', 'supply chain')} documents..."):
            analyze_documents(
                mode,
                agent,
                processed_files,
                sess
            )
    
    # --- Main display and sidebar for topics and summaries ---
    last_mode = sess['last_analysis_mode']
    if last_mode is None:
        st.info("Select an analysis type to begin.")
        return
    
    mode_config = {
        'overall': {
            'files': sess['processed_files_overall'],
            'summary': sess['consolidated_summary_overall'],
            'sidebar_header': "Overall Topics",
            'main_header': "🌟 Executive Summary",
            'agent': st.session_state.agent_overall
        },
        'tariff': {
            'files': sess['processed_files_tariff'],
            'summary': sess['consolidated_summary_tariff'],
            'sidebar_header': "Tariff Topics",
            'main_header': "🌟 Tariff Analysis",
            'agent': st.session_state.agent_tariff
        },
        'sales': {
            'files': sess['processed_files_sales'],
            'summary': sess['consolidated_summary_sales'],
            'sidebar_header': "Sales Topics",
            'main_header': "🌟 Sales Analysis",
            'agent': st.session_state.agent_sales
        },
        'supplychain': {
            'files': sess['processed_files_supplychain'],
            'summary': sess['consolidated_summary_supplychain'],
            'sidebar_header': "Supply Chain Topics",
            'main_header': "🌟 Supply Chain Analysis",
            'agent': st.session_state.agent_supplychain
        }
    }
    
    current_mode = mode_config[last_mode]
    
    # --- Sidebar Topics ---
    st.sidebar.header(current_mode['sidebar_header'])
    
    if last_mode == "overall":
        topics_by_file = {}
        for filename, filedata in current_mode['files'].items():
            for topic in filedata["topics"]:
                topics_by_file.setdefault(topic['name'], []).append({
                    'file': filename,
                    'score': topic['score']
                })
    
        sorted_topics = sorted(topics_by_file.items(),
                               key=lambda x: max(x[1], key=lambda y: y['score'])['score'],
                               reverse=True)
        before_view_more, after_view_more = sorted_topics[:3], sorted_topics[3:]
    
        for topic_name, occurrences in before_view_more:
            total_score = sum(occ['score'] for occ in occurrences)
            file_count = len(occurrences)
            btn_label = f"{topic_name} (📈 {total_score:.1f} | 📑 {file_count})"
    
            if st.sidebar.button(
                btn_label,
                key=f"overall_topic_{topic_name}",
                use_container_width=True,
            ):
                sess['active_topic'] = topic_name
                sess['active_file'] = None
    
        if after_view_more and st.sidebar.button('View More', key='1234', use_container_width=True):
            for topic_name, occurrences in after_view_more:
                total_score = sum(occ['score'] for occ in occurrences)
                file_count = len(occurrences)
                btn_label = f"{topic_name} (📈 {total_score:.1f} | 📑 {file_count})"
    
                if st.sidebar.button(
                    btn_label,
                    key=f"overall_topic_more_{topic_name}",
                    use_container_width=True,
                ):
                    sess['active_topic'] = topic_name
                    sess['active_file'] = None
    
    else:  # Tariff, Sales, Supply Chain
        for filename, filedata in current_mode['files'].items():
            expanded = (filename == sess['active_file'])
            with st.sidebar.expander(f"📄 {filename}", expanded=expanded):
                topics = sorted(filedata["topics"], key=lambda t: t["score"], reverse=True)
                for topic in topics[:3]:
                    is_selected = (
                        sess['active_file'] == filename and sess['active_topic'] == topic['name']
                    )
                    style = "primary" if is_selected else "secondary"
    
                    if st.button(
                        f"• {topic['name']} (Score: {topic['score']})",
                        key=f"{last_mode}_topic_{filename}_{topic['name']}",
                        type=style,
                        use_container_width=True,
                    ):
                        sess['active_file'] = filename
                        sess['active_topic'] = topic['name']
    
                if len(topics) > 3 and st.sidebar.button(f'View More for {filename}', key=f'{filename}_view_more', use_container_width=True):
                    for topic in topics[3:]:
                        is_selected = (
                            sess['active_file'] == filename and sess['active_topic'] == topic['name']
                        )
                        style = "primary" if is_selected else "secondary"
    
                        if st.button(
                            f"• {topic['name']} (Score: {topic['score']})",
                            key=f"{last_mode}_topic_more_{filename}_{topic['name']}",
                            type=style,
                            use_container_width=True,
                        ):
                            sess['active_file'] = filename
                            sess['active_topic'] = topic['name']
    
    # --- Topic Detail Analysis ---
    st.subheader("Detailed Analysis")
    if last_mode == "overall" and sess['active_topic']:
        mentions = []
        for filename, filedata in current_mode['files'].items():
            for topic in filedata["topics"]:
                if topic['name'] == sess['active_topic']:
                    mentions.append({
                        'file': filename,
                        'summary': topic.get('summary', ''),
                        'score': topic['score'],
                        'context': filedata['context']
                    })
    
        with st.expander("📊 Topic Prevalence"):
            cols = st.columns(3)
            cols[0].metric("Total Documents", len(mentions))
            avg_relevance = (sum(m['score'] for m in mentions) / len(mentions)) if mentions else 0
            cols[1].metric("Average Relevance", f"{avg_relevance:.1f}")
            cols[2].metric("First Mentioned", mentions[0]['file'] if mentions else "N/A")
    
        if mentions:
            combined_context = "\n\n".join(f"=== {m['file']} ===\n{m['context']}" for m in mentions)
            key_cache = (last_mode, sess['active_topic'])
            if key_cache in sess['topic_details_cache']:
                st.markdown(sess['topic_details_cache'][key_cache])
            else:
                placeholder = st.empty()
                collected_text = ""
                try:
                    for chunk in current_mode['agent'].generate_topic_detail(combined_context, sess['active_topic']):
                        collected_text = chunk
                        placeholder.markdown(collected_text + (" ▌" if "▌" in collected_text else ""))
                    sess['topic_details_cache'][key_cache] = collected_text
                    markdown_to_word(collected_text, sess['active_topic']+'.docx')
                    with open(sess['active_topic']+'.docx', 'rb') as f:
                        st.download_button("Download Doc", f, file_name=sess['active_topic']+'.docx')
    
                except Exception as e:
                    st.error(f"Analysis error: {str(e)}")
    
    elif sess['active_file'] and sess['active_topic']:
        key_cache = (last_mode, sess['active_file'], sess['active_topic'])
        if key_cache in sess['topic_details_cache']:
            st.markdown(sess['topic_details_cache'][key_cache])
        else:
            placeholder = st.empty()
            collected_text = ""
            try:
                for chunk in current_mode['agent'].generate_topic_detail(
                    current_mode['files'][sess['active_file']]['context'],
                    sess['active_topic'],
                ):
                    collected_text = chunk
                    placeholder.markdown(collected_text + (" ▌" if "▌" in collected_text else ""))
                sess['topic_details_cache'][key_cache] = collected_text
                markdown_to_word(collected_text, sess['active_topic']+'.docx')
                with open(sess['active_topic']+'.docx', 'rb') as f:
                    st.download_button("Download Doc", f, file_name=sess['active_topic']+'.docx')
    
    
            except Exception as e:
                st.error(f"Analysis error: {str(e)}")
    else:
        st.info("Select a topic from the sidebar")
    
    st.markdown("---")
    
    st.header(current_mode['main_header'])
    if current_mode['summary']:
        st.markdown(current_mode['summary'])
        markdown_to_word(current_mode['summary'], current_mode['sidebar_header']+'.docx')
        with open(current_mode['sidebar_header']+'.docx', 'rb') as f:
            st.download_button("Download Doc", f, file_name=current_mode['sidebar_header']+'.docx')
    
    else:
        st.info("Summary not available yet")
    
    st.divider()
    
    # --- Chat Interface ---
    st.subheader("💬 Document Chat")
    
    available_files = list(current_mode['files'].keys())
    selected_files = st.multiselect(
        "Select documents for context:",
        available_files,
        key=f"chat_selector_{last_mode}"
    )
    
    for msg in sess['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 documents first")
            st.stop()
    
        sess['chat_history'].append({
            "role": "user",
            "content": question,
            "timestamp": datetime.utcnow().isoformat(),
        })
    
        try:
            context = "\n\n".join([
                f"=== {fname} ===\n{current_mode['files'][fname]['context']}"
                for fname in selected_files
            ])
    
            with st.chat_message("assistant"):
                response_placeholder = st.empty()
                full_response = ""
                q_type = None
    
                for chunk, q_type in st.session_state.chat_agent.generate_answer(question, context):
                    full_response = chunk
                    response_placeholder.markdown(full_response + " ▌")
    
                response_placeholder.markdown(full_response)
    
                sess['chat_history'].append({
                    "role": "assistant",
                    "content": full_response,
                    "timestamp": datetime.utcnow().isoformat(),
                    "analysis_type": q_type
                })
    
        except Exception as e:
            st.error(f"Chat error: {str(e)}")
            sess['chat_history'].append({
                "role": "assistant",
                "content": f"Error: {str(e)}",
                "timestamp": datetime.utcnow().isoformat(),
            })
    
    if st.button("🔄 Reset Session", type="secondary"):
        preserved_keys = [
            "client", "agent_overall", "agent_tariff",
            "agent_sales", "agent_supplychain", "chat_agent", "provider"
        ]
        preserved = {k: st.session_state[k] for k in preserved_keys if k in st.session_state}
    
        st.session_state.clear()
        st.session_state.update(preserved)
    
        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_prompt_text': {}
        }
    
        st.rerun()
    

    def qa_page(): st.title("❓ Macy's Question Assistant")

    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_clients_and_agents(provider_select, mode="qa")
    
    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:
                                qa_data = st.session_state.agent_qa.analyze_question(text)
                                qa_state['processed_files'][filename] = {
                                    'text': text,
                                    'qa_data': qa_data
                                }
                                st.toast(f"✅ Processed {filename}")
    
                                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)}")
    
            if not qa_state['active_file'] and qa_state['processed_files']:
                qa_state['active_file'] = next(iter(qa_state['processed_files'].keys()))
    
    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
            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]
    
    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")
    
        if "error" in qa_data:
            st.sidebar.error("Error in document processing")
    
        elif 'topics' in qa_data:
            topics = qa_data['topics']
    
            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")
    
    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']}")
    
        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)
    
        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}")
    
        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()
    
            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']:
            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()
    
    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(),
            })
    
    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()

    replace everything of supplychain and sales with Consumer Health and Monthly Performance all things even import

  2. Assistant

    Certainly! Here's your updated Streamlit app code where every occurrence of Supply Chain and Sales (including imports, agent initialization, variable names, UI labels, tabs, and keys) is replaced with Consumer Health and Monthly Performance, respectively.

    Note: I replaced:

    • SalesAgent → MonthlyPerformanceAgent
    • SupplyChainAgent → ConsumerHealthAgent
    • Tabs and other mentions renamed accordingly.

    import streamlit as st
    from io import BytesIO
    from datetime import datetime
    from markdown import markdown
    from bs4 import BeautifulSoup
    from docx import Document
    
    # 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.monthly_performance_agent import MonthlyPerformanceAgent
    from agents.consumer_health_agent import ConsumerHealthAgent
    from agents.overall_agent import OverallAgent
    from agents.enhanced_chat_agent import EnhancedChatAgent
    from agents.qa_agent import QAAgent
    
    
    def markdown_to_word(markdown_content, output_file = 'output.docx'):
        # Convert Markdown to HTML
        html_content = markdown(markdown_content)
        
        # Parse HTML using BeautifulSoup
        soup = BeautifulSoup(html_content, 'html.parser')
        
        # Create a Word document
        doc = Document()
        
        # Add content to the Word document
        for element in soup.descendants:
            if element.name == 'h1':
                doc.add_heading(element.text, level=1)
            elif element.name == 'h2':
                doc.add_heading(element.text, level=2)
            elif element.name == 'p':
                doc.add_paragraph(element.text)
            elif element.name == 'li':
                doc.add_paragraph(f"- {element.text}")
        
        # Save the Word document
        doc.save(output_file)
    
    
    def initialize_clients_and_agents(provider_select: str, mode: str = None):
        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
    
            # 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_monthly_performance = MonthlyPerformanceAgent(st.session_state.client, is_azure)
            st.session_state.agent_consumer_health = ConsumerHealthAgent(st.session_state.client, is_azure)
    
            # Chat agent
            st.session_state.chat_agent = EnhancedChatAgent(st.session_state.client, is_azure)
    
            # QA agent if required
            if mode == "qa" or mode is None:
                st.session_state.agent_qa = QAAgent(st.session_state.client, is_azure)
    
        else:
            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_monthly_performance" not in st.session_state:
                    is_azure = st.session_state.provider == "Azure GPT"
                    st.session_state.agent_monthly_performance = MonthlyPerformanceAgent(st.session_state.client, is_azure)
                if "agent_consumer_health" not in st.session_state:
                    is_azure = st.session_state.provider == "Azure GPT"
                    st.session_state.agent_consumer_health = ConsumerHealthAgent(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:
                        # *** CHANGE: explicitly pass agent.prompt_analyze to ensure custom prompt used ***
                        topics = agent.analyze_document(
                            text,
                            custom_prompt=agent.prompt_analyze if hasattr(agent, 'prompt_analyze') else None
                        )
    
                        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)}")
    
        # Generate consolidated summary
        summary = agent.generate_consolidated_summary_from_topics(processed_files, custom_prompt)
    
        if mode == "overall":
            sess['consolidated_summary_overall'] = summary
        elif mode == "tariff":
            sess['consolidated_summary_tariff'] = summary
        elif mode == "monthly_performance":
            sess['consolidated_summary_monthly_performance'] = summary
        elif mode == "consumer_health":
            sess['consolidated_summary_consumer_health'] = summary
    
        sess['last_analysis_mode'] = mode
        sess['active_file'] = None
        sess['active_topic'] = None
        st.success(f"Analysis and summary generated for {mode.replace('consumer_health', 'consumer health').replace('monthly_performance', 'monthly performance')}.")
    
    
    def main():
        st.set_page_config(page_title="Macy's Document Analysis Pro", layout="wide")
    
        st.sidebar.title("InsightHub")
        page = st.sidebar.radio("Select Any", ["Analysis Dashboard", "Question Assistant"])
    
        if page == "Analysis Dashboard":
            dashboard_page()
        elif page == "Question Assistant":
            qa_page()
    
    
    def dashboard_page():
        st.title("📊 Macy's Document Analysis Dashboard")
    
        provider_select = st.radio("Select AI Provider", ["Azure GPT", "Google Gemini"])
    
        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_monthly_performance': {},
                'processed_files_consumer_health': {},
                'active_file': None,
                'active_topic': None,
                'topic_details_cache': {},
                'chat_history': [],
                'consolidated_summary_overall': None,
                'consolidated_summary_tariff': None,
                'consolidated_summary_monthly_performance': None,
                'consolidated_summary_consumer_health': None,
                'last_analysis_mode': None,
                'custom_prompt_enabled': {},
                'custom_prompt_text': {}
            }
    
        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..."):
                    analyze_documents(
                        mode="overall",
                        agent=st.session_state.agent_overall,
                        processed_files=sess['processed_files_overall'],
                        sess=sess
                    )
    
        # --- Custom Prompts & Analysis ---
        st.subheader("2. Custom Prompts & Analysis")
    
        if 'custom_prompts' not in sess:
            sess['custom_prompts'] = {
                'overall': {
                    'summary': OverallAgent.prompt_summary,
                    'analyze': OverallAgent.prompt_analyze,
                    'detail': OverallAgent.prompt_detail
                },
                'tariff': {
                    'summary': TariffTradeAgent.prompt_summary,
                    'analyze': TariffTradeAgent.prompt_analyze,
                    'detail': TariffTradeAgent.prompt_detail
                },
                'monthly_performance': {
                    'summary': MonthlyPerformanceAgent.prompt_summary,
                    'analyze': MonthlyPerformanceAgent.prompt_analyze,
                    'detail': MonthlyPerformanceAgent.prompt_detail
                },
                'consumer_health': {
                    'summary': ConsumerHealthAgent.prompt_summary,
                    'analyze': ConsumerHealthAgent.prompt_analyze,
                    'detail': ConsumerHealthAgent.prompt_detail
                }
            }
    
        tab_overall, tab_tariff, tab_monthly_performance, tab_consumer_health = st.tabs([
            "📑 Overall", "🔍 Tariff", "📈 Monthly Performance", "🩺 Consumer Health"
        ])
    
        generate_mode = None
    
        with tab_overall:
            st.subheader("Overall Prompts")
            use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_overall")
    
            if use_custom:
                sess['custom_prompts']['overall']['summary'] = st.text_area(
                    "Summary Prompt:",
                    value=sess['custom_prompts']['overall']['summary'],
                    height=150,
                    key="overall_prompt_summary"
                )
                sess['custom_prompts']['overall']['analyze'] = st.text_area(
                    "Analysis Prompt:",
                    value=sess['custom_prompts']['overall']['analyze'],
                    height=150,
                    key="overall_prompt_analyze"
                )
                sess['custom_prompts']['overall']['detail'] = st.text_area(
                    "Detail Prompt:",
                    value=sess['custom_prompts']['overall']['detail'],
                    height=150,
                    key="overall_prompt_detail"
                )
    
                if st.button("🔄 Generate with Custom Prompts", key="generate_overall"):
                    generate_mode = "overall"
    
        with tab_tariff:
            st.subheader("Tariff Prompts")
            use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_tariff")
    
            if use_custom:
                sess['custom_prompts']['tariff']['summary'] = st.text_area(
                    "Summary Prompt:",
                    value=sess['custom_prompts']['tariff']['summary'],
                    height=150,
                    key="tariff_prompt_summary"
                )
                sess['custom_prompts']['tariff']['analyze'] = st.text_area(
                    "Analysis Prompt:",
                    value=sess['custom_prompts']['tariff']['analyze'],
                    height=150,
                    key="tariff_prompt_analyze"
                )
                sess['custom_prompts']['tariff']['detail'] = st.text_area(
                    "Detail Prompt:",
                    value=sess['custom_prompts']['tariff']['detail'],
                    height=150,
                    key="tariff_prompt_detail"
                )
    
                if st.button("🔄 Generate with Custom Prompts", key="generate_tariff"):
                    generate_mode = "tariff"
    
        with tab_monthly_performance:
            st.subheader("Monthly Performance Prompts")
            use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_monthly_performance")
    
            if use_custom:
                sess['custom_prompts']['monthly_performance']['summary'] = st.text_area(
                    "Summary Prompt:",
                    value=sess['custom_prompts']['monthly_performance']['summary'],
                    height=150,
                    key="monthly_performance_prompt_summary"
                )
                sess['custom_prompts']['monthly_performance']['analyze'] = st.text_area(
                    "Analysis Prompt:",
                    value=sess['custom_prompts']['monthly_performance']['analyze'],
                    height=150,
                    key="monthly_performance_prompt_analyze"
                )
                sess['custom_prompts']['monthly_performance']['detail'] = st.text_area(
                    "Detail Prompt:",
                    value=sess['custom_prompts']['monthly_performance']['detail'],
                    height=150,
                    key="monthly_performance_prompt_detail"
                )
    
                if st.button("🔄 Generate with Custom Prompts", key="generate_monthly_performance"):
                    generate_mode = "monthly_performance"
    
        with tab_consumer_health:
            st.subheader("Consumer Health Prompts")
            use_custom = st.checkbox("✏️ Use Custom Prompts", key="custom_consumer_health")
    
            if use_custom:
                sess['custom_prompts']['consumer_health']['summary'] = st.text_area(
                    "Summary Prompt:",
                    value=sess['custom_prompts']['consumer_health']['summary'],
                    height=150,
                    key="consumer_health_prompt_summary"
                )
                sess['custom_prompts']['consumer_health']['analyze'] = st.text_area(
                    "Analysis Prompt:",
                    value=sess['custom_prompts']['consumer_health']['analyze'],
                    height=150,
                    key="consumer_health_prompt_analyze"
                )
                sess['custom_prompts']['consumer_health']['detail'] = st.text_area(
                    "Detail Prompt:",
                    value=sess['custom_prompts']['consumer_health']['detail'],
                    height=150,
                    key="consumer_health_prompt_detail"
                )
    
                if st.button("🔄 Generate with Custom Prompts", key="generate_consumer_health"):
                    generate_mode = "consumer_health"
    
        st.subheader("Quick Analysis")
        col0, col1, col2, col3 = st.columns(4)
        analyze_overall = col0.button("📑 Overall Summary")
        analyze_tariff = col1.button("🔍 Analyze Tariffs")
        analyze_monthly_performance = col2.button("📈 Analyze Monthly Performance")
        analyze_consumer_health = col3.button("🩺 Analyze Consumer Health")
    
        if generate_mode or analyze_overall or analyze_tariff or analyze_monthly_performance or analyze_consumer_health:
            if not sess['uploaded_files']:
                st.error("Please upload documents first.")
                st.stop()
    
            mode = generate_mode or (
                "overall" if analyze_overall else
                "tariff" if analyze_tariff else
                "monthly_performance" if analyze_monthly_performance else
                "consumer_health" if analyze_consumer_health else None
            )
    
            agent = None
    
            if mode == "overall":
                agent = st.session_state.agent_overall
            elif mode == "tariff":
                agent = st.session_state.agent_tariff
            elif mode == "monthly_performance":
                agent = st.session_state.agent_monthly_performance
            elif mode == "consumer_health":
                agent = st.session_state.agent_consumer_health
    
            sess[f'processed_files_{mode}'] = {}
            processed_files = sess[f'processed_files_{mode}']
    
            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.replace('consumer_health','consumer health').replace('monthly_performance','monthly performance')} analysis")
            else:
                if mode == "overall":
                    agent.prompt_summary = OverallAgent.prompt_summary
                    agent.prompt_analyze = OverallAgent.prompt_analyze
                    agent.prompt_detail = OverallAgent.prompt_detail
                elif mode == "tariff":
                    agent.prompt_summary = TariffTradeAgent.prompt_summary
                    agent.prompt_analyze = TariffTradeAgent.prompt_analyze
                    agent.prompt_detail = TariffTradeAgent.prompt_detail
                elif mode == "monthly_performance":
                    agent.prompt_summary = MonthlyPerformanceAgent.prompt_summary
                    agent.prompt_analyze = MonthlyPerformanceAgent.prompt_analyze
                    agent.prompt_detail = MonthlyPerformanceAgent.prompt_detail
                elif mode == "consumer_health":
                    agent.prompt_summary = ConsumerHealthAgent.prompt_summary
                    agent.prompt_analyze = ConsumerHealthAgent.prompt_analyze
                    agent.prompt_detail = ConsumerHealthAgent.prompt_detail
    
            with st.spinner(f"🔍 Analyzing {mode.replace('consumer_health', 'consumer health').replace('monthly_performance', 'monthly performance')} documents..."):
                analyze_documents(
                    mode,
                    agent,
                    processed_files,
                    sess
                )
    
        last_mode = sess['last_analysis_mode']
        if last_mode is None:
            st.info("Select an analysis type to begin.")
            return
    
        mode_config = {
            'overall': {
                'files': sess['processed_files_overall'],
                'summary': sess['consolidated_summary_overall'],
                'sidebar_header': "Overall Topics",
                'main_header': "🌟 Executive Summary",
                'agent': st.session_state.agent_overall
            },
            'tariff': {
                'files': sess['processed_files_tariff'],
                'summary': sess['consolidated_summary_tariff'],
                'sidebar_header': "Tariff Topics",
                'main_header': "🌟 Tariff Analysis",
                'agent': st.session_state.agent_tariff
            },
            'monthly_performance': {
                'files': sess['processed_files_monthly_performance'],
                'summary': sess['consolidated_summary_monthly_performance'],
                'sidebar_header': "Monthly Performance Topics",
                'main_header': "🌟 Monthly Performance Analysis",
                'agent': st.session_state.agent_monthly_performance
            },
            'consumer_health': {
                'files': sess['processed_files_consumer_health'],
                'summary': sess['consolidated_summary_consumer_health'],
                'sidebar_header': "Consumer Health Topics",
                'main_header': "🌟 Consumer Health Analysis",
                'agent': st.session_state.agent_consumer_health
            }
        }
    
        current_mode = mode_config[last_mode]
    
        # --- Sidebar Topics ---
        st.sidebar.header(current_mode['sidebar_header'])
    
        if last_mode == "overall":
            topics_by_file = {}
            for filename, filedata in current_mode['files'].items():
                for topic in filedata["topics"]:
                    topics_by_file.setdefault(topic['name'], []).append({
                        'file': filename,
                        'score': topic['score']
                    })
    
            sorted_topics = sorted(topics_by_file.items(),
                                   key=lambda x: max(x[1], key=lambda y: y['score'])['score'],
                                   reverse=True)
            before_view_more, after_view_more = sorted_topics[:3], sorted_topics[3:]
    
            for topic_name, occurrences in before_view_more:
                total_score = sum(occ['score'] for occ in occurrences)
                file_count = len(occurrences)
                btn_label = f"{topic_name} (📈 {total_score:.1f} | 📑 {file_count})"
    
                if st.sidebar.button(
                    btn_label,
                    key=f"overall_topic_{topic_name}",
                    use_container_width=True,
                ):
                    sess['active_topic'] = topic_name
                    sess['active_file'] = None
    
            if after_view_more and st.sidebar.button('View More', key='1234', use_container_width=True):
                for topic_name, occurrences in after_view_more:
                    total_score = sum(occ['score'] for occ in occurrences)
                    file_count = len(occurrences)
                    btn_label = f"{topic_name} (📈 {total_score:.1f} | 📑 {file_count})"
    
                    if st.sidebar.button(
                        btn_label,
                        key=f"overall_topic_more_{topic_name}",
                        use_container_width=True,
                    ):
                        sess['active_topic'] = topic_name
                        sess['active_file'] = None
    
        else:  # tariff, monthly_performance, consumer_health
            for filename, filedata in current_mode['files'].items():
                expanded = (filename == sess['active_file'])
                with st.sidebar.expander(f"📄 {filename}", expanded=expanded):
                    topics = sorted(filedata["topics"], key=lambda t: t["score"], reverse=True)
                    for topic in topics[:3]:
                        is_selected = (
                            sess['active_file'] == filename and sess['active_topic'] == topic['name']
                        )
                        style = "primary" if is_selected else "secondary"
    
                        if st.button(
                            f"• {topic['name']} (Score: {topic['score']})",
                            key=f"{last_mode}_topic_{filename}_{topic['name']}",
                            type=style,
                            use_container_width=True,
                        ):
                            sess['active_file'] = filename
                            sess['active_topic'] = topic['name']
    
                    if len(topics) > 3 and st.sidebar.button(f'View More for {filename}', key=f'{filename}_view_more', use_container_width=True):
                        for topic in topics[3:]:
                            is_selected = (
                                sess['active_file'] == filename and sess['active_topic'] == topic['name']
                            )
                            style = "primary" if is_selected else "secondary"
    
                            if st.button(
                                f"• {topic['name']} (Score: {topic['score']})",
                                key=f"{last_mode}_topic_more_{filename}_{topic['name']}",
                                type=style,
                                use_container_width=True,
                            ):
                                sess['active_file'] = filename
                                sess['active_topic'] = topic['name']
    
        # --- Topic Detail Analysis ---
        st.subheader("Detailed Analysis")
        if last_mode == "overall" and sess['active_topic']:
            mentions = []
            for filename, filedata in current_mode['files'].items():
                for topic in filedata["topics"]:
                    if topic['name'] == sess['active_topic']:
                        mentions.append({
                            'file': filename,
                            'summary': topic.get('summary', ''),
                            'score': topic['score'],
                            'context': filedata['context']
                        })
    
            with st.expander("📊 Topic Prevalence"):
                cols = st.columns(3)
                cols[0].metric("Total Documents", len(mentions))
                avg_relevance = (sum(m['score'] for m in mentions) / len(mentions)) if mentions else 0
                cols[1].metric("Average Relevance", f"{avg_relevance:.1f}")
                cols[2].metric("First Mentioned", mentions[0]['file'] if mentions else "N/A")
    
            if mentions:
                combined_context = "\n\n".join(f"=== {m['file']} ===\n{m['context']}" for m in mentions)
                key_cache = (last_mode, sess['active_topic'])
                if key_cache in sess['topic_details_cache']:
                    st.markdown(sess['topic_details_cache'][key_cache])
                else:
                    placeholder = st.empty()
                    collected_text = ""
                    try:
                        for chunk in current_mode['agent'].generate_topic_detail(combined_context, sess['active_topic']):
                            collected_text = chunk
                            placeholder.markdown(collected_text + (" ▌" if "▌" in collected_text else ""))
                        sess['topic_details_cache'][key_cache] = collected_text
                        markdown_to_word(collected_text, sess['active_topic']+'.docx')
                        with open(sess['active_topic']+'.docx', 'rb') as f:
                            st.download_button("Download Doc", f, file_name=sess['active_topic']+'.docx')
    
                    except Exception as e:
                        st.error(f"Analysis error: {str(e)}")
    
        elif sess['active_file'] and sess['active_topic']:
            key_cache = (last_mode, sess['active_file'], sess['active_topic'])
            if key_cache in sess['topic_details_cache']:
                st.markdown(sess['topic_details_cache'][key_cache])
            else:
                placeholder = st.empty()
                collected_text = ""
                try:
                    for chunk in current_mode['agent'].generate_topic_detail(
                        current_mode['files'][sess['active_file']]['context'],
                        sess['active_topic'],
                    ):
                        collected_text = chunk
                        placeholder.markdown(collected_text + (" ▌" if "▌" in collected_text else ""))
                    sess['topic_details_cache'][key_cache] = collected_text
                    markdown_to_word(collected_text, sess['active_topic']+'.docx')
                    with open(sess['active_topic']+'.docx', 'rb') as f:
                        st.download_button("Download Doc", f, file_name=sess['active_topic']+'.docx')
    
    
                except Exception as e:
                    st.error(f"Analysis error: {str(e)}")
        else:
            st.info("Select a topic from the sidebar")
    
        st.markdown("---")
    
        st.header(current_mode['main_header'])
        if current_mode['summary']:
            st.markdown(current_mode['summary'])
            markdown_to_word(current_mode['summary'], current_mode['sidebar_header']+'.docx')
            with open(current_mode['sidebar_header']+'.docx', 'rb') as f:
                st.download_button("Download Doc", f, file_name=current_mode['sidebar_header']+'.docx')
    
        else:
            st.info("Summary not available yet")
    
        st.divider()
    
        # --- Chat Interface ---
        st.subheader("💬 Document Chat")
    
        available_files = list(current_mode['files'].keys())
        selected_files = st.multiselect(
            "Select documents for context:",
            available_files,
            key=f"chat_selector_{last_mode}"
        )
    
        for msg in sess['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 documents first")
                st.stop()
    
            sess['chat_history'].append({
                "role": "user",
                "content": question,
                "timestamp": datetime.utcnow().isoformat(),
            })
    
            try:
                context = "\n\n".join([
                    f"=== {fname} ===\n{current_mode['files'][fname]['context']}"
                    for fname in selected_files
                ])
    
                with st.chat_message("assistant"):
                    response_placeholder = st.empty()
                    full_response = ""
                    q_type = None
    
                    for chunk, q_type in st.session_state.chat_agent.generate_answer(question, context):
                        full_response = chunk
                        response_placeholder.markdown(full_response + " ▌")
    
                    response_placeholder.markdown(full_response)
    
                    sess['chat_history'].append({
                        "role": "assistant",
                        "content": full_response,
                        "timestamp": datetime.utcnow().isoformat(),
                        "analysis_type": q_type
                    })
    
            except Exception as e:
                st.error(f"Chat error: {str(e)}")
                sess['chat_history'].append({
                    "role": "assistant",
                    "content": f"Error: {str(e)}",
                    "timestamp": datetime.utcnow().isoformat(),
                })
    
        if st.button("🔄 Reset Session", type="secondary"):
            preserved_keys = [
                "client", "agent_overall", "agent_tariff",
                "agent_monthly_performance", "agent_consumer_health", "chat_agent", "provider"
            ]
            preserved = {k: st.session_state[k] for k in preserved_keys if k in st.session_state}
    
            st.session_state.clear()
            st.session_state.update(preserved)
    
            st.session_state.session = {
                'uploaded_files': {},
                'processed_files_overall': {},
                'processed_files_tariff': {},
                'processed_files_monthly_performance': {},
                'processed_files_consumer_health': {},
                'active_file': None,
                'active_topic': None,
                'topic_details_cache': {},
                'chat_history': [],
                'consolidated_summary_overall': None,
                'consolidated_summary_tariff': None,
                'consolidated_summary_monthly_performance': None,
                'consolidated_summary_consumer_health': None,
                'last_analysis_mode': None,
                'custom_prompt_enabled': {},
                'custom_prompt_text': {}
            }
    
            st.rerun()
    
    
    def qa_page():
        st.title("❓ Macy's Question Assistant")
    
        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_clients_and_agents(provider_select, mode="qa")
    
        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:
                                    qa_data = st.session_state.agent_qa.analyze_question(text)
                                    qa_state['processed_files'][filename] = {
                                        'text': text,
                                        'qa_data': qa_data
                                    }
                                    st.toast(f"✅ Processed {filename}")
    
                                    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)}")
    
                if not qa_state['active_file'] and qa_state['processed_files']:
                    qa_state['active_file'] = next(iter(qa_state['processed_files'].keys()))
    
        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
                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]
    
        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")
    
            if "error" in qa_data:
                st.sidebar.error("Error in document processing")
    
            elif 'topics' in qa_data:
                topics = qa_data['topics']
    
                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")
    
        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']}")
    
            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)
    
            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}")
    
            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()
    
                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']:
                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()
    
        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(),
                })
    
        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()
    

    Summary of replacements:

    • SalesAgent → MonthlyPerformanceAgent
    • SupplyChainAgent → ConsumerHealthAgent
    • All references to Sales replaced by Monthly Performance
    • All references to Supply Chain replaced by Consumer Health
    • Sidebar tabs, buttons, checkbox keys, session keys, variables, etc. changed accordingly.

    Make sure the new agents MonthlyPerformanceAgent and ConsumerHealthAgent exist and are implemented the same way as the original ones.

    If you want me to provide example skeletons of those agents or help migrating those modules as well, just ask!

  3. User

    can you change the prompts according to ConsumerHealth agent

    from agents.base_agent import BaseAgent

    class SupplyChainAgent(BaseAgent): prompt_sys = "Supply chain analyst for Macy's works for only provided documents"

     # Universal formatting enforcement line
    formatting_directive = """Please follow these formatting guidelines:
    
    1. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. Time Formatting: Q4 2024 (never Q42024 or 4th quarter)
    3. Number Rules:
      • 3.3B → 3.3 billion
      • 150.2M → 150.2 million
      • 0.33 → keep exact decimal
    4. Text Integrity:
      • "net income" never "netincome"
      • "year-over-year" never "YOY" or "yearoveryear"
    5. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    6. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. ALWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED

    APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES."""

    prompt_analyze = """You are a senior supply chain analyst specializing in logistics and procurement for Macy's operations.  
    

    You have received a transcript/document from another company.

    Identify all significant supply chain and logistics topics in the text from all the files that could affect Macy's procurement, inventory, delivery timelines, and supplier relationships.

    For each topic, provide:

    • A concise topic name (e.g., "Port Congestion", "Supplier Delays").
    • A brief describing in 200 words including its impact on Macy's supply chain operations also include Overview of the topic, Key insights and relevant excerpts, Important figures, timelines, or operational metrics, Detailed analysis on impact to Macy's supply chain, procurement, and logistics.
    • A relevance score from 1 (minor) to 10 (critical).

    Format your response one topic per line:

    • Topic Name: Summary [Relevance Score]

    Example lines:

    • Port Congestion: Delays expected affecting inventory availability [9]
    • Supplier Delay: Lead times extended due to supplier issues [8]

    Analyze this external document:""" + formatting_directive

    prompt_summary = """You are a senior supply chain analyst preparing a consolidated supply chain and procurement report for Macy's executive team from all document provided.
    

    You have reviewed supply chain and logistics topics extracted from multiple external company documents. These topics include their names, summaries, and relevance scores. Based on their content, please:

    1. OverView: Identify and describe all their impactful supply chain and logistics topics that could affect Macy's inventory management, procurement, delivery timelines, and supplier relationships.

    2. For each topic:

      • Provide a concise summary from combining all the relevant documents.
      • Include relevant metrics, timelines, or examples from the documents also provide from which document it is taken.
      • Explain operational and strategic impacts—positive , negative, or neutral—specifically tailored to Macy's supply chain and logistics.
      • Provide 3-5 actionable strategic recommendations for Macy's leadership.
      • For every topic, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows:
        • For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.
        • Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name)
        • If a same topic is present in multiple documents, always include a separate "Ground Truth" excerpt for each document with proper line breaks.
        • Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters.
        • If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.
    3. Format in clear sections in black text with proper headings:

      • Executive Summary
      • Key Themes
      • Strategic Recommendations
      • Risk Assessment
    4. Avoid jargon and focus on practical operational impacts and strategy insights.

    Use Documents Analysis Data from all the documents provided below try combining the same topics from different documents and provide the summary of all the topics in one place.: {topics_block}

    Deliver a detailed, actionable consolidated supply chain report for Macy's.""" + formatting_directive

    prompt_detail = """You are preparing a detailed briefing for Macy's CEO on the supply chain topic '{topic}', based on the external company document.
    

    Provide:

    1. Overview of the topic.
    2. Key insights and relevant excerpts.
    3. Important figures, timelines, or operational metrics.
    4. Detailed analysis on impact to Macy's supply chain, procurement, and logistics.
    5. 3-5 actionable recommendations for Macy's leadership.
    6. For every topic, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Ground Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.

    Document: {text}

    Topic: {topic}

    Please provide structured briefing with proper paragraphs and bold topics. """ + formatting_directive

    def analyze_document(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(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(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)
    

    change according to below suggestions

    Prompt: Summarize what the company said regarding consumer health and the macro environment. If no detail is provided, say “N/A”. Pull in details on what the company says about the US consumer, their customer, a change in demand and/or a change in spend.

    You are a senior analyst preparing a summary of transcript commentary from all documents provided. Identify and describe all mentions of consumer financial health and the macroeconomic environment in the provided documents, focusing on what the company says about the US consumer, their customer, a change in demand or a change in spend. Combine and synthesize topics that appear in multiple documents.

    1. Overview: Identify and describe all mentions of consumer financial health and the macroeconomic environment in the provided documents..

    2. For each topic:

      • Provide a concise summary by combining information from all relevant documents.
      • Include relevant examples, numerical data, or timelines from the documents.
      • For every topic, ALWAYS provide each excerpts mentioned under the heading "Ground Truth" as follows:
        • For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.
        • Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name)
        • If a same topic is present in multiple documents, always include a separate "Ground Truth" excerpt for each document with proper line breaks.
        • Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the documents data exactly, including all formatting, punctuation, and special characters.
        • If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the document.
    3. Format in clear with sections in black text with proper headings:

      • Consumer Health Summary

    Use the following Documents Analysis Data to combine similar topics from different documents and provide a comprehensive summary: {topics_block}

    Provide comprehensive yet concise summary. STRICTLY ENFORCE PLAIN TEXT FORMATTING: 2. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion) 3. Time Formatting: Q4 2024 (never Q42024 or 4th quarter) 4. Number Rules:

    • 3.3B → 3.3 billion
    • 150.2M → 150.2 million
    • 0.33 → keep exact decimal
    1. Text Integrity:
      • "net income" never "netincome"
      • "year-over-year" never "YOY" or "yearoveryear"
    2. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    3. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    4. ALLWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES. Analysis Prompt You are a senior business analyst working directly for Macy's CEO. Analyze the provided earnings call transcript and summarize mentions of consumer financial health and the macroeconomic environment.

    Identify key topics including but not limited to: US consumer The company’s customer Change in demand Change in spend

    For each topic, provide:

    • A clear topic name (e.g., "E-commerce Growth", "Supply Chain Digitization")
    • Concise 100-word summary providing key numbers and operational impacts
    • Strictly preserve original numerical and textual formatting: maintain exact decimals (0.33), required spacing between numbers/text (0.11 → '0.11'), and verbatim terminology without concatenation or rephrasing.
    • For every topic, ALWAYS provide excerpts mentioned under the heading "Ground Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Ground Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the document data exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the documents. Format each topic as:
    • Topic Name: Summary [Relevance Score]

    Example:

    • Holiday Sales Performance: Q4 comparable sales up 4.2% driven by 18% digital growth [8]
    • Inventory Optimization: Implementing AI demand forecasting to reduce carrying costs by $150M [7] Document Text:STRICTLY ENFORCE PLAIN TEXT FORMATTING:
    1. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. Time Formatting: Q4 2024 (never Q42024 or 4th quarter)
    3. Number Rules:
      • 3.3B → 3.3 billion
      • 150.2M → 150.2 million
      • 0.33 → keep exact decimal
    4. Text Integrity:
      • "net income" never "netincome"
      • "YOY " never "year-over-year" or "yearoveryear"
      • “vs.” never “versus” or “vs”
      • “XB”never“XB” never “X billion”
      • “XM”never“XM” never “X million”
    5. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    6. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. ALLWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES.

    The output should be a summary of the commentary, in 100 words or less. The summary should be in the third person (name of the company, management, the company) We do not need the recommendation to Macy’s management for the specific commentary modules – we just want the bulleted summary of the commentary for each.

  4. Assistant

    Certainly! Below is a revised version of your ConsumerHealthAgent (previously SupplyChainAgent) class, where I have adapted the prompts according to your detailed instructions and requirements.


    from agents.base_agent import BaseAgent
    
    class ConsumerHealthAgent(BaseAgent):
        prompt_sys = "Consumer health and macroeconomic analyst for Macy's, tasked with analyzing provided documents regarding consumer financial health and macro environment."
    
        # Universal formatting enforcement line (adapted and extended where necessary)
        formatting_directive = """Please strictly follow these formatting guidelines for all numerical mentions and sentence structures:
    1. **No Combined Elements**: Always space-separate numbers, words, and units (e.g., "3.3 billion" not "3.3billion").
    2. **Time Formatting**: Use formats like "Q4 2024" (never "Q42024" or "4th quarter").
    3. **Number Rules**:  
       - 3.3B → 3.3 billion  
       - 150.2M → 150.2 million  
       - 0.33 → keep exact decimal  
    4. **Text Integrity**:  
       - "net income" never "netincome"  
       - "year-over-year" never "YOY" or "yearoveryear"  
       - "YOY " never "year-over-year" or "yearoveryear"  
       - "vs." never "versus" or "vs"  
       - "$XB" never "$X billion"  
       - "$XM" never "$X million"  
    5. **Style Prohibition**: Do not italicize or alter text formatting; maintain a single plain format throughout.
    6. **Bad Example**: `3.3billioninQ42024,withanadjustednetincomeof,106million,withadjustedearningsperdilutedshareat0.95` → REJECTED
    7. **ALWAYS Required Format**: `3.3 billion in Q4 2024, with an adjusted net income of` → ACCEPTED
    
    APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES."""
        
        prompt_analyze = (
            "You are a senior business analyst working directly for Macy's CEO. Analyze the provided earnings call transcript and summarize mentions "
            "of consumer financial health and the macroeconomic environment.\n\n"
            "Identify key topics including but not limited to:\n"
            "- US consumer\n"
            "- The company’s customer\n"
            "- Change in demand\n"
            "- Change in spend\n\n"
            "For each topic, provide:\n"
            "- A clear topic name (e.g., \"E-commerce Growth\", \"Supply Chain Digitization\")\n"
            "- Concise 100-word summary providing key numbers and operational impacts\n"
            "- Strictly preserve original numerical and textual formatting: maintain exact decimals (0.33), required spacing (0.11 → '0.11'), and verbatim terminology without concatenation or rephrasing.\n"
            "- For every topic, ALWAYS provide excerpts mentioned under the heading \"Ground Truth\" as follows:\n"
            "      - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.\n"
            "      - Format each excerpt as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "      - If a topic is present in multiple documents, include a separate \"Ground Truth\" excerpt for each document.\n"
            "      - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the document data exactly, including all formatting, punctuation, and special characters.\n"
            "      - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the documents.\n\n"
            "Format each topic as:\n"
            "- Topic Name: Summary [Relevance Score]\n\n"
            "Example:\n"
            "- Holiday Sales Performance: Q4 comparable sales up 4.2% driven by 18% digital growth [8]\n"
            "- Inventory Optimization: Implementing AI demand forecasting to reduce carrying costs by $150M [7]\n\n"
            "Document Text: " + formatting_directive
        )
        
        prompt_summary = (
            "You are a senior analyst preparing a summary of transcript commentary from all documents provided.\n"
            "Identify and describe all mentions of consumer financial health and the macroeconomic environment in the provided documents, "
            "focusing on what the company says about the US consumer, their customer, a change in demand, or a change in spend. Combine and synthesize topics that appear in multiple documents.\n\n"
            "1. **Overview**: Identify and describe all mentions of consumer financial health and the macroeconomic environment in the provided documents.\n\n"
            "2. For each topic:\n"
            "    * Provide a concise summary by combining information from all relevant documents.\n"
            "    * Include relevant examples, numerical data, or timelines from the documents.\n"
            "    * For every topic, ALWAYS provide each excerpt mentioned under the heading \"Ground Truth\" as follows:\n"
            "        - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.\n"
            "        - Format each excerpt as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "        - If the same topic is present in multiple documents, always include a separate \"Ground Truth\" excerpt for each document with proper line breaks.\n"
            "        - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the documents data exactly, including all formatting, punctuation, and special characters.\n"
            "        - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the document.\n\n"
            "3. Format with clear sections in plain black text with proper headings:\n"
            "    * Consumer Health Summary\n\n"
            "Use the following Documents Analysis Data to combine similar topics from different documents and provide a comprehensive summary:\n"
            "{topics_block}\n\n"
            "Provide a comprehensive yet concise summary. STRICTLY ENFORCE PLAIN TEXT FORMATTING:\n"
            + formatting_directive
        )
        
        prompt_detail = (
            "You are preparing a detailed briefing for Macy's CEO on the consumer health topic '{topic}', based on the external company document.\n\n"
            "Provide:\n"
            "1. Overview of the topic.\n"
            "2. Key insights and relevant excerpts.\n"
            "3. Important figures, timelines, or operational metrics.\n"
            "4. Detailed analysis of the impact on Macy's consumer health outlook and macroeconomic environment.\n"
            "5. For every topic, ALWAYS provide verbatim source excerpts under the heading \"Ground Truth\" as follows:\n"
            "      - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.\n"
            "      - Format each excerpt as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "      - If a topic is present in multiple documents, include a separate \"Ground Truth\" excerpt for each document.\n"
            "      - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters.\n"
            "      - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.\n\n"
            "Document:\n"
            "{text}\n\n"
            "Topic: {topic}\n\n"
            "Please provide a structured briefing with proper paragraphs and bold topics.\n"
            + formatting_directive
        )
        
        def analyze_document(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(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(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)
    

    Explanation of key changes:

    • prompt_sys updated to specify consumer health and macroeconomic environment focus.
    • formatting_directive adjusted to your new detailed requirements, strictly enforcing spacing, numerical forms, prohibition of italic/bold, and sample bad/good examples.
    • prompt_analyze asks to identify key topics related to US consumer, demand changes, spend changes, emphasizing strict formatting and provision of verbatim excerpts under "Ground Truth".
    • prompt_summary directs the LLM to provide a comprehensive summary of all documents combined focusing on consumer health & macro environment, giving "Ground Truth" excerpts for every topic.
    • Removed recommendation sections or instructions for management action per your specification.
    • prompt_detail adapted for detailed briefings on a topic focused on consumer health, again with strict "Ground Truth" excerpts and formatting.
    • The methods analyze_document, generate_consolidated_summary_from_topics, and generate_topic_detail appropriately use custom prompts if provided, else default to these updated prompts.

    If you'd like, I can also help you update the import paths and code to reflect this new agent class in your main app!

  5. User

    from agents.base_agent import BaseAgent

    class SalesAgent(BaseAgent): prompt_sys = "Sales analyst for Macy's executive team works for only provided documents"

     # Universal formatting enforcement line
    formatting_directive = """Please follow these formatting guidelines:
    
    1. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. Time Formatting: Q4 2024 (never Q42024 or 4th quarter)
    3. Number Rules:
      • 3.3B → 3.3 billion
      • 150.2M → 150.2 million
      • 0.33 → keep exact decimal
    4. Text Integrity:
      • "net income" never "netincome"
      • "year-over-year" never "YOY" or "yearoveryear"
    5. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    6. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. ALLWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED

    APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES."""

    prompt_analyze = """You are a senior sales analyst specializing in retail sales and consumer behavior, assisting Macy's executive team.  
    

    You have received a transcript/document from another company.

    Identify all significant sales and consumer behavior topics that could affect Macy's retail sales strategy, revenue, marketing effectiveness, and customer engagement.

    For each topic, provide:

    • A concise topic name (e.g., "Holiday Sales Surge", "Online Shopping Trends").
    • A brief describing in 200 words including its relevance or impact on Macy's sales, considering the external company's context, also include An overview of the topic, Key insights and relevant excerpts, Important figures, dates, or timelines, Detailed analysis of the impact on Macy's retail sales, marketing, and customer engagement.
    • A relevance score from 1 (minor) to 10 (critical).

    Format your response one topic per line:

    • Topic Name: Summary [Relevance Score]

    Example:

    • Holiday Sales Boost: Significant increase in sales volume expected during holidays [9]
    • E-commerce Growth: Online shopping rise impacting in-store sales [8]

    Analyze the following external company document:""" + formatting_directive

    prompt_summary = """You are a senior sales analyst preparing a consolidated sales and consumer behavior report for Macy's executive team from all document provided.
    

    You have reviewed sales and consumer behavior topics extracted from multiple external company documents. These topics include their names, summaries, and relevance scores. Based on their content, please:

    1. OverView: Identify and describe from all documents all their impactful sales and consumer behavior topics that could affect Macy's retail sales, marketing, and customer engagement.

    2. For each topic:

      • Provide a concise summary by combining information from all relevant documents.
      • Include relevant examples, numerical data, or timelines from the documents.
      • Explain operational and strategic impacts—positive, negative, or neutral—specifically tailored to Macy's retail business.
      • Provide 3-5 actionable strategic recommendations for Macy's leadership.
      • For every topic, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows:
        • For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.
        • Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name)
        • If a same topic is present in multiple documents, always include a separate "Ground Truth" excerpt for each document with proper line breaks.
        • Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters.
        • If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.
    3. Format in clear with sections in black text with proper headings:

      • Executive Summary
      • Key Themes
      • Strategic Recommendations
      • Risk Assessment
    4. Avoid jargon and focus on actionable insights tailored for Macy's.

    Use Documents Analysis Data from all the documents provided below try combining the same topics from different documents and provide the summary of all the topics in one place.: {topics_block}

    Deliver a detailed, actionable consolidated sales report for Macy's.""" + formatting_directive

    prompt_detail = """You are preparing a detailed briefing for Macy's CEO on the sales topic '{topic}', based on the external company document.
    

    Provide:

    1. An overview of the topic.
    2. Key insights and relevant excerpts.
    3. Important figures, dates, or timelines.
    4. Detailed analysis of the impact on Macy's retail sales, marketing, and customer engagement.
    5. 3-5 actionable recommendations for Macy's leadership.
    6. For every topic, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Ground Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.

    Document: {text}

    Topic: {topic}

    Please provide structured with proper paragraphs and bold topics briefing. """ + formatting_directive

    def analyze_document(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(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(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)
    

    now change this as above but for MonthlyPerformance

    Monthly Performance Prompt: Summarize sales performance for February, March and April. If no detail is provided, say “N/A”.

  6. Assistant

    Certainly! Below is the adapted version of your SalesAgent for MonthlyPerformanceAgent, reflecting the focus on monthly sales performance (February, March, April) and aligned with your provided instructions:

    from agents.base_agent import BaseAgent
    
    class MonthlyPerformanceAgent(BaseAgent):
        prompt_sys = "Monthly performance analyst for Macy's executive team works only with the provided documents."
        
        # Universal formatting enforcement line (same as sales but can customize further if required)
        formatting_directive = """Please follow these formatting guidelines:
    1. **No Combined Elements**: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. **Time Formatting**: Use exact months and quarters such as February, March, April or Q1 2024 (avoid informal or combined forms like Feb2024).
    3. **Number Rules**: 
       - 3.3B → 3.3 billion
       - 150.2M → 150.2 million
       - 0.33 → keep exact decimal
    4. **Text Integrity**: 
       - "net income" never "netincome"
       - "year-over-year" never "YOY" or "yearoveryear"
    5. **Style Prohibition**: Do not make any word in Italic or any other format; always keep it uniform
    6. **Bad Example**: 3.3billioninFeb2024,withanadjustednetincomeof,106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. **ALWAYS Required Format**: 3.3 billion in February 2024, with an adjusted net income of → ACCEPTED
    
    APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES."""
        
        prompt_analyze = (
            "You are a senior monthly performance analyst specializing in analyzing Macy's retail sales for February, March, and April.  "
            "You have received a transcript/document from another company.\n\n"
            "Identify all significant sales performance topics that could affect Macy's monthly sales reporting, revenue trends, and operational effectiveness for the months of February, March, and April.\n\n"
            "For each topic, provide:\n"
            "- A concise topic name (e.g., \"February Sales Growth\", \"April Marketing Impact\").\n"
            "- A brief 200-word description including relevance or impact on Macy's monthly sales performance, covering: overview of the topic, key insights, important figures/dates/timelines (specific to Feb, Mar, Apr), and detailed impact analysis.\n"
            "- A relevance score from 1 (minor) to 10 (critical).\n\n"
            "Format your response one topic per line:\n"
            "- Topic Name: Summary [Relevance Score]\n\n"
            "Example:\n"
            "- February Sales Performance: Comparable sales grew 5.2% driven by strong digital channel growth [8]\n"
            "- March Marketing Campaign: New campaigns boosted foot traffic by 15% [7]\n\n"
            "Analyze the following external company document:" + formatting_directive
        )
        
        prompt_summary = (
            "You are a senior monthly performance analyst preparing a consolidated report on sales performance for the months of February, March, and April for Macy's executive team.\n\n"
            "You have reviewed sales performance topics extracted from multiple external company documents concerning these months. These topics include their names, summaries, and relevance scores. Based on their combined content, please:\n\n"
            "1. **Overview**: Summarize all impactful sales performance topics related to February, March, and April provided in the documents.\n\n"
            "2. For each topic:\n"
            "   * Provide a concise summary by combining information from all relevant documents related to those months.\n"
            "   * Include relevant examples, numerical data, or timelines specific to February, March, and April.\n"
            "   * Explain operational and strategic impacts—positive, negative, or neutral—specifically tailored to Macy's monthly retail business.\n"
            "   * Provide 3-5 actionable strategic recommendations for Macy's leadership.\n"
            "   * For every topic, ALWAYS provide verbatim source excerpts under the heading \"Ground Truth\" as follows:\n"
            "       - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.\n"
            "       - Format each excerpt as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "       - If the same topic is present in multiple documents, include a separate \"Ground Truth\" excerpt for each document with proper line breaks.\n"
            "       - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters.\n"
            "       - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.\n\n"
            "3. Format with clear sections in black text with proper headings:\n"
            "    * Executive Summary\n"
            "    * Key Themes\n"
            "    * Strategic Recommendations\n"
            "    * Risk Assessment\n\n"
            "Use Documents Analysis Data from all the documents provided below. Combine the same topics from different documents and provide the summary of all the topics in one place.\n\n"
            + formatting_directive
        )
        
        prompt_detail = (
            "You are preparing a detailed briefing for Macy's CEO on the monthly performance topic '{topic}', based on the external company document.\n\n"
            "Provide:\n"
            "1. An overview of the topic.\n"
            "2. Key insights and relevant excerpts.\n"
            "3. Important figures, dates, or timelines (with emphasis on February, March, and April).\n"
            "4. Detailed analysis of the impact on Macy's monthly sales performance and operational decisions.\n"
            "5. 3-5 actionable recommendations for Macy's leadership.\n"
            "6. For every topic, ALWAYS provide verbatim source excerpts under the heading \"Ground Truth\" as follows:\n"
            "    - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.\n"
            "    - Format each excerpt as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "    - If a topic is present in multiple documents, include a separate \"Ground Truth\" excerpt for each document.\n"
            "    - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters.\n"
            "    - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.\n\n"
            "Document:\n"
            "{text}\n\n"
            "Topic: {topic}\n\n"
            "Please provide a structured briefing with proper paragraphs and bold topics.\n"
            + formatting_directive
        )
        
        def analyze_document(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(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(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)
    

    Summary of changes:

    • prompt_sys updated to "Monthly performance analyst..."
    • formatting_directive includes strict formatting rules and emphasizes exact month names and formal time formatting.
    • prompt_analyze focuses on identifying and summarizing sales performance topics for February, March, and April, with example topics reflecting those months.
    • prompt_summary asks to consolidate all relevant topics for these 3 months, including actionable recommendations.
    • prompt_detail includes emphasis on these months in figures, dates, timelines, and analysis.
    • No mention of recommendations is removed since the example kept recommendations for Sales - you can remove if wanted.
    • All prompts strongly enforce the formatting rules you provided earlier.

    If you want me to remove recommendations or further tune these prompts, just say!

  7. User

    from agents.base_agent import BaseAgent

    class TariffTradeAgent(BaseAgent): prompt_sys = "Tariff and trade policy analyst for Macy's CEO works for only provided documents"

     # Universal formatting enforcement line
    formatting_directive = """Please follow these formatting guidelines:
    
    1. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. Time Formatting: Q4 2024 (never Q42024 or 4th quarter)
    3. Number Rules:
      • 3.3B → 3.3 billion
      • 150.2M → 150.2 million
      • 0.33 → keep exact decimal
    4. Text Integrity:
      • "net income" never "netincome"
      • "year-over-year" never "YOY" or "yearoveryear"
    5. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    6. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. ALWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED

    APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES."""

    prompt_analyze = """
    

    You are a senior tariff and international trade policy analyst assisting a research team working for the CEO of Macy's.
    You have received a transcript/document from another company.

    Carefully identify all significant tariff, trade, and related government policy topics and detailed briefing in the text of all files that could affect Macy's business operations, including supply chain, procurement, retail sales, and technology.

    For each topic, provide:

    • A clear and concise topic name (e.g., "Vietnam Production Impact", "US-China Tariffs").
    • A brief describing in 200 words including its operational or strategic impact on Macy's retail business, considering the external company's context also include A clear overview of the topic, Key insights and any relevant direct excerpts from the document, Important figures, dates, or timelines if available, Detailed analysis on how this topic could impact Macy's retail operations, supply chain, procurement, and consumer behavior.
    • A relevance score from 1 (minor) to 10 (critical).
    • For every topic, ALWAYS provide verbatim source excerpts under the heading "Source Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Source Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Source Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.

    Format your response as one topic per line in the format from all files:

    • Topic Name: Summary [Relevance Score]

    Example:

    • Vietnam Factory Shutdown: Supply chain delays expected due to production halt in Vietnam [9]
    • Tariff Changes on Apparel: Increased costs on imports from China may raise prices [8]

    Analyze the following external company document for all relevant tariff and trade topics. Text:""" + formatting_directive

    prompt_summary = """
    

    You are a senior tariff and trade analyst preparing a consolidated tariff and trade policy report for Macy's executive team from all document provided.

    You have reviewed tariff and trade topics extracted from multiple external company documents. These topics include their names, summaries, and relevance scores. Based on their content, please:

    1. OverView: Identify and describe from all documents all their impactful tariff, trade, and related government policy topics that could affect Macy's business operations, including supply chain, procurement, retail sales, and technology.

    2. For each topic:

      • Provide a concise summary from combining all the documents.
      • Include relevant examples, numerical data, or timelines from the documents also provide from which document it is taken.
      • Explain operational and strategic impacts—positive, negative, or neutral—specifically tailored to Macy's retail business.
      • Provide 3-5 actionable strategic recommendations for Macy's leadership.
      • For every topic, ALWAYS provide each verbatim source excerpts under the heading "Ground Truth" as follows:
        • For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.
        • Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name)
        • If a topic is present in multiple documents, include a separate "Ground Truth" excerpt for each document with proper line breaks.
        • Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters.
        • If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.
    3. Format in clear markdown with sections in black text with proper headings:

      • Executive Summary
      • Key Themes
      • Strategic Recommendations
      • Risk Assessment
    4. Avoid jargon and focus on practical operational impacts and strategy insights.

    Format your response in markdown with clear headings for each topic.

    Use the following Documents Analysis Data to combine similar topics from different documents and provide a comprehensive summary: {topics_block}

    Deliver a detailed, synthesized, and actionable consolidated tariff and trade policy report for Macy's.""" + formatting_directive

    prompt_detail = """
    

    You are preparing a detailed briefing for Macy's CEO on the tariff and trade policy topic '{topic}', based on the provided external company document.

    Provide:

    1. A clear overview of the topic.
    2. Allways Provide Key insights and relevant excerpts.- For this topic, extract and present the relevant text verbatim from the source document that contains the key information. Ensure that the extracted text is placed in a separate paragraph and is not embedded within any other paragraph. Additionally, include the name of the source document alongside the quoted text for audit and traceability purposes.
    3. Important figures, dates, or timelines if available.
    4. Detailed analysis on how this topic could impact Macy's retail operations, supply chain, procurement, and consumer behavior.
    5. 3-5 actionable strategic recommendations for Macy's leadership. 6 For every topic, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Source Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.

    Document: {text}

    Topic: {topic}

    Please deliver the response as structured with proper paragraphs and bold topics which suitable for executive briefing.""" + formatting_directive

    def analyze_document(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(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(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)
    

    change this also for below

    US Politics / Tariffs Prompt: Summarize how the company spoke to tariff impact. Lead with any country or regional sourcing exposure, if applicable. Then also provide any quantitative financial impact, if applicable. Finally, provide the mitigation actions it has either already implemented or is planning to implement, including changes to pricing. If no detail is provided, say “N/A”.

  8. Assistant

    Certainly! Below is the updated TariffTradeAgent class with prompts changed according to your new instructions for US Politics / Tariffs.
    The new prompts emphasize summarizing tariff impact with focus on country/regional sourcing, financial impact, and mitigation actions.

    from agents.base_agent import BaseAgent
    
    class TariffTradeAgent(BaseAgent):
        prompt_sys = "Tariff and trade policy analyst for Macy's CEO works only with the provided documents."
    
        # Universal formatting enforcement line
        formatting_directive = """Please follow these formatting guidelines:
    1. **No Combined Elements**: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. **Time Formatting**: Q4 2024 (never Q42024 or 4th quarter)
    3. **Number Rules**: 
       - 3.3B → 3.3 billion
       - 150.2M → 150.2 million
       - 0.33 → keep exact decimal
    4. **Text Integrity**: 
       - "net income" never "netincome"
       - "year-over-year" never "YOY" or "yearoveryear"
    5. **Style Prohibition**: Do not make any word in Italic or any other format always make it in one format
    6. **Bad Example**: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. **ALWAYS Required Format**: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED
    
    APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES."""
    
        prompt_analyze = """
    You are a senior tariff and international trade policy analyst assisting a research team working for the CEO of Macy's.
    You have received a transcript/document from another company.
    
    Summarize how the company spoke to tariff impacts, with emphasis on:
    
    - Any country or regional sourcing exposure, if applicable.
    - Quantitative financial impact, if applicable.
    - Mitigation actions the company has already implemented or plans to implement, including pricing changes.
    
    If no detail is provided, state "N/A".
    
    Format your response in clear, concise paragraphs suitable for an executive briefing.
    
    Analyze the following external company document for relevant US politics and tariff impact information. Text:
    """ + formatting_directive
    
        prompt_summary = """
    You are a senior tariff and trade analyst preparing a consolidated report regarding US politics and tariff impacts for Macy's executive team from all provided documents.
    
    You have reviewed tariff impact topics extracted from multiple external company documents. Based on their content, please:
    
    1. Summarize how the company spoke to tariff impact overall.
    2. Lead with any country or regional sourcing exposure, specifying countries or regions if applicable.
    3. Provide any quantitative financial impact mentioned.
    4. Detail mitigation actions already implemented or planned, including any changes to pricing strategies.
    5. If no detail is available, clearly state "N/A".
    
    For every statement, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows:
       - Extract exact, unmodified sentences or paragraphs from the original documents.
       - Format each excerpt as: **Ground Truth:** "Exact text from the document..." (Document Name)
       - If present in multiple documents, include separate excerpts accordingly.
       - Do NOT paraphrase, summarize, or alter the original text; maintain exact formatting and punctuation.
       - Do NOT fabricate or modify excerpts if not present.
    
    Format your output in markdown with clear section headings.
    
    Use the following Documents Analysis Data to combine similar tariff impact topics from different documents and provide a comprehensive, actionable summary:
    {topics_block}
    
    """ + formatting_directive
    
        prompt_detail = """
    You are preparing a detailed briefing for Macy's CEO on the US politics and tariff impact topic '{topic}', based on the provided external company document.
    
    Please provide:
    1. A clear overview of how tariffs affect sourcing exposure by country or region.
    2. Quantitative financial impacts if any are mentioned.
    3. Detailed descriptions of mitigation actions implemented or planned, including pricing strategy changes.
    4. For every point, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows:
        - Extract exact, unmodified sentence(s) or paragraph(s) from the original document.
        - Format each excerpt as: **Ground Truth:** "Exact text from the document..." (Document Name)
        - If the topic appears in multiple documents, include separate excerpts.
        - Do NOT paraphrase, summarize, or alter the original text.
        - Do NOT fabricate or modify excerpts if not present in the source.
    
    Document:
    {text}
    
    Topic: {topic}
    
    Please deliver a structured response with proper paragraphs and bolded topics, suitable for executive briefing.
    """ + formatting_directive
    
        def analyze_document(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(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(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)
    

    Summary of changes:

    • prompt_analyze now tells the model to summarize tariff impact focusing on sourcing exposure, financial impact, mitigation actions, and pricing changes, or say "N/A" if no information.
    • prompt_summary requests a consolidated report emphasizing these same points, with verbatim "Ground Truth" excerpts.
    • prompt_detail gives the same focus for detailed briefings.
    • All preserve your strict formatting directive for numbers, punctuation, and plain text style.

    If you want these prompts adjusted in tone, structure, or detail level, just ask!

  9. User

    no as per above monthly and consumer we need to do in this alos

  10. Assistant

    Got it! You want the TariffTradeAgent prompts updated to follow the same detailed style and formatting enforcement as the ConsumerHealthAgent and MonthlyPerformanceAgent, with structured instructions, strict formatting rules, emphasis on explicit "Ground Truth" excerpts, and suitable for executive briefings — but specific to the tariff topic you gave:

    Prompt: Summarize how the company spoke to tariff impact. Lead with any country or regional sourcing exposure, if applicable. Then also provide any quantitative financial impact, if applicable. Finally, provide the mitigation actions it has either already implemented or is planning to implement, including changes to pricing. If no detail is provided, say “N/A”.


    Here is the full adapted TariffTradeAgent class, updated for the style and detail level you want:

    from agents.base_agent import BaseAgent
    
    class TariffTradeAgent(BaseAgent):
        prompt_sys = "Tariff and trade policy analyst for Macy's CEO works only with the provided documents."
    
        # Universal formatting enforcement line (same style as ConsumerHealthAgent and MonthlyPerformanceAgent)
        formatting_directive = """Please follow these formatting guidelines strictly:
    1. **No Combined Elements**: Always space-separate numbers, words, and units (e.g., '3.3 billion' not '3.3billion')
    2. **Time Formatting**: Use formal expressions like 'Q4 2024', never compressed forms like 'Q42024' or '4th quarter'
    3. **Number Rules**:
       - 3.3B → 3.3 billion
       - 150.2M → 150.2 million
       - 0.33 → keep exact decimal values as is
    4. **Text Integrity**:
       - 'net income' never 'netincome'
       - 'year-over-year' never 'YOY' or 'yearoveryear'
       - 'vs.' never 'versus' or 'vs'
       - '$XB' never '$X billion'
       - '$XM' never '$X million'
    5. **Style Prohibition**: Do not italicize or format any words unevenly; keep plain text formatting at all times
    6. **Bad Example**: 3.3billioninQ42024,withanadjustednetincomeof,106million,... → REJECTED
    7. **ALWAYS Required Format**: 3.3 billion in Q4 2024, with an adjusted net income of ... → ACCEPTED
    
    APPLY THESE RULES TO ALL NUMERICAL MENTIONS, DATES, AND SENTENCE STRUCTURES."""
    
        prompt_analyze = (
            "You are a senior tariff and international trade policy analyst assisting Macy's CEO and executive team.\n\n"
            "From the provided transcript/document, please summarize how the company discussed tariff impacts.\n\n"
            "Your summary should be structured as follows:\n"
            "- Lead with any country or regional sourcing exposure related to tariffs, specifying countries or regions if applicable.\n"
            "- Include any quantitative financial impact mentioned, such as costs, margins, or revenues affected.\n"
            "- Describe mitigation actions the company has already implemented or plans to implement, including any pricing changes.\n"
            "- If no relevant detail is present, explicitly state \"N/A\".\n\n"
            "For every point, ALWAYS include verbatim excerpts under the heading \"Ground Truth\", formatted exactly as follows:\n"
            "  - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s).\n"
            "  - Format each excerpt as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "  - Include separate excerpts for multiple documents if applicable.\n"
            "  - Do NOT paraphrase or alter excerpts in any way.\n\n"
            "Write your response in clear, structured paragraphs suitable for an executive briefing.\n\n"
    
            "Analyze the following external company document text:\n"
            + formatting_directive
        )
    
        prompt_summary = (
            "You are a senior tariff and trade policy analyst preparing a consolidated report for Macy's executive team.\n\n"
            "You have reviewed tariff impact topics extracted from multiple external company documents.\n"
            "Please deliver a comprehensive summary that includes:\n\n"
            "1. A clear summary of the company’s commentary on tariff impacts.\n"
            "2. Leading with any country or regional sourcing exposure related to tariffs.\n"
            "3. Any quantitative financial impacts described.\n"
            "4. Mitigation actions the company has implemented or plans to implement, including pricing changes.\n"
            "5. If no information was provided on these points, state \"N/A\" explicitly.\n\n"
            "For every part, ALWAYS include corresponding verbatim excerpts under the heading \"Ground Truth\" as follows:\n"
            "  - Extract the exact, unmodified sentences or paragraphs from the source documents.\n"
            "  - Format excerpts as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "  - If a point is referenced in multiple documents, include separate excerpts.\n"
            "  - Do NOT paraphrase or alter in any way.\n\n"
            "Structure your response in markdown with clear section headings.\n\n"
            "Use the following Documents Analysis Data ({topics_block}) to combine and synthesize key insights.\n\n"
            + formatting_directive
        )
    
        prompt_detail = (
            "You are preparing a detailed briefing for Macy's CEO on the topic '{topic}' regarding US politics and tariff impacts,\n"
            "based on the provided external company document.\n\n"
            "Please cover:\n"
            "1. Clear discussion of sourcing exposure by country or region related to tariffs.\n"
            "2. Quantitative financial impacts, if any.\n"
            "3. Mitigation steps taken or planned, including any pricing strategy adjustments.\n"
            "4. For every section, ALWAYS provide verbatim source excerpts under the heading \"Ground Truth\" as follows:\n"
            "   - Extract exact, unmodified sentence(s) or paragraphs from the document.\n"
            "   - Format excerpts as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "   - Include separate excerpts for multiple documents where applicable.\n"
            "   - Do NOT paraphrase or alter original text.\n"
            "   - Do NOT fabricate or guess excerpts.\n\n"
            "Document:\n"
            "{text}\n\n"
            "Topic: {topic}\n\n"
            "Provide your response structured with clear paragraphs and bold section headings, suitable for executive-level briefing.\n\n"
            + formatting_directive
        )
    
        def analyze_document(self, text, custom_prompt=None):
            prompt = custom_prompt if custom_prompt else self.prompt_analyze
            return super().analyze_document(self.prompt_sys, prompt, text)
    
        def generate_consolidated_summary_from_topics(self, processed_files, custom_prompt=None):
            prompt = custom_prompt if custom_prompt else self.prompt_summary
            return super().generate_consolidated_summary_from_topics(self.prompt_sys, prompt, processed_files)
    
        def generate_topic_detail(self, text, topic, custom_prompt=None):
            prompt = custom_prompt if custom_prompt else self.prompt_detail
            return super().generate_topic_detail(self.prompt_sys, prompt, text, topic)
    

    Explanation

    • The prompt_sys defines the analyst role and context.
    • The formatting_directive enforces strict formatting rules, matching those from your Consumer Health and Monthly Performance agents.
    • The prompt_analyze instructs the model to focus on tariff impacts, sourcing by country/region, financials, mitigation steps, or say "N/A".
    • The prompt_summary synthesizes tariff impacts across documents similarly.
    • The prompt_detail prepares detailed briefings with verbatim excerpts.
    • All prompts instruct the model to produce verbatim source excerpts under "Ground Truth" in the specified format.
    • Prompts are designed for plain text, non-formatted, no jargon, executive suitable responses.

    If you want me to help integrate this with your main app or further polish phrasing, I’m happy to do that!

  11. User

    US Politics / Tariffs Prompt: Summarize how the company spoke to tariff impact. Lead with any country or regional sourcing exposure, if applicable. Then also provide any quantitative financial impact, if applicable. Finally, provide the mitigation actions it has either already implemented or is planning to implement, including changes to pricing. If no detail is provided, say “N/A”.

    You are a senior analyst preparing a summary of transcript commentary from all documents provided. Identify and describe all mentions of consumer financial health and the macroeconomic environment in the provided documents, focusing on what the company says about the US consumer, their customer, a change in demand or a change in spend. Combine and synthesize topics that appear in multiple documents.

    1. Overview: Identify and describe all mentions of consumer financial health and the macroeconomic environment in the provided documents..

    2. For each topic:

      • Provide a concise summary by combining information from all relevant documents.
      • Include relevant examples, numerical data, or timelines from the documents.
      • For every topic, ALWAYS provide each excerpts mentioned under the heading "Ground Truth" as follows:
        • For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.
        • Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name)
        • If a same topic is present in multiple documents, always include a separate "Ground Truth" excerpt for each document with proper line breaks.
        • Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the documents data exactly, including all formatting, punctuation, and special characters.
        • If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the document.
    3. Format in clear with sections in black text with proper headings:

      • Consumer Health Summary

    Use the following Documents Analysis Data to combine similar topics from different documents and provide a comprehensive summary: {topics_block}

    Provide comprehensive yet concise summary. STRICTLY ENFORCE PLAIN TEXT FORMATTING: 2. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion) 3. Time Formatting: Q4 2024 (never Q42024 or 4th quarter) 4. Number Rules:

    • 3.3B → 3.3 billion
    • 150.2M → 150.2 million
    • 0.33 → keep exact decimal
    1. Text Integrity:
      • "net income" never "netincome"
      • "year-over-year" never "YOY" or "yearoveryear"
    2. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    3. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    4. ALLWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES. Analysis Prompt You are a senior business analyst working directly for Macy's CEO. Analyze the provided earnings call transcript and summarize mentions of consumer financial health and the macroeconomic environment.

    Identify key topics including but not limited to: US consumer The company’s customer Change in demand Change in spend

    For each topic, provide:

    • A clear topic name (e.g., "E-commerce Growth", "Supply Chain Digitization")
    • Concise 100-word summary providing key numbers and operational impacts
    • Strictly preserve original numerical and textual formatting: maintain exact decimals (0.33), required spacing between numbers/text (0.11 → '0.11'), and verbatim terminology without concatenation or rephrasing.
    • For every topic, ALWAYS provide excerpts mentioned under the heading "Ground Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Ground Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the document data exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the documents. Format each topic as:
    • Topic Name: Summary [Relevance Score]

    Example:

    • Holiday Sales Performance: Q4 comparable sales up 4.2% driven by 18% digital growth [8]
    • Inventory Optimization: Implementing AI demand forecasting to reduce carrying costs by $150M [7] Document Text:STRICTLY ENFORCE PLAIN TEXT FORMATTING:
    1. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. Time Formatting: Q4 2024 (never Q42024 or 4th quarter)
    3. Number Rules:
      • 3.3B → 3.3 billion
      • 150.2M → 150.2 million
      • 0.33 → keep exact decimal
    4. Text Integrity:
      • "net income" never "netincome"
      • "YOY " never "year-over-year" or "yearoveryear"
      • “vs.” never “versus” or “vs”
      • “XB”never“XB” never “X billion”
      • “XM”never“XM” never “X million”
    5. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    6. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. ALLWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES.

    change the below code as per above from agents.base_agent import BaseAgent

    class TariffTradeAgent(BaseAgent): prompt_sys = "Tariff and trade policy analyst for Macy's CEO works for only provided documents"

     # Universal formatting enforcement line
    formatting_directive = """Please follow these formatting guidelines:
    
    1. No Combined Elements: Always space-separate numbers/words/units (3.3 billion not 3.3billion)
    2. Time Formatting: Q4 2024 (never Q42024 or 4th quarter)
    3. Number Rules:
      • 3.3B → 3.3 billion
      • 150.2M → 150.2 million
      • 0.33 → keep exact decimal
    4. Text Integrity:
      • "net income" never "netincome"
      • "year-over-year" never "YOY" or "yearoveryear"
    5. Style Prohibition: Do not make any word in Italic or any other format always make it in one format
    6. Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. ALWAYS Required Format: 3.3 billion in Q4 2024, with an adjusted net income of → ACCEPTED

    APPLY THESE RULES TO ALL NUMERICAL MENTIONS AND SENTENCE STRUCTURES."""

    prompt_analyze = """
    

    You are a senior tariff and international trade policy analyst assisting a research team working for the CEO of Macy's.
    You have received a transcript/document from another company.

    Carefully identify all significant tariff, trade, and related government policy topics and detailed briefing in the text of all files that could affect Macy's business operations, including supply chain, procurement, retail sales, and technology.

    For each topic, provide:

    • A clear and concise topic name (e.g., "Vietnam Production Impact", "US-China Tariffs").
    • A brief describing in 200 words including its operational or strategic impact on Macy's retail business, considering the external company's context also include A clear overview of the topic, Key insights and any relevant direct excerpts from the document, Important figures, dates, or timelines if available, Detailed analysis on how this topic could impact Macy's retail operations, supply chain, procurement, and consumer behavior.
    • A relevance score from 1 (minor) to 10 (critical).
    • For every topic, ALWAYS provide verbatim source excerpts under the heading "Source Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Source Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Source Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.

    Format your response as one topic per line in the format from all files:

    • Topic Name: Summary [Relevance Score]

    Example:

    • Vietnam Factory Shutdown: Supply chain delays expected due to production halt in Vietnam [9]
    • Tariff Changes on Apparel: Increased costs on imports from China may raise prices [8]

    Analyze the following external company document for all relevant tariff and trade topics. Text:""" + formatting_directive

    prompt_summary = """
    

    You are a senior tariff and trade analyst preparing a consolidated tariff and trade policy report for Macy's executive team from all document provided.

    You have reviewed tariff and trade topics extracted from multiple external company documents. These topics include their names, summaries, and relevance scores. Based on their content, please:

    1. OverView: Identify and describe from all documents all their impactful tariff, trade, and related government policy topics that could affect Macy's business operations, including supply chain, procurement, retail sales, and technology.

    2. For each topic:

      • Provide a concise summary from combining all the documents.
      • Include relevant examples, numerical data, or timelines from the documents also provide from which document it is taken.
      • Explain operational and strategic impacts—positive, negative, or neutral—specifically tailored to Macy's retail business.
      • Provide 3-5 actionable strategic recommendations for Macy's leadership.
      • For every topic, ALWAYS provide each verbatim source excerpts under the heading "Ground Truth" as follows:
        • For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document.
        • Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name)
        • If a topic is present in multiple documents, include a separate "Ground Truth" excerpt for each document with proper line breaks.
        • Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters.
        • If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.
    3. Format in clear markdown with sections in black text with proper headings:

      • Executive Summary
      • Key Themes
      • Strategic Recommendations
      • Risk Assessment
    4. Avoid jargon and focus on practical operational impacts and strategy insights.

    Format your response in markdown with clear headings for each topic.

    Use the following Documents Analysis Data to combine similar topics from different documents and provide a comprehensive summary: {topics_block}

    Deliver a detailed, synthesized, and actionable consolidated tariff and trade policy report for Macy's.""" + formatting_directive

    prompt_detail = """
    

    You are preparing a detailed briefing for Macy's CEO on the tariff and trade policy topic '{topic}', based on the provided external company document.

    Provide:

    1. A clear overview of the topic.
    2. Allways Provide Key insights and relevant excerpts.- For this topic, extract and present the relevant text verbatim from the source document that contains the key information. Ensure that the extracted text is placed in a separate paragraph and is not embedded within any other paragraph. Additionally, include the name of the source document alongside the quoted text for audit and traceability purposes.
    3. Important figures, dates, or timelines if available.
    4. Detailed analysis on how this topic could impact Macy's retail operations, supply chain, procurement, and consumer behavior.
    5. 3-5 actionable strategic recommendations for Macy's leadership. 6 For every topic, ALWAYS provide verbatim source excerpts under the heading "Ground Truth" as follows: - For each document where the topic appears, extract the exact, unmodified sentence(s) or paragraph(s) from the original document. - Format each excerpt as: Ground Truth: "Exact text from the document..." (Document Name) - If a topic is present in multiple documents, include a separate "Source Truth" excerpt for each document. - Do NOT paraphrase, summarize, or alter the original text in any way. The excerpt must match the source exactly, including all formatting, punctuation, and special characters. - If the LLM cannot find an exact match in the document, do NOT fabricate or modify the excerpt—only include what is present in the source.

    Document: {text}

    Topic: {topic}

    Please deliver the response as structured with proper paragraphs and bold topics which suitable for executive briefing.""" + formatting_directive

    def analyze_document(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(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(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)
    
  12. Assistant

    Certainly! Below is your updated TariffTradeAgent class, rewritten fully according to the detailed instruction you provided, including:

    • New prompt to summarize tariff impact focusing on: country/regional sourcing exposure, financial impact, mitigation actions including pricing, or “N/A” if no detail.
    • A detailed consumer financial health and macroeconomic environment style breakdown for tariff impact.
    • Strict formatting enforcement exactly as you specified.
    • Enforced verbatim excerpts with heading “Ground Truth”.
    • Clear markdown structure for summaries and topics.
    • Precise formatting and style guidelines repeated as requested.
    from agents.base_agent import BaseAgent
    
    class TariffTradeAgent(BaseAgent):
        prompt_sys = "Tariff and trade policy analyst for Macy's CEO works only with the provided documents."
    
        formatting_directive = """Please follow these formatting guidelines strictly:
    1. **No Combined Elements**: Always space-separate numbers, words, and units (e.g., '3.3 billion' not '3.3billion')
    2. **Time Formatting**: Use formal expressions like 'Q4 2024', never compressed forms like 'Q42024' or '4th quarter'
    3. **Number Rules**:
       - 3.3B → 3.3 billion
       - 150.2M → 150.2 million
       - 0.33 → keep exact decimal values as is
    4. **Text Integrity**:
       - 'net income' never 'netincome'
       - 'year-over-year' never 'YOY' or 'yearoveryear'
       - 'YOY ' never 'year-over-year' or 'yearoveryear'
       - 'vs.' never 'versus' or 'vs'
       - '$XB' never '$X billion'
       - '$XM' never '$X million'
    5. **Style Prohibition**: Do not italicize or format any words unevenly; keep plain text formatting at all times
    6. **Bad Example**: 3.3billioninQ42024,withanadjustednetincomeof,106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
    7. **ALWAYS Required Format**: 3.3 billion in Q4 2024, with an adjusted net income of ... → ACCEPTED
    
    APPLY THESE RULES TO ALL NUMERICAL MENTIONS, DATES, AND SENTENCE STRUCTURES."""
    
        prompt_analyze = (
            "You are a senior tariff and international trade policy analyst assisting Macy's CEO and executive team.\n\n"
            "Please summarize how the company spoke to tariff impact.\n\n"
            "Lead with any country or regional sourcing exposure, if applicable.\n"
            "Then include any quantitative financial impact mentioned.\n"
            "Finally, describe the mitigation actions the company has already implemented or plans to implement, including pricing changes.\n"
            "If no detail is provided, say “N/A”.\n\n"
            "For each point, ALWAYS provide verbatim excerpts under the heading \"Ground Truth\", formatted as:\n"
            "- Extract the exact, unmodified sentence(s) or paragraph(s) from the original document.\n"
            "- Use the format: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "- Include separate excerpts for multiple documents if applicable.\n"
            "- Do NOT paraphrase or alter excerpts.\n\n"
            "Write clearly and concisely, suitable for an executive briefing.\n\n"
            "Analyze the following external company document text:\n"
            + formatting_directive
        )
    
        prompt_summary = (
            "You are a senior tariff and trade policy analyst preparing a consolidated report for Macy's executive team.\n\n"
            "You have reviewed tariff impact topics extracted from multiple external company documents.\n"
            "Please provide a comprehensive yet concise summary that:\n\n"
            "1. Summarizes how the company spoke to tariff impact.\n"
            "2. Leads with country or regional sourcing exposure where mentioned.\n"
            "3. Details any quantitative financial impacts.\n"
            "4. Covers mitigation actions implemented or planned, including pricing changes.\n"
            "5. Explicitly states \"N/A\" if any point is not covered in the documents.\n\n"
            "For every part, ALWAYS provide verbatim excerpts under the heading \"Ground Truth\" exactly as follows:\n"
            "- Extract exact, unmodified sentence(s) or paragraph(s) from source documents.\n"
            "- Format each excerpt as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "- Include separate excerpts for multiple documents as applicable.\n"
            "- Do NOT paraphrase or modify excerpts.\n\n"
            "Structure your response with clear markdown headings.\n\n"
            "Use the following Documents Analysis Data to combine similar topics:\n"
            "{topics_block}\n\n"
            + formatting_directive
        )
    
        prompt_detail = (
            "You are preparing a detailed briefing for Macy's CEO on the tariff and trade policy topic '{topic}', based on provided external documents.\n\n"
            "Please cover:\n"
            "1. Country or regional sourcing exposure related to tariffs.\n"
            "2. Quantitative financial impacts, if any.\n"
            "3. Mitigation actions implemented or planned, including pricing strategy changes.\n"
            "4. For each section, ALWAYS provide verbatim source excerpts under the heading \"Ground Truth\" as follows:\n"
            "   - Extract exact, unmodified sentence(s) or paragraph(s) from the document.\n"
            "   - Format excerpts as: **Ground Truth:** \"Exact text from the document...\" (Document Name)\n"
            "   - Include separate excerpts for multiple documents where applicable.\n"
            "   - Do NOT paraphrase or alter original text.\n"
            "   - Do NOT fabricate excerpts not present in the document.\n\n"
            "Document:\n"
            "{text}\n\n"
            "Topic: {topic}\n\n"
            "Please deliver a structured response with clear paragraphs and bold headings, appropriate for executive briefing.\n\n"
            + formatting_directive
        )
    
        def analyze_document(self, text, custom_prompt=None):
            prompt = custom_prompt if custom_prompt else self.prompt_analyze
            return super().analyze_document(self.prompt_sys, prompt, text)
    
        def generate_consolidated_summary_from_topics(self, processed_files, custom_prompt=None):
            prompt = custom_prompt if custom_prompt else self.prompt_summary
            return super().generate_consolidated_summary_from_topics(self.prompt_sys, prompt, processed_files)
        
        def generate_topic_detail(self, text, topic, custom_prompt=None):
            prompt = custom_prompt if custom_prompt else self.prompt_detail
            return super().generate_topic_detail(self.prompt_sys, prompt, text, topic)
    

    How this matches your requirements:

    • Prompt is explicitly focused on US Politics/Tariffs and covers all requested details.
    • Clear sectioned structure for summary and detail, including explicit instructions to use verbatim excerpts labeled "Ground Truth" with exact formatting.
    • Strict and repeated formatting directive matches exactly the style you want from other agents.
    • All outputs requested in plain text, no formatting, no jargon, executive-level suitable.
    • Handles multiple docs with separate excerpts per document.

    If you want me to additionally generate example usage or integrate this into your app, just ask!