Skip to content

Commit bfbe65d

Browse files
authored
Merge pull request #7940 from sagemathinc/llm-translate
translate LLM responses to user's language
2 parents 2e911b0 + cbc4609 commit bfbe65d

File tree

20 files changed

+63
-2
lines changed

20 files changed

+63
-2
lines changed

src/packages/frontend/account/other-settings.tsx

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { FormattedMessage, useIntl } from "react-intl";
99

1010
import { Checkbox, Panel } from "@cocalc/frontend/antd-bootstrap";
1111
import { Rendered, redux, useTypedRedux } from "@cocalc/frontend/app-framework";
12+
import { useLocalizationCtx } from "@cocalc/frontend/app/localize";
1213
import {
1314
A,
1415
HelpIcon,
@@ -22,7 +23,7 @@ import {
2223
import AIAvatar from "@cocalc/frontend/components/ai-avatar";
2324
import { IS_MOBILE, IS_TOUCH } from "@cocalc/frontend/feature";
2425
import LLMSelector from "@cocalc/frontend/frame-editors/llm/llm-selector";
25-
import { labels } from "@cocalc/frontend/i18n";
26+
import { LOCALIZATIONS, labels } from "@cocalc/frontend/i18n";
2627
import {
2728
VBAR_EXPLANATION,
2829
VBAR_KEY,
@@ -33,6 +34,7 @@ import { NewFilenameFamilies } from "@cocalc/frontend/project/utils";
3334
import track from "@cocalc/frontend/user-tracking";
3435
import { webapp_client } from "@cocalc/frontend/webapp-client";
3536
import { DEFAULT_NEW_FILENAMES, NEW_FILENAMES } from "@cocalc/util/db-schema";
37+
import { OTHER_SETTINGS_REPLY_ENGLISH_KEY } from "@cocalc/util/i18n/const";
3638
import { dark_mode_mins, get_dark_mode_config } from "./dark-mode";
3739
import { I18NSelector, I18N_MESSAGE, I18N_TITLE } from "./i18n-selector";
3840
import Tours from "./tours";
@@ -60,6 +62,7 @@ interface Props {
6062

6163
export function OtherSettings(props: Readonly<Props>): JSX.Element {
6264
const intl = useIntl();
65+
const { locale } = useLocalizationCtx();
6366
const isCoCalcCom = useTypedRedux("customize", "is_cocalc_com");
6467
const user_defined_llm = useTypedRedux("customize", "user_defined_llm");
6568

@@ -552,6 +555,24 @@ export function OtherSettings(props: Readonly<Props>): JSX.Element {
552555
);
553556
}
554557

558+
function render_llm_reply_language(): Rendered {
559+
return (
560+
<Checkbox
561+
checked={!!props.other_settings.get(OTHER_SETTINGS_REPLY_ENGLISH_KEY)}
562+
onChange={(e) => {
563+
on_change(OTHER_SETTINGS_REPLY_ENGLISH_KEY, e.target.checked);
564+
}}
565+
>
566+
<FormattedMessage
567+
id="account.other-settings.llm.reply_language"
568+
defaultMessage={`<strong>Always reply in English:</strong>
569+
If set, the replies are always in English. Otherwise, it replies in your language ({lang}).`}
570+
values={{ lang: intl.formatMessage(LOCALIZATIONS[locale].trans) }}
571+
/>
572+
</Checkbox>
573+
);
574+
}
575+
555576
function render_custom_llm(): Rendered {
556577
// on cocalc.com, do not even show that they're disabled
557578
if (isCoCalcCom && !user_defined_llm) return;
@@ -578,6 +599,7 @@ export function OtherSettings(props: Readonly<Props>): JSX.Element {
578599
>
579600
{render_disable_all_llm()}
580601
{render_language_model()}
602+
{render_llm_reply_language()}
581603
{render_custom_llm()}
582604
</Panel>
583605
);

src/packages/frontend/account/types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
OTHER_SETTINGS_USERDEFINED_LLM,
1515
} from "@cocalc/util/db-schema/defaults";
1616
import { LanguageModel } from "@cocalc/util/db-schema/llm-utils";
17+
import { OTHER_SETTINGS_REPLY_ENGLISH_KEY } from "@cocalc/util/i18n/const";
1718
import { PassportStrategyFrontend } from "@cocalc/util/types/passport-types";
1819
import { SETTINGS_LANGUAGE_MODEL_KEY } from "./useLanguageModelSetting";
1920

@@ -50,6 +51,7 @@ export interface AccountState {
5051
news_read_until: number; // JavaScript timestamp in milliseconds
5152
[OTHER_SETTINGS_USERDEFINED_LLM]: string; // string is JSON: CustomLLM[]
5253
[OTHER_SETTINGS_LOCALE_KEY]?: string;
54+
[OTHER_SETTINGS_REPLY_ENGLISH_KEY]?: string;
5355
}>;
5456
stripe_customer?: TypedMap<{
5557
subscriptions: { data: Map<string, any> };

src/packages/frontend/client/llm.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ import {
2424
import * as message from "@cocalc/util/message";
2525
import type { WebappClient } from "./client";
2626
import type { History } from "./types";
27+
import {
28+
LOCALIZATIONS,
29+
OTHER_SETTINGS_LOCALE_KEY,
30+
OTHER_SETTINGS_REPLY_ENGLISH_KEY,
31+
} from "@cocalc/util/i18n/const";
32+
import { sanitizeLocale } from "@cocalc/frontend/i18n";
2733

2834
interface QueryLLMProps {
2935
input: string;
@@ -111,6 +117,19 @@ export class LLMClient {
111117
}
112118
}
113119

120+
// append a sentence to request to translate the output to the user's language – unless disabled
121+
const other_settings = redux.getStore("account").get("other_settings");
122+
const alwaysEnglish = !!other_settings.get(
123+
OTHER_SETTINGS_REPLY_ENGLISH_KEY,
124+
);
125+
const locale = sanitizeLocale(
126+
other_settings.get(OTHER_SETTINGS_LOCALE_KEY),
127+
);
128+
if (!alwaysEnglish && locale != "en") {
129+
const lang = LOCALIZATIONS[locale].name; // name is always in english
130+
system = `${system}\n\nYour answer must be written in the language ${lang}.`;
131+
}
132+
114133
const is_cocalc_com = redux.getStore("customize").get("is_cocalc_com");
115134

116135
if (!isFreeModel(model, is_cocalc_com)) {

src/packages/frontend/i18n/trans/ar_EG.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"account.other-settings.katex": "<strong>KaTeX:</strong> محاولة عرض الصيغ باستخدام {katex} (أسرع بكثير، ولكن بدون خيارات قائمة السياق)",
4747
"account.other-settings.llm.default_llm": "نموذج اللغة الافتراضي AI",
4848
"account.other-settings.llm.disable_all": "<strong>تعطيل جميع تكاملات الذكاء الاصطناعي</strong>، مثل أزرار توليد أو شرح الأكواد في Jupyter، وذكر @chatgpt، إلخ.",
49+
"account.other-settings.llm.reply_language": "<strong>الرد دائمًا باللغة الإنجليزية:</strong> إذا تم التعيين، تكون الردود دائمًا باللغة الإنجليزية. وإلا، فإنه يرد بلغتك ({lang}).",
4950
"account.other-settings.llm.title": "إعدادات AI",
5051
"account.other-settings.markdown_codebar": "<strong>تعطيل شريط كود العلامات</strong> في جميع مستندات العلامات. يؤدي تحديد هذا إلى إخفاء أزرار التشغيل والنسخ والشرح الإضافية في كتل الكود المسورة.",
5152
"account.other-settings.mask_files": "<strong>إخفاء الملفات:</strong> تظليل الملفات في عارض الملفات التي ربما لا تريد فتحها",

src/packages/frontend/i18n/trans/de_DE.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"account.other-settings.katex": "<strong>KaTeX:</strong> Versuch, Formeln mit {katex} zu rendern (viel schneller, aber ohne Kontextmenüoptionen)",
4747
"account.other-settings.llm.default_llm": "Standard-AI-Sprachmodell",
4848
"account.other-settings.llm.disable_all": "<strong>Alle KI-Integrationen deaktivieren</strong>, z.B. Code-Generierungs- oder Erklärungsbuttons in Jupyter, @chatgpt-Erwähnungen usw.",
49+
"account.other-settings.llm.reply_language": "<strong>Immer auf Englisch antworten:</strong> Wenn eingestellt, sind die Antworten immer auf Englisch. Andernfalls antwortet es in Ihrer Sprache ({lang}).",
4950
"account.other-settings.llm.title": "KI-Einstellungen",
5051
"account.other-settings.markdown_codebar": "<strong>Deaktiviere die Markdown-Codeleiste</strong> in allen Markdown-Dokumenten. Wenn Sie dies aktivieren, werden die zusätzlichen Ausführen-, Kopieren- und Erklären-Buttons in umrandeten Codeblöcken ausgeblendet.",
5152
"account.other-settings.mask_files": "<strong>Dateien maskieren:</strong> Dateien im Dateibetrachter ausgrauen, die Sie wahrscheinlich nicht öffnen möchten",

src/packages/frontend/i18n/trans/es_ES.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"account.other-settings.katex": "<strong>KaTeX:</strong> intento de renderizar fórmulas usando {katex} (mucho más rápido, pero sin opciones de menú contextual)",
4747
"account.other-settings.llm.default_llm": "Modelo de Lenguaje AI Predeterminado",
4848
"account.other-settings.llm.disable_all": "<strong>Desactivar todas las integraciones de IA</strong>, por ejemplo, botones de generación de código o explicación en Jupyter, menciones de @chatgpt, etc.",
49+
"account.other-settings.llm.reply_language": "<strong>Siempre responder en inglés:</strong> Si está activado, las respuestas siempre estarán en inglés. De lo contrario, responde en tu idioma ({lang}).",
4950
"account.other-settings.llm.title": "Configuración de IA",
5051
"account.other-settings.markdown_codebar": "<strong>Desactivar la barra de código markdown</strong> en todos los documentos markdown. Al marcar esto, se ocultan los botones adicionales de ejecutar, copiar y explicar en los bloques de código delimitados.",
5152
"account.other-settings.mask_files": "<strong>Archivos ocultos:</strong> atenuar archivos en el visor de archivos que probablemente no desees abrir",

src/packages/frontend/i18n/trans/fr_FR.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"account.other-settings.katex": "<strong>KaTeX :</strong> tentative de rendu des formules en utilisant {katex} (beaucoup plus rapide, mais sans options du menu contextuel)",
4747
"account.other-settings.llm.default_llm": "Modèle de Langage IA par Défaut",
4848
"account.other-settings.llm.disable_all": "<strong>Désactiver toutes les intégrations d'IA</strong>, par exemple, boutons de génération de code ou d'explication dans Jupyter, mentions @chatgpt, etc.",
49+
"account.other-settings.llm.reply_language": "<strong>Toujours répondre en anglais :</strong> Si activé, les réponses sont toujours en anglais. Sinon, elles répondent dans votre langue ({lang}).",
4950
"account.other-settings.llm.title": "Paramètres AI",
5051
"account.other-settings.markdown_codebar": "<strong>Désactiver la barre de code markdown</strong> dans tous les documents markdown. Cocher ceci masque les boutons supplémentaires d'exécution, de copie et d'explication dans les blocs de code délimités.",
5152
"account.other-settings.mask_files": "<strong>Masquer les fichiers :</strong> griser les fichiers dans le visualiseur de fichiers que vous ne souhaitez probablement pas ouvrir",

src/packages/frontend/i18n/trans/he_IL.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"account.other-settings.katex": "<strong>KaTeX:</strong> ניסיון לעבד נוסחאות באמצעות {katex} (מהיר יותר, אך חסרות אפשרויות בתפריט ההקשר)",
4747
"account.other-settings.llm.default_llm": "מודל שפה AI ברירת מחדל",
4848
"account.other-settings.llm.disable_all": "<strong>השבת את כל האינטגרציות של AI</strong>, לדוגמה, כפתורי יצירת קוד או הסבר ב-Jupyter, אזכורי @chatgpt וכו'.",
49+
"account.other-settings.llm.reply_language": "<strong>תמיד להגיב באנגלית:</strong> אם מוגדר, התשובות תמיד באנגלית. אחרת, זה עונה בשפה שלך ({lang}).",
4950
"account.other-settings.llm.title": "הגדרות AI",
5051
"account.other-settings.markdown_codebar": "<strong>השבת את סרגל הקוד של Markdown</strong> בכל מסמכי ה-Markdown. סימון זה מסתיר את כפתורי הריצה, ההעתקה וההסבר הנוספים בקטעי קוד מגודרים.",
5152
"account.other-settings.mask_files": "<strong>הסתר קבצים:</strong> האפור קבצים בצופה הקבצים שבדרך כלל לא תרצה לפתוח",

src/packages/frontend/i18n/trans/hi_IN.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"account.other-settings.katex": "<strong>KaTeX:</strong> सूत्रों को {katex} का उपयोग करके प्रस्तुत करने का प्रयास करें (काफी तेज़, लेकिन संदर्भ मेनू विकल्प गायब हैं)",
4747
"account.other-settings.llm.default_llm": "डिफ़ॉल्ट एआई भाषा मॉडल",
4848
"account.other-settings.llm.disable_all": "<strong>सभी AI एकीकरण अक्षम करें</strong>, जैसे कोड जनरेशन या Jupyter में व्याख्या बटन, @chatgpt उल्लेख, आदि।",
49+
"account.other-settings.llm.reply_language": "<strong>हमेशा अंग्रेजी में उत्तर दें:</strong> यदि सेट किया गया है, तो उत्तर हमेशा अंग्रेजी में होंगे। अन्यथा, यह आपकी भाषा ({lang}) में उत्तर देगा।",
4950
"account.other-settings.llm.title": "एआई सेटिंग्स",
5051
"account.other-settings.markdown_codebar": "<strong>सभी मार्कडाउन दस्तावेज़ों में मार्कडाउन कोड बार को अक्षम करें</strong>. इसे चेक करने से बाड़े गए कोड ब्लॉकों में अतिरिक्त चलाएं, कॉपी करें और समझाएं बटन छिप जाते हैं।",
5152
"account.other-settings.mask_files": "<strong>मास्क फाइल्स:</strong> उन फाइलों को ग्रे आउट करें जिन्हें आप शायद खोलना नहीं चाहते फाइल्स व्यूअर में",

src/packages/frontend/i18n/trans/hu_HU.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"account.other-settings.katex": "<strong>KaTeX:</strong> kísérlet képletek renderelésére {katex} használatával (sokkal gyorsabb, de hiányoznak a helyi menü opciók)",
4747
"account.other-settings.llm.default_llm": "Alapértelmezett AI nyelvi modell",
4848
"account.other-settings.llm.disable_all": "<strong>Az összes AI integráció letiltása</strong>, pl. kódgenerálás vagy magyarázó gombok a Jupyterben, @chatgpt említések stb.",
49+
"account.other-settings.llm.reply_language": "<strong>Mindig válaszoljon angolul:</strong> Ha be van állítva, a válaszok mindig angolul lesznek. Ellenkező esetben a saját nyelvén ({lang}) válaszol.",
4950
"account.other-settings.llm.title": "AI beállítások",
5051
"account.other-settings.markdown_codebar": "<strong>Tiltsa le a markdown kódsávot</strong> minden markdown dokumentumban. Ennek bejelölése elrejti a további futtatás, másolás és magyarázat gombokat a keretezett kódrészletekben.",
5152
"account.other-settings.mask_files": "<strong>Fájlok elrejtése:</strong> szürkítse el a fájlokat a fájlnézegetőben, amelyeket valószínűleg nem akar megnyitni",

0 commit comments

Comments
 (0)