add check and refine
This commit is contained in:
@@ -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<string>('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<string>('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));
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Action Tools (Copy) -->
|
||||
<!-- Action Tools (Copy, Evaluate, Refine) -->
|
||||
<div :class="cn(
|
||||
'absolute top-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center bg-white/90 dark:bg-slate-800/90 rounded-full shadow-lg border dark:border-slate-700 px-1 py-1 z-20',
|
||||
msg.sender === 'me' ? '-left-12' : '-right-12'
|
||||
msg.sender === 'me' ? '-left-24' : '-right-24'
|
||||
)">
|
||||
<button
|
||||
@click="copyWithFeedback(msg.translated, msg.id)"
|
||||
@@ -355,8 +519,76 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
<Check v-if="activeCopyId === msg.id" class="w-3.5 h-3.5 text-green-600" />
|
||||
<Copy v-else class="w-3.5 h-3.5 text-slate-400" />
|
||||
</button>
|
||||
<button
|
||||
@click="evaluateMessage(msg.id)"
|
||||
:disabled="msg.isEvaluating || msg.isRefining"
|
||||
class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full transition-colors disabled:opacity-30"
|
||||
title="审计翻译"
|
||||
>
|
||||
<Loader2 v-if="msg.isEvaluating" class="w-3.5 h-3.5 animate-spin text-blue-500" />
|
||||
<ShieldCheck v-else class="w-3.5 h-3.5 text-slate-400" />
|
||||
</button>
|
||||
<button
|
||||
v-if="msg.evaluation"
|
||||
@click="refineMessage(msg.id)"
|
||||
:disabled="msg.isRefining"
|
||||
class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-full transition-colors disabled:opacity-30"
|
||||
title="执行润色"
|
||||
>
|
||||
<Loader2 v-if="msg.isRefining" class="w-3.5 h-3.5 animate-spin text-purple-500" />
|
||||
<Sparkles v-else class="w-3.5 h-3.5 text-purple-400" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Evaluation Results -->
|
||||
<transition
|
||||
enter-active-class="transition duration-200 ease-out"
|
||||
enter-from-class="transform -translate-y-2 opacity-0"
|
||||
enter-to-class="transform translate-y-0 opacity-100"
|
||||
>
|
||||
<div v-if="msg.evaluation" class="mt-2 w-full max-w-sm">
|
||||
<div class="bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm border border-slate-200 dark:border-slate-800 rounded-xl p-3 shadow-sm space-y-3">
|
||||
<!-- Score & Analysis -->
|
||||
<div class="flex items-start gap-2.5">
|
||||
<div :class="cn(
|
||||
'shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-xs font-black',
|
||||
parseEvaluation(msg.evaluation).score >= 90 ? 'bg-green-100 text-green-600 dark:bg-green-900/30' :
|
||||
parseEvaluation(msg.evaluation).score >= 75 ? 'bg-amber-100 text-amber-600 dark:bg-amber-900/30' :
|
||||
'bg-red-100 text-red-600 dark:bg-red-900/30'
|
||||
)">
|
||||
{{ parseEvaluation(msg.evaluation).score }}
|
||||
</div>
|
||||
<p class="text-[11px] text-slate-600 dark:text-slate-400 leading-relaxed italic">
|
||||
{{ parseEvaluation(msg.evaluation).analysis }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Suggestions with Severity -->
|
||||
<div class="space-y-1.5">
|
||||
<div
|
||||
v-for="sug in parseEvaluation(msg.evaluation).suggestions"
|
||||
:key="sug.id"
|
||||
:class="cn('flex items-center gap-2 px-2 py-1.5 rounded-lg border text-[10px] font-medium transition-all', getSeverityColor(sug.importance))"
|
||||
>
|
||||
<component :is="getSeverityIcon(sug.importance)" class="w-3 h-3 shrink-0" />
|
||||
<span class="flex-1">{{ sug.text }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Refine Action -->
|
||||
<button
|
||||
@click="refineMessage(msg.id)"
|
||||
:disabled="msg.isRefining"
|
||||
class="w-full py-1.5 bg-purple-50 hover:bg-purple-100 dark:bg-purple-900/20 dark:hover:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-lg text-[10px] font-bold transition-all flex items-center justify-center gap-1.5"
|
||||
>
|
||||
<Loader2 v-if="msg.isRefining" class="w-3 h-3 animate-spin" />
|
||||
<Sparkles v-else class="w-3 h-3" />
|
||||
{{ msg.isRefining ? '正在润色...' : '根据建议执行润色' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user