1.0.0初始化源代码
This commit is contained in:
25
backend/app/models/__init__.py
Normal file
25
backend/app/models/__init__.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
数据库模型初始化
|
||||
"""
|
||||
from .base import Base, engine, get_db, SessionLocal
|
||||
from .virtual_user import VirtualUser, VirtualUserPersona
|
||||
from .interaction import InteractionRecord, InteractionType
|
||||
from .token_usage import TokenUsage
|
||||
from .system_config import SystemConfig
|
||||
from .ai_model import AIModelConfig
|
||||
from .news_cache import NewsCache
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"engine",
|
||||
"get_db",
|
||||
"SessionLocal",
|
||||
"VirtualUser",
|
||||
"VirtualUserPersona",
|
||||
"InteractionRecord",
|
||||
"InteractionType",
|
||||
"TokenUsage",
|
||||
"SystemConfig",
|
||||
"AIModelConfig",
|
||||
"NewsCache",
|
||||
]
|
||||
43
backend/app/models/ai_model.py
Normal file
43
backend/app/models/ai_model.py
Normal file
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
AI 模型配置模型
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text, Float
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class AIModelConfig(Base):
|
||||
"""AI 模型配置表"""
|
||||
__tablename__ = "ai_model_configs"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="配置 ID")
|
||||
|
||||
# 模型基本信息
|
||||
model_name = Column(String(100), unique=True, nullable=False, index=True, comment="模型名称(如 gpt-3.5-turbo)")
|
||||
provider = Column(String(50), nullable=False, comment="提供商(openai/zhipu/baidu/aliyun)")
|
||||
display_name = Column(String(200), comment="显示名称")
|
||||
|
||||
# API 配置
|
||||
api_url = Column(String(500), nullable=False, comment="API 地址")
|
||||
api_key = Column(String(500), nullable=False, comment="API Key(加密存储)")
|
||||
api_version = Column(String(50), comment="API 版本")
|
||||
|
||||
# 模型参数
|
||||
temperature = Column(Float, default=0.7, comment="温度(0-1)")
|
||||
max_tokens = Column(Integer, default=1000, comment="最大 Token 数")
|
||||
top_p = Column(Float, default=1.0, comment="Top P 参数")
|
||||
|
||||
# 状态控制
|
||||
is_default = Column(Boolean, default=False, comment="是否为默认模型")
|
||||
is_active = Column(Boolean, default=True, comment="是否启用")
|
||||
|
||||
# 描述信息
|
||||
description = Column(Text, comment="模型描述")
|
||||
|
||||
# 时间戳
|
||||
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<AIModelConfig(id={self.id}, name='{self.model_name}', provider='{self.provider}')>"
|
||||
49
backend/app/models/base.py
Normal file
49
backend/app/models/base.py
Normal file
@@ -0,0 +1,49 @@
|
||||
"""
|
||||
数据库基础配置
|
||||
"""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from contextlib import contextmanager
|
||||
import logging
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 创建数据库引擎
|
||||
engine = create_engine(
|
||||
settings.get_database_url,
|
||||
pool_pre_ping=True,
|
||||
pool_size=20,
|
||||
max_overflow=40,
|
||||
echo=settings.DEBUG,
|
||||
)
|
||||
|
||||
# 创建会话工厂
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# 创建基类
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_db():
|
||||
"""获取数据库会话的上下文管理器"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logger.error(f"Database error: {e}")
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""初始化数据库表"""
|
||||
from . import virtual_user, interaction, token_usage, system_config, ai_model, news_cache
|
||||
Base.metadata.create_all(bind=engine)
|
||||
logger.info("Database tables created successfully")
|
||||
68
backend/app/models/interaction.py
Normal file
68
backend/app/models/interaction.py
Normal file
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
互动记录模型
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Enum, Text, ForeignKey, Boolean, Float
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import relationship
|
||||
import enum
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class InteractionType(str, enum.Enum):
|
||||
"""互动类型枚举"""
|
||||
COMMENT = "comment" # 评论
|
||||
REPLY = "reply" # 回复
|
||||
LIKE = "like" # 点赞
|
||||
FAVORITE = "favorite" # 收藏
|
||||
SHARE = "share" # 转发
|
||||
|
||||
|
||||
class InteractionStatus(str, enum.Enum):
|
||||
"""互动状态枚举"""
|
||||
PENDING = "pending" # 待执行
|
||||
SUCCESS = "success" # 成功
|
||||
FAILED = "failed" # 失败
|
||||
RETRYING = "retrying" # 重试中
|
||||
|
||||
|
||||
class InteractionRecord(Base):
|
||||
"""互动记录表"""
|
||||
__tablename__ = "interaction_records"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="记录 ID")
|
||||
|
||||
# 关联信息
|
||||
virtual_user_id = Column(Integer, ForeignKey("virtual_users.id"), nullable=False, index=True, comment="虚拟用户 ID")
|
||||
virtual_user = relationship("VirtualUser", backref="interaction_records")
|
||||
|
||||
news_id = Column(String(100), nullable=False, index=True, comment="新闻 ID")
|
||||
news_title = Column(String(500), comment="新闻标题")
|
||||
|
||||
# 互动内容
|
||||
interaction_type = Column(Enum(InteractionType), nullable=False, comment="互动类型")
|
||||
content = Column(Text, comment="互动内容(评论/回复的文本)")
|
||||
target_comment_id = Column(String(100), comment="目标评论 ID(回复时使用)")
|
||||
|
||||
# 执行状态
|
||||
status = Column(Enum(InteractionStatus), default=InteractionStatus.PENDING, comment="执行状态")
|
||||
retry_count = Column(Integer, default=0, comment="重试次数")
|
||||
error_message = Column(Text, comment="错误信息(失败时)")
|
||||
|
||||
# AI 相关信息
|
||||
ai_model_used = Column(String(100), comment="使用的 AI 模型")
|
||||
tokens_used = Column(Integer, default=0, comment="消耗的 Token 数")
|
||||
prompt_content = Column(Text, comment="发送给 AI 的提示词")
|
||||
ai_response = Column(Text, comment="AI 返回的内容")
|
||||
|
||||
# 接口响应
|
||||
api_response = Column(Text, comment="会会接口返回的原始响应")
|
||||
api_request_id = Column(String(200), comment="接口请求 ID")
|
||||
|
||||
# 时间戳
|
||||
execution_time = Column(DateTime, server_default=func.now(), comment="执行时间")
|
||||
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<InteractionRecord(id={self.id}, user_id={self.virtual_user_id}, type='{self.interaction_type}', status='{self.status}')>"
|
||||
45
backend/app/models/news_cache.py
Normal file
45
backend/app/models/news_cache.py
Normal file
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
新闻缓存模型
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Text, Boolean, Date
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class NewsCache(Base):
|
||||
"""新闻缓存表"""
|
||||
__tablename__ = "news_cache"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="缓存 ID")
|
||||
|
||||
# 新闻基本信息
|
||||
news_id = Column(String(100), unique=True, nullable=False, index=True, comment="新闻 ID(来自会会接口)")
|
||||
title = Column(String(500), nullable=False, comment="新闻标题")
|
||||
summary = Column(Text, comment="新闻摘要")
|
||||
content = Column(Text, comment="新闻内容")
|
||||
|
||||
# 来源信息
|
||||
source = Column(String(200), comment="来源")
|
||||
author = Column(String(100), comment="作者")
|
||||
publish_time = Column(DateTime, comment="发布时间")
|
||||
|
||||
# 分类标签
|
||||
category = Column(String(100), comment="分类")
|
||||
tags = Column(String(500), comment="标签(逗号分隔)")
|
||||
|
||||
# 互动统计
|
||||
view_count = Column(Integer, default=0, comment="阅读数")
|
||||
comment_count = Column(Integer, default=0, comment="评论数")
|
||||
like_count = Column(Integer, default=0, comment="点赞数")
|
||||
|
||||
# 缓存状态
|
||||
is_cached = Column(Boolean, default=True, comment="是否已缓存")
|
||||
cache_date = Column(Date, server_default=func.now(), index=True, comment="缓存日期")
|
||||
|
||||
# 时间戳
|
||||
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<NewsCache(id={self.id}, news_id='{self.news_id}', title='{self.title[:30]}...')>"
|
||||
32
backend/app/models/system_config.py
Normal file
32
backend/app/models/system_config.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
系统配置模型
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text, JSON
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class SystemConfig(Base):
|
||||
"""系统配置表"""
|
||||
__tablename__ = "system_configs"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="配置 ID")
|
||||
|
||||
# 配置键值
|
||||
config_key = Column(String(100), unique=True, nullable=False, index=True, comment="配置键")
|
||||
config_value = Column(JSON, nullable=False, comment="配置值(JSON 格式)")
|
||||
config_type = Column(String(50), comment="配置类型(schedule/limit/probability等)")
|
||||
|
||||
# 描述信息
|
||||
description = Column(Text, comment="配置描述")
|
||||
|
||||
# 状态
|
||||
is_active = Column(Boolean, default=True, comment="是否启用")
|
||||
|
||||
# 时间戳
|
||||
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<SystemConfig(id={self.id}, key='{self.config_key}')>"
|
||||
36
backend/app/models/token_usage.py
Normal file
36
backend/app/models/token_usage.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
Token 使用记录模型
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Float, Date
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class TokenUsage(Base):
|
||||
"""Token 使用记录表"""
|
||||
__tablename__ = "token_usages"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="记录 ID")
|
||||
|
||||
# 关联信息
|
||||
virtual_user_id = Column(Integer, ForeignKey("virtual_users.id"), nullable=True, index=True, comment="虚拟用户 ID(可为空,系统级消耗)")
|
||||
interaction_id = Column(Integer, ForeignKey("interaction_records.id"), nullable=True, comment="互动记录 ID")
|
||||
|
||||
# Token 信息
|
||||
tokens_used = Column(Integer, nullable=False, comment="使用的 Token 数量")
|
||||
tokens_prompt = Column(Integer, default=0, comment="提示词 Token 数")
|
||||
tokens_completion = Column(Integer, default=0, comment="完成响应 Token 数")
|
||||
|
||||
# AI 模型信息
|
||||
ai_model = Column(String(100), nullable=False, comment="使用的 AI 模型")
|
||||
action_type = Column(String(50), comment="操作类型(generate_comment/generate_reply 等)")
|
||||
|
||||
# 日期分区(便于统计)
|
||||
usage_date = Column(Date, server_default=func.now(), index=True, comment="使用日期")
|
||||
|
||||
# 时间戳
|
||||
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<TokenUsage(id={self.id}, tokens={self.tokens_used}, model='{self.ai_model}')>"
|
||||
91
backend/app/models/virtual_user.py
Normal file
91
backend/app/models/virtual_user.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
虚拟用户模型
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Enum, Text, JSON, Float
|
||||
from sqlalchemy.sql import func
|
||||
from enum import Enum as PyEnum
|
||||
import enum
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class ActivityLevel(str, enum.Enum):
|
||||
"""活跃度枚举"""
|
||||
LOW = "low" # 低:每日 1-2 次
|
||||
MEDIUM = "medium" # 中:每日 2-5 次
|
||||
HIGH = "high" # 高:每日 5-10 次
|
||||
|
||||
|
||||
class UserStatus(str, enum.Enum):
|
||||
"""用户状态枚举"""
|
||||
ACTIVE = "active" # 启用
|
||||
DISABLED = "disabled" # 禁用
|
||||
|
||||
|
||||
class VirtualUser(Base):
|
||||
"""虚拟用户表"""
|
||||
__tablename__ = "virtual_users"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="用户 ID")
|
||||
|
||||
# 基本信息
|
||||
username = Column(String(100), unique=True, nullable=False, index=True, comment="用户名(账号)")
|
||||
password = Column(String(200), nullable=False, comment="密码(加密存储)")
|
||||
nickname = Column(String(100), nullable=False, comment="昵称")
|
||||
avatar_url = Column(String(500), comment="头像 URL")
|
||||
|
||||
# 人格特征
|
||||
writing_style = Column(String(50), comment="写作风格")
|
||||
activity_level = Column(Enum(ActivityLevel), default=ActivityLevel.MEDIUM, comment="活跃度")
|
||||
persona_description = Column(Text, comment="人格描述(AI 生成)")
|
||||
|
||||
# 状态控制
|
||||
status = Column(Enum(UserStatus), default=UserStatus.ACTIVE, comment="状态")
|
||||
is_logged_in = Column(Boolean, default=False, comment="是否已登录")
|
||||
session_token = Column(String(500), comment="会话 Token(登录后)")
|
||||
token_expire_time = Column(DateTime, comment="Token 过期时间")
|
||||
|
||||
# 互动统计
|
||||
total_interactions = Column(Integer, default=0, comment="总互动次数")
|
||||
today_comments = Column(Integer, default=0, comment="今日评论数")
|
||||
today_replies = Column(Integer, default=0, comment="今日回复数")
|
||||
last_interaction_time = Column(DateTime, comment="最后互动时间")
|
||||
|
||||
# 扩展信息
|
||||
extra_info = Column(JSON, default=dict, comment="扩展信息")
|
||||
|
||||
# 时间戳
|
||||
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<VirtualUser(id={self.id}, nickname='{self.nickname}', status='{self.status}')>"
|
||||
|
||||
|
||||
class VirtualUserPersona(Base):
|
||||
"""虚拟用户人格模板表"""
|
||||
__tablename__ = "virtual_user_personas"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, comment="ID")
|
||||
|
||||
# 人格特征
|
||||
name = Column(String(100), unique=True, nullable=False, comment="人格名称")
|
||||
description = Column(Text, comment="人格描述")
|
||||
|
||||
# 风格配置
|
||||
writing_styles = Column(JSON, comment="写作风格列表")
|
||||
personality_traits = Column(JSON, comment="性格特征列表")
|
||||
speech_patterns = Column(JSON, comment="说话模式列表")
|
||||
|
||||
# AI 提示词
|
||||
system_prompt = Column(Text, comment="系统提示词(用于 AI 生成)")
|
||||
|
||||
# 状态
|
||||
is_active = Column(Boolean, default=True, comment="是否启用")
|
||||
|
||||
# 时间戳
|
||||
created_at = Column(DateTime, server_default=func.now(), comment="创建时间")
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<VirtualUserPersona(id={self.id}, name='{self.name}')>"
|
||||
Reference in New Issue
Block a user