src / promptPreprocessor.ts
import {
type ChatMessage,
type PromptPreprocessorController,
} from "@lmstudio/sdk";
import { configSchematics } from "./config";
import { translate } from "./translate";
export async function preprocess(
ctl: PromptPreprocessorController,
userMessage: ChatMessage,
): Promise<ChatMessage> {
// Pull the plugin settings
const pluginConfig = ctl.getPluginConfig(configSchematics);
let sourceLanguage = pluginConfig.get("sourceLanguage");
const targetLang = pluginConfig.get("targetLanguage");
const model = pluginConfig.get("model");
if (!model) {
ctl.debug("[Translate] Model not configured – skipping translation.");
return userMessage; // nothing to do
}
const text = userMessage.getText();
try {
// If it's already in target language, skip translating
if (sourceLanguage === targetLang) return userMessage;
// Translate to target language
const translated = await translate(
ctl,
model,
sourceLanguage,
targetLang,
text
);
ctl.debug("[Translate] End translation.");
// Create a new message that carries the same metadata but with translated text
userMessage.replaceText(translated);
} catch (e: any) {
ctl.debug(`[Translate] Translation error: ${e.message}`);
}
return userMessage;
}