World Cup Agent Cursor commited on
Commit
06caba1
·
1 Parent(s): 17ae2c9

Make post-match learnings terse and data-focused.

Browse files

Tighten reflection prompts to report specific mistakes and endpoint reliability without verbose or sycophantic prose.

Co-authored-by: Cursor <cursoragent@cursor.com>

Files changed (2) hide show
  1. discord_notify.py +73 -0
  2. reflect.py +37 -37
discord_notify.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Discord notification helper. Requires DISCORD_BOT_TOKEN in env."""
2
+
3
+ import logging
4
+ import os
5
+
6
+ import requests
7
+
8
+ CHANNEL_ID = "1515805396575715409"
9
+
10
+
11
+ def _send(message: str) -> None:
12
+ token = os.getenv("DISCORD_BOT_TOKEN", "")
13
+ if not token:
14
+ logging.warning("DISCORD_BOT_TOKEN not set — skipping Discord notification")
15
+ return
16
+ try:
17
+ resp = requests.post(
18
+ f"https://discord.com/api/v10/channels/{CHANNEL_ID}/messages",
19
+ headers={"Authorization": f"Bot {token}", "Content-Type": "application/json"},
20
+ json={"content": message},
21
+ timeout=10,
22
+ )
23
+ resp.raise_for_status()
24
+ except Exception as e:
25
+ logging.error("Discord notify failed: %s", e)
26
+
27
+
28
+ def notify_prediction(match: str, pick: str, confidence: int,
29
+ reasoning: str, research_cost: float, services_used: list,
30
+ kickoff: str) -> None:
31
+ pick_label = {"home": match.split(" vs ")[0], "away": match.split(" vs ")[1], "draw": "DRAW"}.get(pick, pick)
32
+ lines = [
33
+ f"⚽ **{match}** — Prediction",
34
+ f"• Pick: **{pick_label.upper()}** (confidence {confidence}/10)",
35
+ f"• Reasoning: {reasoning}",
36
+ f"• Research: ${research_cost:.4f} spent on {len(services_used)} endpoint(s)",
37
+ f"• Kickoff: {kickoff[:16].replace('T', ' ')} UTC",
38
+ ]
39
+ _send("\n".join(lines))
40
+
41
+
42
+ def notify_outcome(match: str, home: str, away: str, home_score: int, away_score: int,
43
+ pick: str, correct: bool, research_cost: float,
44
+ evaluation: str, new_strategy_snippet: str) -> None:
45
+ result_icon = "✅" if correct else "❌"
46
+ outcome_label = "CORRECT" if correct else "INCORRECT"
47
+ actual = "home" if home_score > away_score else ("away" if away_score > home_score else "draw")
48
+ actual_label = {"home": home, "away": away, "draw": "DRAW"}.get(actual, actual)
49
+ pick_label = {"home": home, "away": away, "draw": "DRAW"}.get(pick, pick)
50
+
51
+ # Grab first substantive line from evaluation as key learning
52
+ learning = ""
53
+ for line in evaluation.splitlines():
54
+ line = line.strip().lstrip("0123456789.-) ").strip()
55
+ if not line or line.endswith(":") or line.upper() in ("MISTAKE", "DATA"):
56
+ continue
57
+ if len(line) > 15:
58
+ learning = line[:140]
59
+ break
60
+
61
+ strategy_snippet = new_strategy_snippet.strip()[:160].replace("\n", " ")
62
+
63
+ lines = [
64
+ f"{result_icon} **{match}** — Result {outcome_label}",
65
+ f"• Score: {home} {home_score}–{away_score} {away}",
66
+ f"• Predicted: {pick_label.upper()} → actual: {actual_label.upper()}",
67
+ f"• Research cost: ${research_cost:.4f}",
68
+ ]
69
+ if learning:
70
+ lines.append(f"• Key takeaway: {learning}")
71
+ if strategy_snippet:
72
+ lines.append(f"• Strategy update: {strategy_snippet}{'…' if len(new_strategy_snippet.strip()) > 160 else ''}")
73
+ _send("\n".join(lines))
reflect.py CHANGED
@@ -136,29 +136,32 @@ research_summary = ""
136
  for svc in entry.get("services_used", []):
137
  research_summary += f"\n- {svc['source']} (${svc['cost']:.4f}): {svc.get('reason', '')}"
138
 
139
- eval_prompt = f"""You are an independent evaluator assessing a World Cup match prediction.
 
 
 
140
 
141
- Match: {MATCH}
142
- Result: {HOME} {result_data['home_score']}-{result_data['away_score']} {AWAY}
143
- Actual winner: {actual_winner}
144
 
145
- Prediction that was made:
146
- - Pick: {pick}
147
- - Confidence: {prediction.get('confidence')}/10
148
- - Reasoning: {prediction.get('reasoning')}
 
149
 
150
- Research purchased (${entry.get('research_cost', 0):.4f} total):{research_summary if research_summary else " (none purchased)"}
 
 
 
 
151
 
152
- Outcome: prediction was {'CORRECT' if correct else 'INCORRECT'}
153
- Research cost: ${entry.get('research_cost', 0):.4f} USDC
154
 
