class OverallAgent(BaseAgent):
prompt_sys = "Macy's Executive Business Analyst works for only provided documents"
code
# Universal formatting enforcement line
formatting_directive = """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
Text Integrity:
"net income" never "netincome"
"year-over-year" never "YOY" or "yearoveryear"
Style Prohibition: Do not make any word in Italic or any other format always make it in one format
Bad Example: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
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."""
code
prompt_analyze = """You are a senior business analyst working directly for Macy's CEO. Analyze the provided earnings call transcript and identify all significant business topics across all operational areas.
Identify key topics including but not limited to:
Financial performance metrics
Consumer behavior trends
Supply chain and logistics
Tariff and trade impacts
Technology investments
Strategic initiatives
Competitive landscape
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
Relevance score (1-10) based on strategic importance to Macy's
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.
Assistant
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:""" + formatting_directive
code
prompt_summary = """You are a senior analyst preparing a consolidated report for Macy's CEO from all documents provided.
Identify and describe all impactful business topics from all the provided documents, focusing on those with broad implications for Macy's operations, strategy, and financial performance. Combine and synthesize topics that appear in multiple documents.
Overview: Identify and describe impactful topics from all documents, especially those related to government policy or other external factors that could affect Macy's business operations.
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 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.
Format in clear with sections in black text with proper headings:
Executive Summary
Key Themes
Strategic Recommendations
Risk Assessment
Use the following Documents Analysis Data to combine similar topics from different documents and provide a comprehensive summary:
{topics_block}
Provide comprehensive yet concise analysis suitable for C-level decision making.""" + formatting_directive
code
prompt_detail ="""You are preparing an executive briefing on '{topic}' for Macy's leadership. Provide:
Overview: Context and importance of this topic across all documents
Cross-Document Insights: Always Provide Key findings from all relevant documents, Provide same text do not make any changes.
Financial Impact: Any disclosed numbers or estimates from all sources
Operational Effects: Combined impacts on retail ops, supply chain, and digital
Recommendations: 3-5 actionable strategies with timelines
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 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 documents.
Include specific examples from documents where available, noting which document they came from.
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.
Relevant document excerpts:
{text}
Deliver response in structured with proper paragraphs and bold topics and headings.""" + formatting_directive
def analyze_document(self, prompt_system, prompt_user, text):
if self.is_azure:
messages = [
{"role": "system", "content": prompt_system},
{"role": "user", "content": prompt_user + "\n\n" + text},
]
response = self.client.generate(messages=messages, temperature=0)
raw_text = response.choices[0].message.content.strip()
print(raw_text)
else:
raw_text = self.client.generate(prompt_system, prompt_user + "\n\n" + text)
return parse_topics(raw_text)
def analyze_question(self, prompt_system, prompt_user, text):
"""New method for QA extraction"""
if self.is_azure:
messages = [
{"role": "system", "content": prompt_system},
{"role": "user", "content": prompt_user + "\n\n" + text},
]
response = self.client.generate(messages=messages, temperature=0)
return response.choices[0].message.content.strip()
else:
return self.client.generate(prompt_system, prompt_user + "\n\n" + text)
def generate_consolidated_summary_from_topics(self, prompt_system, prompt_user_template, processed_files):
topics_block = ""
for filename, filedata in processed_files.items():
topics_block += f"### Topics from document: {filename}\n"
for topic in sorted(filedata["topics"], key=lambda x: x["score"], reverse=True):
topics_block += f"- **{topic['name']}**: {topic['summary']} (Relevance: {topic['score']})\n"
topics_block += "\n"
prompt_user = prompt_user_template.format(topics_block=topics_block)
if self.is_azure:
messages = [
{"role": "system", "content": prompt_system},
{"role": "user", "content": prompt_user},
]
response = self.client.generate(messages=messages, temperature=0)
return response.choices[0].message.content.strip()
else:
return self.client.generate(prompt_system, prompt_user)
def generate_topic_detail(self, prompt_system, prompt_user_template, document_text, topic):
prompt_user = prompt_user_template.format(text=document_text, topic=topic)
if self.is_azure:
messages = [
{"role": "system", "content": prompt_system},
{"role": "user", "content": prompt_user},
]
response = self.client.generate(messages=messages, temperature=0, stream=True)
collected_chunks = []
for chunk in response:
if hasattr(chunk, "choices") and chunk.choices:
delta = chunk.choices[0].delta
content = getattr(delta, "content", "")
if content:
collected_chunks.append(content)
yield "".join(collected_chunks) + "▌"
# Final yield without cursor
if collected_chunks:
yield "".join(collected_chunks)
else:
# For Gemini, we'll simulate streaming with 3 chunks
full_response = self.client.generate(prompt_system, prompt_user)
chunks = self.preserve_formatting_chunks(full_response)
accumulated = ""
for chunk in chunks:
accumulated += chunk
yield accumulated + "▌"
yield accumulated # Final yield without cursor
def preserve_formatting_chunks(self, text):
"""Split response while preserving Markdown formatting"""
# Split by paragraphs first
paragraphs = text.split('\n\n')
chunks = []
for para in paragraphs:
if para.startswith('##') or para.startswith('###') or para.startswith('* '):
# Preserve headers and lists as whole chunks
chunks.append(para + '\n\n')
else:
# Split long paragraphs into sentences
sentences = para.split('. ')
current_chunk = ""
for sentence in sentences:
if not sentence:
continue
if len(current_chunk) + len(sentence) > 150:
if current_chunk:
chunks.append(current_chunk.strip() + '. ')
current_chunk = sentence
else:
current_chunk += sentence + '. '
if current_chunk:
chunks.append(current_chunk.strip() + '\n\n')
return chunks
this is the base agent
import streamlit as st
from io import BytesIO
from datetime import datetime
Assuming these are correctly defined and accessible
from utils.pdf_utils import extract_text
from clients.azure_client import AzureClient
from clients.gemini_client import GeminiClient
from agents.tariff_agent import TariffTradeAgent
from agents.sales_agent import SalesAgent
from agents.supply_chain_agent import SupplyChainAgent
from agents.overall_agent import OverallAgent
from agents.enhanced_chat_agent import EnhancedChatAgent
from agents.qa_agent import QAAgent
def initialize_clients_and_agents(provider_select: str, mode: str = None):
"""
Ensure 'client' and agents are initialized in st.session_state.
If mode is 'dashboard', initialize dashboard agents.
If mode is 'qa', initialize QA agent.
If mode is None, initialize all.
"""
code
need_reinit = (
"client" not in st.session_state
or st.session_state.get("provider") != provider_select
)
if need_reinit:
if provider_select == "Azure GPT":
st.session_state.client = AzureClient()
is_azure = True
else:
st.session_state.client = GeminiClient()
is_azure = False
st.session_state.provider = provider_select
# For dashboard agents
st.session_state.agent_overall = OverallAgent(st.session_state.client, is_azure)
st.session_state.agent_tariff = TariffTradeAgent(st.session_state.client, is_azure)
st.session_state.agent_sales = SalesAgent(st.session_state.client, is_azure)
st.session_state.agent_supplychain = SupplyChainAgent(st.session_state.client, is_azure)
# Chat agent (used on both pages)
st.session_state.chat_agent = EnhancedChatAgent(st.session_state.client, is_azure)
# QA agent only if mode is 'qa' or None (default to initialize all)
if mode == "qa" or mode is None:
st.session_state.agent_qa = QAAgent(st.session_state.client, is_azure)
else:
# If client/provider the same, still validate agents are present and initialize if missing
if mode in [None, "dashboard"]:
if "agent_overall" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_overall = OverallAgent(st.session_state.client, is_azure)
if "agent_tariff" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_tariff = TariffTradeAgent(st.session_state.client, is_azure)
if "agent_sales" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_sales = SalesAgent(st.session_state.client, is_azure)
if "agent_supplychain" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_supplychain = SupplyChainAgent(st.session_state.client, is_azure)
if "chat_agent" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.chat_agent = EnhancedChatAgent(st.session_state.client, is_azure)
if mode in [None, "qa"]:
if "agent_qa" not in st.session_state:
is_azure = st.session_state.provider == "Azure GPT"
st.session_state.agent_qa = QAAgent(st.session_state.client, is_azure)
def analyze_documents(mode, agent, processed_files, sess, custom_prompt=None):
# Process individual files
for filename, file_bytes in sess['uploaded_files'].items():
if filename not in processed_files:
try:
file_obj = BytesIO(file_bytes)
file_obj.name = filename
text = extract_text(file_obj)
if text:
topics = agent.analyze_document(text, custom_prompt)
processed_files[filename] = {
"text": text,
"topics": topics,
"context": text,
}
st.toast(f"✅ Processed {filename}")
else:
st.error(f"❌ Failed to extract text for {filename}")
except Exception as e:
st.error(f"Error processing {filename}: {str(e)}")
if 'qa_page' not in st.session_state:
st.session_state.qa_page = {
'uploaded_files': {},
'processed_files': {},
'active_file': None,
'active_topic': None,
'chat_history': [],
'selected_files': []
}
qa_state = st.session_state.qa_page
provider_select = st.sidebar.radio("Select AI Provider", ["Azure GPT", "Google Gemini"])
# Initialize client and QA agents
initialize_clients_and_agents(provider_select, mode="qa")
# --- File Upload ---
st.subheader("Upload Documents")
uploaded_files = st.file_uploader(
"Upload PDF documents for Q&A extraction",
type=["pdf"],
accept_multiple_files=True,
key="qa_file_uploader"
)
if uploaded_files:
new_files_added = False
for file in uploaded_files:
if file.name not in qa_state['uploaded_files']:
qa_state['uploaded_files'][file.name] = file.getvalue()
new_files_added = True
if new_files_added:
with st.spinner("🔍 Extracting Q&A from new documents..."):
for filename in qa_state['uploaded_files']:
if filename not in qa_state['processed_files']:
try:
file_bytes = qa_state['uploaded_files'][filename]
file_obj = BytesIO(file_bytes)
file_obj.name = filename
text = extract_text(file_obj)
if text:
# Use the QA Agent to generate structured Q&A content
qa_data = st.session_state.agent_qa.analyze_question(text)
# Store the structured data
qa_state['processed_files'][filename] = {
'text': text,
'qa_data': qa_data
}
st.toast(f"✅ Processed {filename}")
# Automatically select the first topic
if not qa_state.get('error') and qa_data.get('topics'):
qa_state['active_topic'] = qa_data['topics'][0]
else:
st.error(f"❌ Failed to extract text for {filename}")
except Exception as e:
st.error(f"Error processing {filename}: {str(e)}")
# Auto-select the first file if none is selected
if not qa_state['active_file'] and qa_state['processed_files']:
qa_state['active_file'] = next(iter(qa_state['processed_files'].keys()))
# --- Document Selection ---
st.sidebar.header("📄 Processed Documents")
for filename in qa_state['processed_files']:
if st.sidebar.button(
f"📄 {filename}",
key=f"qa_file_{filename}",
use_container_width=True,
):
qa_state['active_file'] = filename
# Automatically select the first topic for this document
file_data = qa_state['processed_files'][filename]
qa_data = file_data['qa_data']
if not qa_data.get('error') and qa_data.get('topics'):
qa_state['active_topic'] = qa_data['topics'][0]
# --- Topic Sidebar ---
if qa_state['active_file']:
file_data = qa_state['processed_files'][qa_state['active_file']]
qa_data = file_data['qa_data']
st.sidebar.header("📌 Topics")
# Handle error case
if "error" in qa_data:
st.sidebar.error("Error in document processing")
elif 'topics' in qa_data:
topics = qa_data['topics']
# Display each topic in the sidebar
for topic in topics:
btn_label = f"{topic['topic']} ({topic['mention_count']} mentions)"
if st.sidebar.button(
btn_label,
key=f"topic_{topic['topic']}_{qa_state['active_file']}",
use_container_width=True,
):
qa_state['active_topic'] = topic
else:
st.sidebar.info("No topics found in this document")
# --- Q&A Display ---
st.subheader("📝 Extracted Q&A Content")
if qa_state['active_file']:
file_data = qa_state['processed_files'][qa_state['active_file']]
qa_data = file_data['qa_data']
st.markdown(f"**Document:** {qa_state['active_file']}")
# Handle error case
if "error" in qa_data:
st.error(f"Error processing document: {qa_data['error']}")
if "raw_response" in qa_data:
st.text_area("Raw AI Response", qa_data["raw_response"], height=300)
# Display key takeaways
elif 'key_takeaways' in qa_data and qa_data['key_takeaways']:
st.subheader("Key Takeaways")
for takeaway in qa_data['key_takeaways']:
st.markdown(f"- {takeaway}")
# Display selected topic
if qa_state['active_topic']:
topic = qa_state['active_topic']
st.divider()
st.subheader(topic['topic'])
st.markdown(f"**Mentioned:** {topic['mention_count']} times")
st.divider()
# Display questions for this topic
if 'questions' in topic and topic['questions']:
for idx, question in enumerate(topic['questions']):
firm = question.get('firm', 'Unknown Firm')
st.markdown(f"**Firm:** {firm}")
st.markdown(f"**Question {idx+1}:** {question['question']}")
st.write("---")
else:
st.info("No questions found for this topic")
elif 'topics' in qa_data and qa_data['topics']:
# If no topic selected but topics exist, show the first one
qa_state['active_topic'] = qa_data['topics'][0]
st.experimental_rerun()
else:
st.info("No Q&A content found for this document")
else:
st.info("Upload documents to see extracted Q&A content")
st.divider()
# --- Chat Interface ---
st.subheader("💬 Chat with Documents")
available_files = list(qa_state['processed_files'].keys())
selected_files = st.multiselect(
"Select documents to include in chat context:",
available_files,
default=available_files[:min(3, len(available_files))],
key="qa_chat_selector"
)
qa_state['selected_files'] = selected_files
for msg in qa_state['chat_history']:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
question = st.chat_input("Ask about the documents...")
if question:
if not selected_files:
st.error("Please select at least one document for context")
st.stop()
qa_state['chat_history'].append({
"role": "user",
"content": question,
"timestamp": datetime.utcnow().isoformat(),
})
try:
context = "\n\n".join([
f"=== {filename} ===\n{qa_state['processed_files'][filename]['text']}"
for filename in selected_files
])
with st.chat_message("assistant"):
response_placeholder = st.empty()
full_response = ""
for chunk, _ in st.session_state.chat_agent.generate_answer(question, context):
full_response = chunk
response_placeholder.markdown(full_response + " ▌")
response_placeholder.markdown(full_response)
qa_state['chat_history'].append({
"role": "assistant",
"content": full_response,
"timestamp": datetime.utcnow().isoformat(),
})
except Exception as e:
st.error(f"Chat error: {str(e)}")
qa_state['chat_history'].append({
"role": "assistant",
"content": f"Error: {str(e)}",
"timestamp": datetime.utcnow().isoformat(),
})
# Reset button for QA page
if st.button("🔄 Reset Q&A Session", key="reset_qa_page"):
qa_state.clear()
qa_state.update({
'uploaded_files': {},
'processed_files': {},
'active_file': None,
'active_topic': None,
'chat_history': [],
'selected_files': []
})
st.experimental_rerun()
if name == "main":
main()
this is main.py
my custom prompt for all three analyze_document, generate_consolidated_summary_from_topics, and generate_topic_detail are not working properly in the frontend i can change all three and ask to genrate topics with custom prompt but it is not working
correct my code and give me correct full code
Your architecture for using custom prompts in the agents and calling them in your Streamlit frontend is mostly correct in concept, but the issue is that your OverallAgent class methods that accept custom_prompt parameters do not re-assign the instance prompt variables, so if you pass custom prompts when calling, the base class's original prompts are still used internally in super() calls.
You expect custom_prompt to override the prompt, but you call from your frontend:
python
agent.analyze_document(text, custom_prompt)
where custom_prompt is a string, but your base agent expects prompt_user + (maybe text). You pass custom_prompt fully as the user prompt, but in your UI, you are storing separate prompts for analyze, summary, and detail. However, in your frontend you only pass a single custom prompt string to that method — that is okay if the frontend consistently passes the entire full prompt block.
But the bigger issue is in generate_consolidated_summary_from_topics and generate_topic_detail:
Here, super().generate_consolidated_summary_from_topics expects two args: prompt_system and prompt_user_template.
When you pass in your custom_prompt, it must include the {topics_block} placeholder, otherwise string formatting will break or it won't work as expected.
But inside BaseAgent.generate_topic_detail you expect prompt_user_template with two placeholders {text} and {topic} — your custom prompt string must include those placeholders or your string format will fail or produce broken prompt.
How to fix your code?
1. Correct Method Signatures and Usage
Make sure your custom prompt strings include the required placeholders, e.g.:
For summary prompt: must include {topics_block}
For topic detail prompt: must include {text} and {topic}
Then inside your methods in OverallAgent, you should format the custom prompt string before passing it to super (or at least do so at the base agent level).
2. Pass prompt strings properly:
Update OverallAgent methods like so:
python
def analyze_document(self, text, custom_prompt=None):
prompt_analyze = custom_prompt if custom_prompt else self.prompt_analyze
# For analyze_document, no additional formatting arguments needed
return super().analyze_document(self.prompt_sys, prompt_analyze, text)
def generate_consolidated_summary_from_topics(self, processed_files, custom_prompt=None):
prompt_summary_template = custom_prompt if custom_prompt else self.prompt_summary
# Prompt summary expects to format {topics_block}
topics_block = ""
for filename, filedata in processed_files.items():
topics_block += f"### Topics from document: {filename}\n"
for topic in sorted(filedata["topics"], key=lambda x: x["score"], reverse=True):
topics_block += f"- **{topic['name']}**: {topic['summary']} (Relevance: {topic['score']})\n"
topics_block += "\n"
prompt_summary = prompt_summary_template.format(topics_block=topics_block)
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_template = custom_prompt if custom_prompt else self.prompt_detail
prompt_detail = prompt_detail_template.format(text=text, topic=topic)
# Note: This returns a generator, must yield from super
return super().generate_topic_detail(self.prompt_sys, prompt_detail, text, topic)
But looking at your BaseAgent.generate_topic_detail():
You already do the formatting in the base class - so you should pass the unformatted template string from the agent to base, and let base do the formatting.
So to keep consistent, just pass the custom prompt string unformatted and base will format it.
Correspondingly for summary, base does formatting too.
=> So better approach: Do not format in OverallAgent, just pass the template string and let base do formatting.
If you do this, then you must ensure your custom prompt text contains the exact required placeholders.
If the custom prompt is missing {topics_block}, base fallback .format(topics_block=...) will fail.
3. In your Streamlit UI, make sure that the custom prompt text includes the placeholders correctly
For summary prompt: {topics_block} must exist
For detail prompt: {text}, {topic} must exist
For analyze prompt: no formatting variables are used
4. Clear your agent prompt attributes when switching between default and custom prompts
Your frontend resets agent prompt attributes per the checkbox:
python
# Update agent with custom prompts if used
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']
else:
# Reset to default prompts
This is good. So your frontend probably works here.
Full corrected OverallAgent methods (for clarity):
python
Full BaseAgent generate_consolidated_summary_from_topics and generate_topic_detail do formatting
python
def generate_consolidated_summary_from_topics(self, prompt_system, prompt_user_template, processed_files):
topics_block = ""
for filename, filedata in processed_files.items():
topics_block += f"### Topics from document: {filename}\n"
for topic in sorted(filedata["topics"], key=lambda x: x["score"], reverse=True):
topics_block += f"- **{topic['name']}**: {topic['summary']} (Relevance: {topic['score']})\n"
topics_block += "\n"
prompt_user = prompt_user_template.format(topics_block=topics_block)
if self.is_azure:
messages = [
{"role": "system", "content": prompt_system},
{"role": "user", "content": prompt_user},
]
response = self.client.generate(messages=messages, temperature=0)
return response.choices[0].message.content.strip()
else:
return self.client.generate(prompt_system, prompt_user)
def generate_topic_detail(self, prompt_system, prompt_user_template, document_text, topic):
prompt_user = prompt_user_template.format(text=document_text, topic=topic)
# Then proceed with generation
When you edit your custom prompts in the text areas, make sure you do NOT remove required placeholders like {topics_block} / {text} / {topic} for summary and detail prompts respectively.
When invoking agent methods, pass only the relevant prompt part (like agent.analyze_document(text, custom_prompt) where custom_prompt is the entire analyze prompt text).
For summary and detail methods, do not pre-format in frontend or in agent—only pass raw template strings.
Summary of corrections for your issue:
Do not format the prompt in the agent methods — pass raw template strings to the base agent, which does the formatting.
Make sure your custom prompt texts include necessary placeholders.
Your current methods in OverallAgent for summary and detail should not do .format() but just pass the template string.
On your frontend, when setting the agent.prompt_*, set to full prompt template strings (with placeholders).
When calling agent.generate_consolidated_summary_from_topics(processed_files, custom_prompt=...) or agent.generate_topic_detail(text, topic, custom_prompt=...), pass the full user prompt content (which contains placeholders).
This allows streaming and formatting to operate as expected.
Here is a minimal fix snippet for OverallAgent:
python
class OverallAgent(BaseAgent):
# ... [prompts as you gave]
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_template = custom_prompt if custom_prompt else self.prompt_summary
# Pass raw template - base agent will format topics_block
return super().generate_consolidated_summary_from_topics(self.prompt_sys, prompt_summary_template, processed_files)
def generate_topic_detail(self, text, topic, custom_prompt=None):
prompt_detail_template = custom_prompt if custom_prompt else self.prompt_detail
return super().generate_topic_detail(self.prompt_sys, prompt_detail_template, text, topic)
You do NOT need to change your BaseAgent class because it already does the template .format() calls.
Final notes:
Your custom prompt feature works only if you store and pass the exact full prompt strings with placeholders before passing to agent calls.
If you pass custom prompts without placeholders or pass already formatted strings, your LLM call can fail or produce undesired output.
Verify in your frontend text areas that the prompt template placeholders {topics_block}, {text}, and {topic} are not removed accidentally when editing prompts.
If you want me to, I can provide the full corrected overall_agent.py and the relevant parts of main.py altered to demonstrate exactly how to handle custom prompts, but your main issue is the way you are passing custom prompt strings with the required placeholders to the underlying base agent methods.
Let me know if you want me to provide a runnable, clean example of the full OverallAgent and minimal Streamlit changes!
from agents.base_agent import BaseAgent
class OverallAgent(BaseAgent):
prompt_sys = "Macy's Executive Business Analyst works for only provided documents"
formatting_directive = """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
5. **Text Integrity**:
- "net income" never "netincome"
- "year-over-year" never "YOY" or "yearoveryear"
6. **Style Prohibition**: Do not make any word in Italic or any other format always make it in one format
7. **Bad Example**: 3.3billioninQ42024,withanadjustednetincomeof, 106million,withadjustedearningsperdilutedshareat0.95 → REJECTED
8. **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 business analyst working directly for Macy's CEO. Analyze the provided earnings call transcript and identify all significant business topics across all operational areas.
Identify key topics including but not limited to:
- Financial performance metrics
- Consumer behavior trends
- Supply chain and logistics
- Tariff and trade impacts
- Technology investments
- Strategic initiatives
- Competitive landscape
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
* Relevance score (1-10) based on strategic importance to Macy's
* 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:""" + formatting_directive
prompt_summary = """You are a senior analyst preparing a consolidated report for Macy's CEO from all documents provided.
Identify and describe all impactful business topics from all the provided documents, focusing on those with broad implications for Macy's operations, strategy, and financial performance. Combine and synthesize topics that appear in multiple documents.
1. **Overview**: Identify and describe impactful topics from all documents, especially those related to government policy or other external factors that could affect Macy's business operations.
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 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 the 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:
* Executive Summary
* Key Themes
* Strategic Recommendations
* Risk Assessment
Use the following Documents Analysis Data to combine similar topics from different documents and provide a comprehensive summary:
{topics_block}
Provide comprehensive yet concise analysis suitable for C-level decision making.""" + formatting_directive
prompt_detail ="""You are preparing an executive briefing on '{topic}' for Macy's leadership. Provide:
1. **Overview**: Context and importance of this topic across all documents
2. **Cross-Document Insights**: Always Provide Key findings from all relevant documents, Provide same text do not make any changes.
3. **Financial Impact**: Any disclosed numbers or estimates from all sources
4. **Operational Effects**: Combined impacts on retail ops, supply chain, and digital
5. **Recommendations**: 3-5 actionable strategies with timelines
6. 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 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 documents.
Include specific examples from documents where available, noting which document they came from.
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.
Relevant document excerpts:
{text}
Deliver response in structured with proper paragraphs and bold topics and headings.""" + formatting_directive
def analyze_document(self, text, custom_prompt=None):
print("Analyzing document with custom prompt:", custom_prompt)
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):
print("Generating consolidated summary with custom prompt:", custom_prompt)
prompt_summary_template = custom_prompt if custom_prompt else self.prompt_summary
return super().generate_consolidated_summary_from_topics(self.prompt_sys, prompt_summary_template, processed_files)
def generate_topic_detail(self, text, topic, custom_prompt=None):
print("Generating topic detail with custom prompt:", custom_prompt)
prompt_detail_template = custom_prompt if custom_prompt else self.prompt_detail
return super().generate_topic_detail(self.prompt_sys, prompt_detail_template, text, topic)