this is main.py
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
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()
else:
raw_text = self.client.generate(prompt_system, prompt_user + "\n\n" + text)
return parse_topics(raw_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 my qa agent
from agents.base_agent import BaseAgent
class QAAgent(BaseAgent):
prompt_sys = "Expert in extracting all Questions and Answers from transcripts for Macy's CEO"
code
# Add these prompts that were missing in your original code
prompt_summary = "Summary of extracted Q&A pairs"
prompt_detail = "Detailed Q&A view"
prompt_analyze = """
You are an expert in analyzing transcripts of earnings calls or business meetings. Your task is to carefully review the provided transcript and extract EVERY question and its corresponding answer EXACTLY as they appear, including the speaker information.
Focus specifically on the QUESTION AND ANSWER SECTION of the document
Extract ALL Q&A pairs in this section without exception
what i require in my main.py you can provide a similar QA button as tarrif, supplychain whihc can genrtate the QA from the document make the function in base agent
give me full code of each file
we doesnot want in our qa agent any analysis or consolidate summary provide only with analyze_question
and analyze_question should be available in Base agent
give me full correct code
Certainly! I'll provide the updated and full code for each file you need with the requested features:
Add analyze_question method to BaseAgent.
Update QAAgent to only provide analyze_question; no summary/consolidation.
Add a QA tab and button in main.py similar to tariff/supplychain, which calls analyze_question and stores results.
Make sure QA results persist similar to other modes.
Full, clean, and working code for these three files:
main.py
agents/base_agent.py
agents/qa_agent.py
1. Updated agents/base_agent.py
python
from utils.pdf_utils import parse_topics
class BaseAgent:
def __init__(self, client, is_azure):
self.client = client
self.is_azure = is_azure
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()
else:
raw_text = self.client.generate(prompt_system, prompt_user + "\n\n" + text)
return parse_topics(raw_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
# NEW METHOD: analyze_question - similar to analyze_document, but for Q&A extraction
def analyze_question(self, prompt_system, prompt_user, text):
"""
Analyzes the document text using provided system and user prompts
specifically for Q&A extraction. Returns the raw text response.
"""
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)
2. Updated agents/qa_agent.py
python
from agents.base_agent import BaseAgent
class QAAgent(BaseAgent):
prompt_sys = "Expert in extracting all Questions and Answers from transcripts for Macy's CEO"
# Add these prompts for QA (you can modify these later if needed)
prompt_summary = "Summary of extracted Q&A pairs"
prompt_detail = "Detailed Q&A view"
prompt_analyze = """
You are an expert in analyzing transcripts of earnings calls or business meetings. Your task is to carefully review the provided transcript and extract EVERY question and its corresponding answer EXACTLY as they appear, including the speaker information.
- Focus specifically on the QUESTION AND ANSWER SECTION of the document
- Extract ALL Q&A pairs in this section without exception
- For each pair, include:
- The EXACT question text
- The EXACT answer text
- The speaker who asked the question
- The speaker who answered the question
- Format each Q&A pair as:
Q[#]: [exact question text]
Asked by: [speaker name]
A: [exact answer text]
Answered by: [speaker name]
- Do not skip any questions - capture 100% of questions in the Q&A section
- Do not paraphrase or summarize - use the exact words from the transcript
- Include follow-up questions and responses
- Preserve any numerical data, percentages, or specific terms exactly as spoken
- Ensure complete coverage of all questions regardless of length or importance
Transcript:
{text}
"""
# We only override analyze_question here, we don't provide analyze_document or summaries
def analyze_question(self, text, custom_prompt=None):
prompt_analyze = custom_prompt if custom_prompt else self.prompt_analyze
return super().analyze_question(self.prompt_sys, prompt_analyze, text)
3. Updated main.py
(Changes highlighted with comments, new QA tabs and button added, storing results in session under processed_files_qa)
python
Summary of changes:
BaseAgent now has analyze_question method to extract Q&A.
QAAgent overrides only analyze_question and provides relevant prompt.
main.py
Adds QA tab + button behavior.
Stores QA extracted text separately.
No consolidated summary for QA.
Sidebar lets user pick files to view extracted Q&A text.
Reset clears QA data as well.
If you want, I can help you integrate the new files with your existing project or provide helper utilities like parse_topics. Let me know!