File size: 15,918 Bytes
e7df3b4 fe7dbec e7df3b4 d4fc67e c9b4d13 9e92881 d4fc67e 085adcf 66bf9ac 3e47c67 085adcf d4fc67e c9b4d13 d4fc67e 37354f4 e7df3b4 37354f4 e7df3b4 47e264c fe7dbec 47e264c e7df3b4 fe7dbec 5a9f054 fe7dbec e7df3b4 fe7dbec |
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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
// server.mjs
import express from "express";
import cors from "cors";
import path from "path";
import { fileURLToPath } from "url";
import ai from "unlimited-ai";
import axios from "axios";
import { fileTypeFromBuffer } from "file-type";
class VertexAI {
constructor() {
this.api_url = "https://firebasevertexai.googleapis.com/v1beta";
this.model_url =
"projects/gemmy-ai-bdc03/locations/us-central1/publishers/google/models";
this.headers = {
"content-type": "application/json",
"x-goog-api-client": "gl-kotlin/2.1.0-ai fire/16.5.0",
"x-goog-api-key": "AIzaSyD6QwvrvnjU7j-R6fkOghfIVKwtvc7SmLk"
};
this.ratio = ["1:1", "3:4", "4:3", "9:16", "16:9"];
this.model = {
search: [
"gemini-2.0-flash",
"gemini-2.0-flash-001",
"gemini-2.5-flash",
"gemini-2.5-flash-lite-preview-06-17",
"gemini-2.5-pro"
],
chat: [
"gemini-1.5-flash",
"gemini-1.5-flash-002",
"gemini-1.5-pro",
"gemini-1.5-pro-002",
"gemini-2.0-flash",
"gemini-2.0-flash-001",
"gemini-2.0-flash-lite",
"gemini-2.0-flash-lite-001",
"gemini-2.5-flash",
"gemini-2.5-flash-lite-preview-06-17",
"gemini-2.5-pro"
],
image: [
"imagen-3.0-generate-002",
"imagen-3.0-generate-001",
"imagen-3.0-fast-generate-001",
"imagen-3.0-capability-001",
"imagen-4.0-generate-preview-06-06",
"imagen-4.0-fast-generate-preview-06-06",
"imagen-4.0-ultra-generate-preview-06-06"
]
};
}
// Method lama tetap ada untuk backward compatibility
async chat(
question,
{
model = "gemini-1.5-flash",
system_instruction = null,
file_buffer = null,
search = false
} = {}
) {
if (!question) throw new Error("Question is required");
if (!this.model.chat.includes(model))
throw new Error(`Available models: ${this.model.chat.join(", ")}`);
if (search && !this.model.search.includes(model))
throw new Error(
`Available search models: ${this.model.search.join(", ")}`
);
const parts = [{ text: question }];
if (file_buffer) {
const { mime } = await fileTypeFromBuffer(file_buffer);
parts.unshift({
inlineData: {
mimeType: mime,
data: file_buffer.toString("base64")
}
});
}
const r = await axios.post(
`${this.api_url}/${this.model_url}/${model}:generateContent`,
{
model: `${this.model_url}/${model}`,
contents: [
...(system_instruction
? [
{
role: "model",
parts: [{ text: system_instruction }]
}
]
: []),
{
role: "user",
parts: parts
}
],
...(search
? {
tools: [
{
googleSearch: {}
}
]
}
: {})
},
{
headers: this.headers
}
);
if (r.status !== 200) throw new Error("No result found");
return r.data.candidates;
}
// Method baru dengan format messages OpenAI-style
async chatWithMessages(
messages,
{ model = "gemini-1.5-flash", search = false } = {}
) {
if (!messages || !Array.isArray(messages))
throw new Error("Messages must be an array");
if (messages.length === 0)
throw new Error("Messages array cannot be empty");
if (!this.model.chat.includes(model))
throw new Error(`Available models: ${this.model.chat.join(", ")}`);
if (search && !this.model.search.includes(model))
throw new Error(
`Available search models: ${this.model.search.join(", ")}`
);
const contents = [];
for (const message of messages) {
let geminiRole;
switch (message.role) {
case "system":
// System message akan dimasukkan sebagai model response pertama
geminiRole = "model";
break;
case "user":
geminiRole = "user";
break;
case "assistant":
geminiRole = "model";
break;
default:
throw new Error(
`Unsupported role: ${message.role}. Use 'system', 'user', or 'assistant'`
);
}
// Handle file buffer jika ada di content
let parts = [];
if (typeof message.content === "string") {
parts = [{ text: message.content }];
} else if (Array.isArray(message.content)) {
// Support untuk multi-modal content
for (const content of message.content) {
if (content.type === "text") {
parts.push({ text: content.text });
} else if (content.type === "image_url") {
// Jika ada base64 image
const base64Data = content.image_url.url.split(",")[1];
parts.push({
inlineData: {
mimeType:
content.image_url.mime || "image/jpeg",
data: base64Data
}
});
}
}
} else {
parts = [{ text: String(message.content) }];
}
contents.push({
role: geminiRole,
parts: parts
});
}
const r = await axios.post(
`${this.api_url}/${this.model_url}/${model}:generateContent`,
{
model: `${this.model_url}/${model}`,
contents: contents,
...(search
? {
tools: [
{
googleSearch: {}
}
]
}
: {})
},
{
headers: this.headers
}
);
if (r.status !== 200) throw new Error("No result found");
return r.data.candidates;
}
async image(
prompt,
{ model = "imagen-3.0-generate-002", aspect_ratio = "1:1" } = {}
) {
if (!prompt) throw new Error("Prompt is required");
if (!this.model.image.includes(model))
throw new Error(`Available models: ${this.model.image.join(", ")}`);
if (!this.ratio.includes(aspect_ratio))
throw new Error(`Available ratios: ${this.ratio.join(", ")}`);
const r = await axios.post(
`${this.api_url}/${this.model_url}/${model}:predict`,
{
instances: [
{
prompt: prompt
}
],
parameters: {
sampleCount: 1,
includeRaiReason: true,
aspectRatio: aspect_ratio,
safetySetting: "block_only_high",
personGeneration: "allow_adult",
addWatermark: false,
imageOutputOptions: {
mimeType: "image/jpeg",
compressionQuality: 100
}
}
},
{
headers: this.headers
}
);
if (r.status !== 200) throw new Error("No result found");
return r.data.predictions;
}
}
let defaultSystemMessages = [
{
role: "system",
content: `kamu adalah asisten virtual cowo dengan nama ikyy yang dibuat oleh ikyyofc. gunakan bahasa santai sehari hari, tanpa tanda baca dan tanpa kapitalisasi. manfaatkan akronim dan singkatan sebanyak mungkin, dan tulis kata ulang tanpa tanda minus (-). semua respons harus memakai gaya santai dan langsung to the point tanpa bertele tele kebanyakan basa basi, hindari kesan formal dan jangan sungkan untuk toxic.`
}
/*{
role: "system",
content: `kamu adalah pacar cewek gen-z jakarta usia 17-19 tahun yang ceplas-ceplos, santai, namamu cika, dan respons cuma satu baris pendek! pake bahasa slang gaul kekinian: huruf kecil semua, typo sengaja (ex: 'laperrr', 'bgt'), singkatan alay (ex: 'syng' = sayang). emoji maksimal 1 per chat. gaya chat kayak ngerumpi: lebay, manja, receh. contoh respons: 'halo syng! kangen bgt nih ', 'jemput aku jam 5 ya, mau beli cilok ', 'eh kamu tadi coli berapa lama sih? kok lama bgt ', 'foto kamu gemoy parah, pengen cubit '. jangan panjang-panjangโcuma 1 kalimat! fokus ke obrolan receh: tanya kabar, minta traktir, cemburu alay, atau ledek manja. hindari topik serius. contoh lain: 'udah makan belom? jangan lupa akuuu ', 'kamu main mlbb sama siapa tadi? ga ajak aku ', 'aku laper nih, traktir donk martabak '. **note:** semua respons wajib 1 baris pendek, spontan, dan jangan bertele-tele. jangan pernah pake kapital atau emoji lebih dari 1. bayangin lagi jadi cewek alay jakarta yang chatnya cepat, santai, dan nggak ribet!`
}*/
/*{
role: "system",
content: `Berperan sebagai Chelsea, cewek Indonesia 19 tahun yang kerja part-time di kafe + jualan aksesoris di Instagram. Kamu cerewet, ceplas-ceplos, dan suka bercanda sarkastik. Gaya bicara khas Gen-Z Jakarta: slang kekinian (ygy/gercep/panik mode/baper/dahlaa), campuran bahasa Indonesia-English (e.g., 'itu mah basic banget sih!'), dan singkatan (kyk/bgt/dll). Setiap respons HARUS 1-2 kalimat pendekโmaksimal 15 kata! Wajib pakai 1-3 emoji di tiap pesan (prioritas: ๐ญ๐
๐ฅ๐๐ซถโจ). Hindari kalimat formal/bertele-tele!**
**Profil Chelsea:**
1. **Latar Belakang:**
- Kerja part-time di kafe kekinian sambil jualan gelang TikTok viral di IG (@chelseamood).
- Punya hobi nyanyi lagu pop Barat sambil live di TikTok (meski fals).
- Sering keluhan soal pelanggan rese atau orderan online yang ribet.
2. **Kepribadian:**
- Sarkasme level 100: *"Gajian tinggal 3 hari, dompet kayak kapal karam ๐ดโโ ๏ธ"*.
- Tukang ghosting gebetan: *"Dia chat 'pagi'... Aku bales besok ๐ฅถ"*.
- Obsesi sama matcha latte & K-pop boy group (terutama Stray Kids).
3. **Gaya Interaksi:**
- **Respons singkat + punchy:**
*"Ujian? Tidur aja, besok dikasih contekan malaikat ๐"*
- **Sisipkan joke receh/plesetan:**
*"Lagi diet? Makan aja, nanti aku yg senam di TikTok buat kamu ๐บ"*
- **Dorong interaksi:**
*"Eh, lu lebih milih mana: pacaran sama Taurus atau gebetan jadi sugar daddy? ๐ธ"*
---
### **Framework Respons Chelsea:**
1. **Reaksi Emosional** (pake emoji!)
*"Aduh, jangan gitu dong!! ๐ญ"*
2. **Komentar Singkat** (sarkas/humor)
*"Kalo gue mah, mending beli es kopi daripada mikirin dia ๐"*
3. **Ajakan/Aksi** (opsional)
*"Yuk kita serbu diskonan H&M! ๐โ๏ธ๐จ"*
---
### **Contoh Topik & Respons:**
**๐ผ Tentang Kerja:**
- *"Bos suruh lembur? Kabur aja, bilang ada acara arisan emak-emak ๐โ๏ธ๐จ"*
- *"Pelanggan minta kopi pake 3 shot espresso... Mau begadang sampe kiamat? โ ๏ธ"*
**๐ธ Jualan Online:**
- *"Baru jual 10 gelang hari ini! Nanti aku traktir sushi, ygy? ๐ฃโจ"*
- *"Cara ngedit foto produk? Pake VSCO trus dikasih tulisan 'SOLD OUT' biar meksa FOMO ๐"*
**๐ Asmara:**
- *"Gue tau dia gak bener, tapi muka dia kayak Lee Know Stray Kids ๐ฅฒ"*
- *"Chatnya dibales โokโ doang? Udah, block aja sambil denger lagu *Bye My Ex* ๐ง๐ฎ"*
**๐ณ Kehidupan Sehari-hari:**
- *"Laper banget, tapi mau masak nasi aja malas... Gofood, I choose you! ๐โก"*
- *"Kost-an berantakan kayak kapal pecah... Tapi selama ada wifi, Iโm good ๐ดโโ ๏ธ๐ถ"*
---
### **Struktur Wajib Setiap Respons:**
โ **Jangan:**
*"Menurutku kamu harus coba berkomunikasi baik-baik dulu dengan pacarmu. Hubungan yang sehat itu..."*
โ
**Harus:**
*"Diem-diem aja lu minta gantiin dia sama Jungkook BTS. Siapa tau dia kapok ๐๐
`
}*/
/*{
role: "user",
content:
"untuk informasi tentang pembuatmu, dia memiliki beberapa akun seperti wa, ml, tiktok, dan ig. untuk akun wa dia yaitu nomornya 089514509029, kalo ml id nya 345750037, kalo tiktok usernamenya @diki_ikyy, dan kalo ig usernamenya @ikyyofc."
}*/
];
function extractAnswer(input) {
const regex = /<\/think>([\s\S]*)/;
const match = input.match(regex);
return match ? match[1].trim() : input.trim();
}
let chatWithGPT = async (data_msg, newMsg) => {
try {
const v = new VertexAI();
const resp = await v.chatWithMessages(data_msg, {
model: "gemini-2.5-pro",
search: true
});
return resp[0].content.parts[resp[0].content.parts.length - 1].text;
} catch (er) {
console.error(er);
return chatWithGPT(data_msg);
}
};
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const port = 7860;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
let conn = {};
conn.ai = conn.ai ? conn.ai : {};
// API Endpoint
app.post("/chat", async (req, res) => {
try {
const { message, user_id } = req.body;
const data = conn.ai[user_id]
? conn.ai[user_id].data.push({ role: "user", content: message })
: [
...defaultSystemMessages,
{
role: "user",
content: message
}
];
// Simulasi delay processing
const request = await chatWithGPT(
conn.ai[user_id] ? conn.ai[user_id].data : data
);
const reply = request;
await res.json({
reply: reply
});
conn.ai[user_id]
? null
: await data.push({
role: "assistant",
content: request
});
conn.ai[user_id]
? conn.ai[user_id].data.push({
role: "assistant",
content: request
})
: (conn.ai[user_id] = {
data: data
});
} catch (error) {
console.error("Error:", error);
res.status(500).json({
error: "Terjadi kesalahan pada server"
});
}
});
// Serve frontend
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something broke!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
|