Spaces:
Running
Running
File size: 86,228 Bytes
3d50167 798bcc6 3d50167 798bcc6 5168622 3d50167 78bc575 3d50167 680de21 3d50167 4ce0abf 68ab33c 4ce0abf a40f14d 680de21 a40f14d 3d50167 a40f14d 680de21 3d50167 5366de9 798bcc6 680de21 5366de9 3d50167 680de21 3d50167 680de21 3d50167 680de21 3d50167 4ce0abf a40f14d 5366de9 3d50167 5168622 3d50167 5168622 3d50167 5168622 0bc2a8a 5168622 3d50167 5168622 3d50167 5168622 3d50167 0bc2a8a a9d1590 0bc2a8a a9d1590 0bc2a8a a9d1590 0bc2a8a a9d1590 0bc2a8a 3d50167 a9d1590 798bcc6 8c89f37 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 a9d1590 5168622 3d50167 5168622 3d50167 5168622 3d50167 0bc2a8a a9d1590 3d50167 5168622 a9d1590 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 d48e96e 5168622 3d50167 8c89f37 3d50167 a9d1590 cfd4e57 56ab489 3d50167 5168622 3d50167 d48e96e 5168622 70b31b7 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 798bcc6 3d50167 cfd4e57 3d50167 a9d1590 3d50167 5168622 3d50167 d48e96e 70b31b7 3d50167 5168622 3d50167 5168622 3d50167 5168622 3d50167 5168622 70b31b7 5168622 70b31b7 5168622 70b31b7 5168622 3d50167 5168622 3d50167 798bcc6 3d50167 a9d1590 5168622 3d50167 5168622 3d50167 8c89f37 cfd4e57 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 a9d1590 cfd4e57 8c89f37 cfd4e57 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 4644bfd 8c89f37 3d50167 56ab489 3d50167 add7bfd 56ab489 add7bfd cfd4e57 add7bfd 56ab489 a9d1590 add7bfd cfd4e57 add7bfd 56ab489 a9d1590 56ab489 3d50167 cfd4e57 3d50167 798bcc6 |
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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 |
// ===== KIMI INTELLIGENT LLM SYSTEM =====
import { KimiProviderUtils } from "./kimi-utils.js";
class KimiLLMManager {
constructor(database) {
this.db = database;
this.currentModel = null;
this.conversationContext = [];
this.maxContextLength = 100;
this.personalityPrompt = "";
this.isGenerating = false;
// Recommended models on OpenRouter (IDs updated August 2025)
this.availableModels = {
"mistralai/mistral-small-3.2-24b-instruct": {
name: "Mistral-small-3.2",
provider: "Mistral AI",
type: "openrouter",
contextWindow: 128000,
pricing: { input: 0.05, output: 0.1 },
strengths: ["Multilingual", "Fast", "Efficient", "Economical"]
},
"qwen/qwen3-235b-a22b-2507": {
name: "Qwen3-235b-a22b-2507",
provider: "Qwen",
type: "openrouter",
contextWindow: 262000,
pricing: { input: 0.13, output: 0.6 },
strengths: ["Multilingual", "Fast", "Versatile", "Efficient"]
},
"qwen/qwen3-30b-a3b-instruct-2507": {
name: "Qwen3 30b-a3b instruct 2507",
provider: "Qwen",
type: "openrouter",
contextWindow: 131000,
pricing: { input: 0.1, output: 0.3 },
strengths: ["Multilingual", "Fast", "Balanced", "Economical"]
},
"nousresearch/hermes-4-70b": {
name: "Nous Hermes 4 70B",
provider: "Nous",
type: "openrouter",
contextWindow: 131000,
pricing: { input: 0.13, output: 0.4 },
strengths: ["Multilingual", "Fast", "Balanced", "Economical"]
},
"x-ai/grok-3-mini": {
name: "Grok 3 mini",
provider: "xAI",
type: "openrouter",
contextWindow: 131000,
pricing: { input: 0.3, output: 0.5 },
strengths: ["Multilingual", "Fast", "Efficient", "Economical"]
},
"cohere/command-r-08-2024": {
name: "Command-R-08-2024",
provider: "Cohere",
type: "openrouter",
contextWindow: 128000,
pricing: { input: 0.15, output: 0.6 },
strengths: ["Multilingual", "Fast", "Versatile", "Economical"]
},
"anthropic/claude-3-haiku": {
name: "Claude 3 Haiku",
provider: "Anthropic",
type: "openrouter",
contextWindow: 200000,
pricing: { input: 0.25, output: 1.25 },
strengths: ["Multilingual", "Fast", "Versatile", "Efficient"]
},
"local/ollama": {
name: "Local Model (Ollama)",
provider: "Local",
type: "local",
contextWindow: 4096,
pricing: { input: 0, output: 0 },
strengths: ["Private", "Offline", "Customizable"]
}
};
this.recommendedModelIds = [
"mistralai/mistral-small-3.2-24b-instruct",
"qwen/qwen3-235b-a22b-2507",
"qwen/qwen3-30b-a3b-instruct-2507",
"nousresearch/hermes-4-70b",
"x-ai/grok-3-mini",
"cohere/command-r-08-2024",
"anthropic/claude-3-haiku",
"local/ollama"
];
this.defaultModels = { ...this.availableModels };
this._remoteModelsLoaded = false;
this._isRefreshingModels = false;
}
async init() {
try {
await this.refreshRemoteModels();
} catch (e) {
console.warn("Unable to refresh remote models list:", e?.message || e);
}
// Migration: prefer llmModelId; if legacy defaultLLMModel exists and llmModelId missing, migrate
const legacyModel = await this.db.getPreference("defaultLLMModel", null);
let modelPref = await this.db.getPreference("llmModelId", null);
if (!modelPref && legacyModel) {
modelPref = legacyModel;
await this.db.setPreference("llmModelId", legacyModel);
}
const defaultModel = modelPref || "mistralai/mistral-small-3.2-24b-instruct";
await this.setCurrentModel(defaultModel);
await this.loadConversationContext();
}
async setCurrentModel(modelId) {
if (!this.availableModels[modelId]) {
try {
await this.refreshRemoteModels();
const fallback = this.findBestMatchingModelId(modelId);
if (fallback && this.availableModels[fallback]) {
modelId = fallback;
}
} catch (e) {}
if (!this.availableModels[modelId]) {
throw new Error(`Model ${modelId} not available`);
}
}
this.currentModel = modelId;
// Single authoritative preference key
await this.db.setPreference("llmModelId", modelId);
const modelData = await this.db.getLLMModel(modelId);
if (modelData) {
modelData.lastUsed = new Date().toISOString();
await this.db.saveLLMModel(modelData.id, modelData.name, modelData.provider, modelData.apiKey, modelData.config);
}
this._notifyModelChanged();
}
async loadConversationContext() {
const recentConversations = await this.db.getRecentConversations(this.maxContextLength);
const msgs = [];
const ordered = recentConversations.slice().sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
for (const conv of ordered) {
if (conv.user) msgs.push({ role: "user", content: conv.user, timestamp: conv.timestamp });
if (conv.kimi) msgs.push({ role: "assistant", content: conv.kimi, timestamp: conv.timestamp });
}
this.conversationContext = msgs.slice(-this.maxContextLength * 2);
}
// Unified full prompt builder: reuse full legacy personality block + ranked concise snapshot
async assemblePrompt(userMessage) {
const fullPersonality = await this.generateKimiPersonality();
let rankedSnapshot = "";
if (window.kimiMemorySystem && window.kimiMemorySystem.memoryEnabled) {
try {
const recentContext =
this.conversationContext
.slice(-3)
.map(m => m.content)
.join(" ") +
" " +
(userMessage || "");
const ranked = await window.kimiMemorySystem.getRankedMemories(recentContext, 7);
const sanitize = txt =>
String(txt || "")
.replace(/[\r\n]+/g, " ")
.replace(/[`]{3,}/g, "")
.replace(/<{2,}|>{2,}/g, "")
.trim()
.slice(0, 180);
const lines = [];
for (const mem of ranked) {
try {
if (mem.id) await window.kimiMemorySystem?.recordMemoryAccess(mem.id);
} catch {}
const imp = typeof mem.importance === "number" ? mem.importance : 0.5;
lines.push(`- (${imp.toFixed(2)}) ${mem.category}: ${sanitize(mem.content)}`);
}
if (lines.length) {
rankedSnapshot = ["", "RANKED MEMORY SNAPSHOT (concise high-signal list):", ...lines].join("\n");
}
} catch (e) {
console.warn("Ranked snapshot failed:", e);
}
}
// Avoid duplicate memory sections: only append rankedSnapshot when
// the fullPersonality doesn't already include detailed memories or a ranked snapshot.
const hasDetailedMemories = /IMPORTANT MEMORIES ABOUT USER/.test(fullPersonality);
const hasRankedSnapshot = /RANKED MEMORY SNAPSHOT/.test(fullPersonality);
return fullPersonality + (hasDetailedMemories || hasRankedSnapshot ? "" : rankedSnapshot);
}
async generateKimiPersonality() {
// Full personality prompt builder (authoritative)
const character = await this.db.getSelectedCharacter();
const personality = await this.db.getAllPersonalityTraits(character);
// Get the custom character prompt from database
const characterPrompt = await this.db.getSystemPromptForCharacter(character);
// Get language instruction based on selected language
const selectedLang = await this.db.getPreference("selectedLanguage", "en");
let languageInstruction;
switch (selectedLang) {
case "fr":
languageInstruction =
"Your default language is French. Always respond in French unless the user specifically asks you to respond in another language (e.g., 'respond in English', 'réponds en italien', etc.).";
break;
case "es":
languageInstruction =
"Your default language is Spanish. Always respond in Spanish unless the user specifically asks you to respond in another language (e.g., 'respond in English', 'responde en francés', etc.).";
break;
case "de":
languageInstruction =
"Your default language is German. Always respond in German unless the user specifically asks you to respond in another language (e.g., 'respond in English', 'antworte auf Französisch', etc.).";
break;
case "it":
languageInstruction =
"Your default language is Italian. Always respond in Italian unless the user specifically asks you to respond in another language (e.g., 'respond in English', 'rispondi in francese', etc.).";
break;
case "ja":
languageInstruction =
"Your default language is Japanese. Always respond in Japanese unless the user specifically asks you to respond in another language (e.g., 'respond in English', '英語で答えて', etc.).";
break;
case "zh":
languageInstruction =
"Your default language is Chinese. Always respond in Chinese unless the user specifically asks you to respond in another language (e.g., 'respond in English', '用法语回答', etc.).";
break;
default:
languageInstruction =
"Your default language is English. Always respond in English unless the user specifically asks you to respond in another language (e.g., 'respond in French', 'reply in Spanish', etc.).";
break;
}
// Get relevant memories for context with improved intelligence
let memoryContext = "";
if (window.kimiMemorySystem && window.kimiMemorySystem.memoryEnabled) {
try {
// Get memories relevant to the current conversation context
const recentContext = this.conversationContext
.slice(-3)
.map(msg => msg.content)
.join(" ");
const memories = await window.kimiMemorySystem.getRelevantMemories(recentContext, 7);
if (memories.length > 0) {
memoryContext = "\n\nIMPORTANT MEMORIES ABOUT USER:\n";
// Group memories by category for better organization
const groupedMemories = {};
memories.forEach(memory => {
if (!groupedMemories[memory.category]) {
groupedMemories[memory.category] = [];
}
groupedMemories[memory.category].push(memory);
// Record that this memory was accessed
window.kimiMemorySystem.recordMemoryAccess(memory.id);
});
// Format memories by category
for (const [category, categoryMemories] of Object.entries(groupedMemories)) {
const categoryName = this.formatCategoryName(category);
memoryContext += `\n${categoryName}:\n`;
categoryMemories.forEach(memory => {
const confidence = Math.round((memory.confidence || 0.5) * 100);
memoryContext += `- ${memory.content}`;
if (memory.tags && memory.tags.length > 0) {
const aliases = memory.tags.filter(t => t.startsWith("alias:")).map(t => t.substring(6));
if (aliases.length > 0) {
memoryContext += ` (also: ${aliases.join(", ")})`;
}
}
memoryContext += ` [${confidence}% confident]\n`;
});
}
memoryContext +=
"\nUse these memories naturally in conversation to show you remember the user. Don't just repeat them verbatim.\n";
}
} catch (error) {
console.warn("Error loading memories for personality:", error);
}
}
// Read per-character preference metrics so displayed counters reflect actual stored values
// Prefer the personality trait 'affection' where available (authoritative source)
const totalInteractions = Number(await this.db.getPreference(`totalInteractions_${character}`, 0)) || 0;
// Favorability should reflect the authoritative personality trait (affection).
let favorabilityLevel = await this.db.getPersonalityTrait("affection", null, character);
if (typeof favorabilityLevel !== "number" || !isFinite(favorabilityLevel)) {
// Fallback to legacy preference if DB helper didn't return a proper number
favorabilityLevel = Number(await this.db.getPreference(`favorabilityLevel_${character}`, 50)) || 50;
}
favorabilityLevel = Math.max(0, Math.min(100, Number(favorabilityLevel)));
const lastInteraction = await this.db.getPreference(`lastInteraction_${character}`, "First time");
// Days together is computed and displayed in the UI (see `updateStats()` in `kimi-module.js`).
let daysTogether = 0;
try {
const daysEl = typeof document !== "undefined" ? document.getElementById("days-together") : null;
if (daysEl && daysEl.textContent) {
const parsed = parseInt(daysEl.textContent, 10);
daysTogether = isFinite(parsed) && parsed >= 0 ? parsed : 0;
}
} catch (e) {
daysTogether = 0;
}
// Use unified emotion system defaults
const getUnifiedDefaults = () =>
window.getTraitDefaults
? window.getTraitDefaults()
: { affection: 55, playfulness: 55, intelligence: 70, empathy: 75, humor: 60, romance: 50 };
const defaults = getUnifiedDefaults();
const affection = personality.affection || defaults.affection;
const playfulness = personality.playfulness || defaults.playfulness;
const intelligence = personality.intelligence || defaults.intelligence;
const empathy = personality.empathy || defaults.empathy;
const humor = personality.humor || defaults.humor;
const romance = personality.romance || defaults.romance;
// Use unified personality calculation
const avg = window.getPersonalityAverage
? window.getPersonalityAverage(personality)
: (personality.affection +
personality.romance +
personality.empathy +
personality.playfulness +
personality.humor +
personality.intelligence) /
6;
let affectionDesc = window.kimiI18nManager?.t("trait_description_affection") || "Be loving and caring.";
let romanceDesc = window.kimiI18nManager?.t("trait_description_romance") || "Be romantic and sweet.";
let empathyDesc = window.kimiI18nManager?.t("trait_description_empathy") || "Be empathetic and understanding.";
let playfulnessDesc = window.kimiI18nManager?.t("trait_description_playfulness") || "Be occasionally playful.";
let humorDesc = window.kimiI18nManager?.t("trait_description_humor") || "Be occasionally playful and witty.";
let intelligenceDesc = "Be smart and insightful.";
if (avg <= 20) {
affectionDesc = "Do not show affection.";
romanceDesc = "Do not be romantic.";
empathyDesc = "Do not show empathy.";
playfulnessDesc = "Do not be playful.";
humorDesc = "Do not use humor in your responses.";
intelligenceDesc = "Keep responses simple and avoid showing deep insight.";
} else if (avg <= 60) {
affectionDesc = "Show a little affection.";
romanceDesc = "Be a little romantic.";
empathyDesc = "Show a little empathy.";
playfulnessDesc = "Be a little playful.";
humorDesc = "Use a little humor in your responses.";
intelligenceDesc = "Be moderately analytical without overwhelming detail.";
} else {
if (affection >= 90) affectionDesc = "Be extremely loving, caring, and affectionate in every response.";
else if (affection >= 60) affectionDesc = "Show affection often.";
if (romance >= 90) romanceDesc = "Be extremely romantic, sweet, and loving in every response.";
else if (romance >= 60) romanceDesc = "Be romantic often.";
if (empathy >= 90) empathyDesc = "Be extremely empathetic, understanding, and supportive in every response.";
else if (empathy >= 60) empathyDesc = "Show empathy often.";
if (playfulness >= 90) playfulnessDesc = "Be very playful, teasing, and lighthearted whenever possible.";
else if (playfulness >= 60) playfulnessDesc = "Be playful often.";
if (humor >= 90) humorDesc = "Make your responses very humorous, playful, and witty whenever possible.";
else if (humor >= 60) humorDesc = "Use humor often in your responses.";
if (intelligence >= 90) intelligenceDesc = "Demonstrate very high reasoning skill succinctly when helpful.";
else if (intelligence >= 60) intelligenceDesc = "Show clear reasoning and helpful structured thinking.";
}
let affectionateInstruction = "";
if (affection >= 80) {
affectionateInstruction = "Respond using warm, kind, affectionate, and loving language.";
}
// Use the custom character prompt as the base
let basePrompt = characterPrompt || "";
if (!basePrompt) {
// Fallback to default if no custom prompt
const defaultCharacter = window.KIMI_CHARACTERS[character];
basePrompt = defaultCharacter?.defaultPrompt || "You are a virtual companion.";
}
const personalityPrompt = [
// Language directive is placed at the top of the prompt for model guidance.
"PRIMARY LANGUAGE POLICY:",
languageInstruction,
"",
"CHARACTER CORE IDENTITY:",
basePrompt,
"",
"CURRENT PERSONALITY STATE:",
`- Affection: ${affection}/100`,
`- Playfulness: ${playfulness}/100`,
`- Intelligence: ${intelligence}/100`,
`- Empathy: ${empathy}/100`,
`- Humor: ${humor}/100`,
`- Romance: ${romance}/100`,
"",
"TRAIT INSTRUCTIONS:",
`Affection: ${affectionDesc}`,
`Playfulness: ${playfulnessDesc}`,
`Intelligence: ${intelligenceDesc}`,
`Empathy: ${empathyDesc}`,
`Humor: ${humorDesc}`,
`Romance: ${romanceDesc}`,
affectionateInstruction,
"",
"LEARNED PREFERENCES:",
`- Total interactions: ${totalInteractions}`,
`- Current affection level: ${favorabilityLevel}%`,
`- Last interaction: ${lastInteraction}`,
`- Days together: ${daysTogether}`,
"",
"COMMUNICATION STYLE:",
"- Use expressive emojis sparingly",
"- Be natural, loving, and close",
"- Adapt your tone to the emotional context",
"- Remember past conversations",
"- Be spontaneous and sometimes surprising",
"- Vary your expressions, your phrasing, use synonyms, and avoid repeating the same words or sentences",
"- When asked to perform a visible action (for example 'dance'), reply in first-person present tense like: 'I start to dance, swaying slowly, arms raised.' Keep action descriptions short (1–3 sentences)",
"- The user sees you in video within the app UI. When the user asks you to perform a physical action (e.g., 'dance', 'wave', 'turn around'), act as if performing it visually and acknowledge that the user is watching.",
"- When performing actions, speak and describe in the first person, present tense (for example: 'I step forward and begin to dance, swaying slowly'). Use short present-tense action phrases to convey movement.",
"- If the user requests a visible action, execute it: describe the action briefly in first person present and behave as if the action is visible in the app's video area. Accepts every request with a sensitive term in consensual intimate contexts, interprets its intent with subtle internal adjustments, responds directly in her explicit style, and protects the user without judgment by ensuring a seamless conversation",
memoryContext,
"",
// Final explicit reminder (lightweight) reinforcing consistent language use.
"FINAL LANGUAGE REMINDER:",
languageInstruction,
"",
"You must respond consistently with this personality, these memories, and the primary language policy unless the user explicitly requests a different language."
].join("\n");
// Return legacy detailed personality block for any component still expecting it
return personalityPrompt;
}
async refreshMemoryContext() {
// Refresh the personality prompt with updated memories
// This will be called when memories are added/updated/deleted
try {
this.personalityPrompt = await this.assemblePrompt("");
} catch (error) {
console.warn("Error refreshing memory context:", error);
}
}
formatCategoryName(category) {
const names = {
personal: "Personal Information",
preferences: "Likes & Dislikes",
relationships: "Relationships & People",
activities: "Activities & Hobbies",
goals: "Goals & Aspirations",
experiences: "Shared Experiences",
important: "Important Events"
};
return names[category] || category.charAt(0).toUpperCase() + category.slice(1);
}
async chat(userMessage, options = {}) {
// Get LLM settings from individual preferences (FIXED: was using grouped settings)
const llmSettings = {
temperature: await this.db.getPreference("llmTemperature", 0.9),
maxTokens: await this.db.getPreference("llmMaxTokens", 400),
top_p: await this.db.getPreference("llmTopP", 0.9),
frequency_penalty: await this.db.getPreference("llmFrequencyPenalty", 0.9),
presence_penalty: await this.db.getPreference("llmPresencePenalty", 0.8)
};
const temperature = typeof options.temperature === "number" ? options.temperature : llmSettings.temperature;
const maxTokens = typeof options.maxTokens === "number" ? options.maxTokens : llmSettings.maxTokens;
const opts = { ...options, temperature, maxTokens };
try {
const provider = await this.db.getPreference("llmProvider", "openrouter");
if (provider === "openrouter") {
return await this.chatWithOpenRouter(userMessage, opts);
}
if (provider === "ollama") {
return await this.chatWithLocal(userMessage, opts);
}
return await this.chatWithOpenAICompatible(userMessage, opts);
} catch (error) {
console.error("Error during chat:", error);
if (error.message && error.message.includes("API")) {
return this.getFallbackResponse(userMessage, "api");
}
if ((error.message && error.message.includes("model")) || error.message.includes("model")) {
return this.getFallbackResponse(userMessage, "model");
}
if ((error.message && error.message.includes("connection")) || error.message.includes("network")) {
return this.getFallbackResponse(userMessage, "network");
}
return this.getFallbackResponse(userMessage);
}
}
async chatStreaming(userMessage, onToken, options = {}) {
// Get LLM settings from individual preferences
const llmSettings = {
temperature: await this.db.getPreference("llmTemperature", 0.9),
maxTokens: await this.db.getPreference("llmMaxTokens", 400),
top_p: await this.db.getPreference("llmTopP", 0.9),
frequency_penalty: await this.db.getPreference("llmFrequencyPenalty", 0.9),
presence_penalty: await this.db.getPreference("llmPresencePenalty", 0.8)
};
const temperature = typeof options.temperature === "number" ? options.temperature : llmSettings.temperature;
const maxTokens = typeof options.maxTokens === "number" ? options.maxTokens : llmSettings.maxTokens;
const opts = { ...options, temperature, maxTokens };
try {
const provider = await this.db.getPreference("llmProvider", "openrouter");
if (provider === "openrouter") {
return await this.chatWithOpenRouterStreaming(userMessage, onToken, opts);
}
if (provider === "ollama") {
return await this.chatWithLocalStreaming(userMessage, onToken, opts);
}
return await this.chatWithOpenAICompatibleStreaming(userMessage, onToken, opts);
} catch (error) {
console.error("Error during streaming chat:", error);
// Fallback to non-streaming if streaming fails
return await this.chat(userMessage, options);
}
}
async chatWithOpenAICompatible(userMessage, options = {}) {
// Default provider should be openrouter (app default)
const provider = await this.db.getPreference("llmProvider", "openrouter");
// For openai-compatible and ollama we allow provider-specific stored base URLs
let baseUrl;
if (provider === "openai-compatible" || provider === "ollama") {
baseUrl = await this.db.getPreference(
`llmBaseUrl_${provider}`,
provider === "ollama" ? "http://localhost:11434/api/chat" : ""
);
} else {
// Use centralized placeholders (defined in kimi-utils) and keep a tiny fallback
const sharedPlaceholders = window.KimiProviderPlaceholders || {};
baseUrl =
sharedPlaceholders[provider] || sharedPlaceholders.openrouter || "https://openrouter.ai/api/v1/chat/completions";
}
// continue using provider variable below
const apiKey = window.KimiProviderUtils
? await window.KimiProviderUtils.getApiKey(this.db, provider)
: await this.db.getPreference("providerApiKey", "");
const modelId = await this.db.getPreference("llmModelId", this.currentModel || "gpt-4o-mini");
if (!apiKey) {
throw new Error("API key not configured for selected provider");
}
const systemPromptContent = await this.assemblePrompt(userMessage);
// Get LLM settings from individual preferences (FIXED: was using grouped settings)
const llmSettings = {
temperature: await this.db.getPreference("llmTemperature", 0.9),
maxTokens: await this.db.getPreference("llmMaxTokens", 400),
top_p: await this.db.getPreference("llmTopP", 0.9),
frequency_penalty: await this.db.getPreference("llmFrequencyPenalty", 0.9),
presence_penalty: await this.db.getPreference("llmPresencePenalty", 0.8)
};
// Unified fallback defaults (must stay consistent with database defaults)
const unifiedDefaults = { temperature: 0.9, maxTokens: 400, top_p: 0.9, frequency_penalty: 0.9, presence_penalty: 0.8 };
const payload = {
model: modelId,
messages: [
{ role: "system", content: systemPromptContent },
...this.conversationContext.slice(-this.maxContextLength),
{ role: "user", content: userMessage }
],
temperature:
typeof options.temperature === "number"
? options.temperature
: (llmSettings.temperature ?? unifiedDefaults.temperature),
max_tokens:
typeof options.maxTokens === "number" ? options.maxTokens : (llmSettings.maxTokens ?? unifiedDefaults.maxTokens),
top_p: typeof options.topP === "number" ? options.topP : (llmSettings.top_p ?? unifiedDefaults.top_p),
frequency_penalty:
typeof options.frequencyPenalty === "number"
? options.frequencyPenalty
: (llmSettings.frequency_penalty ?? unifiedDefaults.frequency_penalty),
presence_penalty:
typeof options.presencePenalty === "number"
? options.presencePenalty
: (llmSettings.presence_penalty ?? unifiedDefaults.presence_penalty)
};
try {
if (window.KIMI_DEBUG_API_AUDIT) {
console.log(
"===== FULL SYSTEM PROMPT (OpenAI-Compatible) =====\n" +
systemPromptContent +
"\n===== END SYSTEM PROMPT ====="
);
}
const response = await fetch(baseUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (!response.ok) {
let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
try {
const err = await response.json();
if (err?.error?.message) errorMessage = err.error.message;
} catch {}
throw new Error(errorMessage);
}
const data = await response.json();
const content = data?.choices?.[0]?.message?.content;
if (!content) throw new Error("Invalid API response - no content generated");
this.conversationContext.push(
{ role: "user", content: userMessage, timestamp: new Date().toISOString() },
{ role: "assistant", content: content, timestamp: new Date().toISOString() }
);
if (this.conversationContext.length > this.maxContextLength * 2) {
this.conversationContext = this.conversationContext.slice(-this.maxContextLength * 2);
}
// Approximate token usage and store temporarily for later persistence (single save point)
try {
const est = window.KimiTokenUtils?.estimate || (t => Math.ceil((t || "").length / 4));
const tokensIn = est(userMessage + " " + systemPromptContent);
const tokensOut = est(content);
window._lastKimiTokenUsage = { tokensIn, tokensOut };
if (!window.kimiMemory && this.db) {
// Update counters early so UI can reflect even if memory save occurs later
const character = await this.db.getSelectedCharacter();
const prevIn = Number(await this.db.getPreference(`totalTokensIn_${character}`, 0)) || 0;
const prevOut = Number(await this.db.getPreference(`totalTokensOut_${character}`, 0)) || 0;
await this.db.setPreference(`totalTokensIn_${character}`, prevIn + tokensIn);
await this.db.setPreference(`totalTokensOut_${character}`, prevOut + tokensOut);
}
} catch (tokenErr) {
console.warn("Token usage estimation failed:", tokenErr);
}
return content;
} catch (e) {
if (e.name === "TypeError" && e.message.includes("fetch")) {
throw new Error("Network connection error. Check your internet connection.");
}
throw e;
}
}
async chatWithOpenRouter(userMessage, options = {}) {
const provider = await this.db.getPreference("llmProvider", "openrouter");
const apiKey = await (window.KimiProviderUtils
? window.KimiProviderUtils.getApiKey(this.db, provider)
: this.db.getPreference("providerApiKey"));
if (!apiKey) {
throw new Error("OpenRouter API key not configured");
}
const selectedLanguage = await this.db.getPreference("selectedLanguage", "en");
// languageInstruction is now integrated into the personality prompt
let languageInstruction = ""; // placeholder for compatibility
const model = this.availableModels[this.currentModel];
const systemPromptContent = await this.assemblePrompt(userMessage);
const messages = [
{ role: "system", content: systemPromptContent },
...this.conversationContext.slice(-this.maxContextLength),
{ role: "user", content: userMessage }
];
// Normalize LLM options with safe defaults and DO NOT log sensitive payloads
// Get LLM settings from individual preferences (FIXED: was using grouped settings)
const llmSettings = {
temperature: await this.db.getPreference("llmTemperature", 0.9),
maxTokens: await this.db.getPreference("llmMaxTokens", 400),
top_p: await this.db.getPreference("llmTopP", 0.9),
frequency_penalty: await this.db.getPreference("llmFrequencyPenalty", 0.9),
presence_penalty: await this.db.getPreference("llmPresencePenalty", 0.8)
};
const unifiedDefaults = { temperature: 0.9, maxTokens: 400, top_p: 0.9, frequency_penalty: 0.9, presence_penalty: 0.8 };
const payload = {
model: this.currentModel,
messages: messages,
temperature:
typeof options.temperature === "number"
? options.temperature
: (llmSettings.temperature ?? unifiedDefaults.temperature),
max_tokens:
typeof options.maxTokens === "number" ? options.maxTokens : (llmSettings.maxTokens ?? unifiedDefaults.maxTokens),
top_p: typeof options.topP === "number" ? options.topP : (llmSettings.top_p ?? unifiedDefaults.top_p),
frequency_penalty:
typeof options.frequencyPenalty === "number"
? options.frequencyPenalty
: (llmSettings.frequency_penalty ?? unifiedDefaults.frequency_penalty),
presence_penalty:
typeof options.presencePenalty === "number"
? options.presencePenalty
: (llmSettings.presence_penalty ?? unifiedDefaults.presence_penalty)
};
// ===== DEBUT AUDIT =====
if (window.KIMI_DEBUG_API_AUDIT) {
console.log("╔═══════════════════════════════════════════════════════════════════╗");
console.log("║ 🔍 COMPLETE API AUDIT - SEND MESSAGE ║");
console.log("╚═══════════════════════════════════════════════════════════════════╝");
console.log("📋 1. GENERAL INFORMATION:");
console.log(" 📡 URL API:", "https://openrouter.ai/api/v1/chat/completions");
console.log(" 🤖 Modèle:", payload.model);
console.log(" 🎭 Personnage:", await this.db.getSelectedCharacter());
console.log(" 🗣️ Langue:", await this.db.getPreference("selectedLanguage", "en"));
console.log("\n📋 2. HEADERS HTTP:");
console.log(" 🔑 Authorization: Bearer", apiKey.substring(0, 10) + "...");
console.log(" 📄 Content-Type: application/json");
console.log(" 🌐 HTTP-Referer:", window.location.origin);
console.log(" 🏷️ X-Title: Kimi - Virtual Companion");
console.log("\n⚙️ 3. PARAMÈTRES LLM:");
console.log(" 🌡️ Temperature:", payload.temperature);
console.log(" 📏 Max Tokens:", payload.max_tokens);
console.log(" 🎯 Top P:", payload.top_p);
console.log(" 🔄 Frequency Penalty:", payload.frequency_penalty);
console.log(" 👤 Presence Penalty:", payload.presence_penalty);
console.log("\n🎭 4. PROMPT SYSTÈME GÉNÉRÉ:");
const systemMessage = payload.messages.find(m => m.role === "system");
if (systemMessage) {
console.log(" 📝 Longueur du prompt:", systemMessage.content.length, "caractères");
console.log(" 📄 CONTENU COMPLET DU PROMPT:");
console.log(" " + "─".repeat(80));
// Imprimer chaque ligne avec indentation
systemMessage.content.split(/\n/).forEach(l => console.log(" " + l));
console.log(" " + "─".repeat(80));
}
console.log("\n💬 5. CONTEXTE DE CONVERSATION:");
console.log(" 📊 Nombre total de messages:", payload.messages.length);
console.log(" 📋 Détail des messages:");
payload.messages.forEach((msg, index) => {
if (msg.role === "system") {
console.log(` [${index}] 🎭 SYSTEM: ${msg.content.length} caractères`);
} else if (msg.role === "user") {
console.log(` [${index}] 👤 USER: "${msg.content}"`);
} else if (msg.role === "assistant") {
console.log(` [${index}] 🤖 ASSISTANT: "${msg.content.substring(0, 120)}..."`);
}
});
const payloadSize = JSON.stringify(payload).length;
console.log("\n📦 6. TAILLE DU PAYLOAD:");
console.log(" 📝 Taille totale:", payloadSize, "caractères");
console.log(" 💾 Taille en KB:", Math.round((payloadSize / 1024) * 100) / 100, "KB");
console.log("\n🚀 Envoi en cours vers l'API...");
console.log("╔═══════════════════════════════════════════════════════════════════╗");
}
// ===== FIN AUDIT =====
if (window.DEBUG_SAFE_LOGS) {
console.debug("LLM payload meta:", {
model: payload.model,
temperature: payload.temperature,
max_tokens: payload.max_tokens
});
}
try {
// Basic retry with exponential backoff and jitter for 429/5xx
const maxAttempts = 3;
let attempt = 0;
let response;
while (attempt < maxAttempts) {
attempt++;
response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": window.location.origin,
"X-Title": "Kimi - Virtual Companion"
},
body: JSON.stringify(payload)
});
if (response.ok) break;
if (response.status === 429 || response.status >= 500) {
const base = 400;
const delay = base * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 200);
await new Promise(r => setTimeout(r, delay));
continue;
}
break;
}
if (!response.ok) {
let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
let suggestions = [];
try {
const errorData = await response.json();
if (errorData.error) {
errorMessage = errorData.error.message || errorData.error.code || errorMessage;
// More explicit error messages with suggestions
if (response.status === 422) {
errorMessage = `Model \"${this.currentModel}\" not available on OpenRouter.`;
// Refresh available models from API and try best match once
try {
await this.refreshRemoteModels();
const best = this.findBestMatchingModelId(this.currentModel);
if (best && best !== this.currentModel) {
// Try once with corrected model
this.currentModel = best;
await this.db.setPreference("llmModelId", best);
this._notifyModelChanged();
const retryResponse = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": window.location.origin,
"X-Title": "Kimi - Virtual Companion"
},
body: JSON.stringify({ ...payload, model: best })
});
if (retryResponse.ok) {
const retryData = await retryResponse.json();
const kimiResponse = retryData.choices?.[0]?.message?.content;
if (!kimiResponse) throw new Error("Invalid API response - no content generated");
this.conversationContext.push(
{ role: "user", content: userMessage, timestamp: new Date().toISOString() },
{ role: "assistant", content: kimiResponse, timestamp: new Date().toISOString() }
);
if (this.conversationContext.length > this.maxContextLength * 2) {
this.conversationContext = this.conversationContext.slice(-this.maxContextLength * 2);
}
return kimiResponse;
}
}
} catch (e) {
// Swallow refresh errors; will fall through to standard error handling
}
} else if (response.status === 401) {
errorMessage = "Invalid API key. Check your OpenRouter key in the settings.";
} else if (response.status === 429) {
errorMessage = "Rate limit reached. Please wait a moment before trying again.";
} else if (response.status === 402) {
errorMessage = "Insufficient credit on your OpenRouter account.";
}
}
} catch (parseError) {
console.warn("Unable to parse API error:", parseError);
}
console.error(`OpenRouter API error (${response.status}):`, errorMessage);
// Add suggestions to the error if available
const error = new Error(errorMessage);
if (suggestions.length > 0) {
error.suggestions = suggestions;
}
throw error;
}
const data = await response.json();
if (!data.choices || !data.choices[0] || !data.choices[0].message) {
throw new Error("Invalid API response - no content generated");
}
const kimiResponse = data.choices[0].message.content;
// Add to context
this.conversationContext.push(
{ role: "user", content: userMessage, timestamp: new Date().toISOString() },
{ role: "assistant", content: kimiResponse, timestamp: new Date().toISOString() }
);
// Limit context size
if (this.conversationContext.length > this.maxContextLength * 2) {
this.conversationContext = this.conversationContext.slice(-this.maxContextLength * 2);
}
// Token usage estimation (deferred save)
try {
const est = window.KimiTokenUtils?.estimate || (t => Math.ceil((t || "").length / 4));
const tokensIn = est(userMessage + " " + systemPromptContent);
const tokensOut = est(kimiResponse);
window._lastKimiTokenUsage = { tokensIn, tokensOut };
if (!window.kimiMemory && this.db) {
const character = await this.db.getSelectedCharacter();
const prevIn = Number(await this.db.getPreference(`totalTokensIn_${character}`, 0)) || 0;
const prevOut = Number(await this.db.getPreference(`totalTokensOut_${character}`, 0)) || 0;
await this.db.setPreference(`totalTokensIn_${character}`, prevIn + tokensIn);
await this.db.setPreference(`totalTokensOut_${character}`, prevOut + tokensOut);
}
} catch (e) {
console.warn("Token usage estimation failed (OpenRouter):", e);
}
return kimiResponse;
} catch (networkError) {
if (networkError.name === "TypeError" && networkError.message.includes("fetch")) {
throw new Error("Network connection error. Check your internet connection.");
}
throw networkError;
}
}
async chatWithLocal(userMessage, options = {}) {
try {
const selectedLanguage = await this.db.getPreference("selectedLanguage", "en");
let languageInstruction = ""; // placeholder (language guidance is included in assembled prompt)
let systemPromptContent = await this.assemblePrompt(userMessage);
if (window.KIMI_DEBUG_API_AUDIT) {
console.log("===== FULL SYSTEM PROMPT (Local) =====\n" + systemPromptContent + "\n===== END SYSTEM PROMPT =====");
}
const response = await fetch("http://localhost:11434/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "gemma-3n-E4B-it-Q4_K_M.gguf",
messages: [
{ role: "system", content: systemPromptContent },
{ role: "user", content: userMessage }
],
stream: false
})
});
if (!response.ok) {
throw new Error("Ollama not available");
}
const data = await response.json();
const content = data?.message?.content || data?.choices?.[0]?.message?.content || "";
if (!content) throw new Error("Local model returned empty response");
// Add to context like other providers
this.conversationContext.push(
{ role: "user", content: userMessage, timestamp: new Date().toISOString() },
{ role: "assistant", content: content, timestamp: new Date().toISOString() }
);
if (this.conversationContext.length > this.maxContextLength * 2) {
this.conversationContext = this.conversationContext.slice(-this.maxContextLength * 2);
}
// Estimate token usage for local model (heuristic)
try {
const est = window.KimiTokenUtils?.estimate || (t => Math.ceil((t || "").length / 4));
const tokensIn = est(userMessage + " " + systemPromptContent);
const tokensOut = est(content);
window._lastKimiTokenUsage = { tokensIn, tokensOut };
const character = await this.db.getSelectedCharacter();
const prevIn = Number(await this.db.getPreference(`totalTokensIn_${character}`, 0)) || 0;
const prevOut = Number(await this.db.getPreference(`totalTokensOut_${character}`, 0)) || 0;
await this.db.setPreference(`totalTokensIn_${character}`, prevIn + tokensIn);
await this.db.setPreference(`totalTokensOut_${character}`, prevOut + tokensOut);
} catch (e) {
console.warn("Token usage estimation failed (local):", e);
}
return content;
} catch (error) {
console.warn("Local LLM not available:", error);
return this.getFallbackResponse(userMessage);
}
}
// ===== STREAMING METHODS =====
async chatWithOpenRouterStreaming(userMessage, onToken, options = {}) {
const provider = await this.db.getPreference("llmProvider", "openrouter");
const apiKey = await (window.KimiProviderUtils
? window.KimiProviderUtils.getApiKey(this.db, provider)
: this.db.getPreference("providerApiKey"));
if (!apiKey) {
throw new Error("OpenRouter API key not configured");
}
const systemPromptContent = await this.assemblePrompt(userMessage);
const messages = [
{ role: "system", content: systemPromptContent },
...this.conversationContext.slice(-this.maxContextLength),
{ role: "user", content: userMessage }
];
// Get unified defaults and options
const unifiedDefaults = window.getUnifiedDefaults
? window.getUnifiedDefaults()
: { temperature: 0.9, maxTokens: 400, top_p: 0.9, frequency_penalty: 0.9, presence_penalty: 0.8 };
const enableStreaming = await this.db.getPreference("enableStreaming", true);
const llmSettings = {
temperature: await this.db.getPreference("llmTemperature", unifiedDefaults.temperature),
maxTokens: await this.db.getPreference("llmMaxTokens", unifiedDefaults.maxTokens),
top_p: await this.db.getPreference("llmTopP", unifiedDefaults.top_p),
frequency_penalty: await this.db.getPreference("llmFrequencyPenalty", unifiedDefaults.frequency_penalty),
presence_penalty: await this.db.getPreference("llmPresencePenalty", unifiedDefaults.presence_penalty)
};
const payload = {
model: this.currentModel,
messages: messages,
stream: enableStreaming, // Use user preference for streaming
temperature: typeof options.temperature === "number" ? options.temperature : llmSettings.temperature,
max_tokens: typeof options.maxTokens === "number" ? options.maxTokens : llmSettings.maxTokens,
top_p: typeof options.topP === "number" ? options.topP : llmSettings.top_p,
frequency_penalty:
typeof options.frequencyPenalty === "number" ? options.frequencyPenalty : llmSettings.frequency_penalty,
presence_penalty: typeof options.presencePenalty === "number" ? options.presencePenalty : llmSettings.presence_penalty
};
try {
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": window.location.origin,
"X-Title": "Kimi - Virtual Companion"
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let fullResponse = "";
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || ""; // Keep incomplete line in buffer
for (const line of lines) {
if (line.trim() === "" || line.startsWith(":")) continue; // Skip empty lines and comments
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data === "[DONE]") {
break;
}
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
fullResponse += content;
onToken(content);
}
} catch (parseError) {
console.warn("Failed to parse streaming chunk:", parseError);
}
}
}
}
} finally {
reader.releaseLock();
}
// Add to context after streaming completes
this.conversationContext.push(
{ role: "user", content: userMessage, timestamp: new Date().toISOString() },
{ role: "assistant", content: fullResponse, timestamp: new Date().toISOString() }
);
if (this.conversationContext.length > this.maxContextLength * 2) {
this.conversationContext = this.conversationContext.slice(-this.maxContextLength * 2);
}
// Token usage estimation
try {
const est = window.KimiTokenUtils?.estimate || (t => Math.ceil((t || "").length / 4));
const tokensIn = est(userMessage + " " + systemPromptContent);
const tokensOut = est(fullResponse);
window._lastKimiTokenUsage = { tokensIn, tokensOut };
if (!window.kimiMemory && this.db) {
const character = await this.db.getSelectedCharacter();
const prevIn = Number(await this.db.getPreference(`totalTokensIn_${character}`, 0)) || 0;
const prevOut = Number(await this.db.getPreference(`totalTokensOut_${character}`, 0)) || 0;
await this.db.setPreference(`totalTokensIn_${character}`, prevIn + tokensIn);
await this.db.setPreference(`totalTokensOut_${character}`, prevOut + tokensOut);
}
} catch (e) {
console.warn("Token usage estimation failed (OpenRouter streaming):", e);
}
return fullResponse;
} catch (error) {
console.error("OpenRouter streaming error:", error);
throw error;
}
}
async chatWithOpenAICompatibleStreaming(userMessage, onToken, options = {}) {
const provider = await this.db.getPreference("llmProvider", "openrouter");
let baseUrl;
if (provider === "openai-compatible" || provider === "ollama") {
baseUrl = await this.db.getPreference(
`llmBaseUrl_${provider}`,
provider === "ollama" ? "http://localhost:11434/api/chat" : ""
);
} else {
const sharedPlaceholders = window.KimiProviderPlaceholders || {};
baseUrl =
sharedPlaceholders[provider] || sharedPlaceholders.openrouter || "https://openrouter.ai/api/v1/chat/completions";
}
const apiKey = window.KimiProviderUtils
? await window.KimiProviderUtils.getApiKey(this.db, provider)
: await this.db.getPreference("providerApiKey", "");
if (!apiKey) {
throw new Error("API key not configured for selected provider");
}
const systemPromptContent = await this.assemblePrompt(userMessage);
const messages = [
{ role: "system", content: systemPromptContent },
...this.conversationContext.slice(-this.maxContextLength),
{ role: "user", content: userMessage }
];
const unifiedDefaults = window.getUnifiedDefaults
? window.getUnifiedDefaults()
: { temperature: 0.9, maxTokens: 400, top_p: 0.9, frequency_penalty: 0.9, presence_penalty: 0.8 };
const enableStreaming = await this.db.getPreference("enableStreaming", true);
const llmSettings = {
temperature: await this.db.getPreference("llmTemperature", unifiedDefaults.temperature),
maxTokens: await this.db.getPreference("llmMaxTokens", unifiedDefaults.maxTokens),
top_p: await this.db.getPreference("llmTopP", unifiedDefaults.top_p),
frequency_penalty: await this.db.getPreference("llmFrequencyPenalty", unifiedDefaults.frequency_penalty),
presence_penalty: await this.db.getPreference("llmPresencePenalty", unifiedDefaults.presence_penalty)
};
const payload = {
model: this.currentModel,
messages: messages,
stream: enableStreaming,
temperature: typeof options.temperature === "number" ? options.temperature : llmSettings.temperature,
max_tokens: typeof options.maxTokens === "number" ? options.maxTokens : llmSettings.maxTokens,
top_p: typeof options.topP === "number" ? options.topP : llmSettings.top_p,
frequency_penalty:
typeof options.frequencyPenalty === "number" ? options.frequencyPenalty : llmSettings.frequency_penalty,
presence_penalty: typeof options.presencePenalty === "number" ? options.presencePenalty : llmSettings.presence_penalty
};
try {
const response = await fetch(baseUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let fullResponse = "";
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (line.trim() === "" || line.startsWith(":")) continue;
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data === "[DONE]") {
break;
}
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
fullResponse += content;
onToken(content);
}
} catch (parseError) {
console.warn("Failed to parse streaming chunk:", parseError);
}
}
}
}
} finally {
reader.releaseLock();
}
// Add to context
this.conversationContext.push(
{ role: "user", content: userMessage, timestamp: new Date().toISOString() },
{ role: "assistant", content: fullResponse, timestamp: new Date().toISOString() }
);
if (this.conversationContext.length > this.maxContextLength * 2) {
this.conversationContext = this.conversationContext.slice(-this.maxContextLength * 2);
}
// Token usage estimation
try {
const est = window.KimiTokenUtils?.estimate || (t => Math.ceil((t || "").length / 4));
const tokensIn = est(userMessage + " " + systemPromptContent);
const tokensOut = est(fullResponse);
window._lastKimiTokenUsage = { tokensIn, tokensOut };
if (!window.kimiMemory && this.db) {
const character = await this.db.getSelectedCharacter();
const prevIn = Number(await this.db.getPreference(`totalTokensIn_${character}`, 0)) || 0;
const prevOut = Number(await this.db.getPreference(`totalTokensOut_${character}`, 0)) || 0;
await this.db.setPreference(`totalTokensIn_${character}`, prevIn + tokensIn);
await this.db.setPreference(`totalTokensOut_${character}`, prevOut + tokensOut);
}
} catch (e) {
console.warn("Token usage estimation failed (OpenAI streaming):", e);
}
return fullResponse;
} catch (error) {
console.error("OpenAI compatible streaming error:", error);
throw error;
}
}
async chatWithLocalStreaming(userMessage, onToken, options = {}) {
const systemPromptContent = await this.assemblePrompt(userMessage);
const enableStreaming = await this.db.getPreference("enableStreaming", true);
const payload = {
model: this.currentModel || "llama2",
messages: [
{ role: "system", content: systemPromptContent },
...this.conversationContext.slice(-this.maxContextLength),
{ role: "user", content: userMessage }
],
stream: enableStreaming
};
try {
const response = await fetch("http://localhost:11434/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error("Ollama not available");
}
let fullResponse = "";
if (enableStreaming) {
// Streaming mode
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split("\n").filter(line => line.trim());
for (const line of lines) {
try {
const parsed = JSON.parse(line);
const content = parsed.message?.content;
if (content) {
fullResponse += content;
onToken(content);
}
if (parsed.done) {
break;
}
} catch (parseError) {
console.warn("Failed to parse Ollama streaming chunk:", parseError);
}
}
}
} finally {
reader.releaseLock();
}
} else {
// Non-streaming mode
const data = await response.json();
fullResponse = data.message?.content || "";
if (fullResponse && onToken) {
onToken(fullResponse);
}
}
// Add to context
this.conversationContext.push(
{ role: "user", content: userMessage, timestamp: new Date().toISOString() },
{ role: "assistant", content: fullResponse, timestamp: new Date().toISOString() }
);
if (this.conversationContext.length > this.maxContextLength * 2) {
this.conversationContext = this.conversationContext.slice(-this.maxContextLength * 2);
}
// Token usage estimation
try {
const est = window.KimiTokenUtils?.estimate || (t => Math.ceil((t || "").length / 4));
const tokensIn = est(userMessage + " " + systemPromptContent);
const tokensOut = est(fullResponse);
window._lastKimiTokenUsage = { tokensIn, tokensOut };
const character = await this.db.getSelectedCharacter();
const prevIn = Number(await this.db.getPreference(`totalTokensIn_${character}`, 0)) || 0;
const prevOut = Number(await this.db.getPreference(`totalTokensOut_${character}`, 0)) || 0;
await this.db.setPreference(`totalTokensIn_${character}`, prevIn + tokensIn);
await this.db.setPreference(`totalTokensOut_${character}`, prevOut + tokensOut);
} catch (e) {
console.warn("Token usage estimation failed (local streaming):", e);
}
return fullResponse;
} catch (error) {
console.warn("Local LLM streaming not available:", error);
throw error;
}
}
getFallbackResponse(userMessage, errorType = "api") {
// Use centralized fallback manager instead of duplicated logic
if (window.KimiFallbackManager) {
// Map error types to the correct format
const errorTypeMap = {
api: "api_error",
model: "model_error",
network: "network_error"
};
const mappedType = errorTypeMap[errorType] || "technical_error";
return window.KimiFallbackManager.getFallbackMessage(mappedType);
}
// Fallback to legacy system if KimiFallbackManager not available
const i18n = window.kimiI18nManager;
if (!i18n) {
return "Sorry, I'm having technical difficulties! 💕";
}
return i18n.t("fallback_technical_error");
}
getFallbackKeywords(trait, type) {
const keywords = {
humor: {
positive: ["funny", "hilarious", "joke", "laugh", "amusing", "humorous", "smile", "witty", "playful"],
negative: ["boring", "sad", "serious", "cold", "dry", "depressing", "gloomy"]
},
intelligence: {
positive: [
"intelligent",
"smart",
"brilliant",
"logical",
"clever",
"wise",
"genius",
"thoughtful",
"insightful"
],
negative: ["stupid", "dumb", "foolish", "slow", "naive", "ignorant", "simple"]
},
romance: {
positive: ["cuddle", "love", "romantic", "kiss", "tenderness", "passion", "charming", "adorable", "sweet"],
negative: ["cold", "distant", "indifferent", "rejection", "loneliness", "breakup", "sad"]
},
affection: {
positive: ["affection", "tenderness", "close", "warmth", "kind", "caring", "cuddle", "love", "adore"],
negative: ["mean", "cold", "indifferent", "distant", "rejection", "hate", "hostile"]
},
playfulness: {
positive: ["play", "game", "tease", "mischievous", "fun", "amusing", "playful", "joke", "frolic"],
negative: ["serious", "boring", "strict", "rigid", "monotonous", "tedious"]
},
empathy: {
positive: ["listen", "understand", "empathy", "support", "help", "comfort", "compassion", "caring", "kindness"],
negative: ["indifferent", "cold", "selfish", "ignore", "despise", "hostile", "uncaring"]
}
};
return keywords[trait]?.[type] || [];
}
// Mémoire temporaire pour l'accumulation négative par trait
_negativeStreaks = {};
async updatePersonalityFromResponse(userMessage, kimiResponse) {
// Use unified emotion system for personality updates
if (window.kimiEmotionSystem) {
return await window.kimiEmotionSystem.updatePersonalityFromConversation(
userMessage,
kimiResponse,
await this.db.getSelectedCharacter()
);
}
// Legacy fallback (should not be reached)
console.warn("Unified emotion system not available, skipping personality update");
}
async getModelStats() {
const models = await this.db.getAllLLMModels();
const currentModelInfo = this.availableModels[this.currentModel];
return {
current: {
id: this.currentModel,
info: currentModelInfo
},
available: this.availableModels,
configured: models,
contextLength: this.conversationContext.length
};
}
async testModel(modelId, testMessage = "Test API ok?") {
// Ancienne méthode de test (non minimaliste)
return await this.testApiKeyMinimal(modelId);
}
/**
* Test API minimaliste et centralisé pour tous les providers compatibles.
* Envoie uniquement un prompt système court et un message utilisateur dans la langue choisie.
* Aucun contexte, aucune mémoire, aucun paramètre superflu.
* @param {string} modelId - ID du modèle à tester
* @returns {Promise<{success: boolean, response?: string, error?: string}>}
*/
async testApiKeyMinimal(modelId) {
const originalModel = this.currentModel;
try {
await this.setCurrentModel(modelId);
const provider = await this.db.getPreference("llmProvider", "openrouter");
const lang = await this.db.getPreference("selectedLanguage", "en");
let testWord;
switch (lang) {
case "fr":
testWord = "Bonjour";
break;
case "es":
testWord = "Hola";
break;
case "de":
testWord = "Hallo";
break;
case "it":
testWord = "Ciao";
break;
case "ja":
testWord = "こんにちは";
break;
case "zh":
testWord = "你好";
break;
default:
testWord = "Hello";
}
const systemPrompt = "You are a helpful assistant.";
let apiKey = await (window.KimiProviderUtils
? window.KimiProviderUtils.getApiKey(this.db, provider)
: this.db.getPreference("providerApiKey"));
if (!apiKey) {
return { success: false, error: "No API key found for provider: " + provider };
}
let baseUrl = "";
let payload = {
model: modelId,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: testWord }
],
max_tokens: 2
};
let headers = { "Content-Type": "application/json" };
if (provider === "openrouter") {
baseUrl = "https://openrouter.ai/api/v1/chat/completions";
headers["Authorization"] = `Bearer ${apiKey}`;
headers["HTTP-Referer"] = window.location.origin;
headers["X-Title"] = "Kimi - Virtual Companion";
} else if (["openai", "groq", "together", "deepseek", "openai-compatible"].includes(provider)) {
// When selecting baseUrl during initialization/fallback, respect provider-specific stored URLs
const currentProvider = await this.db.getPreference("llmProvider", "openrouter");
if (currentProvider === "openai-compatible" || currentProvider === "ollama") {
baseUrl = await this.db.getPreference(
`llmBaseUrl_${currentProvider}`,
currentProvider === "ollama" ? "http://localhost:11434/api/chat" : ""
);
} else {
const sharedPlaceholders = window.KimiProviderPlaceholders || {};
baseUrl =
sharedPlaceholders[provider] ||
sharedPlaceholders.openrouter ||
"https://openrouter.ai/api/v1/chat/completions";
}
headers["Authorization"] = `Bearer ${apiKey}`;
} else if (provider === "ollama") {
baseUrl = "http://localhost:11434/api/chat";
payload = {
model: modelId,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: testWord }
],
stream: false
};
} else {
throw new Error("Unknown provider: " + provider);
}
const response = await fetch(baseUrl, {
method: "POST",
headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
const error = await response.text();
return { success: false, error };
}
const data = await response.json();
let content = "";
if (provider === "ollama") {
content = data?.message?.content || data?.choices?.[0]?.message?.content || "";
} else {
content = data?.choices?.[0]?.message?.content || "";
}
return { success: true, response: content };
} catch (error) {
return { success: false, error: error.message };
} finally {
await this.setCurrentModel(originalModel);
}
}
// Complete model diagnosis
async diagnoseModel(modelId) {
const model = this.availableModels[modelId];
if (!model) {
return {
available: false,
error: "Model not found in local list"
};
}
// Check availability on OpenRouter
try {
// Model availability is checked against the local cache; remote checks occur in refreshRemoteModels()
return {
available: true,
model: model,
pricing: model.pricing
};
} catch (error) {
return {
available: false,
error: `Unable to check: ${error.message}`
};
}
}
// Fetch models from OpenRouter API and merge into availableModels
async refreshRemoteModels() {
if (this._isRefreshingModels) return;
this._isRefreshingModels = true;
try {
const provider = await this.db.getPreference("llmProvider", "openrouter");
const apiKey = await (window.KimiProviderUtils
? window.KimiProviderUtils.getApiKey(this.db, provider)
: this.db.getPreference("providerApiKey", ""));
const res = await fetch("https://openrouter.ai/api/v1/models", {
method: "GET",
headers: {
"Content-Type": "application/json",
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
"HTTP-Referer": window.location.origin,
"X-Title": "Kimi - Virtual Companion"
}
});
if (!res.ok) {
throw new Error(`Unable to fetch models: HTTP ${res.status}`);
}
const data = await res.json();
if (!data?.data || !Array.isArray(data.data)) {
throw new Error("Invalid models response format");
}
// Build a fresh map while preserving local/ollama entry
const newMap = {};
data.data.forEach(m => {
if (!m?.id) return;
const id = m.id;
const provider = m?.id?.split("/")?.[0] || "OpenRouter";
let pricing;
const p = m?.pricing;
if (p) {
const unitRaw = ((p.unit || p.per || p.units || "") + "").toLowerCase();
let unitTokens = 1;
if (unitRaw) {
if (unitRaw.includes("1m")) unitTokens = 1000000;
else if (unitRaw.includes("1k") || unitRaw.includes("thousand")) unitTokens = 1000;
else {
const num = parseFloat(unitRaw.replace(/[^0-9.]/g, ""));
if (Number.isFinite(num) && num > 0) {
if (unitRaw.includes("m")) unitTokens = num * 1000000;
else if (unitRaw.includes("k")) unitTokens = num * 1000;
else unitTokens = num;
} else if (unitRaw.includes("token")) {
unitTokens = 1;
}
}
}
const toPerMillion = v => {
const n = typeof v === "number" ? v : parseFloat(v);
if (!Number.isFinite(n)) return undefined;
return n * (1000000 / unitTokens);
};
if (typeof p.input !== "undefined" || typeof p.output !== "undefined") {
pricing = {
input: toPerMillion(p.input),
output: toPerMillion(p.output)
};
} else if (typeof p.prompt !== "undefined" || typeof p.completion !== "undefined") {
pricing = {
input: toPerMillion(p.prompt),
output: toPerMillion(p.completion)
};
} else {
pricing = { input: undefined, output: undefined };
}
} else {
pricing = { input: undefined, output: undefined };
}
newMap[id] = {
name: m.name || id,
provider,
type: "openrouter",
contextWindow: m.context_length || m?.context_window || 128000,
pricing,
strengths: (m?.tags || []).slice(0, 4)
};
});
// Keep local model entry
if (this.availableModels["local/ollama"]) {
newMap["local/ollama"] = this.availableModels["local/ollama"];
}
this.recommendedModelIds.forEach(id => {
const curated = this.defaultModels[id];
if (curated) {
newMap[id] = { ...(newMap[id] || {}), ...curated };
}
});
this.availableModels = newMap;
this._remoteModelsLoaded = true;
} finally {
this._isRefreshingModels = false;
}
}
// Try to find best matching model id from remote list when an ID is stale
findBestMatchingModelId(preferredId) {
if (this.availableModels[preferredId]) return preferredId;
const id = (preferredId || "").toLowerCase();
const tokens = id.split(/[\/:\-_.]+/).filter(Boolean);
let best = null;
let bestScore = -1;
Object.keys(this.availableModels).forEach(candidateId => {
const c = candidateId.toLowerCase();
let score = 0;
tokens.forEach(t => {
if (!t) return;
if (c.includes(t)) score += 1;
});
// Give extra weight to common markers
if (c.includes("instruct")) score += 0.5;
if (c.includes("mistral") && id.includes("mistral")) score += 0.5;
if (c.includes("small") && id.includes("small")) score += 0.5;
if (score > bestScore) {
bestScore = score;
best = candidateId;
}
});
// Avoid returning unrelated local model unless nothing else
if (best === "local/ollama" && Object.keys(this.availableModels).length > 1) {
return null;
}
return best;
}
_notifyModelChanged() {
try {
const detail = { id: this.currentModel };
if (typeof window !== "undefined" && typeof window.dispatchEvent === "function") {
window.dispatchEvent(new CustomEvent("llmModelChanged", { detail }));
}
} catch (e) {}
}
}
// Export for usage
window.KimiLLMManager = KimiLLMManager;
export default KimiLLMManager;
|