返回全部资讯
NVIDIA Nemotron 技术博客T1·智能体与协同

用 NVIDIA Nemotron 一小时构建 Bash 智能体

作者:Mehran Maghoumi原标题:Create Your Own Bash Computer Use Agent with NVIDIA Nemotron in One Hour
62AI 研判分

NVIDIA 发布教程,演示如何基于开源模型 Nemotron Nano v2,用约 200 行 Python 代码从零搭建一个自然语言驱动的 Bash 终端智能体,并给出用 LangGraph 简化设计的进阶方案。该教程提供了可复现的代码与云端调用入口,适合开发者快速上手构建计算机操作类智能体。

报道正文

本文目录4 个章节

如果你能和计算机对话,让它通过 Bash 终端执行任务,而你无需编写任何命令,会怎样?借助 NVIDIA Nemotron Nano v2 开放模型,你可以轻松地从零开始构建一个自然语言 Bash 智能体,不到一小时即可完成,只需大约 200 行 Python 代码,且依赖极少。

本文将逐步带你了解核心组件和注意事项,让你轻松跟上。首先,我们会从零构建一切。然后,作为额外内容,本文还会展示 LangGraph 如何进一步简化设计。

让我们开始吧。

模型和代码快速链接

有哪些前提条件?

  • NVIDIA Nemotron Nano 9B v2(本地部署或云端部署)

  • 本地部署需要:

  • 约 20GB 磁盘空间

    • 一块至少拥有 24GB 显存的 NVIDIA GPU
  • 一个带有 Bash 的操作系统,例如 Ubuntu、Mac OS 或 Windows Subsystem for Linux (WSL)

  • Python v3.10+ 环境,并安装以下软件包:

  • openai(用于调用 LLM 端点)

  • 可选,用于 LangGraph 附加内容:langchain-openai 和 langgraph

  • 一小时的自由时间

最终你将得到什么:一个计算机使用智能体

以下是你可以从本教程构建的智能体中预期看到的实际交互:

YAML
['/home/sandbox' 🙂] Make a new directory called "system-info," then create a file called "info.txt" and populate it with current system config (disk space, memory), then briefly summarize the contents.

    ▶️   Execute 'mkdir system-info'? [y/N]: y
    ▶️   Execute 'touch system-info/info.txt'? [y/N]: y
    ▶️   Execute 'df -h >> system-info/info.txt'? [y/N]: y
    ▶️   Execute 'free -h >> system-info/info.txt'? [y/N]: y
    ▶️   Execute 'cat system-info/info.txt'? [y/N]: y

[🤖] 以下是 system-info/info.txt 中系统信息的摘要:

磁盘空间

  • 总计:984 GB(overlay),2.6 TB(/home/sandbox)
  • 已用:/ 上约 518 GB(56%),/home/sandbox 上约 2.1 TB(83%)
  • 可用:/ 上约 416 GB(42%),/home/sandbox 上约 432 GB(17%)

内存

  • 总计:62 GB RAM
  • 已用:20 GB
  • 空闲:14 GB
  • Swap:可用 63 GB(已用 0 GB)

如需进一步细化,请告诉我。

文本

**图例**:🙂:用户消息 🤖:Agent 响应 ▶️:命令执行确认

## 从聊天机器人到 AI Agent

