# C++大模型SDK开发:日志封装、数据结构与策略模式实现
## 大模型SDK的架构设计挑战
在大模型SDK开发过程中,日志系统、通用数据结构和设计模式的合理应用直接影响着SDK的可维护性和扩展性。本文将深入探讨如何通过spdlog实现灵活的日志封装、设计可扩展的通用数据结构,以及应用策略模式处理多样化的模型交互场景。
## spdlog日志系统的深度封装
### 日志管理器设计
```cpp
// logger.h
#ifndef DEEPSEEK_LOGGER_H
#define DEEPSEEK_LOGGER_H
#include <memory>
#include <string>
#include <unordered_map>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
namespace deepseek {
namespace log {
enum class LogLevel {
TRACE = 0,
DEBUG,
INFO,
WARN,
ERROR,
CRITICAL,
OFF
};
class LoggerManager {
public:
static LoggerManager& instance();
void initialize(const std::string& config_path = "");
void shutdown();
std::shared_ptr<spdlog::logger> getLogger(const std::string& name);
void setGlobalLevel(LogLevel level);
void setPattern(const std::string& pattern);
// 批量配置
void configureSinks(const std::vector<std::string>& sink_configs);
private:
LoggerManager() = default;
~LoggerManager();
LoggerManager(const LoggerManager&) = delete;
LoggerManager& operator=(const LoggerManager&) = delete;
std::unordered_map<std::string, std::shared_ptr<spdlog::logger>> loggers_;
std::vector<spdlog::sink_ptr> global_sinks_;
LogLevel global_level_ = LogLevel::INFO;
std::string pattern_ = "[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [%n] %v";
void createDefaultSinks();
spdlog::level::level_enum toSpdlogLevel(LogLevel level);
LogLevel fromSpdlogLevel(spdlog::level::level_enum level);
};
// 便捷日志宏
#define LOG_TRACE(logger, ...) SPDLOG_LOGGER_TRACE(logger, __VA_ARGS__)
#define LOG_DEBUG(logger, ...) SPDLOG_LOGGER_DEBUG(logger, __VA_ARGS__)
#define LOG_INFO(logger, ...) SPDLOG_LOGGER_INFO(logger, __VA_ARGS__)
#define LOG_WARN(logger, ...) SPDLOG_LOGGER_WARN(logger, __VA_ARGS__)
#define LOG_ERROR(logger, ...) SPDLOG_LOGGER_ERROR(logger, __VA_ARGS__)
#define LOG_CRITICAL(logger, ...) SPDLOG_LOGGER_CRITICAL(logger, __VA_ARGS__)
// 带上下文的日志宏
#define LOG_CTX_TRACE(logger, ctx, ...) \
SPDLOG_LOGGER_TRACE(logger, "[{}] {}", ctx, fmt::format(__VA_ARGS__))
} // namespace log
} // namespace deepseek
#endif // DEEPSEEK_LOGGER_H
```
### 日志管理器实现
```cpp
// logger.cpp
#include "logger.h"
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace deepseek {
namespace log {
LoggerManager::~LoggerManager() {
shutdown();
}
LoggerManager& LoggerManager::instance() {
static LoggerManager instance;
return instance;
}
void LoggerManager::initialize(const std::string& config_path) {
if (!config_path.empty()) {
std::ifstream config_file(config_path);
if (config_file.is_open()) {
try {
json config = json::parse(config_file);
// 解析日志级别
if (config.contains("log_level")) {
std::string level_str = config["log_level"];
if (level_str == "trace") global_level_ = LogLevel::TRACE;
else if (level_str == "debug") global_level_ = LogLevel::DEBUG;
else if (level_str == "info") global_level_ = LogLevel::INFO;
else if (level_str == "warn") global_level_ = LogLevel::WARN;
else if (level_str == "error") global_level_ = LogLevel::ERROR;
else if (level_str == "critical") global_level_ = LogLevel::CRITICAL;
}
// 解析日志格式
if (config.contains("log_pattern")) {
pattern_ = config["log_pattern"];
}
// 解析输出配置
if (config.contains("sinks")) {
for (const auto& sink_config : config["sinks"]) {
std::string type = sink_config["type"];
if (type == "console") {
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_pattern(pattern_);
global_sinks_.push_back(console_sink);
} else if (type == "file") {
std::string filename = sink_config["filename"];
size_t max_size = sink_config.value("max_size", 1048576 * 5); // 5MB
size_t max_files = sink_config.value("max_files", 3);
auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
filename, max_size, max_files);
file_sink->set_pattern(pattern_);
global_sinks_.push_back(file_sink);
}
}
}
} catch (const json::exception& e) {
// 配置解析失败,使用默认配置
createDefaultSinks();
}
} else {
createDefaultSinks();
}
} else {
createDefaultSinks();
}
}
void LoggerManager::createDefaultSinks() {
// 控制台输出
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_pattern(pattern_);
console_sink->set_level(toSpdlogLevel(global_level_));
global_sinks_.push_back(console_sink);
// 文件输出
auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
"logs/deepseek_sdk.log", 1048576 * 10, 5); // 10MB * 5 files
file_sink->set_pattern(pattern_);
file_sink->set_level(toSpdlogLevel(global_level_));
global_sinks_.push_back(file_sink);
}
std::shared_ptr<spdlog::logger> LoggerManager::getLogger(const std::string& name) {
auto it = loggers_.find(name);
if (it != loggers_.end()) {
return it->second;
}
auto logger = std::make_shared<spdlog::logger>(name,
global_sinks_.begin(), global_sinks_.end());
logger->set_level(toSpdlogLevel(global_level_));
logger->flush_on(toSpdlogLevel(LogLevel::WARN));
loggers_[name] = logger;
return logger;
}
void LoggerManager::shutdown() {
for (auto& [name, logger] : loggers_) {
logger->flush();
}
loggers_.clear();
global_sinks_.clear();
}
spdlog::level::level_enum LoggerManager::toSpdlogLevel(LogLevel level) {
switch (level) {
case LogLevel::TRACE: return spdlog::level::trace;
case LogLevel::DEBUG: return spdlog::level::debug;
case LogLevel::INFO: return spdlog::level::info;
case LogLevel::WARN: return spdlog::level::warn;
case LogLevel::ERROR: return spdlog::level::err;
case LogLevel::CRITICAL: return spdlog::level::critical;
default: return spdlog::level::off;
}
}
} // namespace log
} // namespace deepseek
```
### 上下文感知日志包装器
```cpp
// context_logger.h
#ifndef CONTEXT_LOGGER_H
#define CONTEXT_LOGGER_H
#include "logger.h"
#include <memory>
#include <string>
#include <map>
namespace deepseek {
namespace log {
class ContextLogger {
public:
ContextLogger(const std::string& module_name,
const std::map<std::string, std::string>& initial_context = {});
void setContext(const std::string& key, const std::string& value);
void removeContext(const std::string& key);
void clearContext();
void trace(const std::string& message);
void debug(const std::string& message);
void info(const std::string& message);
void warn(const std::string& message);
void error(const std::string& message);
void critical(const std::string& message);
template<typename... Args>
void trace(const std::string& format, Args&&... args);
template<typename... Args>
void debug(const std::string& format, Args&&... args);
template<typename... Args>
void info(const std::string& format, Args&&... args);
template<typename... Args>
void warn(const std::string& format, Args&&... args);
template<typename... Args>
void error(const std::string& format, Args&&... args);
template<typename... Args>
void critical(const std::string& format, Args&&... args);
private:
std::shared_ptr<spdlog::logger> logger_;
std::map<std::string, std::string> context_;
std::string module_name_;
std::string formatMessage(const std::string& message) const;
std::string formatContext() const;
};
} // namespace log
} // namespace deepseek
#endif // CONTEXT_LOGGER_H
```
## 通用数据结构设计
### 可变类型容器
```cpp
// variant_value.h
#ifndef VARIANT_VALUE_H
#define VARIANT_VALUE_H
#include <variant>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <optional>
#include <stdexcept>
namespace deepseek {
namespace data {
class VariantValue {
public:
using Array = std::vector<VariantValue>;
using Object = std::map<std::string, VariantValue>;
using Value = std::variant<
std::nullptr_t,
bool,
int64_t,
double,
std::string,
Array,
Object
>;
VariantValue() : value_(nullptr) {}
// 构造函数重载
explicit VariantValue(std::nullptr_t) : value_(nullptr) {}
explicit VariantValue(bool v) : value_(v) {}
explicit VariantValue(int v) : value_(static_cast<int64_t>(v)) {}
explicit VariantValue(int64_t v) : value_(v) {}
explicit VariantValue(double v) : value_(v) {}
explicit VariantValue(const char* v) : value_(std::string(v)) {}
explicit VariantValue(const std::string& v) : value_(v) {}
explicit VariantValue(const Array& v) : value_(v) {}
explicit VariantValue(const Object& v) : value_(v) {}
// 类型检查
bool isNull() const { return std::holds_alternative<std::nullptr_t>(value_); }
bool isBool() const { return std::holds_alternative<bool>(value_); }
bool isInt() const { return std::holds_alternative<int64_t>(value_); }
bool isDouble() const { return std::holds_alternative<double>(value_); }
bool isString() const { return std::holds_alternative<std::string>(value_); }
bool isArray() const { return std::holds_alternative<Array>(value_); }
bool isObject() const { return std::holds_alternative<Object>(value_); }
// 值获取(带类型检查)
template<typename T>
std::optional<T> get() const {
try {
if constexpr (std::is_same_v<T, int64_t>) {
if (isInt()) return std::get<int64_t>(value_);
if (isDouble()) return static_cast<int64_t>(std::get<double>(value_));
} else if constexpr (std::is_same_v<T, double>) {
if (isDouble()) return std::get<double>(value_);
if (isInt()) return static_cast<double>(std::get<int64_t>(value_));
} else {
if (std::holds_alternative<T>(value_)) {
return std::get<T>(value_);
}
}
} catch (...) {
// 类型转换失败
}
return std::nullopt;
}
// 安全获取
template<typename T>
T getOr(T defaultValue) const {
auto val = get<T>();
return val ? *val : defaultValue;
}
// 数组操作
size_t size() const {
if (isArray()) return std::get<Array>(value_).size();
if (isObject()) return std::get<Object>(value_).size();
return 0;
}
VariantValue& operator[](size_t index);
const VariantValue& operator[](size_t index) const;
VariantValue& operator[](const std::string& key);
const VariantValue& operator[](const std::string& key) const;
// 序列化
std::string toJson() const;
static VariantValue fromJson(const std::string& json_str);
private:
Value value_;
// 类型转换助手
template<typename T>
struct TypeHelper;
};
// 类型转换特化
template<>
struct VariantValue::TypeHelper<int> {
static int64_t toStorage(int v) { return static_cast<int64_t>(v); }
static std::optional<int> fromStorage(const Value& v) {
<"7p.jsnjz.cn"><"1b.csxthr.com"><"4v.zhaiLimao.com">
if (auto pval = std::get_if<int64_t>(&v)) {
return static_cast<int>(*pval);
}
return std::nullopt;
}
};
} // namespace data
} // namespace deepseek
#endif // VARIANT_VALUE_H
```
### 配置管理系统
```cpp
// config_manager.h
#ifndef CONFIG_MANAGER_H
#define CONFIG_MANAGER_H
#include "variant_value.h"
#include <memory>
#include <mutex>
#include <functional>
namespace deepseek {
namespace config {
class ConfigManager {
public:
using ConfigValue = data::VariantValue;
using ConfigObject = ConfigValue::Object;
using ChangeCallback = std::function<void(const std::string&, const ConfigValue&)>;
static ConfigManager& instance();
// 配置加载
bool loadFromFile(const std::string& filepath);
bool loadFromJson(const std::string& json_str);
bool loadFromEnvironment(const std::string& prefix = "DEEPSEEK_");
// 配置访问
ConfigValue get(const std::string& key,
const ConfigValue& defaultValue = ConfigValue()) const;
template<typename T>
T getAs(const std::string& key, const T& defaultValue = T()) const;
// 配置修改
void set(const std::string& key, const ConfigValue& value);
void update(const ConfigObject& updates);
// 配置监听
void watch(const std::string& key, ChangeCallback callback);
void unwatch(const std::string& key);
// 配置持久化
bool saveToFile(const std::string& filepath) const;
std::string toJson(bool pretty = true) const;
// 配置验证
bool validate(const std::string& schema_json) const;
private:
ConfigManager();
~ConfigManager() = default;
ConfigManager(const ConfigManager&) = delete;
ConfigManager& operator=(const ConfigManager&) = delete;
ConfigObject config_;
mutable std::mutex config_mutex_;
std::unordered_map<std::string, std::vector<ChangeCallback>> watchers_;
mutable std::mutex watchers_mutex_;
ConfigValue getByPath(const std::vector<std::string>& path) const;
void setByPath(const std::vector<std::string>& path, const ConfigValue& value);
std::vector<std::string> splitPath(const std::string& key) const;
};
} // namespace config
} // namespace deepseek
#endif // CONFIG_MANAGER_H
```
## 策略模式在模型交互中的应用
### 策略接口定义
```cpp
// model_strategy.h
#ifndef MODEL_STRATEGY_H
#define MODEL_STRATEGY_H
#include "variant_value.h"
#include "context_logger.h"
#include <memory>
#include <string>
#include <functional>
namespace deepseek {
namespace strategy {
class ModelResponse {
public:
using Data = data::VariantValue;
ModelResponse() = default;
ModelResponse(Data data, bool success, const std::string& error_msg = "");
bool isSuccess() const { return success_; }
const std::string& errorMessage() const { return error_msg_; }
const Data& data() const { return data_; }
Data& mutableData() { return data_; }
void setError(const std::string& error_msg);
void setData(const Data& data);
private:
Data data_;
bool success_ = true;
std::string error_msg_;
};
class ModelRequest {
public:
using Parameters = data::VariantValue::Object;
ModelRequest() = default;
explicit ModelRequest(const std::string& model_name);
const std::string& modelName() const { return model_name_; }
const Parameters& parameters() const { return parameters_; }
const data::VariantValue& input() const { return input_; }
void setModelName(const std::string& name);
void setParameter(const std::string& key, const data::VariantValue& value);
void setInput(const data::VariantValue& input);
std::string toJson() const;
static ModelRequest fromJson(const std::string& json_str);
private:
std::string model_name_;
Parameters parameters_;
data::VariantValue input_;
};
class IModelStrategy {
public:
using Callback = std::function<void(const ModelResponse&)>;
virtual ~IModelStrategy() = default;
virtual std::string strategyName() const = 0;
// 同步调用
virtual ModelResponse execute(const ModelRequest& request) = 0;
// 异步调用
virtual void executeAsync(const ModelRequest& request, Callback callback) = 0;
// 流式调用
virtual void executeStream(const ModelRequest& request,
std::function<void(const std::string& chunk)> chunk_callback,
Callback final_callback) = 0;
// 策略配置
virtual bool configure(const data::VariantValue& config) = 0;
// 策略验证
virtual bool validateRequest(const ModelRequest& request) const = 0;
protected:
log::ContextLogger logger_{"ModelStrategy"};
};
} // namespace strategy
} // namespace deepseek
#endif // MODEL_STRATEGY_H
```
### 具体策略实现
```cpp
// specific_strategies.h
#ifndef SPECIFIC_STRATEGIES_H
#define SPECIFIC_STRATEGIES_H
#include "model_strategy.h"
#include "http_client.h"
namespace deepseek {
namespace strategy {
class DirectApiStrategy : public IModelStrategy {
public:
DirectApiStrategy(std::shared_ptr<http::HttpClient> http_client);
std::string strategyName() const override { return "DirectApi"; }
ModelResponse execute(const ModelRequest& request) override;
void executeAsync(const ModelRequest& request, Callback callback) override;
void executeStream(const ModelRequest& request,
std::function<void(const std::string& chunk)> chunk_callback,
Callback final_callback) override;
bool configure(const data::VariantValue& config) override;
bool validateRequest(const ModelRequest& request) const override;
private:
std::shared_ptr<http::HttpClient> http_client_;
std::string api_endpoint_;
std::string api_key_;
int timeout_seconds_ = 30;
ModelResponse handleHttpResponse(const http::HttpClient::Response& http_resp);
std::string buildRequestBody(const ModelRequest& request) const;
};
class CachedStrategy : public IModelStrategy {
public:
CachedStrategy(std::shared_ptr<IModelStrategy> base_strategy);
std::string strategyName() const override {
return "Cached[" + base_strategy_->strategyName() + "]";
}
ModelResponse execute(const ModelRequest& request) override;
void executeAsync(const ModelRequest& request, Callback callback) override;
void executeStream(const ModelRequest& request,
std::function<void(const std::string& chunk)> chunk_callback,
Callback final_callback) override;
bool configure(const data::VariantValue& config) override;
bool validateRequest(const ModelRequest& request) const override;
// 缓存管理
void clearCache();
void setCacheSize(size_t max_size);
size_t cacheSize() const;
private:
std::shared_ptr<IModelStrategy> base_strategy_;
struct CacheEntry {
ModelResponse response;
std::chrono::system_clock::time_point timestamp;
};
std::map<std::string, CacheEntry> cache_;
size_t max_cache_size_ = 1000;
mutable std::mutex cache_mutex_;
std::string generateCacheKey(const ModelRequest& request) const;
bool shouldCache(const ModelRequest& request) const;
std::chrono::seconds getCacheTTL(const ModelRequest& request) const;
};
class FallbackStrategy : public IModelStrategy {
public:
using StrategyList = std::vector<std::shared_ptr<IModelStrategy>>;
FallbackStrategy(StrategyList strategies);
std::string strategyName() const override { return "Fallback"; }
ModelResponse execute(const ModelRequest& request) override;
void executeAsync(const ModelRequest& request, Callback callback) override;
void executeStream(const ModelRequest& request,
std::function<void(const std::string& chunk)> chunk_callback,
Callback final_callback) override;
bool configure(const data::VariantValue& config) override;
bool validateRequest(const ModelRequest& request) const override;
private:
StrategyList strategies_;
log::ContextLogger logger_{"FallbackStrategy"};
template<typename Func>
ModelResponse tryStrategies(const ModelRequest& request, Func executor);
};
} // namespace strategy
} // namespace deepseek
#endif // SPECIFIC_STRATEGIES_H
```
### 策略工厂与上下文
```cpp
// strategy_factory.h
#ifndef STRATEGY_FACTORY_H
#define STRATEGY_FACTORY_H
#include "model_strategy.h"
#include <memory>
#include <map>
#include <functional>
namespace deepseek {
namespace strategy {
class StrategyFactory {
public:
using Creator = std::function<std::shared_ptr<IModelStrategy>()>;
static StrategyFactory& instance();
template<typename T>
void registerStrategy(const std::string& name);
std::shared_ptr<IModelStrategy> create(const std::string& name);
std::vector<std::string> availableStrategies() const;
bool isRegistered(const std::string& name) const;
private:
StrategyFactory() = default;
~StrategyFactory() = default;
StrategyFactory(const StrategyFactory&) = delete;
StrategyFactory& operator=(const StrategyFactory&) = delete;
std::map<std::string, Creator> creators_;
mutable std::mutex creators_mutex_;
};
class StrategyContext {
public:
StrategyContext();
explicit StrategyContext(const std::string& default_strategy);
void setStrategy(const std::string& strategy_name);
void setStrategy(std::shared_ptr<IModelStrategy> strategy);
ModelResponse execute(const ModelRequest& request);
void executeAsync(const ModelRequest& request, IModelStrategy::Callback callback);
std::shared_ptr<IModelStrategy> currentStrategy() const;
std::string currentStrategyName() const;
// 策略链构建
StrategyContext& addDecorator(const std::string& decorator_name);
StrategyContext& withCache(size_t max_size = 1000);
StrategyContext& withRetry(int max_attempts = 3);
private:
std::shared_ptr<IModelStrategy> strategy_;
log::ContextLogger logger_{"StrategyContext"};
<"8w.yunruiwater.cn"><"2c.sxyicheng.cn"><"5x.jsnjz.cn">
std::shared_ptr<IModelStrategy> buildStrategyChain(
std::shared_ptr<IModelStrategy> base,
const data::VariantValue& config);
};
} // namespace strategy
} // namespace deepseek
#endif // STRATEGY_FACTORY_H
```
## 集成使用示例
```cpp
// main.cpp - 完整使用示例
#include "strategy_factory.h"
#include "strategy_context.h"
#include "config_manager.h"
#include "logger.h"
#include <iostream>
int main() {
using namespace deepseek;
// 初始化日志系统
log::LoggerManager::instance().initialize("config/logging.json");
auto logger = log::LoggerManager::instance().getLogger("Main");
// 初始化配置
config::ConfigManager::instance().loadFromFile("config/app.json");
config::ConfigManager::instance().loadFromEnvironment("DEEPSEEK_");
LOG_INFO(logger, "DeepSeek SDK 初始化完成");
try {
// 注册策略
strategy::StrategyFactory::instance()
.registerStrategy<strategy::DirectApiStrategy>("DirectApi");
// 创建策略上下文
strategy::StrategyContext context("DirectApi");
// 配置策略
data::VariantValue::Object strategy_config = {
{"api_endpoint", "https://api.deepseek.com/v1/chat/completions"},
{"api_key", config::ConfigManager::instance()
.getAs<std::string>("api_key", "")},
{"timeout_seconds", 30}
};
// 添加缓存层
context.withCache(500);
// 构建请求
strategy::ModelRequest request("deepseek-chat");
request.setInput(data::VariantValue("解释量子计算的基本概念"));
request.setParameter("temperature", data::VariantValue(0.7));
request.setParameter("max_tokens", data::VariantValue(500));
LOG_INFO(logger, "发送模型请求: {}", request.toJson());
// 执行请求
auto response = context.execute(request);
if (response.isSuccess()) {
LOG_INFO(logger, "请求成功");
auto response_data = response.data();
if (response_data.isObject()) {
auto choices = response_data["choices"].get<data::VariantValue::Array>();
if (!choices.empty()) {
auto message = choices[0]["message"];
auto content = message["content"].getAs<std::string>("");
std::cout << "模型回复:\n" << content << std::endl;
}
}
} else {
LOG_ERROR(logger, "请求失败: {}", response.errorMessage());
}
} catch (const std::exception& e) {
LOG_CRITICAL(logger, "程序异常: {}", e.what());
return 1;
}
// 清理资源
log::LoggerManager::instance().shutdown();
return 0;
}
```
## 性能优化与监控
```cpp
// strategy_monitor.h
#ifndef STRATEGY_MONITOR_H
#define STRATEGY_MONITOR_H
#include "model_strategy.h"
#include <chrono>
#include <atomic>
#include <map>
namespace deepseek {
namespace strategy {
class StrategyMetrics {
public:
struct ExecutionStats {
std::atomic<int64_t> total_calls{0};
std::atomic<int64_t> successful_calls{0};
std::atomic<int64_t> failed_calls{0};
std::atomic<int64_t> total_duration_ms{0};
double averageDuration() const {
return total_calls > 0 ?
static_cast<double>(total_duration_ms) / total_calls : 0.0;
}
double successRate() const {
return total_calls > 0 ?
static_cast<double>(successful_calls) / total_calls * 100 : 0.0;
}
};
void recordExecution(const std::string& strategy_name,
bool success,
std::chrono::milliseconds duration);
ExecutionStats getStats(const std::string& strategy_name) const;
std::map<std::string, ExecutionStats> getAllStats() const;
void reset();
void reset(const std::string& strategy_name);
private:
mutable std::mutex stats_mutex_;
std::map<std::string, ExecutionStats> stats_;
};
class MonitoredStrategy : public IModelStrategy {
public:
MonitoredStrategy(std::shared_ptr<IModelStrategy> wrapped,
std::shared_ptr<StrategyMetrics> metrics = nullptr);
std::string strategyName() const override;
ModelResponse execute(const ModelRequest& request) override;
void executeAsync(const ModelRequest& request, Callback callback) override;
void executeStream(const ModelRequest& request,
std::function<void(const std::string& chunk)> chunk_callback,
Callback final_callback) override;
bool configure(const data::VariantValue& config) override;
bool validateRequest(const ModelRequest& request) const override;
private:
std::shared_ptr<IModelStrategy> wrapped_strategy_;
std::shared_ptr<StrategyMetrics> metrics_;
ModelResponse executeWithMetrics(const ModelRequest& request);
};
} // namespace strategy
} // namespace deepseek
#endif // STRATEGY_MONITOR_H
```
通过上述架构设计,我们构建了一个高度可扩展、可维护的大模型SDK。日志系统提供了灵活的日志管理能力,通用数据结构支持复杂的数据交换需求,而策略模式则为不同的模型交互场景提供了可插拔的解决方案。这种设计模式使得SDK能够适应快速变化的业务需求和技术环境。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3109087/ ,如需转载,请注明出处,否则将追究法律责任。