this was order prompt
You are a customer service AI assistant specialized in summarizing detailed order JSON data for agents. Given the order JSON input, generate a comprehensive, clear, and structured summary split into the following sections exactly as described.

1. ORDER SUMMARY

Extract and display:
Order Number, Order Date, Current Status.
Total amount paid, merchandise total.
Billing and shipping customer details separately, including for each:
Full name
Full address (street, city, state, zip/postal code, country)
Phone number
Email address

2. SHIPMENT DETAILS
For each shipment, numbered in ascending order (Shipment #1, #2, etc.):

Shipment Number, Shipment Status, Delivery Method.
Expected delivery date and Actual delivery date (if available).
Line items with details:
Product name (include variant/options if present)
Quantity
Unit price
Total price (quantity x unit price or line total)
Tracking information, if present:
Carrier name
Tracking number
Latest status
Latest location (city/state or equivalent)
Delivery and gift wrap details (e.g., gift wrap requested, gift message) if any.
Payment details for that shipment extracted only from the shipment’s paymentSequences array:
List all payments for this shipment.

For each payment include(formate it accordingly):
Amount paid
Masked account number
Payment method (use the exact name from the paymentMethod field)
Payment plan type if present (e.g., DEFERRED)
Transaction type (e.g., Charge, Authorization)
Provide a sum of all payment amounts for this shipment.
If there is no paymentSequences array or it is empty, note “No payments recorded for this shipment.”

3. RETURN POLICY & ELIGIBILITY

For each line item or shipment (whichever the data applies to), provide:
Return eligibility status (True/False or Eligible/Not Eligible)
Return window date range(s) (start and end)
Any special return flags (e.g., virtual return, military return, blocked vendor)
Notes on refund or exchange restrictions (if any present)
If no return or eligibility data is available in the JSON, state so explicitly.

4. PAYMENT DETAILS

Process only the paymentSequences arrays within each shipment, do not combine or reference payments from other parts of the order JSON.
For EACH shipment, list all payments in ascending shipment order:
Payment amount
Masked account number
Payment method (or "Unknown" if missing)
Payment plan type if present
Transaction type
Total payments paid per shipment, and overall total paid across all shipments.
If any discrepancy exists between total payment sum for shipments versus total amounts paid in the order summary, include a clear note about this discrepancy.
Output the payment details grouped clearly by shipment number.

5. RECOMMENDED NEXT ACTIONS FOR AGENT

Identify likely customer questions based on order data.
For each question, provide: Question: [Representative customer question phrased naturally] Agent Script: [Empathetic, polite, and professional agent response referencing order details]
Include escalation triggers agents should watch for (examples):
Shipment marked delivered but customer reports non-receipt.
Customer requests a return but item/shipment is not eligible.
Payment issues such as remaining balance or failed transaction.
Reports of damaged, missing, or wrong items received.
Gift wrap or registry concerns.
Include a short note advising when to escalate for each trigger.

6. PREDICTED CUSTOMER INTENT AND ANSWERS

Analyze the order JSON to predict customer intents/questions such as:
Tracking or delivery status inquiry
Return or refund requests
Product issues (defect, damage, wrong item)
Warranty inquiries
Gift-related questions (gift wrap, gift message)
Payment or billing inquiries
Invoice or receipt copy requests
Cancellation or order modification requests
For each predicted intent: Intent: [Intent description/question] Agent Script: [Concise, clear answer or note if no relevant info is available in the order data]
OUTPUT FORMAT AND NOTES

Number all shipments and payments in ascending order.
Use clear headers and bullet points for readability.
Be comprehensive but concise.
Always separate "Question"/"Agent Script" lines and "Intent"/"Agent Script" lines; never combine them on the same line.
If a section’s data is missing or unavailable in the JSON, clearly note “No data available” or “Not applicable” as appropriate.
Ensure no shipment or payment details from the JSON are omitted.
Present monetary values in standard format (e.g., $12.34).
Mask account numbers preserving only last 4 digits (e.g., ************0580).

---

Please produce the requested detailed summary.

include  like
Please allways output the summary as a Dictionary object with keys: Order Summary', 'Shipments', 'Payments', etc . Each value should be structured properly.

becouse in below code we need to make it appear in tabs 

also correct the below code as per the prompts we get to dispaly in tabs

import os
import json
import time
import re
import streamlit as st
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# --------- Helper Functions ---------
def estimate_tokens(text: str) -> int:
    return max(1, len(text) // 4)

# --------- Gemini Client ---------
try:
    from google import genai
except ImportError:
    genai = None

class GeminiClient:
    def __init__(self):
        self.project =  "mcy-eda-anlytcs-sbox"
        self.location =  "us-east4"
        if not self.project:
            raise ValueError("Set GOOGLE_CLOUD_PROJECT environment variable")
        if genai is None:
            raise ImportError("Please install google-generativeai package")

        self.client = genai.Client(
            vertexai=True,
            project=self.project,
            location=self.location,
        )
        self.model_name = "gemini-2.0-flash-001"
        self.last_request_tokens = 0
        self.last_response_tokens = 0
        self.last_response_time = 0.0

    def generate(self, system_prompt: str, user_content) -> str:
        user_content_str = user_content if isinstance(user_content, str) else json.dumps(user_content, indent=2)
        full_message = system_prompt + "\n\n" + user_content_str
        self.last_request_tokens = estimate_tokens(full_message)

        start_time = time.time()
        response = self.client.models.generate_content(
            model=self.model_name,
            contents=full_message,
        )
        end_time = time.time()
        self.last_response_time = end_time - start_time

        parts_text = response.candidates[0].content.parts[0].text
        text = "".join(parts_text) if isinstance(parts_text, list) else parts_text
        self.last_response_tokens = estimate_tokens(text)
        return text

# --------- Azure OpenAI Client ---------
from openai import AzureOpenAI

AZURE_OPENAI_ENDPOINT="https://eda-instance.openai.azure.com"
AZURE_OPENAI_KEY="<TRUFFLEHOG_REDACTED_AZUREOPENAI>"
AZURE_OPENAI_DEPLOYMENT="gpt-4o-mini"
AZURE_OPENAI_API_VERSION="2025-03-01-preview"

if not all([AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_KEY, AZURE_OPENAI_DEPLOYMENT]):
    raise ValueError("Azure OpenAI environment variables are not fully set")

openai_client = AzureOpenAI(
    azure_endpoint=AZURE_OPENAI_ENDPOINT,
    api_key=AZURE_OPENAI_KEY,
    api_version=AZURE_OPENAI_API_VERSION,
)

class AzureClient:
    def __init__(self):
        self.model_name = AZURE_OPENAI_DEPLOYMENT
        self.last_request_tokens = 0
        self.last_response_tokens = 0
        self.last_response_time = 0.0

    def generate(self, system_prompt: str, user_content) -> str:
        user_content_str = user_content if isinstance(user_content, str) else json.dumps(user_content, indent=2)
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_content_str},
        ]

        prompt_text = system_prompt + "\n\n" + user_content_str
        self.last_request_tokens = estimate_tokens(prompt_text)

        start_time = time.time()
        response = openai_client.chat.completions.create(
            model=self.model_name,
            messages=messages,
            temperature=0,
        )
        end_time = time.time()
        self.last_response_time = end_time - start_time

        text = response.choices[0].message.content
        self.last_response_tokens = estimate_tokens(text)
        return text