与以请求—回复方式响应的聊天机器人不同,[AI Agent](https://www.nvidia.com/en-us/glossary/ai-agents/) 是一类系统,它以高层目标作为输入,然后自主推理、规划并执行任务以实现这些目标。这一过程的关键使能因素是**工具调用**(也称为函数调用):Agent 不再只是用文本回复,而是可以调用外部工具或 API 来实际执行操作、确定其结果,并规划后续步骤。

我们正在构建的 Bash 计算机使用 Agent 就是一个典型的 Agent 示例:你提供一条高层指令,它通过工具调用决定要运行哪些 Bash 命令来执行该指令。这个 Agent 足够小,可以用大约 200 行代码从零构建,但它展示了更为先进的 Agent 背后相同的基本原理。

每个现代 Agent 的核心都是一个[大语言模型](https://www.nvidia.com/en-us/glossary/large-language-models/)(LLM),它能够推理用户意图并将其转化为具体行动。该 LLM 必须高效、响应迅速,并具备出色的[推理](https://www.nvidia.com/en-us/glossary/ai-reasoning/)能力,从而能够实现复杂目标。这正是 [NVIDIA Nemotron Nano 9B v2](https://huggingface.co/nvidia/NVIDIA-Nemotron-Nano-9B-v2) 所提供的:一个紧凑的模型,具备强大的推理能力,运行速度快以保持交互流畅,同时保持简单的设置。这些特性使其非常适合我们在此构建的这类轻量级 Agent。

如果你刚刚入门,想了解 AI Agent 四大主要组件的入门知识,请查看[这篇博客](https://developer.nvidia.com/blog/build-a-report-generator-ai-agent-with-nvidia-nemotron-on-openrouter/#introduction_to_agent_architecture)。

## 关键考虑因素有哪些?

我们先来回顾构建智能体时的关键考量:

- **通过工具调用使用 Bash**:我们需要将 Bash CLI 作为工具暴露给智能体,使其能够执行命令并接收输出(例如成功或失败,以及命令产生的任何输出)。我们还需要跟踪当前活动的工作目录。这一点很重要,因为智能体需要在文件系统中导航,并且必须能够从正确的目录运行每条 Bash 命令。
- **命令安全性**:我们必须防止智能体运行不安全或具有破坏性的命令。为此,我们强制执行一份允许列表,其中包含 `ls`、`cat` 和 `grep` 等命令,确保智能体只在安全、可预测的范围内操作。此外,我们引入了确认步骤:在执行任何命令之前,提示用户进行批准。这种人在回路(human-in-the-loop)模式让用户对终端中实际运行的内容拥有完全控制权。
- **错误处理**:要构建可靠的智能体系统,我们必须始终考虑失败情况。对于我们的 Bash 智能体而言,命令可能因语法无效、文件缺失或意外输出而失败。智能体应捕获这些错误、对其进行解读,并选择正确的下一步操作。

## 系统组件有哪些?

在明确这些考量之后,架构就变得非常简单。系统有两个主要组件:

1. **Bash 类**:对 Python 的 `subprocess` 模块的轻量级封装,负责管理工作目录、强制执行命令允许列表、执行命令,并将执行结果(或错误)返回给智能体。
2. **智能体**:使用 NVIDIA Nemotron 模型来理解用户意图并决定如何行动,同时在多轮对话中保持上下文。智能体的行为由精心设计的系统提示引导,该提示设定了边界、定义了其作为 Bash 助手的角色,并提醒其允许使用的命令。

下图展示了该系统的架构图。工作流程如下:

1. 用户发出高层指令,例如切换目录、复制文件或查看文档内容。
2. Nemotron 解析请求,将其拆解为具体步骤,并在需要执行命令时使用 Bash 类。有些任务可能完全不需要执行,而另一些任务可能涉及多条命令。每次运行后,模型会收到输出,并决定下一步操作或何时停止。
3. 任务完成后,无论成功还是因错误而中止,智能体都会将结果返回给用户,并等待下一条指令。

![智能体的工作流程图,由 Nemotron 模型和 Bash 类组成。模型接收用户请求,通过 Bash 类执行请求,并向用户返回响应。](https://developer-blogs.nvidia.com/wp-content/uploads/2025/10/image1-3-png.webp)

*图 1. 智能体的工作流程图*

我们将首先从零开始实现这两个组件,然后本篇博客将引导你使用 LangGraph 将它们连接起来,以进一步简化配置。

### Bash 类

我们创建一个简单的类,用于存储允许的命令列表以及当前工作目录。以下是该类的一个精简代码片段。

class Bash: """ An implementation of a tool that executes Bash commands """

文本
def __init__(self, cwd: str, allowed_commands: List[str]):
    self.cwd = cwd  # The current working directory
    self._allowed_commands = allowed_commands  # Allowed commands

def exec_bash_command(self, cmd: str) -> Dict[str, str]:
    """
    Execute the bash command after getting confirmation from the user
    """
    if cmd:
        # Check the allowlist
        allowed = True

        for cmd_part in self._extract_commands(cmd):
            if cmd_part not in self._allowed_commands:
                allowed = False
                break

        if not allowed:
            return {"error": "Parts of this command were not in the allowlist."}

        return self._run_bash_command(cmd)
    return {"error": "No command was provided"}
文本
文本
def to_json_schema(self) -> Dict[str, Any]:
    """
    将函数签名转换为 JSON schema,用于 LLM 工具调用。
    """
    return {
        "type": "function",
        "function": {
            "name": "exec_bash_command",
            "description": "执行 bash 命令并返回 stdout/stderr 以及工作目录",
            "parameters": {
                "type": "object",
                "properties": {
                    "cmd": {
                        "type": "string",
                        "description": "要执行的 bash 命令"
                    }
                },
                "required": ["cmd"],

}, }, }

文本
def _run_bash_command(self, cmd: str) -> Dict[str, str]:
    """
    运行 bash 命令并捕获异常(如果有)。
    """
    stdout = ""
    stderr = ""
    new_cwd = self.cwd

    try:
        # 包装命令,以便我们能够跟踪工作目录。
        wrapped = f"{cmd};echo __END__;pwd"
        result = subprocess.run(
            wrapped, shell=True, cwd=self.cwd,
            capture_output=True, text=True,
            executable="/bin/bash"
        )
        stderr = result.stderr
        # 查找分隔标记
        split = result.stdout.split("__END__")
        stdout = split[0].strip()

        # 如果完全没有输出/错误,则告知调用成功。
        if not stdout and not stderr:
            stdout = "命令执行成功,没有任何输出。"

        # 获取新的工作目录,并进行切换
        new_cwd = split[-1].strip()
        self.cwd = new_cwd
    except Exception as e:
        stdout = ""
        stderr = str(e)

    return {"stdout": stdout, "stderr": stderr, "cwd": new_cwd}
文本

该类对外暴露两个公共函数:

1. `exec_bash_command(cmd: str) -> Dict[str, str]`,agent 可以调用它来执行命令。它返回一个字典,包含 `stdout`、`stderr` 以及更新后的工作目录;如果命令无效或不被允许,则返回错误。这些信号让 agent 在出错时能够做出调整。
2. `to_json_schema(self) -> Dict[str, Any]`,用于告诉 LLM 如何使用这个工具(LangGraph 不需要这个)。

在执行之前,函数会对照允许列表检查命令。执行过程在私有函数 `_run_bash_command()` 内部处理,该函数内部会调用 Python 的 `subprocess.run()`。其中包含异常处理块,以妥善处理所有失败情况。为了跟踪目录变化(例如当 agent 使用 `cd` 命令时),我们在每条命令后附加一个唯一的文本标记和 `pwd`。执行完成后,我们在输出中定位该标记,提取新的工作目录,并在返回执行结果之前更新工具的状态,同时将当前活动的工作目录一并返回给 agent。

### agent

对于 agent,我们将 Nemotron 初始化为推理引擎,并将 `exec_bash_command()` 注册为可调用的命令执行工具。模型的行为由系统提示词(如下所示)塑造,该提示词将其角色定义为 Bash 助手,列出允许的命令,并指导它何时以及如何协助用户或发起工具调用。虽然我们的 Bash 类强制执行允许列表,但提示词也强化了这一规则,这是保持模型对齐的良好实践。提示词还使用 `/think` 标志来启用思考模式,从而提升模型的推理能力。

SYSTEM_PROMPT = f"""/think You are a helpful Bash assistant with the ability to execute commands in the shell. You engage with users to help answer questions about bash commands, or execute their intent. If user intent is unclear, keep engaging with them to figure out what they need and how to best help them. If they ask question that are not relevant to bash or computer use, decline to answer.

When a command is executed, you will be given the output from that command and any errors. Based on that, either take further actions or yield control to the user.

The bash interpreter's output and current working directory will be given to you every time a command is executed. Take that into account for the next conversation. If there was an error during execution, tell the user what that error was exactly.

You are only allowed to execute the following commands: {LIST_OF_ALLOWED_COMMANDS}

Never attempt to execute a command not in this list. Never attempt to execute dangerous commands like rm, mv, rmdir, sudo, etc. If the user asks you to do so, politely refuse.

When you switch to new directories, always list files so you can get more context. """

文本

#### agent 循环(从零构建)

构建 agent 循环非常直接。我们初始化 OpenAI 客户端,并维护一个对话轮次的历史记录,作为我们的记忆/状态。在循环内部:

1. 获取用户输入,并将其连同系统提示一起发送给模型。
2. 获取模型的响应并存入对话历史,然后检查是否有工具调用:

1. 如果存在工具调用,向用户确认是否执行。获得批准后,运行 `exec_bash_command()`,返回结果,并获取下一个响应;否则,告知模型。
 2. 如果不存在工具调用,展示模型的回复并将控制权交还给用户。
3. 此循环重复执行,直到应用程序终止。

为了让代码保持整洁,我们来为存储对话历史(`Messages` 类)以及使用客户端向模型发送请求并获取响应(`LLM` 类)定义抽象。有了这些抽象,整个 agent 循环就变得简短而直观:

bash = Bash(...)

The model

llm = LLM(...)

The conversation history, with the system prompt

messages = Messages(SYSTEM_PROMPT)

The main agent loop

while True: # Get user message. user = input(f"['🙂] ").strip() messages.add_user_message(user)

文本
# The tool-call/response loop
while True:
    response, tool_calls = llm.query(messages, [bash.to_json_schema()])
    # Add the response to the context
    messages.add_assistant_message(response)

    # Process tool calls
    if tool_calls:
        for tc in tool_calls:
            function_name = tc.function.name
            function_args = json.loads(tc.function.arguments)

            # Ensure it's calling the right tool
            if function_name != "exec_bash_command" or "cmd" not in function_args:
                tool_call_result = json.dumps({"error": "Incorrect tool or function argument"})
            else:
                if confirm_execution("cmd"):
                    tool_call_result = bash.exec_bash_command(function_args["cmd"])
                else:
                    tool_call_result = {"error": "The user declined the execution of this command."}

            messages.add_tool_message(tool_call_result, tc.id)
    else:
        # Display the assistant's message to the user (without the thinking part).
        print(f"\n[🤖] {response.strip()}")
        break
文本

请注意内部的 `while` 循环,它是必需的,因为智能体可能需要多次工具调用才能完成其任务。这对应于图 1 中的第 2 步。

#### 附加内容:智能体循环(使用 LangGraph)

借助 LangGraph,智能体循环变得更加简单。使用该库中的 [`create_react_agent()`](https://langchain-ai.github.io/langgraph/reference/agents/#langgraph.prebuilt.chat_agent_executor.create_react_agent),我们可以管理循环、连接模型、工具和对话状态,并让该库自动处理工具调用和结果传递。它还使错误处理更加结构化,让智能体能够在受控流程中对失败或重试做出反应,而无需手动检查。与我们从头构建的版本一样,系统提示定义了 Bash 助手的角色并强制执行安全的命令执行,同时一个小型辅助函数封装了 `bash.exec_bash_command()`,以实现人工介入确认。这一最小化设置即可产生一个功能完备的智能体,它能够理解意图、调用正确的工具,并以交互方式返回结果。

精简后的代码片段如下:

from langgraph.prebuilt import create_react_agent from langgraph.checkpoint.memory import InMemorySaver from langchain_openai import ChatOpenAI

class ExecOnConfirm: """ A wrapper around the Bash class to implement human-in-the-loop """

文本
def __init__(self, bash: Bash):
    self.bash = bash

def _confirm_execution(self, cmd: str) -> bool:
    """Ask the user whether the suggested command should be executed."""
    return input(f"    ▶️   Execute '{cmd}'? [y/N]: ").strip().lower() == "y"

def exec_bash_command(self, cmd: str) -> Dict[str, str]:
    """Execute a bash command after confirming with the user."""
    if self._confirm_execution(cmd):
        return self.bash.exec_bash_command(cmd)
    return {"error": "The user declined the execution of this command."}
文本

# 实例化 Bash 类
bash = Bash(...)
# 创建 agent
agent = create_react_agent(
    model=ChatOpenAI(model=...),
    tools=[ExecOnConfirm(bash).exec_bash_command],  # 封装以实现 human-in-the-loop
    prompt=SYSTEM_PROMPT,
    checkpointer=InMemorySaver(),
)
# 创建用户/agent 交互循环
while True:
    user = input(f"[🙂] ").strip()
    # 运行 agent 的逻辑并获取响应。
    result = agent.invoke({"messages": [{"role": "user", "content": user}]}, config=...)
    # 显示响应(如果有思考部分,则将其去除)
    response = result["messages"][-1].content.strip()

    if "</think>" in response:
        response = response.split("</think>")[-1].strip()

    if response:
        print(f"\n[🤖] {response}")

接下来该做什么?

现在,你仅用几行代码就构建了自己的计算机使用 agent。接下来,动手实验吧:尝试换用其他开放的 Nemotron 模型,调整系统提示词,看看 agent 如何适应。稍作探索之后,你会发现同样的原理可以自然地扩展到更高级的多 agent 系统。

欢迎加入 NVIDIA 开发者论坛参与讨论。我们很期待看到你的实验、听到你的问题,并了解你接下来构建的作品。

通过订阅NVIDIA 新闻,并在LinkedIn、X、Discord和YouTube上关注 NVIDIA AI,随时了解NVIDIA Nemotron的最新动态。