155
- Evaluate honestly:
156
- 1. Was the prediction correct? Why or why not?
157
- 2. Which purchased research was valuable (if any)?
158
- 3. What was the key factor that determined the outcome?
159
- 4. What should the agent learn from this match?
160
 
161
- Be specific and critical. This evaluation will update the agent's strategy."""
162
 
163
  log("Asking Gemini for evaluation...")
164
  try:
@@ -170,32 +173,28 @@ except Exception as e:
170
 
171
  # ── Step 4: Reflector call (updates strategy) ─────────────────────────────
172
 
173
- recent_results = results[-5:]
174
-
175
- reflect_prompt = f"""You are updating a World Cup prediction strategy document.
176
 
177
- Current strategy (may be empty if this is the first match):
178
- {strategy if strategy else "(empty — this is the first match)"}
179
 
180
- Evaluator's assessment of the latest match ({MATCH}):
181
  {evaluation}
182
 
183
- Recent match history for context:
184
- {json.dumps([{
185
- "match": r.get("match"),
186
- "pick": r.get("prediction", {}).get("pick"),
187
- "correct": r.get("correct"),
188
- "reasoning": r.get("prediction", {}).get("reasoning"),
189
- } for r in recent_results], indent=2)}
 
190
 
191
- Rewrite the strategy document with EXACTLY ONE change based on this match:
192
- - Add a new rule, modify an existing rule, or remove an outdated rule
193
- - Keep all still-valid rules from the current strategy
194
- - Note which x402 data endpoints have been useful vs not useful
195
- - Include the match that informed each rule (e.g., "NED vs JPN: ...")
196
- - Stay under 500 words total
197
 
198
- Return ONLY the updated strategy document text. No preamble, no explanation."""
199
 
200
  log("Asking Gemini to update strategy...")
201
  try:
@@ -227,6 +226,7 @@ with open(lock_path, "w") as lock_file:
227
  "evaluation": evaluation,
228
  "reflected": True,
229
  "reflected_at": datetime.now(timezone.utc).isoformat(),
 
230
  })
231
  tmp = results_path.with_suffix(f".tmp.{HOME}_{AWAY}")
232
  tmp.write_text(json.dumps(results, indent=2))
 
136
  for svc in entry.get("services_used", []):
137
  research_summary += f"\n- {svc['source']} (${svc['cost']:.4f}): {svc.get('reason', '')}"
138
 
139
+ mistake_section = "" if correct else """MISTAKE:
140
+ - One sentence: what the pick got wrong.
141
+ - One sentence: the specific reasoning error.
142
+ """
143
 
144
+ eval_prompt = f"""Write a terse post-match learning note for a prediction agent.
 
 
145
 
146
+ Match: {MATCH}
147
+ Result: {HOME} {result_data['home_score']}-{result_data['away_score']} {AWAY} (winner: {actual_winner})
148
+ Predicted: {pick} (confidence {prediction.get('confidence')}/10) — {'CORRECT' if correct else 'WRONG'}
149
+ Reasoning given: {prediction.get('reasoning')}
150
+ Research purchased (${entry.get('research_cost', 0):.4f}):{research_summary if research_summary else " none"}
151
 
152
+ Rules:
153
+ - Plain text only. No preamble, praise, or filler ("Here is...", "honest evaluation", etc.).
154
+ - No markdown headers, bold, or horizontal rules.
155
+ - Max 120 words.
156
+ - Be blunt and specific. Name the exact mistake, not abstract narratives.
157
 
158
+ Format exactly:
 
159
 
160
+ {mistake_section}DATA:
161
+ - useful: [source] — one line on what it told us that mattered
162
+ - useless: [source] — one line on why it didn't help
 
 
163
 
164
+ List only endpoints that were actually purchased. 2-5 bullets total across useful/useless."""
165
 
166
  log("Asking Gemini for evaluation...")
167
  try:
 
173
 
174
  # ── Step 4: Reflector call (updates strategy) ─────────────────────────────
175
 
176
+ reflect_prompt = f"""Update the agent's strategy document. Write like engineering notes — terse, direct, no marketing language or dramatic rule names.
 
 
177
 
178
+ Current strategy:
179
+ {strategy if strategy else "(empty — first match)"}
180
 
181
+ Latest match note ({MATCH}):
182
  {evaluation}
183
 
184
+ Rewrite with EXACTLY ONE rule change from this match. Keep still-valid existing rules.
185
+
186
+ Format:
187
+
188
+ # Strategy
189
+
190
+ ## Rules
191
+ - MATCH: one sentence rule
192
 
193
+ ## Data sources
194
+ - use: source type — why (MATCH)
195
+ - skip: source type — why (MATCH)
 
 
 
196
 
197
+ Max 250 words. Return ONLY the document."""
198
 
199
  log("Asking Gemini to update strategy...")
200
  try:
 
226
  "evaluation": evaluation,
227
  "reflected": True,
228
  "reflected_at": datetime.now(timezone.utc).isoformat(),
229
+ "strategy_after": new_strategy,
230
  })
231
  tmp = results_path.with_suffix(f".tmp.{HOME}_{AWAY}")
232
  tmp.write_text(json.dumps(results, indent=2))