349 lines
11 KiB
Python
349 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
数据库状态
|
||
"""
|
||
from datetime import datetime, timedelta
|
||
from random import choices
|
||
from typing import Any
|
||
|
||
from pydantic_ai import ModelMessage, ModelMessagesTypeAdapter
|
||
from pydantic_ai._uuid import uuid7
|
||
import reflex as rx
|
||
from sqlalchemy import desc
|
||
from sqlmodel import Field, JSON, SQLModel, select, update
|
||
|
||
from application.states.models import (
|
||
Conversation,
|
||
TaskType,
|
||
TaskStatus,
|
||
RunStatus,
|
||
MessageType,
|
||
Task,
|
||
Run,
|
||
Message,
|
||
deps_to_object,
|
||
usage_validate_python,
|
||
usage_limits_to_object,
|
||
)
|
||
|
||
|
||
class VerificationCodeRecord(SQLModel, table=True, table_name="verification_code"):
|
||
"""
|
||
验证码记录
|
||
"""
|
||
|
||
email: str = Field(..., primary_key=True, description="邮箱")
|
||
verification_code: str = Field(
|
||
default_factory=lambda: "".join(choices("0123456789", k=6)),
|
||
primary_key=True,
|
||
description="验证码",
|
||
)
|
||
is_valid: bool = Field(
|
||
default=True,
|
||
index=True,
|
||
description="验证码有效:True 表示有效,False 表示无效",
|
||
)
|
||
is_verified: bool = Field(
|
||
default=False,
|
||
index=True,
|
||
description="验证码已核验:True 表示已核验,False 表示未核验",
|
||
)
|
||
expired_at: datetime = Field(
|
||
default_factory=lambda: datetime.now() + timedelta(minutes=30),
|
||
primary_key=True,
|
||
description="过期时间",
|
||
)
|
||
|
||
|
||
class UserRecord(SQLModel, table=True, table_name="user"):
|
||
"""
|
||
用户记录
|
||
"""
|
||
|
||
id: str = Field(
|
||
default_factory=lambda: str(uuid7()),
|
||
primary_key=True,
|
||
description="用户唯一标识",
|
||
)
|
||
email: str = Field(..., index=True, description="邮箱")
|
||
|
||
|
||
class ConversationRecord(SQLModel, table=True, table_name="conversation"):
|
||
"""
|
||
会话记录
|
||
"""
|
||
|
||
id: str = Field(
|
||
default_factory=lambda: str(uuid7()),
|
||
primary_key=True,
|
||
description="会话唯一标识",
|
||
)
|
||
user_id: str = Field(..., index=True, description="用户唯一标识")
|
||
description: str = Field(default="新会话", description="会话描述")
|
||
usage: dict[str, Any] = Field(
|
||
default_factory=dict, sa_type=JSON, description="会话使用量"
|
||
)
|
||
is_deleted: bool = Field(
|
||
default=False,
|
||
index=True,
|
||
description="会话已删除:True 表示已删除,False 表示未删除",
|
||
)
|
||
created_at: datetime = Field(
|
||
default_factory=datetime.now, description="会话创建时间"
|
||
)
|
||
|
||
|
||
class MessageRecord(SQLModel, table=True, table_name="message"):
|
||
"""
|
||
消息记录
|
||
"""
|
||
|
||
id: str = Field(
|
||
default_factory=lambda: str(uuid7()),
|
||
primary_key=True,
|
||
description="消息唯一标识",
|
||
)
|
||
conversation_id: str = Field(..., index=True, description="会话唯一标识")
|
||
type: MessageType = Field(..., description="消息类型")
|
||
title: str = Field(default="", description="消息标题")
|
||
content: str = Field(default="", description="消息内容")
|
||
|
||
|
||
class DatabaseState(rx.State):
|
||
"""
|
||
数据库状态
|
||
"""
|
||
|
||
async def create_verification_code_record(self, email: str) -> str:
|
||
"""
|
||
创建验证码记录
|
||
:param email: 邮箱
|
||
:return: 验证码
|
||
"""
|
||
async with rx.asession() as session:
|
||
# 先将该邮箱有效、未核验的验证码记录设置为无效
|
||
await session.exec(
|
||
update(VerificationCodeRecord)
|
||
.where(
|
||
VerificationCodeRecord.email == email, # type: ignore
|
||
VerificationCodeRecord.is_valid == True, # type: ignore
|
||
VerificationCodeRecord.is_verified == False, # type: ignore
|
||
)
|
||
.values(is_valid=False)
|
||
)
|
||
await session.flush()
|
||
# 创建验证码记录
|
||
record = VerificationCodeRecord(
|
||
email=email,
|
||
)
|
||
session.add(record)
|
||
await session.commit()
|
||
await session.refresh(record)
|
||
return record.verification_code
|
||
|
||
async def verify_verification_code(
|
||
self, email: str, verification_code: str
|
||
) -> bool:
|
||
"""
|
||
核验验证码
|
||
:param email: 邮箱
|
||
:param verification_code: 验证码
|
||
:return: 是否核验成功,True 表示核验成功,False 表示核验失败(根据邮箱和验证码未查询到有效且未核验的记录,或失效)
|
||
"""
|
||
async with rx.asession() as session:
|
||
result = await session.exec(
|
||
select(VerificationCodeRecord).where(
|
||
VerificationCodeRecord.email == email,
|
||
VerificationCodeRecord.verification_code == verification_code,
|
||
VerificationCodeRecord.is_valid == True,
|
||
VerificationCodeRecord.is_verified == False,
|
||
VerificationCodeRecord.expired_at > datetime.now(),
|
||
)
|
||
)
|
||
record = result.first()
|
||
if not record:
|
||
return False
|
||
record.is_verified = True
|
||
await session.commit()
|
||
await session.refresh(record)
|
||
return True
|
||
|
||
async def create_user_record(self, email: str) -> str:
|
||
"""
|
||
创建用户记录
|
||
:param email: 邮箱
|
||
:return: 用户唯一标识
|
||
"""
|
||
async with rx.asession() as session:
|
||
result = await session.exec(
|
||
select(UserRecord).where(UserRecord.email == email)
|
||
)
|
||
record = result.first()
|
||
# 若用户记录已存在则返回用户唯一标识,否则先创建用户记录再返回用户唯一标识
|
||
if record:
|
||
return record.id
|
||
record = UserRecord(email=email)
|
||
session.add(record)
|
||
await session.commit()
|
||
await session.refresh(record)
|
||
return record.id
|
||
|
||
async def get_conversations(self, user_id: str) -> dict[str, Conversation]:
|
||
"""
|
||
获取当前用户的会话字典
|
||
:param user_id: 用户唯一标识
|
||
:return: 当前用户的会话字典
|
||
"""
|
||
conversations: dict[str, Conversation] = {}
|
||
async with rx.asession() as session:
|
||
result = await session.exec(
|
||
select(ConversationRecord, MessageRecord)
|
||
.outerjoin(MessageRecord, MessageRecord.conversation_id == ConversationRecord.id) # type: ignore
|
||
.where(
|
||
ConversationRecord.user_id == user_id,
|
||
ConversationRecord.is_deleted == False,
|
||
)
|
||
.order_by(ConversationRecord.id, MessageRecord.id)
|
||
)
|
||
for (
|
||
conversation_record,
|
||
message_record,
|
||
) in result.all():
|
||
conversation = conversations.setdefault(
|
||
conversation_record.id,
|
||
Conversation(
|
||
id=conversation_record.id,
|
||
description=conversation_record.description,
|
||
usage=usage_validate_python(conversation_record.usage),
|
||
created_at=conversation_record.created_at,
|
||
),
|
||
)
|
||
if not message_record:
|
||
continue
|
||
conversation.messages.setdefault(
|
||
message_record.id,
|
||
Message(
|
||
id=message_record.id,
|
||
type=message_record.type,
|
||
title=message_record.title,
|
||
content=message_record.content,
|
||
),
|
||
)
|
||
return conversations
|
||
|
||
async def create_conversation_record(self, user_id: str) -> dict[str, Conversation]:
|
||
"""
|
||
创建会话记录
|
||
:param user_id: 用户唯一标识
|
||
:return: 会话实例
|
||
"""
|
||
async with rx.asession() as session:
|
||
record = ConversationRecord(user_id=user_id)
|
||
session.add(record)
|
||
await session.commit()
|
||
await session.refresh(record)
|
||
return {
|
||
record.id: Conversation(
|
||
id=record.id,
|
||
description=record.description,
|
||
created_at=record.created_at,
|
||
)
|
||
}
|
||
|
||
async def delete_conversation_record(self, conversation_id: str) -> None:
|
||
"""
|
||
删除会话记录(逻辑删除)
|
||
:param conversation_id: 指定会话唯一标识
|
||
:return: None
|
||
"""
|
||
async with rx.asession() as session:
|
||
record = await session.get(ConversationTable, conversation_id)
|
||
if not record:
|
||
return
|
||
record.is_deleted = True
|
||
await session.commit()
|
||
|
||
async def create_dialog_record(
|
||
self,
|
||
conversation_id: str,
|
||
id: str,
|
||
user_prompt: str,
|
||
thoughts: dict[int, Any],
|
||
result_output: str,
|
||
usage: dict[str, Any],
|
||
) -> dict[str, Dialog]:
|
||
"""
|
||
创建对话记录
|
||
:param conversation_id: 会话唯一标识
|
||
:param user_prompt: 用户提示词
|
||
:param result_output: 结果输出
|
||
:return: 创建对话记录的唯一标识
|
||
"""
|
||
async with rx.asession() as session:
|
||
record = DialogRecord(
|
||
id=id,
|
||
conversation_id=conversation_id,
|
||
user_prompt=user_prompt,
|
||
thoughts=thoughts,
|
||
result_output=result_output,
|
||
usage=usage,
|
||
)
|
||
session.add(record)
|
||
await session.commit()
|
||
await session.refresh(record)
|
||
return {
|
||
record.id: Dialog(
|
||
id=record.id,
|
||
user_prompt=record.user_prompt,
|
||
thoughts=record.thoughts,
|
||
result_output=record.result_output,
|
||
usage=record.usage,
|
||
)
|
||
}
|
||
|
||
async def create_result_record(
|
||
self,
|
||
conversation_id: str,
|
||
dialog_id: str,
|
||
new_messages: list[ModelMessage],
|
||
) -> None:
|
||
"""
|
||
创建结果记录
|
||
:param conversation_id: 会话唯一标识
|
||
:param dialog_id: 对话唯一标识
|
||
:param new_messages: 新增消息
|
||
:return: None
|
||
"""
|
||
async with rx.asession() as session:
|
||
session.add(
|
||
ResultRecord(
|
||
conversation_id=conversation_id,
|
||
dialog_id=dialog_id,
|
||
new_messages=ModelMessagesTypeAdapter.dump_json(
|
||
new_messages
|
||
).decode(
|
||
"utf-8"
|
||
), # 序列化为 JSON 字符串
|
||
)
|
||
)
|
||
await session.commit()
|
||
|
||
async def get_message_history(self, conversation_id: str) -> list[ModelMessage]:
|
||
"""
|
||
获取消息历史列表
|
||
:param conversation_id: 会话唯一标识
|
||
:return: 消息历史
|
||
"""
|
||
records: list[ModelMessage] = []
|
||
async with rx.asession() as session:
|
||
result = await session.exec(
|
||
select(ResultRecord)
|
||
.where(ResultRecord.conversation_id == conversation_id)
|
||
.order_by(desc(ResultRecord.dialog_id))
|
||
)
|
||
for record in result.all():
|
||
records.extend(
|
||
ModelMessagesTypeAdapter.validate_json(record.new_messages)
|
||
)
|
||
return records
|