数据生成#

本文档描述了CAMEL的关键数据生成模块,这些模块通过先进的推理和指令调优技术实现高质量训练数据的创建。这些模块包括:

  • 思维链 (CoT): 生成明确的推理路径

  • Self-Instruct: 创建多样化的指令跟随数据

  • Source2Synth:将源代码转换为自然语言

  • 自我改进的CoT:通过自我批评迭代优化推理链条

思维链(CoT)数据生成#

概述#

思维链(CoT)数据生成模块实现了一个通过聊天代理交互生成高质量推理路径的复杂系统。它结合了多种先进算法来生成和验证推理链。

主要特性#

  • 用于解决方案探索的蒙特卡洛树搜索(MCTS)

  • 用于精确定位错误的二分搜索错误检测

  • 用于质量保证的双代理验证系统

  • 用于跟踪推理路径的解决方案树管理

核心组件#

CoTDataGenerator 类#

实现CoT生成系统的主要类,具有以下功能:

  • 双代理架构: 支持单代理(传统)和双代理两种模式

  • 答案生成: 使用MCTS进行复杂的答案生成

  • 答案验证: 使用黄金答案的鲁棒验证系统

  • 错误检测: 基于二分查找的解决方案错误检测

  • 解决方案管理: 全面的解决方案树管理和导出功能

使用方法#

基础示例#

from camel.agents import ChatAgent
from camel.datagen import CoTDataGenerator

# Initialize agents
generator_agent = ChatAgent("System message for generator")
verifier_agent = ChatAgent("System message for verifier")

# Define golden answers
golden_answers = {
    "question1": "answer1",
    "question2": "answer2"
}

# Create generator
cot_generator = CoTDataGenerator(
    generator_agent=generator_agent,
    verifier_agent=verifier_agent,
    golden_answers=golden_answers,
    search_limit=100
)

# Generate solution
solution = cot_generator.solve("question1")

数据导入/导出#

# Import QA pairs from JSON
cot_generator.import_qa_from_json("qa_pairs.json")

# Export solutions
cot_generator.export_solutions("solutions.json")

解决方案生成过程#

  1. 直接解决方案尝试

    • 首先尝试直接解决问题

    • 对照标准答案进行验证

  2. 基于MCTS的探索

    • 如果直接解决方案失败,使用MCTS探索解决方案空间

    • 基于之前的尝试构建解决方案树

  3. 错误检测与纠正

    • 使用二分搜索来定位解决方案中的错误

    • 基于正确的部分生成新的解决方案

  4. 解决方案验证

    • 使用双代理系统或标准答案验证解决方案

    • 通过严格验证保持解决方案质量

配置选项#

  • search_limit: 最大搜索迭代次数(默认值:100)

  • generator_agent: 专门用于答案生成的代理

  • verifier_agent: 专门用于答案验证的代理

  • golden_answers: 预定义的正确答案用于验证

输出格式#

解决方案树以JSON格式导出,包含:

  • 包含中间步骤的解决方案

  • 用于验证的黄金答案

  • 导出时间戳

  • 解决方案评分和验证结果

Self-Instruct: 指令生成#

概述#

Self-Instruct模块实现了一个用于生成和管理机器生成任务指令的流程。它结合人工编写的种子指令和机器生成的指令,创建多样化、高质量的任务指令,同时通过可配置的过滤机制确保质量。

核心组件#

Self Instruct 流程#

协调指令生成过程的主要流水线类。

主要功能:

  • 使用可配置的比例结合人工编写和机器生成的指令

  • 支持分类和非分类任务类型

  • 内置指令过滤和验证

  • 自动生成任务实例

  • 基于JSON的数据输入/输出

指令过滤器#

一个用于验证和筛选生成指令的全面过滤系统。

功能特性:

  • 基于长度的过滤

  • 关键词过滤

  • 标点符号检查

  • 非英文文本检测

  • 用于去重的ROUGE相似度过滤

  • 用于自定义过滤器的可扩展过滤器注册表

使用方法#

基础示例#

from camel.agents import ChatAgent
from camel.datagen.self_instruct import SelfInstructPipeline

# Initialize agent
agent = ChatAgent()

