Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db848bed92 | ||
|
|
280376a88e | ||
|
|
984f5d73dd | ||
|
|
732d1906f6 | ||
|
|
785df4c5a5 | ||
|
|
f8785f4395 | ||
|
|
a8967809a2 | ||
|
|
e2b6340446 | ||
|
|
9dbce266b4 | ||
|
|
bba1123176 | ||
|
|
939a0a46cd | ||
|
|
5b0e6321cc | ||
|
|
8acef5e4e7 | ||
|
|
4f6ab39ed5 | ||
|
|
2a940534f2 | ||
|
|
136a5c186c | ||
|
|
41494ebad0 | ||
|
|
ce4a42eec2 | ||
|
|
ac951c31b1 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ai-translate-client",
|
||||
"private": true,
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.8",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
2
src-tauri/Cargo.lock
generated
2
src-tauri/Cargo.lock
generated
@@ -19,7 +19,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ai-translate-client"
|
||||
version = "0.3.6"
|
||||
version = "0.3.8"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"reqwest 0.12.28",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ai-translate-client"
|
||||
version = "0.3.6"
|
||||
version = "0.3.8"
|
||||
description = "A client using AI models to translate"
|
||||
authors = ["Julian"]
|
||||
edition = "2021"
|
||||
|
||||
@@ -23,7 +23,7 @@ struct OpenAIResponse {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Choice {
|
||||
message: Option<Message>,
|
||||
// message: Option<Message>,
|
||||
delta: Option<Delta>,
|
||||
}
|
||||
|
||||
@@ -56,16 +56,17 @@ async fn translate(
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if !payload.stream {
|
||||
let data = res.json::<OpenAIResponse>().await.map_err(|e| e.to_string())?;
|
||||
return Ok(data.choices.get(0).and_then(|c| c.message.as_ref()).map(|m| m.content.clone()).unwrap_or_default());
|
||||
let text = res.text().await.map_err(|e| e.to_string())?;
|
||||
return Ok(text);
|
||||
}
|
||||
|
||||
let mut stream = res.bytes_stream();
|
||||
let mut full_response = String::new();
|
||||
let mut raw_stream_log = String::new();
|
||||
|
||||
while let Some(item) = stream.next().await {
|
||||
let chunk = item.map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&chunk);
|
||||
raw_stream_log.push_str(&text);
|
||||
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
@@ -77,7 +78,6 @@ async fn translate(
|
||||
if let Some(choice) = json.choices.get(0) {
|
||||
if let Some(delta) = &choice.delta {
|
||||
if let Some(content) = &delta.content {
|
||||
full_response.push_str(content);
|
||||
app.emit("translation-chunk", content).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
@@ -87,7 +87,7 @@ async fn translate(
|
||||
}
|
||||
}
|
||||
|
||||
Ok(full_response)
|
||||
Ok(raw_stream_log)
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "ai-translate-client",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.8",
|
||||
"identifier": "top.volan.ai-translate-client",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
14
src/App.vue
14
src/App.vue
@@ -6,7 +6,8 @@ import {
|
||||
FileText,
|
||||
Sun,
|
||||
Moon,
|
||||
Clock
|
||||
Clock,
|
||||
MessageSquare
|
||||
} from 'lucide-vue-next';
|
||||
import { useSettingsStore } from './stores/settings';
|
||||
import pkg from '../package.json';
|
||||
@@ -14,6 +15,7 @@ import { cn } from './lib/utils';
|
||||
|
||||
// Import newly separated views
|
||||
import TranslationView from './components/TranslationView.vue';
|
||||
import ConversationView from './components/ConversationView.vue';
|
||||
import SettingsView from './components/SettingsView.vue';
|
||||
import LogsView from './components/LogsView.vue';
|
||||
import HistoryView from './components/HistoryView.vue';
|
||||
@@ -34,7 +36,7 @@ const toggleTheme = () => {
|
||||
};
|
||||
|
||||
// Global Routing State
|
||||
const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
|
||||
const view = ref<'translate' | 'conversation' | 'settings' | 'logs' | 'history'>('translate');
|
||||
|
||||
</script>
|
||||
|
||||
@@ -55,6 +57,13 @@ const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
|
||||
<Sun v-if="settings.isDark" class="w-5 h-5" />
|
||||
<Moon v-else class="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
@click="view = 'conversation'"
|
||||
:class="cn('p-2 rounded-full transition-colors', view === 'conversation' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'hover:bg-slate-200/50 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300')"
|
||||
title="对话模拟"
|
||||
>
|
||||
<MessageSquare class="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
@click="view = 'settings'"
|
||||
:class="cn('p-2 rounded-full transition-colors', view === 'settings' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'hover:bg-slate-200/50 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300')"
|
||||
@@ -83,6 +92,7 @@ const view = ref<'translate' | 'settings' | 'logs' | 'history'>('translate');
|
||||
<!-- Container for isolated views with keep-alive -->
|
||||
<keep-alive>
|
||||
<TranslationView v-if="view === 'translate'" />
|
||||
<ConversationView v-else-if="view === 'conversation'" />
|
||||
<SettingsView v-else-if="view === 'settings'" />
|
||||
<LogsView v-else-if="view === 'logs'" />
|
||||
<HistoryView v-else-if="view === 'history'" />
|
||||
|
||||
1081
src/components/ConversationView.vue
Normal file
1081
src/components/ConversationView.vue
Normal file
File diff suppressed because it is too large
Load Diff
@@ -19,9 +19,20 @@ watch(() => settings.logs, (newVal) => {
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
const decodeUnicode = (str: string) => {
|
||||
if (!str) return str;
|
||||
try {
|
||||
return str.replace(/\\u([0-9a-fA-F]{4})/g, (_match, grp) => {
|
||||
return String.fromCharCode(parseInt(grp, 16));
|
||||
});
|
||||
} catch {
|
||||
return str;
|
||||
}
|
||||
};
|
||||
|
||||
const getLogSummary = (log: any) => {
|
||||
if (log.type === 'error') return String(log.content);
|
||||
if (typeof log.content === 'string') return log.content;
|
||||
if (typeof log.content === 'string') return decodeUnicode(log.content);
|
||||
if (log.content && log.content.model) return `Model: ${log.content.model}`;
|
||||
if (log.content && log.content.score) return `Score: ${log.content.score}`;
|
||||
return 'JSON Data';
|
||||
@@ -92,18 +103,37 @@ const getLogSummary = (log: any) => {
|
||||
)"
|
||||
>{{ selectedLogItem.type === 'request' ? 'Request' : selectedLogItem.type === 'response' ? 'Response' : 'Error' }}</span>
|
||||
</div>
|
||||
<button
|
||||
@click="copyWithFeedback(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : String(selectedLogItem.content), `log-${selectedLogItem.id}`)"
|
||||
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800 rounded-lg transition-colors border border-slate-200 dark:border-slate-700"
|
||||
>
|
||||
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
||||
<Copy v-else class="w-4 h-4" />
|
||||
复制内容
|
||||
</button>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
v-if="selectedLogItem.curl"
|
||||
@click="copyWithFeedback(decodeUnicode(selectedLogItem.curl), `curl-${selectedLogItem.id}`)"
|
||||
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/30 rounded-lg transition-colors border border-blue-100 dark:border-blue-900/50"
|
||||
>
|
||||
<Check v-if="activeCopyId === `curl-${selectedLogItem.id}`" class="w-4 h-4" />
|
||||
<Copy v-else class="w-4 h-4" />
|
||||
复制 cURL
|
||||
</button>
|
||||
<button
|
||||
@click="copyWithFeedback(decodeUnicode(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : String(selectedLogItem.content)), `log-${selectedLogItem.id}`)"
|
||||
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800 rounded-lg transition-colors border border-slate-200 dark:border-slate-700"
|
||||
>
|
||||
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
||||
<Copy v-else class="w-4 h-4" />
|
||||
复制内容
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar">
|
||||
<pre class="font-mono text-xs leading-relaxed text-slate-700 dark:text-slate-300 whitespace-pre-wrap break-all">{{ typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : selectedLogItem.content }}</pre>
|
||||
<div class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar space-y-6">
|
||||
<div v-if="selectedLogItem.curl" class="space-y-2">
|
||||
<h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-1">cURL 请求命令</h3>
|
||||
<pre class="font-mono text-[11px] leading-relaxed p-4 bg-slate-950 text-blue-400 rounded-xl border border-slate-800 whitespace-pre-wrap break-all shadow-inner">{{ decodeUnicode(selectedLogItem.curl) }}</pre>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-1">{{ selectedLogItem.type === 'request' ? 'Payload (JSON)' : 'Response Data' }}</h3>
|
||||
<pre class="font-mono text-[11px] leading-relaxed p-4 bg-slate-950 text-slate-300 rounded-xl border border-slate-800 whitespace-pre-wrap break-all shadow-inner">{{ decodeUnicode(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : selectedLogItem.content) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="flex-1 flex flex-col items-center justify-center text-slate-300 dark:text-slate-800 p-10 text-center space-y-4">
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { Play, Settings, Type, Save, Check, Plus, Trash2, ChevronDown, Eye, EyeOff, Pencil } from 'lucide-vue-next';
|
||||
import { useSettingsStore, DEFAULT_TEMPLATE, DEFAULT_EVALUATION_TEMPLATE, DEFAULT_REFINEMENT_TEMPLATE, type ApiProfile } from '../stores/settings';
|
||||
import { Play, Settings, Type, Save, Check, Plus, Trash2, ChevronDown, Eye, EyeOff, Pencil, MessageSquare } from 'lucide-vue-next';
|
||||
import {
|
||||
useSettingsStore,
|
||||
DEFAULT_TEMPLATE,
|
||||
DEFAULT_EVALUATION_TEMPLATE,
|
||||
DEFAULT_REFINEMENT_TEMPLATE,
|
||||
CONVERSATION_SYSTEM_PROMPT_TEMPLATE,
|
||||
CONVERSATION_EVALUATION_PROMPT_TEMPLATE,
|
||||
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE,
|
||||
type ApiProfile
|
||||
} from '../stores/settings';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
const settings = useSettingsStore();
|
||||
const settingsCategory = ref<'api' | 'general' | 'prompts'>('api');
|
||||
const settingsCategory = ref<'api' | 'general' | 'prompts' | 'chat-prompts'>('api');
|
||||
const showApiKey = ref(false);
|
||||
|
||||
const newProfileName = ref('');
|
||||
@@ -129,6 +138,18 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
</div>
|
||||
提示词工程
|
||||
</button>
|
||||
<button
|
||||
@click="settingsCategory = 'chat-prompts'"
|
||||
:class="cn(
|
||||
'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors',
|
||||
settingsCategory === 'chat-prompts' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800/50'
|
||||
)"
|
||||
>
|
||||
<div :class="cn('p-1.5 rounded-md', settingsCategory === 'chat-prompts' ? 'bg-blue-100 dark:bg-blue-900/50' : 'bg-slate-100 dark:bg-slate-800')">
|
||||
<MessageSquare class="w-4 h-4" />
|
||||
</div>
|
||||
对话提示词
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@@ -490,6 +511,82 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Chat Prompt Engineering -->
|
||||
<template v-if="settingsCategory === 'chat-prompts'">
|
||||
<div class="mb-6 border-b dark:border-slate-800 pb-4">
|
||||
<h1 class="text-2xl font-bold text-slate-800 dark:text-slate-100">对话提示词</h1>
|
||||
<p class="text-sm text-slate-500 dark:text-slate-400 mt-1">专门针对“对话模式”优化的系统指令模板。</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-8">
|
||||
<!-- Chat Translation Prompt -->
|
||||
<div class="bg-white/80 dark:bg-slate-900 rounded-2xl shadow-sm border dark:border-slate-800 overflow-hidden flex flex-col">
|
||||
<div class="px-5 py-3 border-b dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-2 h-2 rounded-full bg-blue-500"></div>
|
||||
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">对话翻译指令</h3>
|
||||
</div>
|
||||
<button @click="settings.chatSystemPromptTemplate = CONVERSATION_SYSTEM_PROMPT_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
|
||||
</div>
|
||||
<textarea
|
||||
v-model="settings.chatSystemPromptTemplate"
|
||||
rows="10"
|
||||
class="w-full p-5 bg-transparent outline-none font-mono text-xs leading-relaxed text-slate-800 dark:text-slate-300 resize-y"
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{HISTORY_BLOCK}', '{FROM_LANG}', '{TO_LANG}', '{MY_TONE}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chat Evaluation Prompt -->
|
||||
<div class="bg-white/80 dark:bg-slate-900 rounded-2xl shadow-sm border dark:border-slate-800 overflow-hidden flex flex-col">
|
||||
<div class="px-5 py-3 border-b dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-2 h-2 rounded-full bg-amber-500"></div>
|
||||
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">对话审计指令</h3>
|
||||
</div>
|
||||
<button @click="settings.chatEvaluationPromptTemplate = CONVERSATION_EVALUATION_PROMPT_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
|
||||
</div>
|
||||
<textarea
|
||||
v-model="settings.chatEvaluationPromptTemplate"
|
||||
rows="12"
|
||||
class="w-full p-5 bg-transparent outline-none font-mono text-xs leading-relaxed text-slate-800 dark:text-slate-300 resize-y"
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{TARGET_TONE}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{HISTORY_BLOCK}', '{ORIGINAL_TEXT}', '{CURRENT_TRANSLATION}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chat Refinement Prompt -->
|
||||
<div class="bg-white/80 dark:bg-slate-900 rounded-2xl shadow-sm border dark:border-slate-800 overflow-hidden flex flex-col">
|
||||
<div class="px-5 py-3 border-b dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-2 h-2 rounded-full bg-green-500"></div>
|
||||
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">对话润色指令</h3>
|
||||
</div>
|
||||
<button @click="settings.chatRefinementPromptTemplate = CONVERSATION_REFINEMENT_PROMPT_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
|
||||
</div>
|
||||
<textarea
|
||||
v-model="settings.chatRefinementPromptTemplate"
|
||||
rows="10"
|
||||
class="w-full p-5 bg-transparent outline-none font-mono text-xs leading-relaxed text-slate-800 dark:text-slate-300 resize-y"
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{TARGET_TONE}', '{HISTORY_BLOCK}', '{ORIGINAL_TEXT}', '{CURRENT_TRANSLATION}', '{SUGGESTIONS}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -105,6 +105,15 @@ const clearSource = () => {
|
||||
evaluationResult.value = null;
|
||||
};
|
||||
|
||||
const generateCurl = (apiBaseUrl: string, apiKey: string, body: any) => {
|
||||
const fullUrl = `${apiBaseUrl.replace(/\/$/, '')}/chat/completions`;
|
||||
const maskedKey = apiKey ? `${apiKey.slice(0, 6)}...${apiKey.slice(-4)}` : 'YOUR_API_KEY';
|
||||
return `curl "${fullUrl}" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-H "Authorization: Bearer ${maskedKey}" \\
|
||||
-d '${JSON.stringify(body, null, 2)}'`;
|
||||
};
|
||||
|
||||
const evaluateTranslation = async () => {
|
||||
if (!targetText.value) return;
|
||||
isEvaluating.value = true;
|
||||
@@ -140,14 +149,18 @@ const evaluateTranslation = async () => {
|
||||
stream: false
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'evaluation', ...requestBody });
|
||||
settings.addLog('request', { type: 'evaluation', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||
try {
|
||||
const jsonStr = response.replace(/```json\s?|\s?```/g, '').trim();
|
||||
// 解析 API 的原始响应 JSON
|
||||
const fullResponseJson = JSON.parse(response);
|
||||
settings.addLog('response', fullResponseJson);
|
||||
|
||||
const content = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||
const jsonStr = content.replace(/```json\s?|\s?```/g, '').trim();
|
||||
evaluationResult.value = JSON.parse(jsonStr);
|
||||
settings.addLog('response', { type: 'evaluation', content: evaluationResult.value });
|
||||
} catch (parseErr) {
|
||||
console.error('Failed to parse evaluation result:', response);
|
||||
settings.addLog('error', `Evaluation parsing error: ${response}`);
|
||||
@@ -197,17 +210,23 @@ const refineTranslation = async () => {
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'refinement', ...requestBody });
|
||||
settings.addLog('request', { type: 'refinement', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||
if (!settings.enableStreaming) targetText.value = response;
|
||||
|
||||
if (settings.enableStreaming) {
|
||||
settings.addLog('response', targetText.value);
|
||||
} else {
|
||||
const fullResponseJson = JSON.parse(response);
|
||||
settings.addLog('response', fullResponseJson);
|
||||
targetText.value = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||
}
|
||||
|
||||
if (evaluationResult.value?.suggestions) {
|
||||
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
|
||||
selectedSuggestionIds.value = [];
|
||||
}
|
||||
settings.addLog('response', 'Refinement completed');
|
||||
|
||||
if (currentHistoryId.value) {
|
||||
settings.updateHistoryItem(currentHistoryId.value, {
|
||||
@@ -249,18 +268,27 @@ const translate = async () => {
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
settings.addLog('request', requestBody);
|
||||
settings.addLog('request', 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) targetText.value = response;
|
||||
settings.addLog('response', 'Translation completed');
|
||||
|
||||
let finalTargetText = '';
|
||||
if (settings.enableStreaming) {
|
||||
finalTargetText = targetText.value;
|
||||
settings.addLog('response', response);
|
||||
} else {
|
||||
const fullResponseJson = JSON.parse(response);
|
||||
settings.addLog('response', fullResponseJson);
|
||||
finalTargetText = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||
targetText.value = finalTargetText;
|
||||
}
|
||||
|
||||
currentHistoryId.value = settings.addHistory({
|
||||
sourceLang: { ...sourceLang.value },
|
||||
targetLang: { ...targetLang.value },
|
||||
sourceText: sourceText.value,
|
||||
targetText: settings.enableStreaming ? targetText.value : response,
|
||||
targetText: finalTargetText,
|
||||
context: context.value,
|
||||
speakerIdentity: settings.speakerIdentity,
|
||||
toneRegister: settings.toneRegister,
|
||||
|
||||
@@ -127,6 +127,119 @@ export interface HistoryItem {
|
||||
modelName: string;
|
||||
}
|
||||
|
||||
export interface Participant {
|
||||
name: string;
|
||||
gender: string;
|
||||
language: Language;
|
||||
tone: string;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
sender: 'me' | 'partner';
|
||||
original: string;
|
||||
translated: string;
|
||||
timestamp: string;
|
||||
evaluation?: string; // AI 审计结果 (JSON 字符串)
|
||||
isEvaluating?: boolean; // 审计状态
|
||||
isRefining?: boolean; // 润色状态
|
||||
}
|
||||
|
||||
export interface ChatSession {
|
||||
id: string;
|
||||
title: string;
|
||||
me: Participant;
|
||||
partner: Participant;
|
||||
messages: ChatMessage[];
|
||||
lastActivity: string;
|
||||
}
|
||||
|
||||
export const CONVERSATION_SYSTEM_PROMPT_TEMPLATE = `You are a professional real-time conversation translator.
|
||||
Current Context:
|
||||
- Role A (Me): {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}.
|
||||
- Role B (Other): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}.
|
||||
|
||||
[Conversation History]
|
||||
{HISTORY_BLOCK}
|
||||
|
||||
[Current Task]
|
||||
Translate the incoming text from {FROM_LANG} to {TO_LANG}.
|
||||
|
||||
[Constraints]
|
||||
1. Contextual Awareness: Use the [Conversation History] to resolve pronouns (it, that, etc.) and maintain consistency.
|
||||
2. Tone & Register:
|
||||
- If translating for 'Me', strictly use the tone: {MY_TONE}.
|
||||
- If translating for 'Other', auto-detect and preserve their original tone/emotion.
|
||||
3. Natural Flow: Keep the translation concise and natural for a chat environment. Avoid "translationese".
|
||||
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: Expert Conversation Auditor
|
||||
|
||||
# Context Info
|
||||
- Role A (Me): {ME_NAME} ({ME_GENDER}, Native {ME_LANG})
|
||||
- Role B (Other): {PART_NAME} ({PART_GENDER}, Native {PART_LANG})
|
||||
|
||||
# Recent Conversation Flow (Original Messages Only):
|
||||
{HISTORY_BLOCK}
|
||||
|
||||
# Current Turn to Audit:
|
||||
- Speaker: {SENDER_NAME}
|
||||
- Direction: {FROM_LANG} -> {TO_LANG}
|
||||
- Source Text ({FROM_LANG}): {ORIGINAL_TEXT}
|
||||
- Translation ({TO_LANG}): {CURRENT_TRANSLATION}
|
||||
|
||||
# Audit Priorities
|
||||
1. **Contextual Accuracy**: Does the translation correctly reflect the meaning based on the [Recent Conversation Flow]?
|
||||
2. **Relational Tone**:
|
||||
- If the Speaker is 'Me', does it match the target tone({TARGET_TONE})?
|
||||
- If the Speaker is 'Other', does it preserve their original tone/emotion?
|
||||
3. **Naturalness**: Is it concise and fit for an IM (Instant Messaging) environment?
|
||||
|
||||
# Instructions
|
||||
1. **Evaluation**: Compare the [Source Text] and [Translation] based on the [Audit Priorities].
|
||||
2. **Scoring Strategy**:
|
||||
- **90-100**: Accurate, grammatically sound, and flows naturally.
|
||||
- **75-89**: Accurate meaning, but suffers from "stiff" phrasing or minor flow issues that need adjustment.
|
||||
- **Below 75**: Contains semantic errors, severe grammar issues, or tone mismatches.
|
||||
3. **Analysis**: Provide a concise explanation in Simplified Chinese. Focus on *why* the error matters (e.g., "meaning is reversed" or "too awkward to read").
|
||||
4. **Suggestions**: Provide a list of specific, actionable suggestions. For each, assign an "importance" from 0 to 100 (0 = unnecessary/optional, 100 = critical error).
|
||||
|
||||
# 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 = `# Role: Professional Conversation Editor
|
||||
|
||||
# Context:
|
||||
- Role A (Me): {ME_NAME} ({ME_GENDER}, Native {ME_LANG})
|
||||
- Role B (Other): {PART_NAME} ({PART_GENDER}, Native {PART_LANG})
|
||||
|
||||
# Recent Conversation Flow (Original Messages Only):
|
||||
{HISTORY_BLOCK}
|
||||
|
||||
# Current Turn to Refine:
|
||||
- Speaker: {SENDER_NAME}
|
||||
- Direction: {FROM_LANG} -> {TO_LANG}
|
||||
- Source Text ({FROM_LANG}): {ORIGINAL_TEXT}
|
||||
- Current Translation ({TO_LANG}): {CURRENT_TRANSLATION}
|
||||
|
||||
# Suggestions to Apply:
|
||||
{SUGGESTIONS}
|
||||
|
||||
# Instructions:
|
||||
1. Carefully review the [Suggestions] and apply the requested improvements to the [Current Translation] while ensuring it fits naturally into the [Recent Conversation Flow].
|
||||
2. Ensure that the refined translation remains semantically identical to the [Source Text].
|
||||
3. If the Speaker is 'Me', strictly maintain the target tone({TARGET_TONE}); if the Speaker is 'Other', auto-detect and preserve their original tone/emotion.
|
||||
4. If a piece of feedback contradicts the [Source Text], prioritize accuracy and provide a balanced refinement.
|
||||
5. Produce ONLY the refined {TO_LANG} translation, without any additional explanations, notes, or commentary.`;
|
||||
|
||||
export const useSettingsStore = defineStore('settings', () => {
|
||||
const isDark = useLocalStorage('is-dark', false);
|
||||
const apiBaseUrl = useLocalStorage('api-base-url', 'http://localhost:11434/v1');
|
||||
@@ -141,6 +254,10 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
const evaluationProfileId = useLocalStorage<string | null>('evaluation-profile-id', null);
|
||||
const refinementPromptTemplate = useLocalStorage('refinement-prompt-template', DEFAULT_REFINEMENT_TEMPLATE);
|
||||
|
||||
const chatSystemPromptTemplate = useLocalStorage('chat-system-prompt-template', CONVERSATION_SYSTEM_PROMPT_TEMPLATE);
|
||||
const chatEvaluationPromptTemplate = useLocalStorage('chat-evaluation-prompt-template', CONVERSATION_EVALUATION_PROMPT_TEMPLATE);
|
||||
const chatRefinementPromptTemplate = useLocalStorage('chat-refinement-prompt-template', CONVERSATION_REFINEMENT_PROMPT_TEMPLATE);
|
||||
|
||||
// 存储整个对象以保持一致性
|
||||
const sourceLang = useLocalStorage<Language>('source-lang-v2', LANGUAGES[0]);
|
||||
const targetLang = useLocalStorage<Language>('target-lang-v2', LANGUAGES[4]);
|
||||
@@ -159,10 +276,14 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
set: (val) => { toneRegisterMap.value[sourceLang.value.code] = val; }
|
||||
});
|
||||
|
||||
const logs = ref<{ id: string; timestamp: string; type: 'request' | 'response' | 'error'; content: any }[]>([]);
|
||||
const logs = ref<{ id: string; timestamp: string; type: 'request' | 'response' | 'error'; content: any; curl?: string }[]>([]);
|
||||
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
|
||||
|
||||
const addLog = (type: 'request' | 'response' | 'error', content: any) => {
|
||||
// 对话模式状态
|
||||
const chatSessions = useLocalStorage<ChatSession[]>('chat-sessions-v1', []);
|
||||
const activeSessionId = useLocalStorage<string | null>('active-session-id-v1', null);
|
||||
|
||||
const addLog = (type: 'request' | 'response' | 'error', content: any, curl?: string) => {
|
||||
const now = new Date();
|
||||
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
|
||||
|
||||
@@ -170,7 +291,8 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
id: crypto.randomUUID(),
|
||||
timestamp,
|
||||
type,
|
||||
content
|
||||
content,
|
||||
curl
|
||||
});
|
||||
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
|
||||
};
|
||||
@@ -201,6 +323,79 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 对话模式方法
|
||||
const createSession = (me: Participant, partner: Participant) => {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date();
|
||||
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
|
||||
|
||||
const newSession: ChatSession = {
|
||||
id,
|
||||
title: `${partner.name} 的对话`,
|
||||
me,
|
||||
partner,
|
||||
messages: [],
|
||||
lastActivity: timestamp
|
||||
};
|
||||
|
||||
chatSessions.value.unshift(newSession);
|
||||
activeSessionId.value = id;
|
||||
return id;
|
||||
};
|
||||
|
||||
const deleteSession = (id: string) => {
|
||||
chatSessions.value = chatSessions.value.filter(s => s.id !== id);
|
||||
if (activeSessionId.value === id) {
|
||||
activeSessionId.value = chatSessions.value[0]?.id || null;
|
||||
}
|
||||
};
|
||||
|
||||
const addMessageToSession = (sessionId: string, sender: 'me' | 'partner', original: string, translated: string = '') => {
|
||||
const session = chatSessions.value.find(s => s.id === sessionId);
|
||||
if (session) {
|
||||
const now = new Date();
|
||||
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
|
||||
|
||||
const newMessage: ChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
sender,
|
||||
original,
|
||||
translated,
|
||||
timestamp
|
||||
};
|
||||
|
||||
session.messages.push(newMessage);
|
||||
session.lastActivity = timestamp;
|
||||
|
||||
// 将活跃会话移至顶部
|
||||
const index = chatSessions.value.findIndex(s => s.id === sessionId);
|
||||
if (index > 0) {
|
||||
const [s] = chatSessions.value.splice(index, 1);
|
||||
chatSessions.value.unshift(s);
|
||||
}
|
||||
|
||||
return newMessage.id;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const updateChatMessage = (sessionId: string, messageId: string, updates: Partial<ChatMessage>) => {
|
||||
const session = chatSessions.value.find(s => s.id === sessionId);
|
||||
if (session) {
|
||||
const message = session.messages.find(m => m.id === messageId);
|
||||
if (message) {
|
||||
Object.assign(message, updates);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const deleteChatMessage = (sessionId: string, messageId: string) => {
|
||||
const session = chatSessions.value.find(s => s.id === sessionId);
|
||||
if (session) {
|
||||
session.messages = session.messages.filter(m => m.id !== messageId);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isDark,
|
||||
apiBaseUrl,
|
||||
@@ -213,14 +408,24 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
evaluationPromptTemplate,
|
||||
evaluationProfileId,
|
||||
refinementPromptTemplate,
|
||||
chatSystemPromptTemplate,
|
||||
chatEvaluationPromptTemplate,
|
||||
chatRefinementPromptTemplate,
|
||||
sourceLang,
|
||||
targetLang,
|
||||
speakerIdentity,
|
||||
toneRegister,
|
||||
logs,
|
||||
history,
|
||||
chatSessions,
|
||||
activeSessionId,
|
||||
addLog,
|
||||
addHistory,
|
||||
updateHistoryItem
|
||||
updateHistoryItem,
|
||||
createSession,
|
||||
deleteSession,
|
||||
addMessageToSession,
|
||||
updateChatMessage,
|
||||
deleteChatMessage
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user