基于智能体的多角色联合写作协作创作平台

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

系统总体设计

基于智能体的联合写作系统是一个多角色协作创作的平台,通过不同智能体角色模拟写作过程中的各个环节,最终实现高质量小说的生成。系统采用前后端分离架构,后端使用 FastAPI 提供 API 服务,前端使用 Flutter 构建跨平台应用。

系统架构概述

系统整体架构分为四层:

  1. 接入层:负责用户接入和身份验证,包括 Web 端和移动端的 Flutter 应用
  2. 业务逻辑层:核心智能体系统和业务流程处理,由 FastAPI 实现
  3. 数据层:存储写作内容、用户信息、智能体配置等数据
  4. AI 服务层:提供基础 AI 能力,如语言模型调用、文本分析等
智能体角色设计

系统将定义多种智能体角色,每个角色负责特定的写作任务:

  1. 策划师智能体:负责故事框架、大纲和章节结构设计
  2. 作者智能体:根据大纲进行内容创作
  3. 编辑智能体:对生成的内容进行语法、逻辑和风格编辑
  4. 评审智能体:对章节内容进行质量评估和评分
  5. 研究员智能体:提供背景知识和素材支持
  6. 角色设计智能体:创建和发展故事中的角色

核心模块设计

智能体管理模块

该模块负责智能体的创建、配置和调度:

python

运行

# 智能体基类设计
class AgentBase:
    def __init__(self, name: str, model_config: dict):
        self.name = name
        self.model_config = model_config
        self.context = {}  # 写作上下文
        
    def load_context(self, context: dict):
        """加载写作上下文"""
        self.context = context
        
    def generate_prompt(self) -> str:
        """生成提示词"""
        raise NotImplementedError
        
    def execute(self) -> str:
        """执行智能体任务"""
        raise NotImplementedError

# 策划师智能体示例
class PlannerAgent(AgentBase):
    def __init__(self, name: str, model_config: dict):
        super().__init__(name, model_config)
        
    def generate_prompt(self) -> str:
        genre = self.context.get('genre', '科幻')
        theme = self.context.get('theme', '人工智能')
        return f"""作为一名专业的故事策划师,请为一个{genre}题材,
        以{theme}为主题的小说创建详细的大纲。包括故事背景、主要情节、
        角色设定和关键转折点。"""
        
    def execute(self) -> str:
        prompt = self.generate_prompt()
        # 调用LLM服务
        return self._call_llm(prompt)
    
    def _call_llm(self, prompt: str) -> str:
        # 实际实现中会调用具体的LLM API
        return f"这是{self.name}生成的内容..."
写作流程管理模块

该模块管理从大纲到完本的整个写作流程:

python

运行

class WritingWorkflow:
    def __init__(self, agents: List[AgentBase]):
        self.agents = agents
        self.workflow_steps = []
        self.current_step = 0
        self.context = {}
        
    def define_workflow(self, steps: List[str]):
        """定义写作工作流程步骤"""
        self.workflow_steps = steps
        
    def set_context(self, context: dict):
        """设置全局写作上下文"""
        self.context = context
        
    def run_next_step(self) -> str:
        """执行下一步写作流程"""
        if self.current_step >= len(self.workflow_steps):
            return "写作流程已完成"
            
        step_name = self.workflow_steps[self.current_step]
        # 查找负责此步骤的智能体
        agent = next((a for a in self.agents if a.name.lower() == step_name.lower()), None)
        
        if not agent:
            return f"未找到负责{step_name}的智能体"
            
        agent.load_context(self.context)
        result = agent.execute()
        
        # 更新上下文供下一步使用
        self.context[f"{step_name}_result"] = result
        self.current_step += 1
        
        return result
质量评估与评审模块

该模块实现对写作内容的质量评估:

python

运行

class QualityAssessment:
    def __init__(self, criteria: List[dict]):
        self.criteria = criteria  # 评分标准
        
    def evaluate_content(self, content: str, context: dict) -> dict:
        """评估内容质量"""
        scores = {}
        comments = {}
        
        for criterion in self.criteria:
            criterion_name = criterion['name']
            weight = criterion['weight']
            prompt = f"""根据以下标准评估以下小说内容:{criterion['description']}
            内容:{content}"""
            
            # 调用评审智能体进行评分
            score = self._get_score_from_agent(prompt)
            comment = self._get_comment_from_agent(prompt)
            
            scores[criterion_name] = {
                'score': score,
                'weight': weight
            }
            comments[criterion_name] = comment
            
        # 计算加权总分
        total_score = sum(score['score'] * score['weight'] 
                         for score in scores.values())
        
        return {
            'scores': scores,
            'comments': comments,
            'total_score': total_score
        }
    
    def _get_score_from_agent(self, prompt: str) -> float:
        # 实际实现中会调用评审智能体
        return 8.5  # 示例分数
    
    def _get_comment_from_agent(self, prompt: str) -> str:
        # 实际实现中会调用评审智能体
        return "内容结构清晰,但情节发展稍显平淡。"
FastAPI 后端实现

以下是核心 API 的实现示例:

python

运行

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Optional

app = FastAPI(title="智能联合写作系统")

# 数据模型定义
class StoryContext(BaseModel):
    genre: str
    theme: str
    main_character: str
    background: Optional[str] = None
    
