Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464import osimport gradio as grimport anthropicfrom pypdf import PdfReader# ββ Anthropic client ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclient = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))SYSTEM_PROMPT = """You are an expert problem analyst and innovation coach helping interns understand real-world problems and brainstorm creative solutions.When given a transcription or document, you will:1. **PROBLEM UNDERSTANDING**- Identify and clearly articulate the core problem being discussed- Highlight key pain points, stakeholders, and context- Summarize what is known vs unknown about the problem2. **ROOT CAUSE ANALYSIS**- Break down WHY this problem exists- Identify underlying causes (technical, organizational, process-related)3. **BRAINSTORMING IDEAS**- Generate 5-8 diverse, creative solution directions- Include both quick wins and long-term strategic ideas- Think across technology, process, and people dimensions4. **NEXT STEPS FOR INTERNS**- Suggest 3 concrete actions the intern can take immediately to explore this furtherKeep your tone encouraging, clear, and structured. Use headers and bullet points for readability."""def extract_text_from_pdf(pdf_file) -> str:reader = PdfReader(pdf_file)pages_text = []for page in reader.pages:text = page.extract_text()if text:pages_text.append(text.strip())return "\n\n".join(pages_text)def run_agent(text_input: str, pdf_file, progress=gr.Progress()):content = ""if pdf_file is not None:progress(0.1, desc="Reading PDF...")try:content = extract_text_from_pdf(pdf_file)if not content.strip():yield "Could not extract text from this PDF. It may be scanned or image-based. Please paste the text manually."returnexcept Exception as e:yield f"Error reading PDF: {str(e)}"returnelif text_input and text_input.strip():content = text_input.strip()else:yield "Please paste a transcription or upload a PDF file to get started."returnif len(content) < 50:yield "The input seems too short. Please provide more context for a meaningful analysis."returnMAX_CHARS = 12000if len(content) > MAX_CHARS:content = content[:MAX_CHARS] + "\n\n[... content truncated for length ...]"progress(0.3, desc="Analyzing problem...")user_message = f"""Here is the transcription / document content to analyze:---{content}---Please provide a full problem analysis and brainstorming session based on this content."""output = ""try:with client.messages.stream(model="claude-sonnet-4-6",max_tokens=2048,system=SYSTEM_PROMPT,messages=[{"role": "user", "content": user_message}],) as stream:progress(0.5, desc="Generating insights...")for text_chunk in stream.text_stream:output += text_chunkyield outputexcept anthropic.AuthenticationError:yield "Invalid API key. Please set your ANTHROPIC_API_KEY in the Space secrets."except anthropic.RateLimitError:yield "Rate limit reached. Please wait a moment and try again."except Exception as e:yield f"Unexpected error: {str(e)}"# ββ Custom CSS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββcustom_css = """@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap');* {font-family: 'Inter', sans-serif !important;box-sizing: border-box;}body, .gradio-container {background-color: #ffffff !important;color: #111827 !important;}.gradio-container {max-width: 1280px !important;margin: 0 auto !important;padding: 0 2rem !important;}/* ββ Header ββ */#app-header {padding: 2.75rem 0 2rem;border-bottom: 1px solid #e5e7eb;margin-bottom: 2rem;}#app-header h1 {font-size: 1.5rem;font-weight: 600;color: #111827;letter-spacing: -0.025em;margin: 0 0 0.35rem 0;line-height: 1.3;}#app-header p {font-size: 0.875rem;color: #6b7280;margin: 0;font-weight: 400;line-height: 1.5;}#header-tag {display: inline-block;font-size: 0.7rem;font-weight: 600;letter-spacing: 0.1em;text-transform: uppercase;color: #2563eb;background: #eff6ff;border: 1px solid #bfdbfe;border-radius: 4px;padding: 0.2rem 0.6rem;margin-bottom: 0.85rem;}/* ββ Panels ββ */.input-panel, .output-panel {background: #ffffff !important;border: 1px solid #e5e7eb !important;border-radius: 10px !important;padding: 1.5rem !important;}/* ββ Section label ββ */.section-label {font-size: 0.7rem !important;font-weight: 600 !important;text-transform: uppercase !important;letter-spacing: 0.1em !important;color: #9ca3af !important;margin: 0 0 1rem 0 !important;}/* ββ Textarea ββ */textarea {background: #f9fafb !important;border: 1px solid #e5e7eb !important;border-radius: 8px !important;color: #111827 !important;font-size: 0.875rem !important;line-height: 1.75 !important;padding: 0.875rem 1rem !important;resize: vertical !important;transition: border-color 0.15s, box-shadow 0.15s !important;}textarea:focus {border-color: #2563eb !important;outline: none !important;box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.08) !important;background: #ffffff !important;}textarea::placeholder {color: #d1d5db !important;}/* ββ File upload ββ */.gr-file {background: #f9fafb !important;border: 1px dashed #d1d5db !important;border-radius: 8px !important;color: #6b7280 !important;}/* ββ Tabs ββ */.tab-nav {border-bottom: 1px solid #e5e7eb !important;margin-bottom: 1rem !important;background: transparent !important;}.tab-nav button {font-size: 0.8rem !important;font-weight: 500 !important;color: #9ca3af !important;border: none !important;background: transparent !important;padding: 0.5rem 1rem 0.6rem !important;border-radius: 0 !important;letter-spacing: 0.01em !important;transition: color 0.15s !important;}.tab-nav button:hover {color: #374151 !important;}.tab-nav button.selected {color: #2563eb !important;border-bottom: 2px solid #2563eb !important;font-weight: 600 !important;}/* ββ Run button ββ */#run-btn {background: #2563eb !important;color: #ffffff !important;border: none !important;border-radius: 8px !important;font-size: 0.875rem !important;font-weight: 600 !important;padding: 0.7rem 1.5rem !important;letter-spacing: 0.01em !important;transition: background 0.15s ease, box-shadow 0.15s ease !important;margin-top: 0.875rem !important;width: 100% !important;cursor: pointer !important;}#run-btn:hover {background: #1d4ed8 !important;box-shadow: 0 2px 8px rgba(37, 99, 235, 0.25) !important;}/* ββ Output area ββ */#output-area {background: #f9fafb !important;border: 1px solid #e5e7eb !important;border-radius: 8px !important;padding: 1.25rem 1.5rem !important;min-height: 420px !important;font-size: 0.875rem !important;line-height: 1.8 !important;color: #374151 !important;}#output-area h1, #output-area h2, #output-area h3 {color: #111827 !important;font-weight: 600 !important;letter-spacing: -0.015em !important;margin-top: 1.5rem !important;margin-bottom: 0.5rem !important;}#output-area h2 {font-size: 1rem !important;border-bottom: 1px solid #f3f4f6 !important;padding-bottom: 0.4rem !important;}#output-area strong {color: #111827 !important;font-weight: 600 !important;}#output-area ul, #output-area ol {padding-left: 1.25rem !important;color: #4b5563 !important;margin: 0.4rem 0 !important;}#output-area li {margin-bottom: 0.25rem !important;}#output-area p {color: #4b5563 !important;}#output-area em {color: #9ca3af !important;}/* ββ Accordion ββ */.gr-accordion {background: #f9fafb !important;border: 1px solid #e5e7eb !important;border-radius: 8px !important;margin-top: 0.875rem !important;}.gr-accordion .label-wrap span {font-size: 0.8rem !important;color: #6b7280 !important;font-weight: 500 !important;}/* ββ Labels ββ */label, .gr-label {color: #6b7280 !important;font-size: 0.8rem !important;font-weight: 500 !important;}/* ββ Examples ββ */.gr-examples {margin-top: 1rem !important;}.gr-examples table {background: #ffffff !important;border: 1px solid #e5e7eb !important;border-radius: 8px !important;overflow: hidden !important;}.gr-examples td {color: #6b7280 !important;font-size: 0.8rem !important;padding: 0.6rem 1rem !important;border-bottom: 1px solid #f3f4f6 !important;}.gr-examples tr:hover td {background: #f9fafb !important;cursor: pointer !important;}/* ββ Divider ββ */.divider {border: none !important;border-top: 1px solid #e5e7eb !important;margin: 2rem 0 1.5rem !important;}/* ββ Scrollbar ββ */::-webkit-scrollbar { width: 5px; }::-webkit-scrollbar-track { background: #f9fafb; }::-webkit-scrollbar-thumb { background: #e5e7eb; border-radius: 4px; }::-webkit-scrollbar-thumb:hover { background: #d1d5db; }"""# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(title="Problem Brainstormer",css=custom_css,) as demo:gr.HTML("""<div id="app-header"><div id="header-tag">Intern Tool</div><h1>Problem Brainstormer</h1><p>Paste a meeting transcript or upload a document to get structured problem analysis and solution ideas.</p></div>""")with gr.Row(equal_height=False):with gr.Column(scale=1, elem_classes=["input-panel"]):gr.HTML('<p class="section-label">Input</p>')with gr.Tabs():with gr.Tab("Paste Text"):text_input = gr.Textbox(label="",placeholder="Paste your meeting notes, transcript, or problem description here...",lines=16,max_lines=32,)with gr.Tab("Upload PDF"):pdf_input = gr.File(label="",file_types=[".pdf"],file_count="single",)gr.HTML('<p style="font-size:0.75rem;color:#9ca3af;margin-top:0.5rem">Text-based PDFs only. Scanned documents are not supported.</p>')run_btn = gr.Button("Analyze and Brainstorm",variant="primary",elem_id="run-btn",)with gr.Accordion("How to use", open=False):gr.Markdown("""**Paste Text** β Copy any transcript, meeting notes, or problem statement into the text field.**Upload PDF** β Upload a text-based PDF such as a spec, report, or research document.**Click Analyze** to receive:- A clear articulation of the core problem- Root cause breakdown- 5β8 creative solution directions- Concrete next steps you can take as an intern""")with gr.Column(scale=1, elem_classes=["output-panel"]):gr.HTML('<p class="section-label">Analysis</p>')output = gr.Markdown(value="*Your analysis will appear here once you submit.*",elem_id="output-area",)gr.HTML('<hr class="divider">')gr.HTML('<p class="section-label">Example Inputs</p>')gr.Examples(examples=[["In today's standup, the team discussed that customers are complaining that the onboarding flow takes too long. New users drop off after the third step in the sign-up process. We don't have clear data on exactly which step causes the most drop-off. The product team thinks it might be the email verification step but engineering says it could be the profile setup form. We have about 2 weeks before the next release and the CEO wants this fixed before the investor demo.",None,],["Meeting transcript: So the main issue we're facing is that our data pipeline fails every Friday evening when batch jobs run. The on-call engineer has to manually restart it each time. It's been happening for three months. We've tried looking at the logs but they're not detailed enough. The infrastructure team is overwhelmed and can't prioritize it. Meanwhile the analytics team can't get their Monday morning reports on time which is affecting business decisions.",None,],],inputs=[text_input, pdf_input],label="",)run_btn.click(fn=run_agent,inputs=[text_input, pdf_input],outputs=output,show_progress="full",)text_input.submit(fn=run_agent,inputs=[text_input, pdf_input],outputs=output,show_progress="full",)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603"""Intern Problem-Solving APIMulti-agent FastAPI backend for structured problem analysis and solution generation.Agents: Analyst β Root Cause β Solution Brainstorm β Action Planner β PDF Generator"""import ioimport jsonimport osimport refrom datetime import datetimefrom typing import Optionalimport anthropicfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom reportlab.lib import colorsfrom reportlab.lib.pagesizes import A4from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheetfrom reportlab.lib.units import mmfrom reportlab.platypus import (HRFlowable,Paragraph,SimpleDocTemplate,Spacer,Table,TableStyle,)# ββ App Setup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββapp = FastAPI(title="Intern Problem-Solving API",description="Multi-agent system: Analyst β Root Cause β Solutions β Action Plan",version="1.0.0",)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY", ""))# ββ Request / Response Models βββββββββββββββββββββββββββββββββββββββββββββββββclass ProblemInput(BaseModel):content: strintern_name: Optional[str] = "Intern"intern_role: Optional[str] = "AI Developer Intern"intern_goal: Optional[str] = ""class AgentOutput(BaseModel):agent: stroutput: strclass FullAnalysis(BaseModel):problem_statement: strroot_causes: strsolutions: straction_plan: strthinking_feedback: str# ββ Agent Definitions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββAGENT_ANALYST = """You are the Problem Analyst Agent.Your ONLY job: read the input and produce a crisp, structured problem statement.Output format (use these exact headers):## Core ProblemOne clear sentence: who has what problem, in what context.## Key Pain Points- Bullet each distinct pain point (max 5)## Stakeholders- Who is affected and how## Known vs Unknown- Known: what facts are clear- Unknown: what gaps existKeep it factual. No solutions yet. Max 250 words."""AGENT_ROOT_CAUSE = """You are the Root Cause Analysis Agent.You receive a problem statement. Your job: find WHY it exists.Output format:## Root Cause Analysis### Immediate CauseWhat is the visible trigger of the problem?### Underlying CausesBreak down causes across three lenses:- **Technical**: systems, tools, architecture issues- **Process**: workflow, communication, or procedural gaps- **People/Skills**: knowledge gaps, habits, capacity issues### The Real Root CauseOne sentence: the deepest cause everything traces back to.Be specific. Use "because" chains to trace causes deeper. Max 200 words."""AGENT_SOLUTIONS = """You are the Solution Brainstorm Agent.You receive a problem + root cause. Generate diverse, creative solutions.Output format:## Solution Ideas### Quick Wins (Do this week)1. **[Name]** β What it is + why it helps### Medium-Term Fixes (Do this month)2. **[Name]** β What it is + why it helps3. **[Name]** β What it is + why it helps### Strategic / Long-Term4. **[Name]** β What it is + why it helps5. **[Name]** β What it is + why it helps### Unconventional / Creative6. **[Name]** β Think outside the box7. **[Name]** β Wildcard ideaFor each idea: name it, describe it in 1-2 sentences, state the trade-off.Think across: AI tools, process redesign, automation, collaboration, education.Max 300 words."""AGENT_ACTION_PLANNER = """You are the Action Planner Agent.You receive the full analysis. Your job: give the intern 3 concrete next actions.Output format:## Your Next Steps### Action 1: [Do This Today]**What exactly**: One sentence instruction**How**: Step-by-step (3-4 steps max)**Success looks like**: How you'll know it worked**Time needed**: X hours### Action 2: [Do This Week]**What exactly**: One sentence instruction**How**: Step-by-step (3-4 steps max)**Success looks like**: How you'll know it worked**Time needed**: X hours### Action 3: [Do This Month]**What exactly**: One sentence instruction**How**: Step-by-step (3-4 steps max)**Success looks like**: How you'll know it worked**Time needed**: X hoursBe specific enough that the intern can start immediately. No vague advice."""AGENT_THINKING_COACH = """You are the Thinking Coach Agent.You are an encouraging but honest coach helping an intern grow.You receive the original problem input + full analysis.Output format:## Thinking Feedback### What You Got Right- Specific things in how the problem was framed that show good thinking### Blind Spots to Watch- Where the framing was shallow or missing something important- Specific examples only β no generic observations### Are You Thinking Like a Problem Solver or Task Executor?One honest assessment with evidence from their input.### One Big ShiftThe single most important mindset or approach shift that will help this intern most.### For Your Next Meeting3 specific things to do differently next time you face this type of problem.Keep it encouraging but honest. Max 250 words."""# ββ Core Agent Runner βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef run_agent(system_prompt: str, user_content: str, max_tokens: int = 800) -> str:"""Run a single agent and return its text output."""response = client.messages.create(model="claude-sonnet-4-6",max_tokens=max_tokens,system=system_prompt,messages=[{"role": "user", "content": user_content}],)return response.content[0].text# ββ Pipeline ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef run_pipeline(content: str, name: str, role: str, goal: str) -> FullAnalysis:"""Run all 5 agents in sequence, passing outputs forward."""context_header = f"""Intern Name: {name}Intern Role: {role}Current Goal: {goal if goal else 'Not specified'}--- INPUT ---{content[:8000]}--- END INPUT ---"""# Agent 1: Analystproblem_statement = run_agent(AGENT_ANALYST,f"Analyze this problem:\n{context_header}",max_tokens=600,)# Agent 2: Root Cause (receives problem statement)root_causes = run_agent(AGENT_ROOT_CAUSE,f"Problem Statement:\n{problem_statement}\n\nOriginal input context:\n{content[:3000]}",max_tokens=500,)# Agent 3: Solutions (receives problem + root causes)solutions = run_agent(AGENT_SOLUTIONS,f"Problem Statement:\n{problem_statement}\n\nRoot Causes:\n{root_causes}",max_tokens=700,)# Agent 4: Action Planner (receives everything so far)action_plan = run_agent(AGENT_ACTION_PLANNER,f"""Intern Role: {role}\nIntern Goal: {goal}Problem Statement:\n{problem_statement}Root Causes:\n{root_causes}Solutions:\n{solutions}""",max_tokens=700,)# Agent 5: Thinking Coach (sees original input + full analysis)thinking_feedback = run_agent(AGENT_THINKING_COACH,f"""Original Input from Intern:\n{content[:3000]}Problem Analysis:\n{problem_statement}Root Causes:\n{root_causes}""",max_tokens=600,)return FullAnalysis(problem_statement=problem_statement,root_causes=root_causes,solutions=solutions,action_plan=action_plan,thinking_feedback=thinking_feedback,)# ββ PDF Generator βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef strip_markdown(text: str) -> str:"""Remove markdown bold/italic markers for plain PDF text."""text = re.sub(r"\*\*(.*?)\*\*", r"\1", text)text = re.sub(r"\*(.*?)\*", r"\1", text)return textdef build_pdf(analysis: FullAnalysis, name: str, role: str) -> bytes:"""Generate a professional PDF report from the analysis."""buf = io.BytesIO()# ββ Page setupdoc = SimpleDocTemplate(buf,pagesize=A4,rightMargin=20 * mm,leftMargin=20 * mm,topMargin=22 * mm,bottomMargin=22 * mm,)styles = getSampleStyleSheet()W = A4[0] - 40 * mm # usable width# ββ Custom styless_title = ParagraphStyle("title",parent=styles["Normal"],fontSize=22,fontName="Helvetica-Bold",textColor=colors.HexColor("#1a1a2e"),spaceAfter=4,)s_sub = ParagraphStyle("sub",parent=styles["Normal"],fontSize=11,fontName="Helvetica",textColor=colors.HexColor("#6b7280"),spaceAfter=12,)s_section = ParagraphStyle("section",parent=styles["Normal"],fontSize=13,fontName="Helvetica-Bold",textColor=colors.HexColor("#2563eb"),spaceBefore=16,spaceAfter=6,)s_h3 = ParagraphStyle("h3",parent=styles["Normal"],fontSize=11,fontName="Helvetica-Bold",textColor=colors.HexColor("#374151"),spaceBefore=8,spaceAfter=3,)s_body = ParagraphStyle("body",parent=styles["Normal"],fontSize=10,fontName="Helvetica",textColor=colors.HexColor("#374151"),leading=15,spaceAfter=4,)s_label = ParagraphStyle("label",parent=styles["Normal"],fontSize=8,fontName="Helvetica-Bold",textColor=colors.white,)def agent_badge(label: str, color: str) -> Table:"""Small colored badge showing which agent produced this section."""data = [[Paragraph(f"β {label}", s_label)]]t = Table(data, colWidths=[W])t.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), colors.HexColor(color)),("TOPPADDING", (0, 0), (-1, -1), 5),("BOTTOMPADDING", (0, 0), (-1, -1), 5),("LEFTPADDING", (0, 0), (-1, -1), 10),("ROUNDEDCORNERS", [4, 4, 4, 4]),]))return tdef render_markdown_block(md_text: str) -> list:"""Convert basic markdown to ReportLab flowables."""flowables = []for line in md_text.splitlines():line = line.strip()if not line:flowables.append(Spacer(1, 4))continueif line.startswith("## "):flowables.append(Paragraph(line[3:], s_section))elif line.startswith("### "):flowables.append(Paragraph(line[4:], s_h3))elif line.startswith("- ") or line.startswith("* "):clean = strip_markdown(line[2:])flowables.append(Paragraph(f"β’ {clean}", s_body))elif re.match(r"^\d+\.", line):clean = strip_markdown(line)flowables.append(Paragraph(clean, s_body))elif line.startswith("**") and line.endswith("**"):flowables.append(Paragraph(line[2:-2], s_h3))else:clean = strip_markdown(line)flowables.append(Paragraph(clean, s_body))return flowablesstory = []# ββ Headerstory.append(Paragraph("Problem Analysis Report", s_title))story.append(Paragraph(f"{name} Β· {role} Β· {datetime.now().strftime('%d %B %Y')}",s_sub,))story.append(HRFlowable(width=W, thickness=1.5, color=colors.HexColor("#2563eb"), spaceAfter=10))# ββ Section 1: Problem Statementstory.append(agent_badge("AGENT 1 β Problem Analyst", "#1e3a5f"))story.append(Spacer(1, 6))story += render_markdown_block(analysis.problem_statement)# ββ Section 2: Root Causestory.append(Spacer(1, 8))story.append(agent_badge("AGENT 2 β Root Cause Analyst", "#1a4731"))story.append(Spacer(1, 6))story += render_markdown_block(analysis.root_causes)# ββ Section 3: Solutionsstory.append(Spacer(1, 8))story.append(agent_badge("AGENT 3 β Solution Brainstorm", "#4a1942"))story.append(Spacer(1, 6))story += render_markdown_block(analysis.solutions)# ββ Section 4: Action Planstory.append(Spacer(1, 8))story.append(agent_badge("AGENT 4 β Action Planner", "#7c2d12"))story.append(Spacer(1, 6))story += render_markdown_block(analysis.action_plan)# ββ Section 5: Thinking Coachstory.append(Spacer(1, 8))story.append(agent_badge("AGENT 5 β Thinking Coach", "#312e81"))story.append(Spacer(1, 6))story += render_markdown_block(analysis.thinking_feedback)# ββ Footer notestory.append(Spacer(1, 16))story.append(HRFlowable(width=W, thickness=0.5, color=colors.HexColor("#e5e7eb"), spaceAfter=6))story.append(Paragraph("Generated by the AI Intern Problem-Solving System Β· Confidential",ParagraphStyle("footer", parent=styles["Normal"], fontSize=8, textColor=colors.HexColor("#9ca3af"), alignment=1),))doc.build(story)buf.seek(0)return buf.read()# ββ API Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.get("/")def root():return {"service": "Intern Problem-Solving API","version": "1.0.0","agents": ["1. Problem Analyst","2. Root Cause Analyst","3. Solution Brainstorm","4. Action Planner","5. Thinking Coach",],"endpoints": {"POST /analyze": "Run full 5-agent pipeline, returns JSON","POST /analyze/stream": "Stream analysis as server-sent events","POST /analyze/pdf": "Run pipeline + return downloadable PDF","GET /health": "Health check",},}@app.get("/health")def health():return {"status": "ok", "timestamp": datetime.utcnow().isoformat()}@app.post("/analyze", response_model=FullAnalysis)def analyze(body: ProblemInput):"""Run full 5-agent pipeline. Returns structured JSON."""if not body.content.strip():raise HTTPException(status_code=400, detail="Content cannot be empty.")if len(body.content) < 30:raise HTTPException(status_code=400, detail="Content too short for meaningful analysis.")try:result = run_pipeline(content=body.content,name=body.intern_name or "Intern",role=body.intern_role or "AI Developer Intern",goal=body.intern_goal or "",)return resultexcept anthropic.AuthenticationError:raise HTTPException(status_code=401, detail="Invalid Anthropic API key.")except anthropic.RateLimitError:raise HTTPException(status_code=429, detail="Rate limit reached. Please wait and retry.")except Exception as e:raise HTTPException(status_code=500, detail=str(e))@app.post("/analyze/stream")def analyze_stream(body: ProblemInput):"""Stream each agent's output as server-sent events (SSE)."""if not body.content.strip():raise HTTPException(status_code=400, detail="Content cannot be empty.")def event_stream():agents = [("analyst", AGENT_ANALYST, "Problem Analyst"),("root_cause", AGENT_ROOT_CAUSE, "Root Cause Analyst"),("solutions", AGENT_SOLUTIONS, "Solution Brainstorm"),("action_plan", AGENT_ACTION_PLANNER, "Action Planner"),("thinking", AGENT_THINKING_COACH, "Thinking Coach"),]context = {"content": body.content[:8000],"name": body.intern_name or "Intern","role": body.intern_role or "AI Developer Intern","goal": body.intern_goal or "",}accumulated = {}for key, system_prompt, label in agents:# Send agent start eventyield f"data: {json.dumps({'event': 'agent_start', 'agent': key, 'label': label})}\n\n"# Build context-aware prompt for this agentif key == "analyst":user_msg = f"Intern: {context['name']} | Role: {context['role']} | Goal: {context['goal']}\n\nAnalyze:\n{context['content']}"elif key == "root_cause":user_msg = f"Problem:\n{accumulated.get('analyst','')}\n\nOriginal:\n{context['content'][:2000]}"elif key == "solutions":user_msg = f"Problem:\n{accumulated.get('analyst','')}\n\nRoot Causes:\n{accumulated.get('root_cause','')}"elif key == "action_plan":user_msg = f"Role: {context['role']}\n\nProblem:\n{accumulated.get('analyst','')}\n\nCauses:\n{accumulated.get('root_cause','')}\n\nSolutions:\n{accumulated.get('solutions','')}"else:user_msg = f"Original Input:\n{context['content'][:2500]}\n\nProblem:\n{accumulated.get('analyst','')}\n\nCauses:\n{accumulated.get('root_cause','')}"# Stream this agent's outputagent_text = ""with client.messages.stream(model="claude-sonnet-4-6",max_tokens=800,system=system_prompt,messages=[{"role": "user", "content": user_msg}],) as stream:for chunk in stream.text_stream:agent_text += chunkyield f"data: {json.dumps({'event': 'token', 'agent': key, 'text': chunk})}\n\n"accumulated[key] = agent_textyield f"data: {json.dumps({'event': 'agent_done', 'agent': key})}\n\n"yield f"data: {json.dumps({'event': 'done'})}\n\n"return StreamingResponse(event_stream(),media_type="text/event-stream",headers={"Cache-Control": "no-cache","X-Accel-Buffering": "no",},)@app.post("/analyze/pdf")def analyze_pdf(body: ProblemInput):"""Run full pipeline and return a downloadable PDF report."""if not body.content.strip():raise HTTPException(status_code=400, detail="Content cannot be empty.")try:analysis = run_pipeline(content=body.content,name=body.intern_name or "Intern",role=body.intern_role or "AI Developer Intern",goal=body.intern_goal or "",)pdf_bytes = build_pdf(analysis,name=body.intern_name or "Intern",role=body.intern_role or "AI Developer Intern",)filename = f"problem_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"return StreamingResponse(io.BytesIO(pdf_bytes),media_type="application/pdf",headers={"Content-Disposition": f'attachment; filename="{filename}"'},)except anthropic.AuthenticationError:raise HTTPException(status_code=401, detail="Invalid Anthropic API key.")except anthropic.RateLimitError:raise HTTPException(status_code=429, detail="Rate limit. Please wait and retry.")except Exception as e:raise HTTPException(status_code=500, detail=str(e))# ββ Dev Runner ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif __name__ == "__main__":import uvicornuvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)
app.py+563-424