Spaces:
Sleeping
Sleeping
File size: 9,245 Bytes
f8c6ae8 42a16b0 f8c6ae8 42a16b0 28a218f f8c6ae8 12234ff 26ed94f f8c6ae8 2fcba66 bc4b3e7 42a16b0 2fcba66 42a16b0 2fcba66 42a16b0 2fcba66 f8c6ae8 42a16b0 f8c6ae8 fc7f322 f8c6ae8 | 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 | import os
from crewai import Agent, Task, Crew, Process, LLM
from crewai.tools import tool
from rapidfuzz import process
from data_loader import teams
from probability_engine import elo_probability, monte_carlo_group
# Create valid team set from dataset
VALID_TEAMS = set(teams["team"].str.upper())
def match_team_name(name):
if not name:
return None
match, score, _ = process.extractOne(name.upper(), VALID_TEAMS)
if score > 70:
return match
return None
# os.environ["GROQ_API_KEY"] = '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'
os.environ["GROQ_API_KEY"] = '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'
os.environ["OPENAI_API_KEY"] = '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'
os.environ["OPENAI_BASE_URL"] = "https://openrouter.ai/api/v1"
@tool
def match_probability(teamA: str, teamB: str):
"""
Simulate match probability
Returns probability of a team winning.
"""
return elo_probability(teamA, teamB)
@tool
def simulate_group_stage(group: str):
"""
Simulate a tournament group using Monte Carlo simulations.
Returns probability of teams qualifying.
"""
return monte_carlo_group(group)
llm = LLM(
# model = "openrouter/qwen/qwen-2.5-14b-instruct",
# model = "openrouter/mistralai/mistral-7b-instruct",
model = "groq/llama-3.1-8b-instant",
temperature=0.2
)
# Get the intent
def detect_intent(user_query):
prompt = f"""
You are an intent classifier for a cricket app.
Return ONLY valid JSON. No explanation. No markdown.
The JSON must have EXACTLY these fields:
{{
"intent": "match_prediction" | "group_progression" | "tournament_prediction" | "unknown",
"teamA": "country name or null",
"teamB": "country name or null",
"group": "group letter like A, B, C or null",
"venue": "city or null",
"tournament_team": "country 1" | "country 2" | "country 3" | "country 4" | "null"
}}
Examples:
- "Who wins if India take on the Aussies" β intent: match_prediction, teamA: India, teamB: Australia
- "Who advances from Group C" β intent: group_progression, group: C
- "Who are the favourites to win" β intent: tournament_prediction
- "Give me the semi finalists" β intent: tournament_prediction
User: {user_query}
"""
response = llm.call(prompt)
try:
json_start = response.find("{")
json_end = response.rfind("}") + 1
clean_json = response[json_start:json_end]
parsed = json.loads(clean_json)
except:
parsed = {
"intent": "unknown",
"teamA": None,
"teamB": None,
"group": None,
"venue": None,
"tournament_team": None,
"context": None
}
# π₯ STEP 1 β normalize using fuzzy match
parsed["teamA"] = match_team_name(parsed.get("teamA"))
parsed["teamB"] = match_team_name(parsed.get("teamB"))
# π₯ STEP 2 β fallback extraction from query if LLM failed
if parsed["intent"] == "match_prediction":
if not parsed["teamA"] or not parsed["teamB"]:
query_lower = user_query.lower()
found = []
for team in VALID_TEAMS:
if team.lower() in query_lower:
found.append(team)
if len(found) >= 2:
parsed["teamA"] = found[0]
parsed["teamB"] = found[1]
# π₯ STEP 3 β final safety
if parsed["intent"] == "match_prediction":
if not parsed["teamA"] or not parsed["teamB"]:
parsed["intent"] = "unknown"
return parsed
statistician = Agent(
role="Cricket Statistician",
goal="Analyze match probabilities using Elo ratings",
backstory="A veteran cricket data scientist who specializes in statistical modelling and match prediction.",
tools=[match_probability, simulate_group_stage],
llm=llm,
verbose=True
)
strategist = Agent(
role="Cricket Strategist",
goal="Evaluate player strengths and match conditions",
backstory="A former international cricket coach who studies tactical matchups and team combinations.",
llm=llm,
verbose=True
)
chaos_agent = Agent(
role="Chaos Analyst",
goal="Identify upset scenarios",
backstory="A pundit who believes cricket is unpredictable and focuses on variance and surprise outcomes.",
llm=llm,
verbose=True
)
compere = Agent(
role="Debate Host",
goal="Summarize debate and provide the verdict",
backstory="A neutral studio host moderating a panel of cricket experts discussing match predictions.",
llm=llm,
verbose=True
)
def run_agents(query_type, teamA=None, teamB=None, venue=None, group=None):
if query_type == "match":
stats_description = f"""
You are analyzing the match between {teamA} and {teamB}.
IMPORTANT:
You MUST call the tool `match_probability`
with teamA="{teamA}" and teamB="{teamB}"
Do NOT estimate probabilities yourself.
Do NOT invent Elo ratings.
Use the tool output to produce your answer.
Venue: {venue if venue else "Neutral conditions assumed"}
Output:
- Team A win probability
- Team B win probability
- Short explanation
"""
strategist_description = f"""
Consider the statistical prediction for {teamA} vs {teamB}.
Now evaluate tactical factors:
- batting strengths
- bowling strengths
- venue conditions
Explain how these factors may influence the match.
"""
chaos_description = f"""
Challenge the prediction for {teamA} vs {teamB}.
Discuss possible upset scenarios.
Consider:
- volatility of T20 cricket
- early wickets
- momentum shifts
Explain when the weaker team might win.
"""
compere_description = f"""
Summarize the panel discussion for the match {teamA} vs {teamB}.
Combine insights from:
- statistics
- strategy
- chaos analysis
Provide final verdict:
- predicted winner
- probability
- key factors
"""
elif query_type == "group":
stats_description = f"""
Simulate Group {group} using the simulate_group_stage tool.
Provide:
- probability of each team qualifying
- explanation of results
"""
strategist_description = f"""
Interpret the Group {group} simulation results.
Discuss:
- strongest teams
- potential challengers
- possible group surprises
"""
chaos_description = f"""
Highlight possible upset scenarios in Group {group}.
Explain how weaker teams could still qualify.
"""
compere_description = f"""
Summarize the analysis for Group {group}.
Provide:
- top teams expected to qualify
- overall tournament outlook
"""
elif query_type == "tournament":
stats_description = "Analyze all teams and predict the top 4 semifinalists using historical Elo data."
strategist_description = "Discuss which teams have the best tactical setups for a World Cup campaign."
chaos_description = "Which dark horses could shock the world? Who could be the Zimbabwe of this tournament?"
compere_description = "Summarize the panel's tournament predictions. Name your top 4 and a winner."
else:
raise ValueError('query_type must be "match" or "group"')
stats_task = Task(
description=stats_description,
expected_output="""
Output format:
Team A:
Win Probability:
Team B:
Win Probability:
Explanation:
""",
agent=statistician
)
strategist_task = Task(
description=strategist_description,
expected_output="Strategic match analysis",
agent=strategist
)
chaos_task = Task(
description=chaos_description,
expected_output="Upset scenarios and uncertainty discussion",
agent=chaos_agent
)
compere_task = Task(
description=compere_description,
expected_output="Final verdict combining all insights",
agent=compere
)
crew = Crew(
agents=[statistician, strategist, chaos_agent, compere],
tasks=[stats_task, strategist_task, chaos_task, compere_task],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
# EXTRACT OUTPUTS
stats_output = stats_task.output.raw
strategist_output = strategist_task.output.raw
chaos_output = chaos_task.output.raw
compere_output = compere_task.output.raw
return {
"stats": stats_output,
"strategist": strategist_output,
"chaos": chaos_output,
"compere": compere_output,
"result": result
}
# return result
|