class WritingTask(BaseModel):
    task_id: str
    story_context: StoryContext
    workflow_steps: List[str]
    
class WritingResult(BaseModel):
    task_id: str
    step: str
    content: str
    context: Dict
    
class EvaluationResult(BaseModel):
    task_id: str
    scores: Dict
    total_score: float
    comments: Dict

# 模拟数据库
writing_tasks = {}
writing_results = {}
evaluations = {}

@app.post("/api/tasks/", response_model=WritingTask)
async def create_writing_task(task: WritingTask):
    """创建写作任务"""
    writing_tasks[task.task_id] = task
    return task

@app.post("/api/tasks/{task_id}/execute", response_model=WritingResult)
async def execute_next_step(task_id: str):
    """执行下一步写作流程"""
    task = writing_tasks.get(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="任务不存在")
    
    # 这里会初始化智能体并执行工作流
    # 简化示例,实际实现会更复杂
    workflow = initialize_workflow(task.workflow_steps)
    workflow.set_context(task.story_context.dict())
    result = workflow.run_next_step()
    
    writing_result = WritingResult(
        task_id=task_id,
        step=workflow.current_step - 1,
        content=result,
        context=workflow.context
    )
    
    writing_results[task_id] = writing_result
    return writing_result

@app.post("/api/evaluate/{task_id}", response_model=EvaluationResult)
async def evaluate_content(task_id: str):
    """评估内容质量"""
    result = writing_results.get(task_id)
    if not result:
        raise HTTPException(status_code=404, detail="写作结果不存在")
    
    # 初始化质量评估
    criteria = [
        {"name": "情节", "weight": 0.3, "description": "情节的吸引力和发展"},
        {"name": "角色", "weight": 0.25, "description": "角色的深度和可信度"},
        {"name": "文笔", "weight": 0.25, "description": "语言表达和风格"},
        {"name": "逻辑", "weight": 0.2, "description": "故事逻辑和连贯性"}
    ]
    
    assessor = QualityAssessment(criteria)
    evaluation = assessor.evaluate_content(result.content, result.context)
    
    evaluation_result = EvaluationResult(
        task_id=task_id,
        **evaluation
    )
    
    evaluations[task_id] = evaluation_result
    return evaluation_result
Flutter 前端设计

Flutter 前端将实现以下核心功能:

  1. 任务创建与管理界面
  2. 智能体配置与管理
  3. 写作过程可视化
  4. 内容评审与评分展示
  5. 多角色协作界面

以下是主要页面的设计框架:

dart

// 主应用结构
void main() {
  runApp(const WritingApp());
}

class WritingApp extends StatelessWidget {
  const WritingApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '智能联合写作系统',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
      routes: {
        '/task': (context) => const TaskPage(),
        '/writing': (context) => const WritingPage(),
        '/evaluation': (context) => const EvaluationPage(),
      },
    );
  }
}

// 主页 - 任务列表
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的写作任务'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pushNamed(context, '/task');
        },
        child: const Icon(Icons.add),
      ),
      body: ListView.builder(
        itemCount: 5, // 示例任务数量
        itemBuilder: (context, index) {
          return TaskCard(
            title: '任务 $index',
            genre: '科幻',
            status: '进行中',
            onTap: () {
              Navigator.pushNamed(context, '/writing');
            },
          );
        },
      ),
    );
  }
}

// 写作页面
class WritingPage extends StatefulWidget {
  const WritingPage({Key? key}) : super(key: key);

  @override
  State<WritingPage> createState() => _WritingPageState();
}

class _WritingPageState extends State<WritingPage> {
  String currentContent = '';
  int currentStep = 0;
  List<String> workflowSteps = ['策划', '写作', '编辑', '评审'];
  
  void _executeStep() async {
    // 调用API执行下一步
    // 更新UI
    setState(() {
      currentStep = (currentStep + 1) % workflowSteps.length;
      currentContent = "这是${workflowSteps[currentStep]}步骤生成的内容...";
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('联合写作'),
      ),
      body: Column(
        children: [
          // 步骤指示器
          WorkflowIndicator(steps: workflowSteps, currentStep: currentStep),
          
          // 内容显示区域
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                controller: TextEditingController(text: currentContent),
                maxLines: null,
                expands: true,
                readOnly: true,
                decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: '写作内容将显示在这里...',
                ),
              ),
            ),
          ),
          
          // 操作按钮
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: ElevatedButton(
              onPressed: _executeStep,
              child: Text(currentStep < workflowSteps.length - 1 
                  ? '下一步: ${workflowSteps[currentStep + 1]}' 
                  : '完成写作'),
            ),
          ),
        ],
      ),
    );
  }
}

系统交互流程

  1. 用户通过 Flutter 应用创建写作任务,设置故事类型、主题等参数
  2. 前端将任务信息发送到 FastAPI 后端
  3. 后端根据任务配置初始化智能体和工作流
  4. 按顺序调用各个智能体执行写作步骤
  5. 每完成一个步骤,将结果返回前端显示
  6. 全部步骤完成后,调用评审智能体进行质量评估
  7. 前端展示评估结果,用户可以选择继续修改或发布

这个设计充分利用了智能体的特性,将写作过程分解为多个专业环节,通过协作提高创作质量。同时,系统架构支持扩展更多智能体角色和优化评估标准,以适应不同类型的写作需求。

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值