Skip to content

Commit 9a6d0a7

Browse files
committed
fix: honor user language for AI responses
1 parent 353383c commit 9a6d0a7

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

backend/src/routes/ai.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,21 @@ import { getConnectionPolicy } from '../services/connectionPolicy.js';
77

88
const router = Router();
99

10+
const AI_LANGUAGE_NAMES = {
11+
en: 'English',
12+
ru: 'Russian',
13+
de: 'German',
14+
es: 'Spanish',
15+
fr: 'French',
16+
it: 'Italian',
17+
zhCN: 'Simplified Chinese',
18+
};
19+
20+
function aiLanguageInstruction(language) {
21+
const name = AI_LANGUAGE_NAMES[language] || 'the user interface language';
22+
return `Always respond in ${name}, unless the user explicitly asks for another language. For email drafting and rewriting, preserve the original email language when it differs from ${name}.`;
23+
}
24+
1025
// ── Admin: AI provider configuration ──────────────────────────────────────────
1126

1227
router.get('/admin/ai', requireAdmin, async (req, res) => {
@@ -163,6 +178,13 @@ router.post('/ai/chat', requireAuth, async (req, res) => {
163178
}
164179
}
165180

181+
const prefResult = await query('SELECT preferences FROM users WHERE id = $1', [req.session.userId]);
182+
const language = prefResult.rows[0]?.preferences?.language || 'en';
183+
const providerMessages = [
184+
{ role: 'system', content: aiLanguageInstruction(language) },
185+
...messages,
186+
];
187+
166188
const apiKey = cfg.apiKey ? decrypt(cfg.apiKey) : null;
167189
const headers = { 'Content-Type': 'application/json' };
168190
if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
@@ -173,7 +195,7 @@ router.post('/ai/chat', requireAuth, async (req, res) => {
173195
const aiRes = await fetch(`${cfg.baseUrl}/chat/completions`, {
174196
method: 'POST',
175197
headers,
176-
body: JSON.stringify({ model: cfg.model, messages, stream: true }),
198+
body: JSON.stringify({ model: cfg.model, messages: providerMessages, stream: true }),
177199
signal: AbortSignal.timeout(120000),
178200
});
179201

0 commit comments

Comments
 (0)