当前位置: 代码网 > it编程>编程语言>C/C++ > C++通过控制台访问deepseek接口并进行对话

C++通过控制台访问deepseek接口并进行对话

2025年02月10日 C/C++ 我要评论
如题,其实对于调试一个接口来说并不复杂,关键在于会遇到json输入和解析的字符处理问题,比如中文的输入和解析,动不动就会遇到乱码,经过与deepseek的深度碰撞(发给deepseek),同比通义千问

如题,其实对于调试一个接口来说并不复杂,关键在于会遇到json输入和解析的字符处理问题,比如中文的输入和解析,动不动就会遇到乱码,经过与deepseek的深度碰撞(发给deepseek),同比通义千问给的方案,更加的准确和高效

开发环境:win11,visual stutio 2022

注意事项:在创建控制台项目后,对main.cpp(或者你自定义的cpp文件)点击顶部“文件”-xxxx.cpp另存为,选择”保存“按钮右侧的更多按钮下的“编码保存”

以下是代码方案

#include <iostream>
#include <json/json.h>
#include <curl/curl.h>
#include <vector>
#include <windows.h>
#include <sstream>
using namespace std;

// 回调函数
static size_t writecallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

void addmessage(std::vector<json::value>& messages, const std::string& role, const std::string& content) {
    json::value message;
    message["role"] = role;
    message["content"] = content;
    messages.push_back(message);
}

int main() {
    // 设置控制台为utf-8模式
    system("chcp 65001 > nul");
    setconsoleoutputcp(cp_utf8);
    setconsolecp(cp_utf8);

    std::string apikey = "这里放你自己申请的apikey(注意不要尖括号)";
    std::vector<json::value> messages;
    addmessage(messages, "system", "you are a helpful assistant.");

    curl* curl = curl_easy_init();
    if (curl) {
        std::string readbuffer;
        std::string userinput;

        while (true) {
            std::cout << "user: ";
            std::getline(std::cin, userinput);
            if (userinput == "exit") break;

            addmessage(messages, "user", userinput);

            // 构建json请求
            json::value jsondata;
            jsondata["model"] = "deepseek-chat";
            jsondata["stream"] = false;
            for (const auto& msg : messages) {
                jsondata["messages"].append(msg);
            }

            // 生成json字符串
            json::streamwriterbuilder writerbuilder;
            writerbuilder.settings_["emitutf8"] = true;
            std::string jsonstring = json::writestring(writerbuilder, jsondata);

            // 设置curl选项
            curl_easy_setopt(curl, curlopt_url, "https://api.deepseek.com/chat/completions");
            curl_easy_setopt(curl, curlopt_postfields, jsonstring.c_str());
            curl_easy_setopt(curl, curlopt_writefunction, writecallback);
            curl_easy_setopt(curl, curlopt_writedata, &readbuffer);

            struct curl_slist* headers = null;
            headers = curl_slist_append(headers, "content-type: application/json");
            headers = curl_slist_append(headers, ("authorization: bearer " + apikey).c_str());
            curl_easy_setopt(curl, curlopt_httpheader, headers);

            // 执行请求
            curlcode res = curl_easy_perform(curl);
            if (res != curle_ok) {
                std::cerr << "request failed: " << curl_easy_strerror(res) << std::endl;
            }

            // 处理响应
            json::charreaderbuilder readerbuilder;
            std::unique_ptr<json::charreader> reader(readerbuilder.newcharreader());
            json::value root;
            std::string errs;

            if (reader->parse(readbuffer.c_str(), readbuffer.c_str() + readbuffer.size(), &root, &errs)) {
                if (root.ismember("choices") && root["choices"].size() > 0) {
                    std::string response = root["choices"][0]["message"]["content"].asstring();
                    std::cout << "assistant: " << response << std::endl;
                    addmessage(messages, "assistant", response);
                }
                else {
                    std::cerr << "api error: " << root.tostyledstring() << std::endl;
                }
            }
            else {
                std::cerr << "json parse error: " << errs << std::endl;
            }

            readbuffer.clear();
            curl_slist_free_all(headers);
            curl_easy_reset(curl);
        }
        curl_easy_cleanup(curl);
    }
    return 0;
}

ps:由于deepseek官方api服务目前不稳定,经常会出现空响应,多试几次即可。

后续:目前代码未支持流式输出,另外实际上对于有需要的朋友,可以设计几个辅助功能

1、创建新话题,和保存旧话题内容

2、对于想要留存到本地的价值内容,可以设计个事件,将对话内容以word或者txt的方式存放到一个专门的文件夹中

到此这篇关于c++通过控制台访问deepseek接口并进行对话的文章就介绍到这了,更多相关c++控制台访问deepseek接口内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com