ai_executor_module.md 2.8 KB

AI Executor 模块文档 (重构版)

模块目的

AI执行服务模块负责协调AI任务执行流程,包括:

  • 任务参数准备
  • 大模型API调用
  • 结果解析验证
  • 执行记录存储

核心概念

  1. 任务类型(AITaskType):定义可执行的AI任务类别

    • MARKETING_COPY: 营销文案生成
    • COMPETITOR_ANALYSIS: 竞品关键词分析
  2. 任务处理器(AITaskHandler):每个任务类型对应一个处理器类,负责:

    • 格式化提示词
    • 定义结果模型
    • 提供输出格式要求
  3. 执行记录(AIExecutionRecord):存储每次任务执行的完整上下文和结果

架构设计

classDiagram
    class AITaskHandler{
        <<interface>>
        +task_type() AITaskType
        +format_prompt() str
        +get_result_model() Type[BaseModel]
    }
    
    class MarketingCopyGenerator{
        +task_type = MARKETING_COPY
        +format_prompt()
    }
    
    class CompetitorAnalyzer{
        +task_type = COMPETITOR_ANALYSIS
        +format_prompt()
    }
    
    class AIExecutorService{
        +execute_task()
        +execute_multi_model_task()
    }
    
    AITaskHandler <|-- MarketingCopyGenerator
    AITaskHandler <|-- CompetitorAnalyzer
    AIExecutorService --> AITaskHandler

使用示例

1. 营销文案生成

# 初始化服务
service = AIExecutorService(product)

# 执行任务
result = await service.execute_task(
    task_type=AITaskType.MARKETING_COPY,
    model_name="gpt-4",
    custom_prompt=user_template
)

2. 多模型竞品分析

results = await service.execute_multi_model_task(
    task_type=AITaskType.COMPETITOR_ANALYSIS,
    model_names=["gpt-4", "claude-3"],
    custom_prompt=competitor_template
)

数据存储

所有执行记录存储在MongoDB的AIExecutionRecords集合中,包含字段:

  • task_type: 任务类型
  • model_name: 使用的AI模型
  • input_data: 原始输入(如提示词)
  • output_data: AI原始输出
  • analysis_result: 解析后的结果对象
  • created_at: 执行时间戳

扩展新任务类型

  1. AITaskType中添加新枚举值
  2. 创建结果模型(继承BaseAIExecution)
  3. 实现任务处理器(继承AITaskHandler)
  4. TaskHandlerFactory中注册

示例:

# 新增产品评论分析
class ProductReviewResult(BaseAIExecution):
    analysis_result: ReviewAnalysisResult

class ReviewAnalyzer(AITaskHandler):
    task_type = AITaskType.PRODUCT_REVIEW
    
    async def format_prompt(self, product: Product) -> str:
        ...
    
    def get_result_model(self):
        return ProductReviewResult

最佳实践

  1. 每个任务类型应有明确的单一职责
  2. 提示词模板应参数化以便复用
  3. 结果模型应严格定义输出结构
  4. 多模型比较时建议使用相同提示词