生成式人工智能/大语言模型

使用 NVIDIA AgentIQ 开源工具包改进 AI 代码生成

随着 NVIDIA AgentIQ (用于连接和优化 AI 智能体团队的开源库) 的发布,开发者、专业人士和研究人员可以创建自己的代理式 AI 应用。本教程通过 AI 代码生成示例,向您展示如何在 AgentIQ 中开发应用。我们将使用 LangGraph 和推理模型构建测试驱动的编码代理,以扩展测试时计算。

在预训练、后训练和推理中, Scaling laws 正在推动更智能的 AI 系统的发展。 大语言模型 (LLMs) 的大规模预训练提供了令人印象深刻的结果,但进一步扩展具有挑战性。 自主 AI 智能体 和测试时计算方法 (例如 Deepseek-R1 使用的方法) 通过扩展后训练和推理计算提供了显著的改进。在为逻辑、数学或编码等复杂任务构建 agentic 工作流时,这一点势在必行。

这些新颖的扩展方法更易于与 AgentIQ 结合使用,因为组织可以更好地设计、测试、部署和优化其 AI 智能体应用。我们来深入探讨如何在 AgentIQ 中改进 AI 代码生成工作流。

为何使用 AgentIQ 构建编码智能体

LLM 擅长编码任务,但仅限于聊天界面,缺乏自主性和与现实世界的集成。相比之下,由这些 LLM 提供支持的 AI 智能体旨在实现现实世界的目标。他们通常使用工具、内存和规划来执行文件编辑、代码执行或信息搜索等任务,从而与环境进行交互。

AI 智能体设计注意事项

AI 智能体是扩展推理时计算以提高 AI 性能的示例之一。要构建智能体或 多智能体系统 ,您必须平衡灵活性和结构。

灵活的智能体可能会被赋予 shell、代码编辑器和 Web 浏览器,并且只需执行最少的指令即可。相比之下,结构化智能体可能包含预定义的步骤,例如在更大的代码库中定位失败的测试用例,然后执行代码更改,直到错误得到解决。流工程是一个热门的中间地带,其中定义了状态和转换,并在每个状态内执行代理或工具。

推理模型和搜索方法是另一个需要推理时间计算的示例。在提供最终输出之前,DeepSeek-r1OpenAI o1 等推理模型会花费额外的时间在单个思维链中探索各种推理路径和解决方案。Beam Search 等搜索方法还会利用评分函数 (例如可验证的结果或近似值) 来探索各种分支。

借助 AgentIQ 轻松开发 AI 智能体

评估、部署和优化是开发者可以使用 AgentIQ 解决的一些常见挑战。下表总结了 AgentIQ 的一些特性和优势。

特征 优势
包含 Agent Framework 生态系统 继续使用您喜欢的工具(例如 LangGraph 和 CrewAI)进行构建。
通用规格 支持跨项目的可复用性和兼容性,包括 AgentIQ 中的许多示例。项目可以通过 AgentIQ 注册系统共享。
评估工具 工作流程的快速开发和迭代。定义一组预期输出,并通过更新配置文件轻松测试不同的模型、工具和工作流程。
内置部署选项 使用 aiq serve 轻松启动微服务,或利用开源的 chatbot 风格用户界面。
优化功能 使用工作流分析器识别瓶颈,并利用并行工具调用和与 NVIDIA Dynamo 集成等功能实现出色性能。
可观察性 通过与 Phoenix、OpenTelemetry Collector 和自定义提供程序紧密集成进行监控和调试。
表 1。AgentIQ 的特性和优势

请参阅文档或 GitHub ,了解功能的详细列表。

教程预备知识

您需要以下设置:

如何在 NVIDIA AgentIQ 中构建 AI 代码生成智能体

您将学习如何集成 AI 智能体和推理模型,以在 AgentIQ 中创建 AI 代码生成智能体。我们使用 LangGraph 构建核心代理,集成用于安全和控制的沙盒代码执行工具,并使用 DeepSeek-r1 增强纠错功能。最后,我们展示了如何使用监督代理将智能体集成到更大的系统中。

设置项目支架

首先,克隆 NVIDIA AgentIQ GitHub 资源库。按照 README 中的说明安装 AgentIQ 库。

现在,使用 AIQ 支架命令创建新项目模板。支架将包含一个默认工作流程和配置文件。

aiq workflow create code_gen_example

NVIDIA AgentIQ 将智能体工作流和可调用工具的概念统一到一个类(即函数)下。我们可以将代码生成代理作为函数实现,并将其用作监督代理(例如 ReACT 代理 )中的可调用工具。其他代理(例如研究代理、错误定位代理或测试生成代理)可以由 supervisor 管理并异步启动,以处理复杂的任务。

代码生成代理的输入将是问题语句、待修复代码和单元测试。该代理遵循一个简单的过程:

  1. 给出问题陈述 (例如 GitHub issue) 、代码修复和单元测试,智能体使用代码 LLM 进行代码生成,以创建 git 补丁来解决问题。
  2. 更新后的代码将在安全代码执行沙盒中针对单元测试运行。
  3. 如果测试失败,推理模型将根据输出提出更改建议。
  4. 重复执行第 1-3 步,直到生成的代码通过所需的单元测试,或者超过迭代次数上限。

