Files
sillytavern-rts-mode/src/LLMAdapter.js
T
2025-08-03 17:35:34 -07:00

54 lines
1.8 KiB
JavaScript

import GameStateManager from './GameStateManager.js';
import { buildPrompt } from './PromptCompressor.js';
/**
* Extracts the first JSON code block from a string.
* @param {string} text The text to search.
* @returns {object|null} The parsed JSON object or null if not found.
*/
function extractJson(text) {
const match = /```json\n([\s\S]+?)\n```/.exec(text);
if (match && match[1]) {
try {
return JSON.parse(match[1]);
} catch (error) {
console.error('RTS-Mode: Failed to parse JSON from LLM response.', error);
return null;
}
}
return null;
}
/**
* Sends the user's command to the LLM and processes the turn.
* @param {string} userCmd The user's command.
*/
export async function sendTurn(userCmd) {
try {
const stateJSON = GameStateManager.toCompressedJSON();
const prompt = buildPrompt(stateJSON, userCmd);
// Using SillyTavern's built-in LLM broker
const reply = await window.LLMBroker.generate(prompt);
if (!reply) {
throw new Error('LLM returned an empty response.');
}
const diff = extractJson(reply);
if (diff) {
GameStateManager.applyDiff(diff);
// For now, log the narrative part to the console.
const narrative = reply.replace(/```json\n[\s\S]+?\n```/, '').trim();
console.log('RTS Narrative:', narrative);
} else {
console.warn('RTS-Mode: No valid JSON diff found in LLM response.');
// Log the raw reply for debugging.
console.log('Raw LLM Response:', reply);
}
} catch (error) {
console.error('RTS-Mode: Error during sendTurn:', error);
// Optionally, display an alert to the user.
alert(`RTS-Mode Error: ${error.message}`);
}
}