基于LangChain实现自主代理 | 青训营X豆包MarsCode 技术训练营

85 阅读4分钟

在这节课中,我学习了如何利用LangChain框架,结合Auto-GPT、BabyAGI和HuggingGPT等自治代理项目,染后创建一个能够自主完成任务的智能代理。以下是学习要点的总结和实现解析:

一、自治代理的基本概念

  1. 定义

    模拟代理(Simulation Agents) :用于模拟特定场景,进行角色扮演,不能直接应用于真实任务。

    自治代理(Autonomous Agents) :设计为能够自主执行任务,追求长期目标,例如Auto-GPT、BabyAGI等。

  2. 优势

    任务分解:自动化将复杂目标分解为子任务。

    连续执行:根据上下文动态生成新任务并调整优先级。

    持久记忆:可通过向量存储技术保存执行结果以便后续任务使用。

  3. 核心技术栈

    LangChain框架:提供组件支持(代理、工具、记忆)。

    LLM(大语言模型) :如GPT-4,负责推理和任务执行。

    向量数据库:如FAISS,用于上下文存储和检索。

二、LangChain实现BabyAGI的核心流程

1. 实现目标

通过LangChain,创建一个BabyAGI代理,使其能够根据气候变化自动制定鲜花存储策略。

2. 代码解析

我们使用LangChain的链式处理方法,构建三个关键功能模块:

三、任务创建链(TaskCreationChain)

负责生成新任务,根据目标和已完成任务的结果,提出未完成的任务。

  • 代码实现
class TaskCreationChain(LLMChain):
    """负责生成任务的链"""
    @classmethod
    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:
        task_creation_template = (
            "You are a task creation AI that uses the result of an execution agent"
            " to create new tasks with the following objective: {objective},"
            " The last completed task has the result: {result}."
            " This result was based on this task description: {task_description}."
            " These are incomplete tasks: {incomplete_tasks}."
            " Based on the result, create new tasks to be completed"
            " by the AI system that do not overlap with incomplete tasks."
            " Return the tasks as an array."
        )
        prompt = PromptTemplate(
            template=task_creation_template,
            input_variables=[
                "result", "task_description", "incomplete_tasks", "objective"
            ],
        )
        return cls(prompt=prompt, llm=llm, verbose=verbose)
  • 功能解析

    • 接收已完成任务的结果、未完成任务列表和目标,生成新的任务。
    • 返回的任务以数组形式存储,方便后续处理。

四、任务优先级链(TaskPrioritizationChain)

负责重新排序任务优先级,根据目标动态调整任务的执行顺序。

  • 代码实现
class TaskPrioritizationChain(LLMChain):
    """负责任务优先级排序的链"""
    @classmethod
    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:
        task_prioritization_template = (
            "You are a task prioritization AI tasked with cleaning the formatting of and reprioritizing"
            " the following tasks: {task_names}."
            " Consider the ultimate objective of your team: {objective}."
            " Do not remove any tasks. Return the result as a numbered list, like:"
            " #. First task"
            " #. Second task"
            " Start the task list with number {next_task_id}."
        )
        prompt = PromptTemplate(
            template=task_prioritization_template,
            input_variables=["task_names", "next_task_id", "objective"],
        )
        return cls(prompt=prompt, llm=llm, verbose=verbose)
  • 功能解析

    • 使用提示模板,通过LLM对任务列表重新排序。
    • 任务编号便于程序进一步处理。

五、任务执行链(ExecutionChain)

负责具体任务的执行,调用LLM获取任务结果。

  • 代码实现
class ExecutionChain(LLMChain):
    """负责执行任务的链"""
    @classmethod
    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:
        execution_template = (
            "You are an AI who performs one task based on the following objective: {objective}."
            " Take into account these previously completed tasks: {context}."
            " Your task: {task}."
            " Response:"
        )
        prompt = PromptTemplate(
            template=execution_template,
            input_variables=["objective", "context", "task"],
        )
        return cls(prompt=prompt, llm=llm, verbose=verbose)
  • 功能解析

    • 根据目标执行单个任务,结合历史任务结果生成新的上下文。
    • 任务结果存储在向量数据库中。

六、其他功能函数

在实现中还包含若干辅助函数,用于任务分配和处理:

  • 生成新任务
def get_next_task(task_creation_chain, result, task_description, task_list, objective):
    """获取新任务"""
    incomplete_tasks = ", ".join(task_list)
    response = task_creation_chain.run(
        result=result,
        task_description=task_description,
        incomplete_tasks=incomplete_tasks,
        objective=objective,
    )
    new_tasks = response.split("\n")
    return [{"task_name": task_name} for task_name in new_tasks if task_name.strip()]
  • 任务排序
python
复制代码
def prioritize_tasks(task_prioritization_chain, this_task_id, task_names, objective):
    """任务排序"""
    response = task_prioritization_chain.run(
        task_names=task_names, next_task_id=this_task_id, objective=objective
    )
    return response.split("\n")

七、整体框架运行逻辑

  1. 初始化LangChain环境,加载所需组件(LLM、向量存储)。
  2. 使用任务生成链创建初始任务列表。
  3. 通过任务优先级链动态调整任务优先级。
  4. 使用任务执行链逐步完成任务,并根据结果生成新任务。
  5. 循环执行,直到目标达成。

八、总结与反思

  • 创新点

    • 将复杂任务拆解为子任务并动态调整,极大提升了AI代理的灵活性。
    • 自治代理展示了朝向通用人工智能(AGI)的潜力。
  • 不足

    • 实验性较强,长时间运行可能会因模型局限性而陷入循环。
    • 运行成本较高,尤其是在处理复杂任务时。

通过本节学习,我不仅理解了LangChain在自主代理开发中的核心价值,还掌握了如何通过代码实现BabyAGI的关键功能模块。这为我们后续开发更复杂、更智能的代理奠定了坚实基础。