# Create pipeline with default settings
pipeline = SelfInstructPipeline(
    agent=agent,
    seed='seed_tasks.jsonl',  # Path to human-written seed tasks
    num_machine_instructions=5,
    data_output_path='./data_output.json',
    human_to_machine_ratio=(6, 2)  # Use 6 human tasks and 2 machine tasks for generation
)

# Generate instructions
pipeline.generate()

自定义筛选#

from camel.datagen.self_instruct import SelfInstructPipeline
from camel.datagen.self_instruct.filter import InstructionFilter

# Configure filters
filter_config = {
    "length": {},  # Default length constraints
    "keyword": {},  # Keyword-based filtering
    "punctuation": {},  # Punctuation checks
    "non_english": {},  # Non-English text detection
    "rouge_similarity": {  # ROUGE-based similarity filtering
        "threshold": 0.7,
        "metric": "rouge-l"
    }
}

# Create pipeline with custom filter configuration
pipeline = SelfInstructPipeline(
    agent=agent,
    seed='seed_tasks.jsonl',
    instruction_filter=InstructionFilter(filter_config),
    num_machine_instructions=5
)

配置选项#

流水线参数#

  • agent: 用于生成指令的ChatAgent实例

  • seed: 指向人工编写的种子任务的路径,JSONL格式

  • num_machine_instructions: 要生成的机器生成指令数量(默认值:5)

  • data_output_path: 保存生成数据的路径(默认:'./data_output.json')

  • human_to_machine_ratio: 生成任务中人工与机器任务的比例(默认值:(6, 2))

  • instruction_filter: 自定义InstructionFilter实例(可选)

  • filter_config: 默认过滤器的配置字典(可选)

过滤器配置#

默认过滤器配置包括:

  • length: 配置指令的长度限制

  • keyword: 设置基于关键词的过滤规则

  • punctuation: 定义标点符号验证规则

  • non_english: 配置非英文文本检测

  • rouge_similarity: 设置ROUGE相似度阈值用于去重

流水线阶段#

  1. 种子加载

    • 从JSONL文件加载人工编写的指令

    • 验证种子格式

    • 初始化任务存储

  2. 指令生成

    • 基于比例的人类和机器任务样本

    • 使用ChatAgent生成新指令

    • 应用指令过滤器

  3. 任务分类

    • 识别任务是分类任务还是非分类任务

    • 根据任务类型生成合适的提示词

  4. 实例生成

    • 为每个任务生成输入-输出对

    • 根据任务类型解析和格式化实例

    • 应用质量过滤器

  5. 数据输出

    • 将生成的任务和实例保存为JSON

    • 包含元数据和配置详情

    • 保持结构化输出格式

输入/输出格式#

种子任务(输入)#

{"instruction": "Classify the sentiment of this text as positive or negative."}
{"instruction": "Generate a summary of the given paragraph."}

生成的数据(输出)#

{
  "machine_instructions": [
    {
      "instruction": "...",
      "is_classification": true,
      "instances": [
        {
          "input": "...",
          "output": "..."
        }
      ]
    }
  ]
}

Source2Synth: 多跳问题-答案生成#

概述#

Source2Synth是一个复杂的数据生成系统,旨在从源文本数据创建多跳问答对。它实现了一个处理原始文本、提取信息对并生成具有可配置复杂度阈值的复杂多跳推理问题的流程。

核心组件#

用户数据处理器#

管理从文本处理到数据集生成的整个流程的主要协调器类。

功能特性:

  • 支持单文本和批量处理功能

  • 可配置的AI模型或基于规则的处理

  • 与MultiHopGeneratorAgent集成用于问答生成

  • 随机种子控制以确保可复现性

ExampleConstructor#

处理从原始文本数据构建训练样本的过程。

功能特性:

  • 文本预处理和质量验证

  • 基于前提-中间-结论关系的信息对提取

  • 使用AI或基于规则的方法生成多跳问答对

  • 生成示例的复杂度评分

DataCurator#

管理和策划多跳问答对的数据集。

功能特性:

  • 基于可配置标准的质量过滤

  • 复杂度阈值过滤

  • 相似示例的去重

  • 数据集采样以达到目标大小

  • 用于可重复采样的随机种子控制

使用方法#

基础示例#

from camel.datagen.source2synth import (
    UserDataProcessor,
    ProcessorConfig
)

