File size: 2,360 Bytes
568802f | 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 | /**
* Logika internal untuk berkomunikasi dengan API Bonsai
*/
async function getBonsaiResponse(userMessage) {
const url = "https://prism-ml-bonsai-demo.hf.space/v1/chat/completions";
const payload = {
messages: [{ role: "user", content: userMessage }],
stream: true,
temperature: 0.5,
max_tokens: -1,
samplers: ["penalties", "dry", "top_n_sigma", "top_k", "typ_p", "top_p", "min_p", "xtc", "temperature"]
};
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Referer": "https://prism-ml-bonsai-demo.hf.space/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
},
body: JSON.stringify(payload),
});
if (!response.body) throw new Error("No response body from Bonsai");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split("\n");
for (const line of lines) {
if (line.startsWith("data: ") && line !== "data: [DONE]") {
try {
const jsonStr = line.replace("data: ", "");
const data = JSON.parse(jsonStr);
const content = data.choices[0]?.delta?.content || "";
fullResponse += content;
} catch (e) {
// Mengabaikan error parsing kecil pada chunk yang tidak lengkap
}
}
}
}
return fullResponse;
}
// Export untuk sistem Plug-and-Play Fastify
module.exports = {
path: '/bonsai-chat',
method: 'GET',
handler: async (request, reply) => {
const { q } = request.query; // Menggunakan param 'q' untuk pertanyaan
if (!q) {
return reply.status(400).send({
status: "error",
message: "Query parameter 'q' diperlukan. Contoh: /bonsai-chat?q=halo"
});
}
try {
const result = await getBonsaiResponse(q);
return {
status: "success",
plugin: "bonsai_ai",
input: q,
response: result
};
} catch (err) {
return reply.status(500).send({
status: "error",
message: err.message
});
}
}
}; |