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