# Create configuration
config = ProcessorConfig(
    seed=42,
    min_length=50,
    max_length=1000,
    complexity_threshold=0.5,
    dataset_size=10,
    use_ai_model=True,
)

# Initialize processor
processor = UserDataProcessor(config)

# Process a single text
result = processor.process_text(
    "Your source text here",
    source="example_source"
)

# Process multiple texts
texts = ["Text 1", "Text 2", "Text 3"]
sources = ["source1", "source2", "source3"]
batch_results = processor.process_batch(texts, sources)

配置选项#

ProcessorConfig#

关键参数:

  • seed: 用于可重复性的随机种子

  • min_length: 文本处理的最小长度

  • max_length: 文本处理的最大长度

  • complexity_threshold: 最小复杂度分数(0.0-1.0)

  • dataset_size: 最终数据集的目标大小

  • use_ai_model: 在AI模型和基于规则的处理之间切换

  • hop_generating_agent: 自定义MultiHopGeneratorAgent实例(可选)

流水线阶段#

  1. 文本预处理

    • 长度验证

    • 质量检查

    • 文本标准化

  2. 信息抽取

    • 前提识别

    • 中间关系抽取

    • 结论形成

  3. 问答生成

    • 多跳问题生成

    • 答案验证

    • 复杂度评分

  4. 数据集整理

    • 质量过滤

    • 复杂度阈值

    • 去重

    • 目标尺寸采样

自我改进的CoT数据生成#

概述#

自我改进的CoT数据生成管道实现了一种迭代方法,用于生成和改进问题解决任务的推理轨迹。该实现基于自学习推理的方法论,其中AI代理通过自我评估和反馈来学习改进其推理过程。

架构#

该流水线包含四个主要阶段:

  1. 初始推理轨迹生成

  2. 自我评估

  3. 基于反馈的改进

  4. 迭代优化

关键组件#

SelfImprovingCoTPipeline 类#

实现STaR方法论的核心类,具有以下特性:

  • 可自定义的推理和评估代理

  • 支持基于代理的评估和外部奖励模型

  • 可配置不同评估维度的质量阈值

  • 可自定义最大迭代次数的迭代改进流程

  • 可选的少量示例,用于生成更好的推理结果

  • 灵活的输出格式和文件保存选项

使用方法#

基础示例#

from camel.agents import ChatAgent
from camel.datagen import SelfImprovingCoTPipeline

# Initialize agents
reason_agent = ChatAgent(
    """Answer my question and give your 
    final answer within \\boxed{}."""
)

evaluate_agent = ChatAgent(
    "You are a highly critical teacher who evaluates the student's answers "
    "with a meticulous and demanding approach."
)

# Prepare your problems
problems = [
    {"problem": "Your problem text here"},
    # Add more problems...
]

# Create and run the pipeline
pipeline = SelfImprovingCoTPipeline(
    reason_agent=reason_agent,
    evaluate_agent=evaluate_agent,
    problems=problems,
    max_iterations=3,
    output_path="star_output.json"
)

results = pipeline.generate()

使用外部奖励模型的高级用法#

from camel.models.reward import NemotronRewardModel

# Initialize reward model
reward_model = NemotronRewardModel(
    model_type=ModelType.NVIDIA_NEMOTRON_340B_REWARD,
    url="https://integrate.api.nvidia.com/v1",
    api_key="your_api_key"
)

# Create pipeline with reward model
pipeline = SelfImprovingCoTPipeline(
    reason_agent=reason_agent,
    evaluate_agent=evaluate_agent,
    problems=problems,
    reward_model=reward_model,
    score_threshold={
        "correctness": 0.8,
        "clarity": 0.7,
        "completeness": 0.7
    }
)

输入/输出格式#

输入格式#

该流水线期望问题以JSON格式呈现:

{
    "problems": [
        {
            "problem": "Problem text here",
            "solution": "Optional solution text"
        }
    ]
}

输出格式#

该流水线生成的输出为JSON格式,包含以下内容:

  • 原始问题

  • 最终推理轨迹

  • 带有迭代的改进历史

  • 每次迭代的评估分数和反馈

配置选项#

  • max_iterations: 最大改进迭代次数(默认值:3)

  • score_threshold: 评估维度的质量阈值(默认值:0.7)

  • few_shot_examples: 用于小样本学习的可选示例

  • output_path: 用于保存结果的路径(可选)