Spaces:
Sleeping
Sleeping
File size: 16,667 Bytes
c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 08d0709 c4bd9b0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | """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()
|