C++代码实现调用OpenAi接口Api

在网上找了一圈C++如何调用OpenAi的接口,找到的例子比较简单,完全照搬下来修改一下也能用,不过i整合在自己的类里面就莫名奇妙的问题:

1. 比如 coredump

     url_easy_perform的执行和curl_easy_setopt放在了两个函数中就出问题了,很奇怪。。。至今不知道原因,有知道的小伙伴可以评论告诉我。O(∩_∩)O

    暖心提示:

    curl_easy_setopt和url_easy_perform 别分开写。

2. 发送api key,放入head中时,

     curl_slist_append的返回值必须用同一个head指针来接收才行,例如:

     struct curl_slist* headers

      curl_slist_append(this->headers, contentType_header.c_str());

       curl_slist_append(this->headers, contentType_header.c_str());

       就会导致认证失败,因为必须:

       headers = curl_slist_append(this->headers, contentType_header.c_str());

       headers = curl_slist_append(this->headers, contentType_header.c_str());

       你以为就这?还有:

       你下一次使用前要把 headers = NULL才行(贴个没问题的代码截图如下):

       

    ======================================================================

上示例代码:

sudo apt install nlohmann-json3-dev

Ubuntu 22.04上面安装下上面的json库

1. openai.h

#pragma once

#include <nlohmann/json_fwd.hpp>
#include <nlohmann/json.hpp>
#include <curl/curl.h>
#include <string>
using namespace std;
using namespace nlohmann;

class OpenAi {
    public:
        static OpenAi* GetInstance();
        ~OpenAi();
        const std::string& GetClassName();
        void Initialize();
        void Finalitialize();
        void SetModel(const std::string& model = "gpt-3.5-turbo");
        void SetUri(const std::string& uri = "https://api.openai.com/v1/chat/completions");
        void SetApiKey(const std::string& apiKey);
        void SetRole(const std::string& role = "user");
        void SetContent(const std::string& content);
        void SetContentType(const std::string& contentType = "application/json");
        void PostMessage();
&

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值