MENU

【C++/Agent开发】开发自己的Agent(一):基础功能的实现

2026 年 11 月 27 日 • 文章

算法岗找不到就去开发喽,姑且积攒一下实践的经验。

前言

这个项目的开发,我人工编写功能代码,功能代码不依赖代码补全和Vibe Coding。测试代码则是由GPT来编写。总体的开发思路会和GPT、Gemini进行交流。第一阶段的开发没什么难度,但是因为我手头还有科研的任务,导致一周才完成。

开发和科研都是很有意思的事情。

在第一部分中,我完成了:

  • 部分实现了OpenAI API的支持。能够构造请求并发送请求,并且能够对远端的回复进行处理。
  • 实现了简单的工具调用。
  • 实现了简单的Agent。

我对于Agent的理解还是和最开始无异,Agent是基于大模型的,而大模型就是一个「序列-序列」的转换机器。需要开发的部分,和大模型没有特别大的关系,依然是传统后端的重点,就是数据库、网络连接、安全性的处理。

环境配置

这次我用的是Windows 11 + WSL的配置,开发语言选择的是C++,构建系统是CMake+vcpkg,外部的依赖库只选择了一个用于处理网络连接的cpr和一个用于处理JSON库的nlohmann-json。vcpkg.json内容如下:

{
  "name": "mini-cpp-agent",
  "version-string": "0.1.0",
  "dependencies": [
    "cpr",
    "nlohmann-json"
  ]
}

客户端的实现

在这里,我首先设计的是客户端,客户端的作用很明显,发送信息,然后接收回复,负责每一次「发送-接收」的过程。为了后续兼容更多类型的协议和标准,我首先设计了一个最基础的父类IModelClient:

#pragma once
#include <nlohmann/json.hpp>

using json = nlohmann::json;

struct ModelTurn {
    json assistant_message;
    std::string finish_reason;
};

class IModelClient {
public:
    virtual ~IModelClient() = default;
    virtual ModelTurn generate(
        const json& messages,
        const json& tools
    ) = 0;
};

这里设计的重点在我看来只有两个,一个是抽象类的设计,编译器生成析构函数。将来用 std::unique_ptr<IModelClient> 保存派生对象时,销毁需要从实际的派生类开始。IModelClient 是抽象类,需要提供生成信息接收信息的接口,可实例化的派生类需要有对应实现。另一个则是信息结构的设计,保存原生的信息,也要保存结束的原因。

对于OpenAI客户端的实现,则没什么好说的,比较简单:

#include <minicppagent/OpenAIClient.hpp>
#include <minicppagent/Utils.hpp>
#include <cpr/cpr.h>

OpenAIClient::OpenAIClient(ModelConfig model_config) : model_config_(std::move(model_config)) {
    if(model_config_.api_key.empty() || model_config_.base_url.empty() || model_config_.model_name.empty()) {
        throw std::invalid_argument("Check your model config, which should not be empty.");
    }
    if(model_config_.base_url.back() == '/') model_config_.base_url.pop_back();

}

ModelTurn OpenAIClient::generate(
    const json& messages,
    const json& tools
) {
    json chat_request = utils::make_chat_request(model_config_.model_name, messages, tools);
    const cpr::Response response = cpr::Post(
        cpr::Url{model_config_.base_url + "/chat/completions"},
        cpr::Header{{"Content-Type", "application/json"}, {"Authorization", "Bearer " + model_config_.api_key}},
        cpr::Body{chat_request.dump()},
        cpr::ConnectTimeout{1000000},
        cpr::Timeout{1000000}
    );

    if (response.error) {
        throw std::runtime_error("Transport error: " + response.error.message);
    }
    if (response.status_code < 200 || response.status_code >= 300) {
        throw std::runtime_error(
            "HTTP error " + std::to_string(response.status_code) + ": " + response.text
        );
    }

    const json reply = json::parse(response.text);
    return utils::parse_chat_completion(reply);
}

利用cpr库组装请求,发送出去,然后将回复恢复为JSON格式,最后编写函数,验证得到的回复即可。

工具的调用

在Agent软件中,工具通常长这个样子:

{
  "type": "function",
  "function": {
    "name": "add",
    "description": "Return the sum of two numbers.",
    "parameters": {
      "type": "object",
      "properties": {
        "a": {"type": "number"},
        "b": {"type": "number"}
      },
      "required": ["a", "b"],
      "additionalProperties": false
    }
  }
}

也就是包含两个部分:

  1. 给模型看的说明,模型据此决定调用什么、该给哪些参数。
  2. 程序中的处理函数,在这个例子中,就是给定参数,执行加法,返回JSON。

那么,在实际的开发中,工具的注册我应用了一个ToolRegistry类来管理:

#pragma once
#include <functional>
#include <unordered_map>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

using ToolHandler = std::function<json(const json&)>;

struct Tool {
    json declaration;
    ToolHandler handler;
};

struct ToolResult {
    bool is_success;
    std::string message;
};

class ToolRegistry {
private:
    std::unordered_map<std::string, Tool> tools_;
public:
    void register_tool(Tool& tool);
    json declaration() const;
    json invoke(const std::string name, const json& arguments) const;
};

其中,register_tool负责让系统记住工具的信息,通过一个无序哈希表来维护;declaration则负责返回所有工具的详细信息,而invoke则是调用工具的这样一个过程。所有的工具可以通过同样的结构调用,没有模型、协议、标准的分别,故使用了一个简单的类来完成。工具的实现也很简单,每个工具接收参数,然后调用对应的工具执行即可,两数相加的工具的实现如下:

