Spaces:
Running
Running
File size: 8,684 Bytes
7a6b1e3 dac0054 7a6b1e3 9718b29 0fd2753 7a6b1e3 24cdb24 7a6b1e3 92ed062 7a6b1e3 0fd2753 7a6b1e3 0fd2753 8b3566b 7a6b1e3 8b3566b 0fd2753 9ac37a1 0fd2753 7a6b1e3 a2a5db6 be24e06 61e4298 be24e06 8ec3d53 61e4298 be24e06 61e4298 be24e06 7a6b1e3 dac0054 fbfa43d |
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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
import express from 'express';
import axios from 'axios';
import crypto from 'crypto';
import FormData from 'form-data'; // Import modul form-data untuk menghandle multipart
import Groq from 'groq-sdk';
import bytes from 'bytes';
import { feloAI } from '../lib/feloAI.js';
import { toAnime } from '../lib/toanime.js';
import { convertWebpToPng } from '../lib/converter.js';
const APIrouter = express.Router();
const ISauthenticate = async (req, res, next) => {
try {
// Contoh sederhana: menggunakan menit UTC sebagai secret
const secretResponse = new Date().getUTCMinutes().toString();
const generatedApiKey = generateApiKey(secretResponse);
console.log(generatedApiKey);
console.log(req.headers);
const authHeader = req.headers['authorization'];
if (!authHeader || authHeader !== `Bearer ${generatedApiKey}`) {
return res.status(403).json({ success: false, message: 'Unauthorized' });
}
next();
} catch (error) {
console.error('Authentication error:', error);
return res.status(500).json({ success: false, message: 'Internal Server Error' });
}
};
// Inisialisasi Groq SDK
const client = new Groq({
apiKey: process.env.GROQ_API_KEY || "",
dangerouslyAllowBrowser: true,
});
APIrouter.get('/', (req, res) => {
res.send('Hello World');
});
APIrouter.get('/msecret', (req, res) => {
const secret = new Date().getUTCMinutes().toString();
res.json({ msec: secret });
});
APIrouter.post('/gpt/completions', ISauthenticate, async (req, res) => {
const {
messages,
model,
temperature,
max_completion_tokens,
top_p,
stream,
stop,
searchMode
} = req.body;
try {
// Set header untuk streaming (Server-Sent Events)
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Mode tanpa search (normal GPT response stream)
if (searchMode === false) {
const chatStream = await client.chat.completions.create({
messages,
model,
temperature,
max_completion_tokens,
top_p,
stream,
stop,
});
// Kirim setiap chunk stream ke client
for await (const chunk of chatStream) {
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
}
res.write('data: [DONE]\n\n');
return res.end();
}
// Mode dengan search (tool use)
else if (searchMode === true) {
// Definisi fungsi searchEngine
const searchEngine = async (query, langcode = 'en-US') => {
try {
console.log("searching...");
console.log("query:", query);
console.log("lang:", langcode);
const searchResult = await feloAI(query, langcode);
// Susun hasil pencarian
let result = { answer: "", source: [] };
result.answer = searchResult.answer;
for (let i = 0; i < 5; i++) {
result.source.push({
title: searchResult.source[i].title,
link: searchResult.source[i].link,
snippet: searchResult.source[i].snippet
});
}
return result;
} catch (error) {
console.error(error);
return null;
}
};
// Definisi tool untuk searchEngine
const tools = [
{
type: "function",
function: {
name: "searchEngine",
description:
"Mencari informasi secara real-time dengan search engine berdasarkan query dan target daerah.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "Query pencarian untuk search engine."
},
langcode: {
type: "string",
description:
"Kode atau nama daerah target (misalnya 'id-MM', 'en-US', atau lainnya)."
}
},
required: ["query", "langcode"]
}
}
}
];
// Panggilan awal ke Groq untuk mendapatkan tool call
const response = await client.chat.completions.create({
model: model,
messages,
stream: false,
tools,
tool_choice: "auto",
max_completion_tokens: 4096
});
const responseMessage = response.choices[0].message;
console.log("Response message:", JSON.stringify(responseMessage, null, 2));
// Hapus properti yang tidak didukung
if (responseMessage.reasoning) {
delete responseMessage.reasoning;
}
const toolCalls = responseMessage.tool_calls || [];
if (toolCalls.length > 0) {
const availableFunctions = { searchEngine };
// Tambahkan respons awal ke array pesan
messages.push(responseMessage);
// Eksekusi setiap tool call
for (const toolCall of toolCalls) {
const functionName = toolCall.function.name;
const functionToCall = availableFunctions[functionName];
const functionArgs = JSON.parse(toolCall.function.arguments);
const functionResponse = await functionToCall(
functionArgs.query,
functionArgs.langcode
);
messages.push({
tool_call_id: toolCall.id,
role: "tool",
name: functionName,
content: JSON.stringify(functionResponse)
});
}
}
// Panggilan kedua dengan opsi streaming
const secondResponseStream = await client.chat.completions.create({
model: model,
messages,
stream,
});
let finalContent = "";
try {
for await (const chunk of secondResponseStream) {
// Ambil chunk respons (sesuaikan dengan struktur output model)
const contentChunk =
(chunk.choices && chunk.choices[0].delta && chunk.choices[0].delta.content) || "";
finalContent += contentChunk;
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
}
} catch (err) {
console.error("Error processing stream:", err);
}
res.write('data: [DONE]\n\n');
res.end();
}
} catch (error) {
console.error('GPT completion error:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
});
APIrouter.get('/gpt/modellist', ISauthenticate, async (req, res) => {
try {
const models = await client.models.list();
res.json(models);
} catch (error) {
console.error('GPT completion error:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
});
APIrouter.post('/toanime', async (req, res) => {
try {
console.log(req.body)
const { images } = req.body
if (!images) return res.json({ success: false, message: 'Required an images!' })
if (/^(https?|http):\/\//i.test(images)) {
const data_img = await axios.request({
method: "GET",
url: images,
responseType: "arraybuffer"
})
const response = await toAnime({ imgBuffer: data_img.data });
//const type_img = await fileTypeFromBuffer(response)
//res.setHeader('Content-Type', type_img.mime)
res.json({
status: true,
data: response
})
} else if (images && typeof images == 'string' && isBase64(images)) {
const response = await toAnime({ imgBuffer: Buffer.from(images, "base64") });
//const converted = await convertWebpToPng(response);
//const type_img = await fileTypeFromBuffer(response)
//res.setHeader('Content-Type', type_img.mime)
res.json({
status: true,
data: response
})
} else {
res.json({
success: false, message: 'No url or base64 detected!!'
})
}
} catch (e) {
console.log(e)
e = String(e)
res.json({ error: true, message: e === '[object Object]' ? 'Internal Server Error' : e })
}
})
export default APIrouter;
function generateApiKey(secret) {
// Ambil menit saat ini sebagai nilai integer
const currentMinute = Math.floor(Date.now() / 60000).toString();
// Buat HMAC menggunakan algoritma SHA256 dan secret key
const hmac = crypto.createHmac('sha256', secret);
hmac.update(currentMinute);
// Kembalikan hash dalam format hexadecimal
return hmac.digest('hex');
};
function formatSize(num) {
return bytes(+num || 0, { unitSeparator: ' ' })
}
function isBase64(str) {
try {
return btoa(atob(str)) === str
} catch {
return false
}
} |