-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenaiManager.cpp
168 lines (144 loc) · 5.08 KB
/
OpenaiManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#include "OpenaiManager.h"
#include <QDebug>
#include <QEventLoop>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
OpenaiManager *OpenaiManager::instance = nullptr;
OpenaiManager *OpenaiManager::getInstance()
{
if (instance == nullptr)
{
instance = new OpenaiManager();
}
return instance;
}
OpenaiManager::OpenaiManager(QObject *parent)
: QObject(parent), networkManager(new QNetworkAccessManager(this))
{
qDebug() << "初始化OpenAI管理器";
}
OpenaiManager::~OpenaiManager()
{
delete networkManager;
}
QString OpenaiManager::sendMessage(const QString &url, const QString &apiKey, const QString &model,
const QString &prompt, const QVector<QString> &userPrompts,
const QVector<QString> &assistantPrompts)
{
QJsonArray messages;
// 添加系统消息
QJsonObject systemMessage;
systemMessage["role"] = "system";
systemMessage["content"] = prompt;
messages.append(systemMessage);
// 添加示例对话
int maxExamples = qMin(userPrompts.size(), assistantPrompts.size());
for (int i = 0; i < maxExamples; ++i)
{
// 添加用户示例
QJsonObject userMessage;
userMessage["role"] = "user";
userMessage["content"] = userPrompts[i];
messages.append(userMessage);
// 添加助手示例
QJsonObject assistantMessage;
assistantMessage["role"] = "assistant";
assistantMessage["content"] = assistantPrompts[i];
messages.append(assistantMessage);
}
// 如果还有剩余的用户示例,继续添加
for (int i = maxExamples; i < userPrompts.size(); ++i)
{
QJsonObject userMessage;
userMessage["role"] = "user";
userMessage["content"] = userPrompts[i];
messages.append(userMessage);
}
// 如果还有剩余的助手示例,继续添加
for (int i = maxExamples; i < assistantPrompts.size(); ++i)
{
QJsonObject assistantMessage;
assistantMessage["role"] = "assistant";
assistantMessage["content"] = assistantPrompts[i];
messages.append(assistantMessage);
}
// 构建请求JSON
QJsonObject jsonObject;
jsonObject["model"] = model;
jsonObject["messages"] = messages;
QJsonDocument jsonDoc(jsonObject);
QString jsonString = jsonDoc.toJson();
// qDebug() << "\n完整请求JSON:";
// qDebug().noquote() << jsonString;
return sendRequest(jsonString, url, apiKey);
}
bool OpenaiManager::testApi(const QString &url, const QString &apiKey, const QString &model)
{
try
{
// 使用默认的测试提示
QString testPrompt = "You are a useful assistant!";
QVector<QString> userPrompts = {"hi", "How are you?"};
QVector<QString> assistantPrompts = {"Hello!"};
QString response = sendMessage(url, apiKey, model, testPrompt, userPrompts, assistantPrompts);
qDebug() << "测试响应:" << response;
return !response.isEmpty();
}
catch (...)
{
qDebug() << "API测试失败";
return false;
}
}
QString OpenaiManager::sendRequest(const QString &jsonData, const QString &url,
const QString &apiKey)
{
QNetworkRequest request;
request.setUrl(QUrl(url));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Authorization", QString("Bearer %1").arg(apiKey).toUtf8());
QNetworkReply *reply = networkManager->post(request, jsonData.toUtf8());
// 使用事件循环等待响应
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() != QNetworkReply::NoError)
{
qDebug() << "网络错误:" << reply->errorString();
qDebug() << "错误代码:" << reply->error();
qDebug() << "HTTP状态码:"
<< reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->deleteLater();
return QString();
}
// 解析响应
QByteArray responseData = reply->readAll();
// qDebug() << "原始响应数据:";
// qDebug().noquote() << QString::fromUtf8(responseData);
QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
QJsonObject jsonObject = jsonResponse.object();
QString result;
if (jsonObject.contains("choices") && jsonObject["choices"].isArray())
{
QJsonArray choices = jsonObject["choices"].toArray();
if (!choices.isEmpty())
{
QJsonObject choice = choices[0].toObject();
if (choice.contains("message") && choice["message"].isObject())
{
QJsonObject message = choice["message"].toObject();
result = message["content"].toString();
}
}
}
if (result.isEmpty())
{
qDebug() << "警告: 未能从响应中提取有效内容";
}
reply->deleteLater();
return result;
}