feat: 足球 LLM 预测服务初始提交

Profeto — 给 LLM 提供数据,让 LLM 预测足球比分。

核心模块:
- FastAPI 后端 + PostgreSQL (SQLAlchemy async)
- 多 Agent LLM 预测 (5 专家 + 终裁)
- 数据采集 (bzzoiro / understat / injuries)
- React 前端 (Vite + Tailwind)

包含:
- 数据源抽象 (DataSource 协议 + 注册表)
- Alembic 数据库迁移
- Prompt 模板 (单/多 Agent)
- 核心路径单元测试
This commit is contained in:
shangfangjian
2026-09-09 02:10:47 +08:00
commit 0a27b18c27
74 changed files with 5667 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+64
View File
@@ -0,0 +1,64 @@
from logging.config import fileConfig
import sys
from pathlib import Path
from sqlalchemy import engine_from_config, pool
from alembic import context
# 把项目根加入 pythonpath,让 alembic 能找到 src 包
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from src.db.base import Base # noqa: E402
from src.db.models import * # noqa: E402,F401,F403 # 导入所有模型确保注册
from src.core.config import settings # noqa: E402
# this is the Alembic Config object
config = context.config
# 用 settings 的 DATABASE_URL,但转成 sync 驱动
DB_URL = settings.DATABASE_URL
if DB_URL.startswith("postgresql+asyncpg"):
DB_URL = DB_URL.replace("postgresql+asyncpg", "postgresql+psycopg2", 1)
config.set_main_option("sqlalchemy.url", DB_URL)
# Interpret the config file for Python logging.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode."""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
+129
View File
@@ -0,0 +1,129 @@
"""initial_tables
Revision ID: 0001_initial
Revises:
Create Date: 2026-09-07 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = '0001_initial'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic ###
op.create_table('leagues',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=20), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('country', sa.String(length=50), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
op.create_table('teams',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=120), nullable=False),
sa.Column('name_zh', sa.String(length=60), nullable=True),
sa.Column('team_type', sa.String(length=20), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('matches',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('league_id', sa.Integer(), nullable=False),
sa.Column('season', sa.String(length=12), nullable=True),
sa.Column('home_team_id', sa.Integer(), nullable=False),
sa.Column('away_team_id', sa.Integer(), nullable=False),
sa.Column('match_date', sa.DateTime(timezone=True), nullable=False),
sa.Column('match_date_date', sa.Date(), nullable=False),
sa.Column('match_status', sa.String(length=20), nullable=False),
sa.Column('home_goals', sa.Integer(), nullable=True),
sa.Column('away_goals', sa.Integer(), nullable=True),
sa.Column('home_ht_goals', sa.Integer(), nullable=True),
sa.Column('away_ht_goals', sa.Integer(), nullable=True),
sa.Column('match_stage', sa.String(length=100), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(['away_team_id'], ['teams.id'], ),
sa.ForeignKeyConstraint(['home_team_id'], ['teams.id'], ),
sa.ForeignKeyConstraint(['league_id'], ['leagues.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_matches_away_date', 'matches', ['away_team_id', sa.text('match_date DESC')], unique=False)
op.create_index('ix_matches_home_date', 'matches', ['home_team_id', sa.text('match_date DESC')], unique=False)
op.create_index('ix_matches_league_date', 'matches', ['league_id', sa.text('match_date DESC')], unique=False)
op.create_index('ix_matches_status_date', 'matches', ['match_status', sa.text('match_date DESC')], unique=False)
op.create_index('ix_matches_unique', 'matches', ['league_id', 'home_team_id', 'away_team_id', 'match_date_date'], unique=True)
op.create_index(op.f('ix_matches_match_date_date'), 'matches', ['match_date_date'], unique=False)
op.create_table('match_stats',
sa.Column('match_id', sa.Integer(), nullable=False),
sa.Column('home_xg', sa.Float(), nullable=True),
sa.Column('away_xg', sa.Float(), nullable=True),
sa.Column('home_shots', sa.Integer(), nullable=True),
sa.Column('away_shots', sa.Integer(), nullable=True),
sa.Column('home_shots_on_target', sa.Integer(), nullable=True),
sa.Column('away_shots_on_target', sa.Integer(), nullable=True),
sa.Column('home_corners', sa.Integer(), nullable=True),
sa.Column('away_corners', sa.Integer(), nullable=True),
sa.Column('home_possession', sa.Float(), nullable=True),
sa.Column('home_yellow_cards', sa.Integer(), nullable=True),
sa.Column('away_yellow_cards', sa.Integer(), nullable=True),
sa.Column('home_red_cards', sa.Integer(), nullable=True),
sa.Column('away_red_cards', sa.Integer(), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(['match_id'], ['matches.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('match_id')
)
op.create_table('predictions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('match_id', sa.Integer(), nullable=False),
sa.Column('provider', sa.String(length=30), nullable=False),
sa.Column('model', sa.String(length=80), nullable=False),
sa.Column('prompt_version', sa.String(length=20), nullable=False),
sa.Column('prompt_tokens', sa.Integer(), nullable=True),
sa.Column('completion_tokens', sa.Integer(), nullable=True),
sa.Column('latency_ms', sa.Integer(), nullable=True),
sa.Column('pred_home_goals', sa.Float(), nullable=True),
sa.Column('pred_away_goals', sa.Float(), nullable=True),
sa.Column('pred_1x2', sa.String(length=3), nullable=True),
sa.Column('confidence', sa.Float(), nullable=True),
sa.Column('reasoning', sa.Text(), nullable=True),
sa.Column('raw_response', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('actual_home_goals', sa.Integer(), nullable=True),
sa.Column('actual_away_goals', sa.Integer(), nullable=True),
sa.Column('settled', sa.Boolean(), nullable=False),
sa.ForeignKeyConstraint(['match_id'], ['matches.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_predictions_match'), 'predictions', ['match_id'], unique=False)
op.create_index('ix_predictions_provider_model', 'predictions', ['provider', 'model'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic ###
op.drop_index('ix_predictions_provider_model', table_name='predictions')
op.drop_index(op.f('ix_predictions_match'), table_name='predictions')
op.drop_table('predictions')
op.drop_table('match_stats')
op.drop_index(op.f('ix_matches_match_date_date'), table_name='matches')
op.drop_index('ix_matches_unique', table_name='matches')
op.drop_index('ix_matches_status_date', table_name='matches')
op.drop_index('ix_matches_league_date', table_name='matches')
op.drop_index('ix_matches_home_date', table_name='matches')
op.drop_index('ix_matches_away_date', table_name='matches')
op.drop_table('matches')
op.drop_table('teams')
op.drop_table('leagues')
# ### end Alembic commands ###
+28
View File
@@ -0,0 +1,28 @@
"""add agent outputs to predictions
Revision ID: 0002_agent_outputs
Revises: 0001_initial
Create Date: 2026-09-08
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = '0002_agent_outputs'
down_revision: Union[str, None] = '0001_initial'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column('predictions', sa.Column('mode', sa.String(length=20), nullable=False, server_default='single'))
op.add_column('predictions', sa.Column('agent_outputs', postgresql.JSONB(astext_type=sa.Text()), nullable=True))
def downgrade() -> None:
op.drop_column('predictions', 'agent_outputs')
op.drop_column('predictions', 'mode')
+48
View File
@@ -0,0 +1,48 @@
"""add injuries table
Revision ID: 0003_injuries
Revises: 0002_agent_outputs
Create Date: 2026-09-09
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '0003_injuries'
down_revision: Union[str, None] = '0002_agent_outputs'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table('injuries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('player_id', sa.Integer(), nullable=True),
sa.Column('player_name', sa.String(length=120), nullable=False),
sa.Column('team_id', sa.Integer(), nullable=True),
sa.Column('fixture_id', sa.Integer(), nullable=True),
sa.Column('league_id', sa.Integer(), nullable=True),
sa.Column('injury_type', sa.String(length=50), nullable=True),
sa.Column('reason', sa.String(length=200), nullable=True),
sa.Column('injury_date', sa.Date(), nullable=True),
sa.Column('return_date', sa.Date(), nullable=True),
sa.Column('retrieved_at', sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(['team_id'], ['teams.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('player_id', 'fixture_id', 'injury_type', name='ix_injuries_player_fixture')
)
op.create_index(op.f('ix_injuries_injury_date'), 'injuries', ['injury_date'], unique=False)
op.create_index(op.f('ix_injuries_player_id'), 'injuries', ['player_id'], unique=False)
op.create_index(op.f('ix_injuries_team_date'), 'injuries', ['team_id', 'injury_date'], unique=False)
op.create_index(op.f('ix_injuries_team_id'), 'injuries', ['team_id'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_injuries_team_id'), table_name='injuries')
op.drop_index(op.f('ix_injuries_team_date'), table_name='injuries')
op.drop_index(op.f('ix_injuries_player_id'), table_name='injuries')
op.drop_index(op.f('ix_injuries_injury_date'), table_name='injuries')
op.drop_table('injuries')