更新配置文件

AgentIQ 中的配置文件定义了整个工作流程。通过更新配置文件 (例如添加工具 (函数) 、交换 LLM 或更改其他组件) ,可以通过 aiq eval cli 命令快速迭代代理工作流。

scaffold 命令会创建一个默认配置文件。更新三个部分:functions,llms 和 workflow。functions 部分包含可供 agents 使用的工具,llms 部分定义可供 agents 和 tools 使用的模型,workflow 是主要入口点。在此处,将 workflow 类型指定为 react_agent ,这将使用 AgentIQ 工具包中的默认 ReACT 代理。

functions:
  code_gen_tool:
    _type: code_gen_tool
    debug_llm: reasoning_llm
   	 code_llm: code_generation_llm
    max_iterations: 3

llms:
  reasoning_llm: 
    _type: nim 
    model_name: deepseek-ai/deepseek-r1
    max_tokens: 8000
  code_generation_llm:
    _type: nim 
    model_name: qwen/qwen2.5-coder-32b-instruct 
    max_tokens: 2048
  general_llm:
    _type: nim 
    model_name: meta/llama-3.3-70b-instruct  
    max_tokens: 2048


workflow:
  _type: react_agent
  tool_names:
    - code_gen_tool
  llm_name: general_llm
  verbose: true
  retry_parsing_errors: true

在本示例中,所有三个 LLM 均配备 NVIDIA NIM ,可通过 NVIDIA API Catalog 访问或在本地托管。OpenAI 和其他 LLM 提供商也得到支持。访问文档了解详情。

实现代码生成函数

创建配置文件中引用的代码生成函数。在项目支架中,打开 register.py 文件并添加:

class CodeGenToolConfig(FunctionBaseConfig, name="code_gen_tool"):

    reasoning_llm: str

    code_llm: str

    max_iterations: int = 5

@register_function(config_type=CodeGenToolConfig)

async def code_generation(config: CodeGenToolConfig, builder: Builder):

在此函数中,我们将定义辅助函数和主要可运行函数 _code_gen_tool,以便在调用工具时运行。通过四个步骤实施 LangGraph 工作流程:

1. 用户 (或其他智能体) 输入问题陈述 (例如 GitHub issue) 、待修复的代码以及应通过或待修复的单元测试。系统会提示代理使用配置的编码 LLM 创建一个 git 补丁来解决问题。

2. 更新后的代码在代码执行工具中运行,以评估结果。

3. 如果测试失败,系统会提示推理模型根据问题陈述、代码和测试输出提出更改建议。4。重复执行第 1-3 步,直到生成的代码通过所需的单元测试,或者超过迭代次数上限。

workflow = StateGraph(CodeState)

workflow.add_node("code_generation", generate_code)

workflow.add_node("run_unit_test", test_code)

workflow.add_node("debug", debug_code)

workflow.add_edge(START, "code_generation")

workflow.add_edge("code_generation", "run_unit_test")

workflow.add_conditional_edges(

    "run_unit_test",

    should_continue,

    {

        "end": END,

        "debug": "debug"

    }

)

workflow.add_edge("debug", "code_generation")

agent = workflow.compile()

LangGraph 智能体中的每个节点都在 Python 函数中定义,该函数可以是自主智能体、工具调用或任何其他函数。 generate_code 节点使用 Qwen NIM 生成代码 run_unit_test 节点针对沙盒环境中更新的代码运行测试 debug 节点使用 Deepseek-R1 进行故障高级推理

AgentIQ 使用 yield 将函数注册为可从任何其他函数调用的函数。提供详细且准确的函数描述对于开发相互有效交互的智能体至关重要。

yield FunctionInfo.from_fn(

     _code_generation,

        description=("This tool is a code generation agent using test driven development. Provide input including the issue, current code, and unit tests."))
Flowchart showing the code modification agent workflow: user input, code generation with NVIDIA NIM, unit test execution with a sandbox code execution tool, and reflection and debugging with NVIDIA NIM reasoning model.
图 1。代码修改代理图

在本教程中,我们省略了 LangGraph 工作流的一些实现细节。 AgentIQ 示例目录 包含各种完整示例,可供开始使用。

运行示例工作流程

AgentIQ 为 CLI 提供各种功能,包括运行工作流程、启动服务器和执行评估。

直接运行工作流程:

aiq run --config_file=examples/code_gen_example/configs/config.yml --input 'Write a Python function named largest_rectangle that computes the area of the largest rectangle in the histogram. Given an array heights of non-negative integers representing the histogram bar heights where the width of each bar is 1, return the area of the largest rectangle that can be formed within the histogram. Use the following files:
test_path: "/home/aiq/rectangle_tests.py",
solution_path: “/home/aiq/rectangle_solution.py"'

