# AI对话模块生成提示词 ## 模块概述 请实现一个完整的AI对话模块,集成阿里云百炼平台(DashScope),支持流式/非流式对话、会话管理、消息记录和费用计算功能。 ## 技术栈 - 后端框架:FastAPI - ORM:SQLAlchemy 2.0 - 数据库:PostgreSQL(schema: aigcspace) - AI平台:阿里云百炼平台(dashscope SDK) - 认证:JWT Token(已有auth中间件) ## 功能需求 ### 1. DashScope客户端封装 创建 `app/services/dashscope_client.py`: - 封装阿里云百炼平台API调用 - 支持非流式调用(Generation.call) - 支持流式调用(stream=True, incremental_output=True) - 参数支持:model、messages、temperature、top_p、max_tokens - API密钥从用户数据动态获取,不使用全局配置 ### 2. LLM服务层 创建 `app/services/llm_service.py`: - 初始化时接收db、api_key、user_id参数 - 模型验证:检查模型是否存在且category=0(LLM类型) - 非流式对话:调用DashScope,返回完整响应 - 流式对话:返回SSE格式的AsyncGenerator - 使用 `incremental_output=True`,每次返回增量内容 - 累积完整内容用于保存:`full_content += chunk.content` - 流结束时发送 `data: [DONE]\n\n` - 消息记录:对话完成后自动保存用户消息和助手消息到数据库 - 获取LLM模型列表 ### 3. 会话管理 创建 `app/models/conversation.py`: **AIConversation表**(ai_conversation): - id: 主键 - user_id: 用户ID(外键关联users表) - title: 会话标题 - total_input_tokens: 输入token总量 - total_output_tokens: 输出token总量 - total_tokens: token总量 - bill: 会话费用(Numeric(12,4)) - created_at, updated_at: 时间戳 **AIMessage表**(ai_message): - id: 主键 - conversation_id: 会话ID(外键,级联删除) - role: 消息角色(user/assistant/system) - content: 消息内容(Text类型) - input_tokens, output_tokens, total_tokens: token统计 - model_id: 模型ID(外键,允许为空) - model_name: 模型名称 - created_at: 创建时间 ### 4. 会话服务层 创建 `app/services/conversation_service.py`: - create_conversation: 创建新会话 - get_conversation: 根据ID获取会话 - get_user_conversations: 获取用户所有会话(按更新时间倒序) - update_token_stats: 累加更新token统计 - update_bill: 累加更新费用 - delete_conversation: 删除会话(级联删除消息) - update_title: 更新会话标题 ### 5. 消息服务层 创建 `app/services/message_service.py`: - create_message: 创建消息并自动更新会话统计 - user角色:仅记录input_tokens - assistant角色:仅记录output_tokens - 自动调用BillingCalculator计算费用 - get_conversation_messages: 获取会话所有消息 ### 6. 计费计算器 创建 `app/services/billing_calculator.py`: - 支持两种计费模式: - simple(简单计费):费用 = (input_tokens × input_price + output_tokens × output_price) / 1000 - tier(阶梯计费):根据token数量匹配对应阶梯价格 - 通过model_id获取关联的price_info - 费用精度:4位小数,使用Decimal类型 ### 7. API路由 创建 `app/routers/llm_router.py`: ``` POST /api/llm/chat - 统一对话端点,支持流式和非流式 - 需要用户认证 - 请求体:model, messages, stream, temperature, top_p, max_tokens, conversation_id - 流式返回:StreamingResponse (text/event-stream) - 非流式返回:ApiResponse包装 GET /api/llm/models - 获取所有LLM模型列表(category=0) ``` 创建 `app/routers/conversation_router.py`: ``` POST /api/conversations - 创建会话 GET /api/conversations - 获取用户会话列表 GET /api/conversations/{id} - 获取会话详情(含消息) PUT /api/conversations/{id} - 更新会话标题 DELETE /api/conversations/{id} - 删除会话 GET /api/conversations/{id}/messages - 获取会话消息 ``` ### 8. Schema定义 创建 `app/schemas/llm_schema.py`: ```python ChatMessage: role(Literal["system","user","assistant"]), content ChatRequest: model, messages, stream, temperature, top_p, max_tokens, conversation_id UsageInfo: input_tokens, output_tokens, total_tokens ChatResponse: content, finish_reason, usage StreamChunk: content, finish_reason, usage(Optional) ``` 创建 `app/schemas/conversation_schema.py`: ```python ConversationCreate: title ConversationUpdate: title ConversationResponse: id, user_id, title, tokens统计, bill, 时间戳 MessageResponse: id, conversation_id, role, content, tokens统计, model_id, model_name, created_at ConversationDetailResponse: 会话信息 + messages列表 ``` ## 数据库迁移 创建迁移文件: **011_create_ai_conversation_table.sql**: - 创建ai_conversation表 - 添加user_id外键约束 - 创建索引 **012_create_ai_message_table.sql**: - 创建ai_message表 - 添加conversation_id外键约束(级联删除) - 添加model_id外键约束 - 添加role检查约束 - 创建索引 ## 关键实现细节 ### 流式响应累积内容 ```python full_content = "" for response in self.client.call_stream(...): if choice.message.content: full_content += choice.message.content # 累加,不是覆盖 yield f"data: {chunk.model_dump_json()}\n\n" # 流结束后保存full_content到数据库 ``` ### SSE格式 ``` data: {"content":"你好","finish_reason":null}\n\n data: {"content":"!","finish_reason":"stop","usage":{...}}\n\n data: [DONE]\n\n ``` ### 权限控制 - 对话API需要用户认证 - 会话只能被创建者访问/修改/删除 - API密钥从当前用户的apikey字段获取 ## 注册路由 在 `main.py` 中注册: ```python from app.routers import llm_router, conversation_router app.include_router(llm_router.router) app.include_router(conversation_router.router) ``` ## 依赖关系 - 依赖已有的Model、ModelPrice、ModelPriceTier模型 - 依赖已有的User模型和认证中间件 - 依赖已有的ApiResponse响应格式