json add_number(const json& arguments) {
    if (!arguments.is_object() || arguments.size() != 2 || !arguments.contains("a") || !arguments.contains("b")) {
        throw std::invalid_argument("Invalid arguments structure.");
    }

    const json& a = arguments.at("a"), b = arguments.at("b");

    if (!a.is_number() || !b.is_number()) {
        throw std::invalid_argument("Both arguments must be numbers.");
    }

    double x = a.get<double>();
    double y = b.get<double>();

    if (!std::isfinite(x) || !std::isfinite(y)) {
        throw std::invalid_argument("Arguments must be finite.");
    }

    double result = x + y;

    if (!std::isfinite(result)) {
        throw std::overflow_error("Addition overflow.");
    }

    return result;
}

Agent的实现

在我的设计中,Agent负责让程序负责流转与停止,并且在适当的时候调用工具,一个简单的声明是这样的:

#pragma once

#include "minicppagent/ToolRegistry.hpp"
#include <minicppagent/IModelClient.hpp>
#include <cstddef>
#include <string>

class Agent {
private:
    IModelClient &client_;
    const ToolRegistry &tool_registry_;
    json history_;
    
public:
    Agent(IModelClient &client, const ToolRegistry &tool_registry);
    std::string run(const std::string& input, std::size_t max_model_turns = 4);
};  

保存对应的客户端、可用的工具与历史,然后负责多次的client的生成-回复过程即可。由于每次,模型可能会产生模型调用,也可能会产生一个纯文本的回复,我又使用了一个std::variant变量,来维护模型的回复:

#pragma once

#include <optional>
#include <string>
#include <variant>
#include <vector>

struct ToolCall {
    std::string id;
    std::string name;
    std::string arguments_json;
};

struct FinalAnswer {
    std::string text;
};

struct ToolBatch {
    std::optional<std::string> text;
    std::vector<ToolCall> calls;
};

using ModelAction = std::variant<FinalAnswer, ToolBatch>;

run函数的流程,核心是一个循环:

 for (std::size_t turn = 0;
         turn < max_model_turns;
         ++turn) {

        ModelTurn response = client_.generate(messages, tools);

        ModelAction action = utils::to_model_action(response);

        if (const auto* answer = std::get_if<FinalAnswer>(&action)) {

            messages.push_back(response.assistant_message);

            history_ = std::move(messages);

            return answer->text;
        }

        if (const auto* batch = std::get_if<ToolBatch>(&action)) {

            if (turn + 1 >= max_model_turns) {
                throw std::runtime_error("Max model turns exceeded.");
            }

            messages.push_back(response.assistant_message);

            for (const ToolCall& call : batch->calls) {
                json tool_result;

                json arguments = json::parse(
                    call.arguments_json,
                    nullptr,
                    false
                );

                if (arguments.is_discarded()) {
                    tool_result = result_to_json({
                        false, "invalid_arguments"
                    });
                }
                else {
                    tool_result = tool_registry_.invoke(
                        call.name,
                        arguments
                    );
                }

                messages.push_back({
                    {"role", "tool"},
                    {"tool_call_id", call.id},
                    {"content", tool_result.dump()}
                });
            }

            continue;
        }

        throw std::runtime_error("Invalid model action.");
    }

实际效果

一个简单的效果是:

~/Programs/MiniCppAgent$ ./build/mini_cpp_agent
Ask something (for example: Please add 2 and 3): 你觉得面包和薯片哪个好吃
这个问题可太难选了!因为面包和薯片完全是两种不同维度的“快乐源泉”,取决于你当时的心情和状态:

  1. 选择面包的时刻:

    • 当你想获得慰藉和饱腹感时: 面包(尤其是刚出炉的、带着黄油香气或麦香的吐司、法棍、欧包,或者夹着丰富馅料的汉堡、三明治)会给人一种非常踏实、温暖的幸福感。它能填饱肚子,味道也更有层次。
    • 健康或日常代餐: 相对于薯片,面包的选择面更广,从健康的粗粮面包到罪恶的甜面包应有尽有。
  2. 选择薯片的时刻:

    • 当你想追求极致的爽快感时: 薯片的灵魂就在于那个“咔嚓”的酥脆声和浓郁的调味(海苔味、烧烤味、黄油蜂蜜味……)。它不需要咀嚼太久,是看电影、追剧、打游戏时的绝配,吃起来根本停不下来。
    • 纯粹的零食快乐: 薯片不为了管饱,只为了那一瞬间的碳水和油脂带来的多巴胺爆发。

总结我的看法:

  • 如果要当饭吃或者追求温暖治愈,我选面包。
  • 如果是闲暇娱乐或者想解压,我选薯片。

你呢?你平时更偏爱哪一个?

目前只能支持单次的发送-回答,一个调用工具的结果是:

~/Programs/MiniCppAgent$ ./build/mini_cpp_agent
Ask something (for example: Please add 2 and 3): 2+3等于几,你可以使用本地的工具看看,给出结果,并说明你是否调用了工具
2+3等于 5。

我调用了本地的加法工具 (add_number) 来计算这个结果。

后记

水完了一篇,哈哈。后面需要支持流式输出,还要处理持久化之类的事情,基本上就是在这个简陋的demo上修修改改的问题。