"""MIPRO optimizer for the text agent. Training examples based on Elliot Jarbe's actual writing style — structured, specific, action-oriented. Usage: NVIDIA_NIM_API_KEY=nvapi-xxx python optimize.py """ import sys import dspy from dspy.teleprompt import MIPROv2 from text_agent import ( EmailDrafter, TeamsDrafter, ToneAnalyzer, STYLE_GUIDE, ) # ── Email examples (Elliot's actual style) ── EMAIL_EXAMPLES = [ dspy.Example( context=( "Donna from Utilities asked about the " "AI Governance Framework timeline. " "Handbook draft is done (AI-001 + GenAI " "guidelines). ITS reviewing now. Security " "and Legal feedback on data handling and " "Sunshine Law already incorporated. " "Steering Group sign-off week of April 6, " "draft to Utilities week of April 20, " "final version early May. Need from Donna " "by next Wednesday: 3-5 high-priority AI " "use cases for next 6-12 months and " "existing training/comms channels. Will " "send summary deck by Friday with " "governance model, sample AIA workflow, " "and Utilities training outline. " "Recipient: Donna. Sender: Elliot Jarbe, " "IT Technical Lead & AI Manager, " "Manatee County Government." ), tone="professional", style=STYLE_GUIDE, subject=( "Re: AI Governance Framework \u2013 " "Finalizing Timeline for Utilities" ), body=( "Hi Donna,\n\n" "Thanks for the detailed questions \u2014 " "here\u2019s a concise update on status, " "dates, and what I need from Utilities." "\n\n" "1) Current status\n" "We\u2019ve completed the AI Governance " "Handbook draft (including AI\u20110001 " "and the Generative AI usage guidelines). " "ITS is reviewing it now, and we\u2019ve " "already incorporated Security and Legal " "feedback on data handling and Sunshine " "Law / public records issues.\n\n" "2) Timeline (assuming only minor edits)\n" "- Internal Steering Group sign-off: " "week of April 6\n" "- Draft shared with Utilities + small " "pilot group: week of April 20\n" "- Final version for executive review: " "early May\n\n" "If the Steering Group requests major " "structural changes (for example, " "expanding the Algorithmic Impact " "Assessment section), add about one week " "to the dates above.\n\n" "3) What I need from you (by next " "Wednesday)\n" "To tailor this for Utilities, could you " "send me:\n" "- 3\u20135 high-priority AI use cases " "Utilities expects in the next 6\u201312 " "months\n" "- Any existing training / communication " "channels we should plug into (e.g., " "town halls, recurring meetings, " "intranet pages)\n\n" "A simple bullet-point list is perfect " "\u2014 no slides or formal document " "needed.\n\n" "4) Next touchpoint\n" "I\u2019ll send you a short summary deck " "by Friday with:\n" "- The proposed governance model\n" "- A sample AIA workflow\n" "- The Utilities-specific training " "outline\n\n" "If the dates above collide with other " "Utilities projects, I can adjust the " "rollout so we start with a smaller " "pilot and expand once you and Kendall " "are comfortable.\n\n" "Best,\n" "Elliot\n\n" "Elliot A. Jarbe\n" "IT Technical Lead & AI Manager\n" "Manatee County Government" ), ).with_inputs("context", "tone", "style"), dspy.Example( context=( "Need to inform the IT Director (Mark) " "that the new firewall migration is " "complete. 47 rules migrated, 3 " "deprecated rules removed. Zero downtime " "during cutover window (Saturday 2am-6am)." " Monitoring for 48 hours. One issue: " "VPN tunnel to County EOC needs manual " "re-key by Wednesday. Need Mark to " "approve the EOC re-key change window. " "Sender: Elliot Jarbe, IT Technical Lead." ), tone="professional", style=STYLE_GUIDE, subject=( "Firewall Migration Complete \u2014 " "One Action Item for EOC VPN" ), body=( "Hi Mark,\n\n" "Quick update \u2014 the firewall " "migration wrapped up cleanly this " "weekend.\n\n" "1) Migration summary\n" "- 47 rules migrated successfully\n" "- 3 deprecated rules removed " "(documented in the change log)\n" "- Zero downtime during the Saturday " "2am\u20136am cutover window\n\n" "2) Monitoring\n" "We\u2019re in a 48-hour monitoring " "period through Tuesday EOD. So far no " "alerts or anomalies.\n\n" "3) One action item (needs your " "approval)\n" "The VPN tunnel to County EOC needs a " "manual re-key. I\u2019d like to " "schedule that for Wednesday morning " "(6\u20137am, ~5 min outage to EOC " "tunnel only).\n\n" "Can you approve that window? I\u2019ll " "coordinate with EOC ops once you give " "the green light.\n\n" "Best,\n" "Elliot" ), ).with_inputs("context", "tone", "style"), dspy.Example( context=( "Scheduling a lunch-and-learn session " "about prompt engineering for the " "department. Date: March 28, noon-1pm, " "conf room B. Pizza provided. Audience: " "all ITS staff. Will cover basics of " "prompt structure, few-shot examples, " "and how to use the county's approved " "AI tools. No prep needed, just bring " "a laptop. RSVP by March 25. " "Sender: Elliot." ), tone="friendly", style=STYLE_GUIDE, subject=( "Lunch & Learn: Prompt Engineering " "Basics \u2014 March 28" ), body=( "Hi team,\n\n" "I\u2019m hosting a lunch-and-learn on " "prompt engineering \u2014 here are the " "details.\n\n" "1) What we\u2019ll cover\n" "- How to structure effective prompts\n" "- Few-shot examples and when to use " "them\n" "- Hands-on with the county\u2019s " "approved AI tools\n\n" "2) Logistics\n" "- Date: Friday, March 28\n" "- Time: noon\u20131pm\n" "- Location: Conference Room B\n" "- Pizza provided \ud83c\udf55\n\n" "3) What to bring\n" "Just your laptop. No prep needed.\n\n" "Please RSVP by March 25 so I can get " "an accurate headcount for food.\n\n" "Looking forward to it!\n" "Elliot" ), ).with_inputs("context", "tone", "style"), ] # ── Teams examples (same content, tighter) ── TEAMS_EXAMPLES = [ dspy.Example( context=( "Donna from Utilities asked about the " "AI Governance Framework timeline. " "Handbook draft is done (AI-001 + GenAI " "guidelines). ITS reviewing now. Security " "and Legal feedback already incorporated. " "Steering Group sign-off week of April 6, " "draft to Utilities week of April 20, " "final version early May. Need from Donna " "by next Wednesday: 3-5 AI use cases and " "existing training channels. Will send " "summary deck by Friday." ), tone="friendly", style=STYLE_GUIDE, message=( "Hey Donna \u2014 quick update on AI " "governance for Utilities \ud83d\udc47\n\n" "1) Status\n" "Draft of the AI Governance Handbook is " "done (AI\u20110001 + GenAI guidelines). " "ITS is reviewing now, and we\u2019ve " "already pulled in Security and Legal " "feedback on data handling and " "Sunshine/public records.\n\n" "2) Timeline (assuming only minor " "edits)\n" "- Steering Group sign\u2011off: week " "of April 6\n" "- Draft to Utilities + small pilot " "group: week of April 20\n" "- Final version to execs: early May\n\n" "If the Steering Group requests major " "structural changes (for example, a " "bigger Algorithmic Impact Assessment " "section), expect about +1 week on " "those dates.\n\n" "3) What I need from you (by next Wed)\n" "To tune this for Utilities, can you " "drop in:\n" "- 3\u20135 high\u2011priority AI use " "cases you expect in the next " "6\u201312 months\n" "- Existing training/comms channels we " "should hook into (town halls, recurring " "meetings, intranet pages, etc.)\n\n" "Just a quick bullet list here in Teams " "is perfect \u2014 no slides.\n\n" "4) Next touchpoint\n" "By Friday I\u2019ll post a short deck " "in this thread with:\n" "- The proposed governance model\n" "- A sample AIA workflow\n" "- A Utilities\u2011specific training " "outline\n\n" "If these dates collide with other " "Utilities work, I can reorder the " "rollout so we start with a smaller " "pilot and expand once you and Kendall " "are comfortable." ), ).with_inputs("context", "tone", "style"), dspy.Example( context=( "Firewall migration complete. 47 rules " "migrated, 3 deprecated removed. Zero " "downtime Saturday 2am-6am. Monitoring " "48hrs. VPN tunnel to EOC needs re-key " "Wednesday 6-7am. Need Mark to approve." ), tone="professional", style=STYLE_GUIDE, message=( "Hey Mark \u2014 firewall migration " "update \ud83d\udee1\ufe0f\n\n" "1) Done\n" "- 47 rules migrated, 3 deprecated " "removed\n" "- Zero downtime during Saturday " "2\u20136am window\n\n" "2) Monitoring\n" "48-hour watch through Tuesday EOD. " "No alerts so far.\n\n" "3) One ask\n" "EOC VPN tunnel needs a manual re-key. " "Proposed window: Wednesday 6\u20137am " "(~5 min outage, EOC tunnel only).\n\n" "Can you approve? I\u2019ll coordinate " "with EOC ops once you give the go." ), ).with_inputs("context", "tone", "style"), dspy.Example( context=( "Lunch-and-learn on prompt engineering, " "March 28 noon-1pm, conf room B, pizza. " "All ITS staff. Covers prompt basics, " "few-shot, county AI tools. Bring laptop. " "RSVP by March 25." ), tone="friendly", style=STYLE_GUIDE, message=( "Hey team \ud83d\udc4b Lunch & learn " "on prompt engineering \u2014 details " "below\n\n" "1) What\n" "- Prompt structure basics\n" "- Few-shot examples\n" "- Hands-on with county AI tools\n\n" "2) When/where\n" "- Fri March 28, noon\u20131pm\n" "- Conf Room B\n" "- Pizza provided \ud83c\udf55\n\n" "3) Bring\n" "Just your laptop. No prep needed.\n\n" "RSVP by March 25 so I can order food. " "See you there!" ), ).with_inputs("context", "tone", "style"), ] # ── Tone examples ── TONE_EXAMPLES = [ dspy.Example( text="Hey! Let's grab coffee soon!", tone="casual", ).with_inputs("text"), dspy.Example( text=( "Dear Mr. Thompson, I am writing to " "formally request an extension." ), tone="formal", ).with_inputs("text"), dspy.Example( text="CRITICAL: Server down. Need help NOW.", tone="urgent", ).with_inputs("text"), dspy.Example( text=( "Thanks for the detailed questions " "\u2014 here\u2019s a concise update " "on status, dates, and what I need." ), tone="professional", ).with_inputs("text"), dspy.Example( text=( "Hey team \ud83d\udc4b quick update " "on the project \u2014 details below" ), tone="friendly", ).with_inputs("text"), ] # ── Metrics ── def email_metric(example, pred, trace=None): """Score email: structure, specificity.""" score = 0.0 body = pred.body # Has numbered sections if any(f"{i})" in body for i in range(1, 6)): score += 0.3 # Has bullet points if "- " in body: score += 0.2 # Has signature if "Best," in body or "Elliot" in body: score += 0.1 # Reasonable length if len(body) > 200: score += 0.2 # Context words appear ctx = example.context.lower().split() matches = sum( 1 for w in ctx if w in body.lower() ) if matches >= 3: score += 0.2 return min(score, 1.0) def teams_metric(example, pred, trace=None): """Score Teams: structure, conciseness.""" score = 0.0 msg = pred.message # Has numbered sections if any(f"{i})" in msg for i in range(1, 6)): score += 0.3 # Has bullet points if "- " in msg: score += 0.2 # No signature block if "Best," not in msg: score += 0.1 # Concise (shorter than email) if 100 < len(msg) < 2000: score += 0.2 # Context words ctx = example.context.lower().split() matches = sum( 1 for w in ctx if w in msg.lower() ) if matches >= 3: score += 0.2 return min(score, 1.0) def tone_metric(example, pred, trace=None): """Score tone: exact match.""" return 1.0 if pred.tone == example.tone else 0.0 # ── Optimizers ── def optimize_email(lm): dspy.configure(lm=lm) optimizer = MIPROv2( metric=email_metric, auto="light", num_threads=2, ) return optimizer.compile( dspy.ChainOfThought(EmailDrafter), trainset=EMAIL_EXAMPLES, ) def optimize_teams(lm): dspy.configure(lm=lm) optimizer = MIPROv2( metric=teams_metric, auto="light", num_threads=2, ) return optimizer.compile( dspy.ChainOfThought(TeamsDrafter), trainset=TEAMS_EXAMPLES, ) def optimize_tone(lm): dspy.configure(lm=lm) optimizer = MIPROv2( metric=tone_metric, auto="light", num_threads=2, ) return optimizer.compile( dspy.Predict(ToneAnalyzer), trainset=TONE_EXAMPLES, ) def main(): model = sys.argv[1] if len(sys.argv) > 1 else ( "nvidia_nim/nvidia/" "nemotron-3-super-120b-a12b" ) print(f"Optimizing with model: {model}") lm = dspy.LM(model, max_tokens=4096) print("\n--- Optimizing Email Drafter ---") opt_email = optimize_email(lm) opt_email.save("optimized_email.json") print("Saved: optimized_email.json") print("\n--- Optimizing Teams Drafter ---") opt_teams = optimize_teams(lm) opt_teams.save("optimized_teams.json") print("Saved: optimized_teams.json") print("\n--- Optimizing Tone Analyzer ---") opt_tone = optimize_tone(lm) opt_tone.save("optimized_tone.json") print("Saved: optimized_tone.json") print("\nDone!") if __name__ == "__main__": main()