98 lines
2.5 KiB
TypeScript
98 lines
2.5 KiB
TypeScript
import { _decorator, Component, EditBox, Label, Node } from "cc";
|
|
import { l10n } from "db://localization-editor/l10n";
|
|
import { DemoManager } from "./DemoManager";
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass("ChatGPTService")
|
|
export class ChatGPTService extends Component {
|
|
@property(DemoManager)
|
|
manager: DemoManager = null;
|
|
|
|
@property(EditBox)
|
|
editBox: EditBox = null;
|
|
|
|
private apiurl: string = "https://cloud.fastgpt.cn/api/v1/chat/completions";
|
|
private apikey: string =
|
|
"fastgpt-gZSIl62Oznoqirj4zrs8tuvYH8Yk9C7GaOiOQtIh6UdLfup7QW2zSWS3";
|
|
// 发送POST请求
|
|
public async Post(data: GPTResquest): Promise<GPTResult> {
|
|
const self = this;
|
|
return new Promise(function (resolve, reject) {
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.onreadystatechange = function () {
|
|
if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
|
|
const response = xhr.responseText;
|
|
if (response) {
|
|
const d = JSON.parse(response);
|
|
resolve(d);
|
|
} else {
|
|
resolve(null);
|
|
}
|
|
}
|
|
};
|
|
xhr.open("POST", self.apiurl, true);
|
|
xhr.setRequestHeader("Content-Type", "application/json");
|
|
xhr.setRequestHeader("Authorization", "Bearer " + self.apikey);
|
|
xhr.send(JSON.stringify(data));
|
|
});
|
|
}
|
|
|
|
protected async start(): Promise<void> {
|
|
// console.log(l10n.t("hello"));
|
|
// l10n.changeLanguage("zh-Hans-CN");
|
|
// console.log(l10n.t("hello"));
|
|
// l10n.changeLanguage("en");
|
|
// console.log(l10n.t("hello"));
|
|
}
|
|
|
|
public async OnClickSend() {
|
|
const str = this.editBox.string;
|
|
if (!str || str == "") return;
|
|
console.log("post:" + str);
|
|
|
|
if (this.manager) {
|
|
this.manager.updateDialog(true, str);
|
|
}
|
|
|
|
let ret = await this.Post({
|
|
model: "llama3.1:8b",
|
|
messages: [{ role: "user", content: str }],
|
|
temperature: 0.8,
|
|
});
|
|
|
|
const rep = ret.choices[0].message.content;
|
|
if (rep == null) {
|
|
console.warn("rep null");
|
|
}
|
|
if (this.manager) {
|
|
this.manager.updateDialog(false, rep);
|
|
}
|
|
console.log("ret:" + rep);
|
|
}
|
|
}
|
|
|
|
export type GPTResquest = {
|
|
model: string; //gpt-3.5-turbo
|
|
messages: { role: string; content: string }[];
|
|
temperature: number;
|
|
};
|
|
export type GPTResult = {
|
|
id: string;
|
|
object: string;
|
|
created: number;
|
|
model: string;
|
|
usage: {
|
|
prompt_tokens: number;
|
|
completion_tokens: number;
|
|
total_tokens: number;
|
|
};
|
|
choices: {
|
|
message: {
|
|
role: string;
|
|
content: string;
|
|
};
|
|
finish_reason: string;
|
|
index: number;
|
|
}[];
|
|
};
|