diff --git a/src/components/ConversationView.vue b/src/components/ConversationView.vue index e2bba82..4a6b092 100644 --- a/src/components/ConversationView.vue +++ b/src/components/ConversationView.vue @@ -3,9 +3,19 @@ import { ref, computed, nextTick, onMounted, onUnmounted, watch } from 'vue'; import { Plus, Search, Trash2, Send, User, Type, ChevronDown, Check, MessageSquare, Loader2, Copy, - X, Sparkles, Languages, Venus, Mars, CircleSlash + X, Sparkles, Languages, Venus, Mars, CircleSlash, + ShieldCheck, TriangleAlert, AlertCircle } from 'lucide-vue-next'; -import { useSettingsStore, LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS, CONVERSATION_SYSTEM_PROMPT_TEMPLATE, type Participant } from '../stores/settings'; +import { + useSettingsStore, + LANGUAGES, + SPEAKER_IDENTITY_OPTIONS, + TONE_REGISTER_OPTIONS, + CONVERSATION_SYSTEM_PROMPT_TEMPLATE, + CONVERSATION_EVALUATION_PROMPT_TEMPLATE, + CONVERSATION_REFINEMENT_PROMPT_TEMPLATE, + type Participant +} from '../stores/settings'; import { cn } from '../lib/utils'; import { invoke } from '@tauri-apps/api/core'; import { listen } from '@tauri-apps/api/event'; @@ -109,6 +119,12 @@ onMounted(async () => { }); onUnmounted(() => { if (unlisten) unlisten(); }); +const generateCurl = (baseUrl: string, key: string, body: any) => { + const fullUrl = `${baseUrl.replace(/\/$/, '')}/chat/completions`; + const maskedKey = key ? `${key.slice(0, 6)}...${key.slice(-4)}` : 'YOUR_API_KEY'; + return `curl "${fullUrl}" \\\n -H "Content-Type: application/json" \\\n -H "Authorization: Bearer ${maskedKey}" \\\n -d '${JSON.stringify(body, null, 2)}'`; +}; + const translateMessage = async (sender: 'me' | 'partner') => { if (!activeSession.value || isTranslating.value) return; @@ -130,7 +146,6 @@ const translateMessage = async (sender: 'me' | 'partner') => { // 2. Prepare Context const historyLimit = 10; - // 获取最近的对话历史(不包括当前正在翻译的这条) const sessionMessages = activeSession.value.messages; const recentMessages = sessionMessages.filter(m => m.id !== messageId).slice(-historyLimit); @@ -165,12 +180,6 @@ const translateMessage = async (sender: 'me' | 'partner') => { stream: settings.enableStreaming }; - const generateCurl = (baseUrl: string, key: string, body: any) => { - const fullUrl = `${baseUrl.replace(/\/$/, '')}/chat/completions`; - const maskedKey = key ? `${key.slice(0, 6)}...${key.slice(-4)}` : 'YOUR_API_KEY'; - return `curl "${fullUrl}" \\\n -H "Content-Type: application/json" \\\n -H "Authorization: Bearer ${maskedKey}" \\\n -d '${JSON.stringify(body, null, 2)}'`; - }; - settings.addLog('request', { type: 'conversation', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody)); try { @@ -199,6 +208,161 @@ const translateMessage = async (sender: 'me' | 'partner') => { } }; +const evaluateMessage = async (messageId: string) => { + if (!activeSession.value) return; + const msg = activeSession.value.messages.find(m => m.id === messageId); + if (!msg || msg.isEvaluating) return; + + settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: true }); + + const historyLimit = 10; + const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit); + const historyBlock = recentMessages.map(m => { + const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name; + return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`; + }).join('\n'); + + // 动态确定目标语气约束 + const targetTone = msg.sender === 'me' + ? (TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和') + : '自动识别 (保留原作者原始语气和情绪)'; + + const systemPrompt = CONVERSATION_EVALUATION_PROMPT_TEMPLATE + .replace(/{ME_NAME}/g, activeSession.value.me.name) + .replace(/{ME_GENDER}/g, activeSession.value.me.gender) + .replace(/{ME_LANG}/g, activeSession.value.me.language.englishName) + .replace(/{PART_NAME}/g, activeSession.value.partner.name) + .replace(/{PART_GENDER}/g, activeSession.value.partner.gender) + .replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName) + .replace(/{HISTORY_BLOCK}/g, historyBlock || 'None') + .replace(/{TARGET_TONE}/g, targetTone); + + const userPrompt = `[Source Text]\n${msg.original}\n\n[Current Translation]\n${msg.translated}`; + + const requestBody = { + model: settings.modelName, + messages: [ + { role: "system", content: systemPrompt }, + { role: "user", content: userPrompt } + ], + stream: false + }; + + settings.addLog('request', { type: 'conversation-eval', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody)); + + try { + const response = await invoke('translate', { + apiAddress: settings.apiBaseUrl, + apiKey: settings.apiKey, + payload: requestBody + }); + const fullResponseJson = JSON.parse(response); + settings.addLog('response', fullResponseJson); + const evaluationJson = fullResponseJson.choices?.[0]?.message?.content || response; + settings.updateChatMessage(activeSession.value.id, messageId, { evaluation: evaluationJson }); + } catch (err: any) { + settings.addLog('error', String(err)); + } finally { + settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: false }); + scrollToBottom(); + } +}; + +const refineMessage = async (messageId: string) => { + if (!activeSession.value) return; + const msg = activeSession.value.messages.find(m => m.id === messageId); + if (!msg || !msg.evaluation || msg.isRefining) return; + + let evalData; + try { + evalData = JSON.parse(msg.evaluation); + } catch (e) { return; } + + const suggestionsText = evalData.suggestions.map((s: any) => `- ${s.text} (Importance: ${s.importance})`).join('\n'); + + settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: true, translated: '' }); + currentStreamingMessageId.value = messageId; + + const historyLimit = 10; + const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit); + const historyBlock = recentMessages.map(m => { + const senderName = m.sender === 'me' ? activeSession.value!.me.name : activeSession.value!.partner.name; + return `${senderName}: [Original] ${m.original} -> [Translated] ${m.translated}`; + }).join('\n'); + + const myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和'; + + const systemPrompt = CONVERSATION_REFINEMENT_PROMPT_TEMPLATE + .replace(/{ME_NAME}/g, activeSession.value.me.name) + .replace(/{ME_GENDER}/g, activeSession.value.me.gender) + .replace(/{ME_LANG}/g, activeSession.value.me.language.englishName) + .replace(/{PART_NAME}/g, activeSession.value.partner.name) + .replace(/{PART_GENDER}/g, activeSession.value.partner.gender) + .replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName) + .replace(/{HISTORY_BLOCK}/g, historyBlock || 'None') + .replace(/{CURRENT_TRANSLATION}/g, msg.translated) + .replace(/{SUGGESTIONS}/g, suggestionsText) + .replace(/{MY_TONE}/g, myToneLabel); + + const requestBody = { + model: settings.modelName, + messages: [ + { role: "system", content: systemPrompt }, + { role: "user", content: `Please refine the following original text: ${msg.original}` } + ], + stream: settings.enableStreaming + }; + + settings.addLog('request', { type: 'conversation-refine', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody)); + + try { + const response = await invoke('translate', { + apiAddress: settings.apiBaseUrl, + apiKey: settings.apiKey, + payload: requestBody + }); + + if (!settings.enableStreaming) { + const fullResponseJson = JSON.parse(response); + const refinedText = fullResponseJson.choices?.[0]?.message?.content || response; + settings.updateChatMessage(activeSession.value.id, messageId, { translated: refinedText }); + } + } catch (err: any) { + settings.addLog('error', String(err)); + } finally { + settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: false, evaluation: undefined }); + currentStreamingMessageId.value = null; + scrollToBottom(); + } +}; + +const parseEvaluation = (evalStr?: string) => { + if (!evalStr) return null; + try { + // 1. 清洗数据:剔除 Markdown 代码块标记 (如 ```json ... ``` 或 ``` ...) + let cleanStr = evalStr.trim(); + if (cleanStr.startsWith('```')) { + cleanStr = cleanStr.replace(/^```[a-zA-Z]*\n?/, '').replace(/\n?```$/, '').trim(); + } + return JSON.parse(cleanStr); + } catch (e) { + console.error('Failed to parse evaluation JSON:', e, 'Raw string:', evalStr); + return { score: 0, analysis: '无法解析审计结果,请查看日志', suggestions: [] }; + } +}; + +const getSeverityColor = (importance: number) => { + if (importance >= 80) return 'text-red-500 bg-red-50 dark:bg-red-900/20 border-red-100 dark:border-red-900/30'; + if (importance >= 40) return 'text-amber-500 bg-amber-50 dark:bg-amber-900/20 border-amber-100 dark:border-amber-900/30'; + return 'text-blue-500 bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-900/30'; +}; + +const getSeverityIcon = (importance: number) => { + if (importance >= 80) return AlertCircle; + if (importance >= 40) return TriangleAlert; + return ShieldCheck; +}; + const handleGlobalClick = () => { myToneDropdownOpen.value = false; closeAllModalDropdowns(); @@ -342,10 +506,10 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));

- +
+ +
+ + + +
+
+ +
+
+ {{ parseEvaluation(msg.evaluation).score }} +
+

+ {{ parseEvaluation(msg.evaluation).analysis }} +

+
+ + +
+
+ + {{ sug.text }} +
+
+ + + +
+
+
diff --git a/src/stores/settings.ts b/src/stores/settings.ts index 50716c3..33b52a9 100644 --- a/src/stores/settings.ts +++ b/src/stores/settings.ts @@ -140,6 +140,9 @@ export interface ChatMessage { original: string; translated: string; timestamp: string; + evaluation?: string; // AI 审计结果 (JSON 字符串) + isEvaluating?: boolean; // 审计状态 + isRefining?: boolean; // 润色状态 } export interface ChatSession { @@ -171,6 +174,66 @@ Translate the incoming text from {FROM_LANG} to {TO_LANG}. 4. Strictly avoid over-translation: Do not add extra information not present in the source text. 5. Output ONLY the translated text, no explanations.`; +export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role +You are an expert Conversation Auditor. Your task is to evaluate if the [Current Translation] accurately reflects the [Source Text] within the specific flow of the [Conversation History]. + +# Context Info +- Me: {ME_NAME} ({ME_GENDER}, {ME_LANG}) +- Partner: {PART_NAME} ({PART_GENDER}, {PART_LANG}) +- Target Tone: {TARGET_TONE} + +[Conversation History] +{HISTORY_BLOCK} + +# Audit Priorities +1. **Contextual Accuracy**: Do pronouns (it, that, etc.) correctly point to objects/topics mentioned in the [Conversation History]? +2. **Relational Tone**: Does the translation match the [Target Tone]? (e.g., if set to 'Polite', is it too casual?) +3. **Consistency**: Are names, terms, or previously established facts handled consistently? +4. **Naturalness**: Is it concise and fit for an IM (Instant Messaging) environment? + +# Instructions +1. Analyze the [Source Text] and [Current Translation] against the history. +2. Scoring: 0-100. +3. Suggestions: Provide actionable improvements. +4. **Severity Level**: For each suggestion, assign an "importance" score (0-100). + - **80-100 (Critical)**: Misunderstanding meaning, wrong pronoun reference, or offensive tone. + - **40-79 (Moderate)**: Unnatural phrasing, minor tone mismatch. + - **0-39 (Minor)**: Polishing, stylistic preferences. + +# Output Format +Respond ONLY in JSON. "analysis" and "text" MUST be in Simplified Chinese: +{ + "score": number, + "analysis": "string", + "suggestions": [ + { "id": 1, "text": "suggestion text", "importance": number } + ] +}`; + +export const CONVERSATION_REFINEMENT_PROMPT_TEMPLATE = `You are a professional conversation editor. Refine the [Current Translation] based on the [Audit Suggestions] and [Conversation History]. + +# Context Info +- Role A (Me): {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}. +- Role B (Partner): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}. +- Target Tone: {TARGET_TONE} + +[Conversation History] +{HISTORY_BLOCK} + +[Current Translation] +{CURRENT_TRANSLATION} + +[Audit Suggestions] +{SUGGESTIONS} + +# Task +Produce a new, refined version of the translation that addresses the suggestions while remaining naturally integrated into the conversation flow. + +# Constraints +1. Maintain semantic identity with the [Source Text]. +2. Strictly follow the {TARGET_TONE}. +3. Output ONLY the refined translation text. No explanations.`; + export const useSettingsStore = defineStore('settings', () => { const isDark = useLocalStorage('is-dark', false); const apiBaseUrl = useLocalStorage('api-base-url', 'http://localhost:11434/v1');