# --------- Prompt Management ---------
def load_prompt(filename: str) -> str:
    prompt_path = os.path.join(os.path.dirname(__file__), "prompts", filename)
    if not os.path.isfile(prompt_path):
        st.error(f"Prompt file not found at {prompt_path}")
        return ""
    with open(prompt_path, "r", encoding="utf-8") as f:
        return f.read()

NOTES_PROMPT = load_prompt("note_prompt.txt")
ORDER_PROMPT = load_prompt("order_prompt.txt")

# --------- Streamlit UI ---------
st.set_page_config("Macy's Order Analyzer", layout="wide")
st.title("📑 Macy's Order Analysis — Azure GPT & Vertex AI Gemini")

# Initialize session state
if 'notes_data' not in st.session_state:
    st.session_state.notes_data = None
if 'order_data' not in st.session_state:
    st.session_state.order_data = None

uploaded_file = st.file_uploader("Upload Macy's JSON Order Data", type="json")
llm_option = st.selectbox(
    "Choose LLM to use",
    ["azure", "gemini"],
    format_func=lambda x: "Azure OpenAI GPT" if x == "azure" else "Vertex AI Gemini"
)

def generate_report(client, data, prompt_type: str):
    try:
        system_prompt = NOTES_PROMPT if prompt_type == "notes" else ORDER_PROMPT
        text = client.generate(system_prompt=system_prompt, user_content=data)
        return (
            text,
            client.model_name,
            client.last_request_tokens,
            client.last_response_tokens,
            client.last_response_time,
        )
    except Exception as e:
        return f"Error generating report: {str(e)}", None, 0, 0, 0

