C++AI大模型接入SDK—模型provider编写


项目地址: 橘子师兄/ai-model-acess-tech - Gitee.com

博客专栏:C++AI大模型接入SDK_橘子师兄的博客-CSDN博客

博主首页:橘子师兄-CSDN博客

1、策略模式

假设你现在要从宿舍去学校图书馆,但宿舍到图书馆之间有一段距离,你可以采用下属三方 式去:

• 走路(最节省钱,但慢)
• 骑自行车(中等速度,中等花销)
• 坐校内公交车(最快,但贵)

传统方式

if(今天没钱){
	用走路();
}else if(今天想省时间){
	用打车();
}else{
	用自行车();
}

策略模式

设置策略(打车)
执行策略()

//////////////////////////////////////
设置不同的策略,行为方式就改变,程序美观且灵活

策略方式实现:

  • 定义一个接口 TransportStrategy (出行策略)。
  • 分别实现 WalkStrategy 、BikeStrategy 、TaxiStrategy
  • 在运行时,你可以随时切换策略:
class TransportStrategy {
public:
	virtual void go() = 0;
};
class WalkStrategy : public TransportStrategy {
public:
	virtual void go() override { cout << "走路去机房🚶"; }
};
class BikeStrategy : public TransportStrategy {
public:
virtual void go() override { cout << "骑车去机房🚴"; }
};
class BusStrategy : public TransportStrategy {
public:
	virtual void go() override { cout << "打车去机房🚕"; }
};
class Student {
private:
	TransportStrategy* strategy;
public:
	void setStrategy(TransportStrategy* s) { strategy = s; }
	void goToLab() { strategy->go(); }
};
int main(){
	Student me;
    me.setStrategy(new WalkStrategy());
	me.goToLab(); // 输出: 走路去机房🚶
	me.setStrategy(new BusStrategy());
	me.goToLab(); // 输出: 打车去机房🚕
	return 0;
}

程序非常美观且灵活,在使用时只需和TransportStrategy 打交道,不需要知道背后到底是WalkStrategy、BikeStrategy或BusStrategy。如果想更换模式,只需要更换一个具体的策略对象即可,程序基本不需要改动。

策略模式是设计模式的一种,它的核心思想是它定义了一些列算法,将每一个算法(或行为)封装起来,使它们可以相互替换,而不用再代码中写一堆if-else/switch来决定用哪个算法。即把“做事的方式”抽象出来,运行时根据需要选择哪种方式去执行。

2、LLMProvider

后续会借助API的方式接入DeepSeek、ChatGPT、Gemini, Qwen等大模型,每个大模型将来都需要:

a. 初始化
b. 检测模型是否有效
c. 发送消息给模型
d. 获取模型名称
e. 获取模型描述
f. 保存模型的有效状态、API Key、模型描述。

操作基本都是相同的,只是实现细节上稍微不同,因此借助策略模式将接入模块架构设计如下:

在这里插入图片描述

#include <string>
#include <map>
namespace ai_chat_sdk {
class LLMProvider{
public:
	// 初始化模型
	virtual bool initModel(const std::map<std::string, std::string>&
model_config) = 0;
	// 检测模型是否有效
	virtual bool isAvailable() = 0;
	// 获取模型名称
	virtual std::string getModelName()const = 0;
	// 获取模型描述信息
	virtual std::string getModelDesc()const = 0;
	// 发送消息给模型
	virtual std::string sendMessage(const std::vector<Message>& messages, const
std::map<std::string,
std::string>& request_param) = 0;
	// 发送消息给模型 - 流式响应
	virtual std::string sendMessageStream(const std::vector<Message>& messages,
const std::map<std::string, std::string>& request_param,
std::function<void(const std::string&, bool)> callback) = 0;
protected:
	bool _isAvailable = false; // 标记模型是否有效
	std::string _api_key; // 保存模型的API Key
	std::string _endPoint; // 保存模型的base url
};
} // end ai_chat_sdk

更多推荐