-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathollamaclient.cpp
76 lines (64 loc) · 2.15 KB
/
ollamaclient.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
#include "ollamaclient.h"
#include <QUrl>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
OllamaClient::OllamaClient(QObject *parent) : QObject(parent)
{
manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished, this, &OllamaClient::onReplyFinished);
}
void OllamaClient::askQuestion(const QString &question)
{
QUrl url("http://localhost:11434/api/generate"); // 假设 ollama 服务运行在本地
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// 构建请求体
QJsonObject json;
json["model"] = "deepseek-r1:1.5b";
json["prompt"] = question;
json["stream"] = true;
// 添加上下文
if (!context.isEmpty()) {
QJsonArray contextArray;
for (const QString &ctx : context) {
contextArray.append(ctx);
}
json["context"] = contextArray;
}
QJsonDocument doc(json);
QByteArray data = doc.toJson();
currentReply = manager->post(request, data);
connect(currentReply, &QNetworkReply::readyRead, this, &OllamaClient::onReadyRead);
}
void OllamaClient::resetContext()
{
context.clear(); // 清空上下文
}
void OllamaClient::onReplyFinished(QNetworkReply *reply)
{
if (reply->error() == QNetworkReply::NoError) {
QByteArray responseData = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(responseData);
QJsonObject json = doc.object();
QString response = json["response"].toString();
QString newContext = json["context"].toString(); // 获取新的上下文
// 更新上下文
if (!newContext.isEmpty()) {
context.append(newContext);
}
emit responseReceived(response);
} else {
emit errorOccurred(reply->errorString());
}
reply->deleteLater();
}
void OllamaClient::onReadyRead()
{
QByteArray data = currentReply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject json = doc.object();
QString response = json["response"].toString();
emit streamDataReceived(response);
}