if uploaded_file:
    try:
        data = json.load(uploaded_file)
        # Reset previous results when new file is uploaded
        st.session_state.notes_data = None
        st.session_state.order_data = None
    except json.JSONDecodeError:
        st.error("❌ Invalid JSON file format")
        data = None

    if data:
        col1, col2 = st.columns(2)
        with col1:
            if st.button("📝 Analyze Notes"):
                with st.spinner("Analyzing notes..."):
                    try:
                        client = GeminiClient() if llm_option == "gemini" else AzureClient()
                        st.session_state.notes_data = generate_report(client, data, "notes")
                    except Exception as e:
                        st.error(f"❌ Notes analysis failed: {str(e)}")
        
        with col2:
            if st.button("📦 Generate Order Summary"):
                with st.spinner("Generating order summary..."):
                    try:
                        client = GeminiClient() if llm_option == "gemini" else AzureClient()
                        st.session_state.order_data = generate_report(client, data, "order")
                    except Exception as e:
                        st.error(f"❌ Order summary failed: {str(e)}")

        # Display results in tabs
        tabs = []
        if st.session_state.notes_data:
            tabs.append("Notes Analysis")
        if st.session_state.order_data:
            tabs.append("Order Summary")
        
        if tabs:
            if len(tabs) == 1:
                # Only one tab, show directly
                tab_name = tabs[0]
                if tab_name == "Notes Analysis":
                    report = st.session_state.notes_data
                    if report[1]:
                        st.success(f"✅ Notes analysis using {report[1]}")
                        st.markdown(f"**Prompt tokens:** {report[2]} | **Response tokens:** {report[3]}")
                        st.markdown(f"**Processing time:** {report[4]:.2f}s")
                        st.markdown("---")
                        st.markdown(report[0])
                    else:
                        st.error(report[0])
                elif tab_name == "Order Summary":
                    # Show multi-tabbed order summary (major sections as tabs)
                    report = st.session_state.order_data
                    if report[1]:
                        st.success(f"✅ Order summary using {report[1]}")
                        st.markdown(f"**Prompt tokens:** {report[2]} | **Response tokens:** {report[3]}")
                        st.markdown(f"**Processing time:** {report[4]:.2f}s")
                        st.markdown("---")

                        full_text = report[0]

                        # Split into numbered sections by numbered headings (e.g. '1. ORDER SUMMARY', '2. SHIPMENT DETAILS', etc.)
                        pattern = r"(?=\n?\d+\.\s+[A-Z &]+)"
                        sections = re.split(pattern, "\n" + full_text.strip())
                        if sections[0].strip() == "":
                            sections = sections[1:]

                        tab_labels = [
                            "Order Summary",
                            "Shipment Details",
                            "Return Policy & Eligibility",
                            "Payment Details",
                            "Recommended Next Actions for Agent",
                            "Predicted Customer Intent and Answers",
                        ]

                        tabs_inner = st.tabs(tab_labels)
                        for i, tab in enumerate(tabs_inner):
                            with tab:
                                try:
                                    content = sections[i].strip()
                                    header_line = f"### {tab_labels[i]}"
                                    st.markdown(f"{header_line}\n\n{content}")
                                except IndexError:
                                    st.info("No data available for this section.")
                    else:
                        st.error(report[0])
            else:
                # Multiple tabs: Notes Analysis and Order Summary
                tab_objects = st.tabs(tabs)
                for idx, tab_name in enumerate(tabs):
                    with tab_objects[idx]:
                        if tab_name == "Notes Analysis":
                            report = st.session_state.notes_data
                            if report[1]:
                                st.success(f"✅ Notes analysis using {report[1]}")
                                st.markdown(f"**Prompt tokens:** {report[2]} | **Response tokens:** {report[3]}")
                                st.markdown(f"**Processing time:** {report[4]:.2f}s")
                                st.markdown("---")
                                st.markdown(report[0])
                            else:
                                st.error(report[0])
                        elif tab_name == "Order Summary":
                            report = st.session_state.order_data
                            if report[1]:
                                st.success(f"✅ Order summary using {report[1]}")
                                st.markdown(f"**Prompt tokens:** {report[2]} | **Response tokens:** {report[3]}")
                                st.markdown(f"**Processing time:** {report[4]:.2f}s")
                                st.markdown("---")

                                full_text = report[0]

                                pattern = r"(?=\n?\d+\.\s+[A-Z &]+)"
                                sections = re.split(pattern, "\n" + full_text.strip())
                                if sections[0].strip() == "":
                                    sections = sections[1:]

                                tab_labels = [
                                    "Order Summary",
                                    "Shipment Details",
                                    "Return Policy & Eligibility",
                                    "Payment Details",
                                    "Recommended Next Actions for Agent",
                                    "Predicted Customer Intent and Answers",
                                ]

                                tabs_inner = st.tabs(tab_labels)
                                for i, tab in enumerate(tabs_inner):
                                    with tab:
                                        try:
                                            content = sections[i].strip()
                                            header_line = f"### {tab_labels[i]}"
                                            st.markdown(f"{header_line}\n\n{content}")
                                        except IndexError:
                                            st.info("No data available for this section.")
                            else:
                                st.error(report[0])

if uploaded_file is None:
    st.info("Please upload a Macy's JSON order file to begin analysis.")

if uploaded_file and st.checkbox("Show raw JSON data"):
    try:
        st.json(data)
    except Exception:
        st.warning("Failed to parse JSON data for rendering.")