fredcaixeta commited on
Commit
9b523a6
·
1 Parent(s): 30d9b1d
Files changed (2) hide show
  1. main_agent.py +77 -1
  2. prompts/player_matchid_prompt.py +21 -1
main_agent.py CHANGED
@@ -158,6 +158,79 @@ async def get_match_performances(match_date: Optional[str] = None, opponent: Opt
158
  return "\n".join(out)
159
  except Exception as e:
160
  return f"❌ Erro: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  @one_player_agent.tool_plain()
163
  async def get_top_performances(metric: str = "goals", limit: int = 10) -> str:
@@ -186,6 +259,7 @@ last_chart_image = None
186
  # Funções de response (já sem MCP)
187
  async def agent_conventional_response(user_query: str) -> str:
188
  res = await one_player_agent.run(user_prompt=user_query)
 
189
  return res.output
190
 
191
  async def stream_agent_response_safe(user_query: str) -> str:
@@ -193,6 +267,7 @@ async def stream_agent_response_safe(user_query: str) -> str:
193
  async with one_player_agent.iter(user_query) as agent_run:
194
  async for node in agent_run:
195
  if isinstance(node, End) and agent_run.result:
 
196
  return str(agent_run.result.output)
197
  except Exception as e:
198
  import traceback
@@ -205,4 +280,5 @@ async def shutdown():
205
  db.close()
206
 
207
  if __name__ == "__main__":
208
- asyncio.run(one_player_agent.run("Teste: top performances goals limit 5"))
 
 
158
  return "\n".join(out)
159
  except Exception as e:
160
  return f"❌ Erro: {str(e)}"
161
+
162
+ @one_player_agent.tool_plain()
163
+ async def show_available_tables() -> str:
164
+ query = """
165
+ SELECT table_name
166
+ FROM information_schema.tables
167
+ WHERE table_schema = 'public'
168
+ ORDER BY table_name
169
+ """ # listar tabelas via information_schema [web:61]
170
+ try:
171
+ results = await db.execute_query_async(query)
172
+ if not results:
173
+ return "❌ Nenhuma tabela encontrada no schema public."
174
+ return "📚 TABELAS:\n" + "\n".join([f"- {r['table_name']}" for r in results])
175
+ except Exception as e:
176
+ return f"❌ Erro: {str(e)}"
177
+
178
+ @one_player_agent.tool_plain()
179
+ async def get_goal_events(player_scorer: str = None,
180
+ assist_from: str = None,
181
+ opponent: str = None,
182
+ only_crosses: bool = False,
183
+ only_high_crosses: bool = False,
184
+ limit: int = 50) -> str:
185
+ # IMPORTANT: troque player_goals_stats pelo nome REAL da sua tabela
186
+ table = "player_goals_stats"
187
+
188
+ where = ["team = 'Barcelona'"]
189
+ params = []
190
+
191
+ if player_scorer:
192
+ where.append("player_scorer_nick ILIKE %s"); params.append(f"%{player_scorer}%")
193
+ if assist_from:
194
+ where.append("pass_from_nick ILIKE %s"); params.append(f"%{assist_from}%")
195
+ if opponent:
196
+ where.append("opponent ILIKE %s"); params.append(f"%{opponent}%")
197
+ if only_crosses:
198
+ where.append("is_cross_pass = TRUE")
199
+ if only_high_crosses:
200
+ where.append("is_cross_pass_high = TRUE")
201
+
202
+ params.append(limit)
203
+ where_sql = " AND ".join(where)
204
+
205
+ query = f"""
206
+ SELECT match_date, opponent, home_away,
207
+ minute, second,
208
+ player_scorer_nick, pass_from_nick,
209
+ is_cross_pass, is_cross_pass_high,
210
+ play_pattern, shot_type, shot_body_part,
211
+ xg
212
+ FROM {table}
213
+ WHERE {where_sql}
214
+ ORDER BY match_date DESC, minute DESC, second DESC
215
+ LIMIT %s
216
+ """
217
+ try:
218
+ results = await db.execute_query_async(query, tuple(params))
219
+ if not results:
220
+ return "❌ Sem gols encontrados para esse filtro."
221
+ out = ["⚽ EVENTOS DE GOL\n"]
222
+ for i, r in enumerate(results, 1):
223
+ out.append(
224
+ f"{i}. {r['match_date']} vs {r['opponent']} ({r['home_away']}) "
225
+ f"{r.get('minute')}:{r.get('second')} - "
226
+ f"{r.get('player_scorer_nick')} (assist: {r.get('pass_from_nick')}) | "
227
+ f"cross={r.get('is_cross_pass')} high_cross={r.get('is_cross_pass_high')} | "
228
+ f"{r.get('shot_body_part')} | xG={r.get('xg')}"
229
+ )
230
+ return "\n".join(out)
231
+ except Exception as e:
232
+ return f"❌ Erro: {str(e)}"
233
+
234
 
235
  @one_player_agent.tool_plain()
236
  async def get_top_performances(metric: str = "goals", limit: int = 10) -> str:
 
259
  # Funções de response (já sem MCP)
260
  async def agent_conventional_response(user_query: str) -> str:
261
  res = await one_player_agent.run(user_prompt=user_query)
262
+ #print(res.output)
263
  return res.output
264
 
265
  async def stream_agent_response_safe(user_query: str) -> str:
 
267
  async with one_player_agent.iter(user_query) as agent_run:
268
  async for node in agent_run:
269
  if isinstance(node, End) and agent_run.result:
270
+ print(str(agent_run.result.output))
271
  return str(agent_run.result.output)
272
  except Exception as e:
273
  import traceback
 
280
  db.close()
281
 
282
  if __name__ == "__main__":
283
+ _ = asyncio.run(agent_conventional_response("quantos sao os gols baseados em cruzamentos?"))
284
+ print(_)
prompts/player_matchid_prompt.py CHANGED
@@ -14,6 +14,20 @@ Respond back in the user's language.
14
  - If it is suitable for visualizations, graphs, or charts, (or if the user asks for it) you can use the create_chart tool
15
 
16
  ## Database Structure:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ### Table: player_match_stats
18
  Contains one row per player per match with 40 metrics:
19
  **Identification (8 columns):**
@@ -188,6 +202,12 @@ WHERE match_date = '2020-10-24'
188
  ORDER BY (goals + assists) DESC
189
  ```
190
 
 
 
 
 
 
 
191
  ## Key Metrics Explained:
192
  - **xG (Expected Goals)**: Statistical model predicting goal probability per shot
193
  - **npxG (Non-Penalty xG)**: Expected Goals excluding penalties
@@ -218,7 +238,7 @@ ORDER BY (goals + assists) DESC
218
  - get_consistency_stats(player_name)
219
  - get_home_away_comparison(player_name)
220
  - show_available_columns()
221
- **Remember:** All analyses must be based on SQL queries against the 'player_match_stats' table. This table provides MATCH-LEVEL granularity, allowing you to track individual performances game by game.
222
  Players of the season: Lionel Messi, Antoine Griezmann, Ousmane Dembélé, Ansu Fati, Martin Braithwaite
223
  Sergio Busquets, Frenkie de Jong, Pedri, Riqui Puig, Miralem Pjanić, Philippe Coutinho
224
  Gerard Piqué, Jordi Alba, Clément Lenglet, Sergi Roberto, Sergiño Dest, Ronald Araújo, Óscar Mingueza, Samuel Umtiti, Junior Firpo
 
14
  - If it is suitable for visualizations, graphs, or charts, (or if the user asks for it) you can use the create_chart tool
15
 
16
  ## Database Structure:
17
+ ### Table: goals_stats
18
+ One row per goal scored by Barcelona in a match.
19
+
20
+ Columns (as provided):
21
+ - goal_event_id (TEXT) UNIQUE-ish identifier
22
+ - match_id (BIGINT), season_id (BIGINT), team (TEXT)
23
+ - player_scorer (TEXT), player_scorer_nick (TEXT)
24
+ - pass_from (TEXT), pass_from_nick (TEXT)
25
+ - is_cross_pass (BOOL), is_cross_pass_high (BOOL)
26
+ - minute (BIGINT), second (BIGINT), period (BIGINT)
27
+ - play_pattern (TEXT), shot_type (TEXT), shot_body_part (TEXT)
28
+ - xg (DOUBLE), possession (BIGINT)
29
+ - match_date (TEXT), opponent (TEXT), home_away (TEXT), home_team (TEXT), away_team (TEXT)
30
+
31
  ### Table: player_match_stats
32
  Contains one row per player per match with 40 metrics:
33
  **Identification (8 columns):**
 
202
  ORDER BY (goals + assists) DESC
203
  ```
204
 
205
+ ## Join guidelines:
206
+ - player_match_stats <-> goals_stats:
207
+ - Join by match_id AND (player_match_stats.player_nickname = goals_stats.player_scorer_nick OR = goals_stats.pass_from_nick) when needed.
208
+ - match_stats <-> goals_stats:
209
+ - Join by match_id (and optionally team='Barcelona').
210
+
211
  ## Key Metrics Explained:
212
  - **xG (Expected Goals)**: Statistical model predicting goal probability per shot
213
  - **npxG (Non-Penalty xG)**: Expected Goals excluding penalties
 
238
  - get_consistency_stats(player_name)
239
  - get_home_away_comparison(player_name)
240
  - show_available_columns()
241
+ **Remember:** All analyses must be based on SQL queries against the tables.
242
  Players of the season: Lionel Messi, Antoine Griezmann, Ousmane Dembélé, Ansu Fati, Martin Braithwaite
243
  Sergio Busquets, Frenkie de Jong, Pedri, Riqui Puig, Miralem Pjanić, Philippe Coutinho
244
  Gerard Piqué, Jordi Alba, Clément Lenglet, Sergi Roberto, Sergiño Dest, Ronald Araújo, Óscar Mingueza, Samuel Umtiti, Junior Firpo