日志将显示在控制台中,并且智能体可以轻松地与 AgentIQ 用户界面集成。

以下是输出示例。

Configuration Summary:
--------------------
Workflow Type: react_agent
Number of Functions: 1
Number of LLMs: 3
Number of Embedders: 0
Number of Memory: 0
Number of Retrievers: 0

2025-02-27 17:33:27,459 - aiq.agent.react_agent.agent - INFO - The user's question was: 'Write a Python function named largest_rectangle that computes the area of the largest rectangle in the histogram. Given an array heights of non-negative integers representing the histogram bar heights where the width of each bar is 1, return the area of the largest rectangle that can be formed within the histogram. Use the following files:
test_path: "/home/aiq/rectangle_tests.py",
solution_path: “/home/aiq/rectangle_solution.py"'
2025-02-27 17:33:27,460 - aiq.agent.react_agent.agent - INFO - The agent's thoughts are:
Thought: To solve this problem, we need to write a Python function that calculates the area of the largest rectangle in a histogram.

Action: code_gen_tool
Action Input: {"problem_statement": "Write a Python function named largest_rectangle that computes the area of the largest rectangle in the histogram. Given an array heights of non-negative integers representing the histogram bar heights where the width of each bar is 1, return the area of the largest rectangle that can be formed within the histogram.", "solution_path": "/home/cmunley/aiq-225-2/rectangle_solution.py","test_path": "/home/cmunley/aiq-225-2/rectangle_tests.py"}
===============================================================================
STARTING NEW CODE GENERATION TASK
===============================================================================
Initial Code:

def largest_rectangle(heights):

-------------------------------------------------------------------------------
Generating solution...

largest_rectangle(heights):
    stack = []
    max_area = 0
    index = 0
    while index < len(heights):
        if not stack or heights[index] >= heights[stack[-1]]:
            stack.append(index)
            index += 1
        else:
            top_of_stack = stack.pop()
            width = index if not stack else index - stack[-1] - 1
            area = heights[top_of_stack] * width
            max_area = max(max_area, area)

    while stack:
        top_of_stack = stack.pop()
        width = index if not stack else len(heights) - stack[-1] - 1
        area = heights[top_of_stack] * width
        max_area = max(max_area, area)

    return max_area
-------------------------------------------------------------------------------
Test Results:

FAILED: Expected -1, got 0
PASS
PASS
-------------------------------------------------------------------------------
Test Failed - Attempt 1/3
-------------------------------------------------------------------------------
Analyzing errors:

The error is likely due to the fact that the function is not handling the case where the input list is empty. In this case, the function should return -1, but it's currently returning 0. [truncated for the sake of this post]
-------------------------------------------------------------------------------
Generating updated solution...

largest_rectangle(heights):
    if not heights:
        return -1
    stack = []
    max_area = 0
    index = 0
    while index < len(heights):
        if not stack or heights[index] >= heights[stack[-1]]:
            stack.append(index)
            index += 1
        else:
            top_of_stack = stack.pop()

            width = index if not stack else index - stack[-1] - 1
            area = heights[top_of_stack] * width
            max_area = max(max_area, area)

    while stack:
        top_of_stack = stack.pop()
        width = index if not stack else len(heights) - stack[-1] - 1
        area = heights[top_of_stack] * width
        max_area = max(max_area, area)

    return max_area
-------------------------------------------------------------------------------
Updated Test Results:

PASS
PASS
PASS
-------------------------------------------------------------------------------
Tests passed successfully!

The agent's thoughts are:
Thought: The code generation tool has generated the Python function largest_rectangle and the unit tests have passed, indicating that the function is correct.

Final Answer: The final answer is that the Python function largest_rectangle has been successfully generated and tested, and it correctly calculates the area of the largest rectangle in a histogram.

在配置文件中添加函数以执行各种任务

向监督代理添加功能(例如 Web 搜索或使用计算器)就像在配置文件中添加功能一样简单。AgentIQ 提供了许多实用工具,助您快速入门。在 AgentIQ 工具文件夹 中,查看代理默认可用工具的完整列表。

结语

代码生成问题是测试时计算扩展的绝佳候选对象,因为可以确定解决方案何时正确。例如,测试驱动的开发代理可以对提出的解决方案进行迭代,而迭代次数仅受计算预算的限制。推理 LLMs(例如 DeepSeek 的 R1 模型)提供的反射可以准确地引导代码生成模型完成调试过程。可以集成代理式工具使用、内存和规划来改进系统。

NVIDIA AgentIQ 库简化了代理式系统的开发,提供可重复使用的组件和简单的工具包,与整个生态系统兼容,并经过优化以实现最佳性能。 通过在一个全面且经过优化的工具包中编排不同的模型、框架和工具,我们正在通过解决复杂的现实任务来改变未来的工作。

观看此视频,了解如何使用 AgentIQ 分析器 注册 AgentIQ 黑客松,学习使用开源工具包来构建实操技能,帮助您提升代理式系统。

 

 

标签