使用c++调用deepseek的api(附带源码)
可以给服务器添加deepseek这样就相当于多了一个智能ai助手
- deepseek的api申请地址
- 使用格式
- 测试效果
- 源码
deepseek的api申请地址
这边使用硅基流动的api,注册就有免费额度
硅基流动: link
使用格式
api的调用格式,ds的api调用就是用固定协议然后发送到对应服务器即可
然后解析json格式的文件。
让ds有记忆需要这样的格式发送数据,相当于把回答的和之前的问题合一起
测试效果
20250421_191636
源码
#include <iostream>
#include <string>
#include <vector>
#include <curl/curl.h>
#include <json/json.h>using namespace Json;static size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) {size_t total_size = size * nmemb;response->append((char*)contents, total_size);return total_size;
}class ChatGPTClient {
public:ChatGPTClient(const std::string& api_key): api_key_(api_key),endpoint_("https://api.siliconflow.cn/v1/chat/completions"),model_("deepseek-ai/DeepSeek-R1") {curl_ = curl_easy_init();// 初始化系统消息addSystemMessage(u8"你是一个乐于助人的AI助手,我发送的可能是gbk格式数据给你,你可能要自己转换");}~ChatGPTClient() {if (curl_) curl_easy_cleanup(curl_);}void addSystemMessage(const std::string& content) {Value message;message["role"] = "system";message["content"] = content;history_.append(message);}std::string ask(const std::string& question) {if (!curl_) return "Error: CURL init failed";// 添加用户问题到历史Value userMessage;userMessage["role"] = "user";userMessage["content"] = question;history_.append(userMessage);// 构建请求体Value request;request["model"] = model_;request["messages"] = history_;request["temperature"] = 0.7;request["max_tokens"] = 4096;// 序列化StreamWriterBuilder writer;std::string post_data = writeString(writer, request);// 发送请求struct curl_slist* headers = nullptr;headers = curl_slist_append(headers, "Content-Type: application/json");headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key_).c_str());std::string response_str;char error_buffer[CURL_ERROR_SIZE] = { 0 };curl_easy_setopt(curl_, CURLOPT_URL, endpoint_.c_str());curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers);curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, post_data.c_str());curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, WriteCallback);curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response_str);curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buffer);curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L);CURLcode res = curl_easy_perform(curl_);curl_slist_free_all(headers);if (res != CURLE_OK) {return "CURL Error: " + std::string(error_buffer);}// 解析响应CharReaderBuilder reader;Value response_json;std::string parse_errors;std::istringstream response_stream(response_str);bool parse_ok = Json::parseFromStream(reader, response_stream, &response_json, &parse_errors);if (!parse_ok) return "JSON Error: " + parse_errors;if (response_json.isMember("error")) {return "API Error: " + response_json["error"]["message"].asString();}const Value& choices = response_json["choices"];if (!choices.empty() && choices[0].isMember("message")) {// 添加AI回复到历史Value assistantMessage = choices[0]["message"];history_.append(assistantMessage);return assistantMessage["content"].asString();}return "No valid response";}private:CURL* curl_;std::string api_key_;std::string endpoint_;std::string model_;Value history_; // 使用JSON数组存储对话历史
};int main() {ChatGPTClient client("填key");while (true) {std::cout << "You: ";std::string input;std::getline(std::cin, input);if (input == "exit") break;std::cout << "AI: " << client.ask(input) << "\n\n";}return 0;
}
要下载
jsoncpp和ucrl
https://github.com/open-source-parsers/jsoncpp
https://github.com/curl/curl
编译参考这个文章,和libevent的编译流程一样
https://blog.csdn.net/m0_54069809/article/details/147250776?spm=1001.2014.3001.5502