在网上找了一圈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&