| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278 |
- <script setup lang="ts">
- import { ref, onMounted, watch } from 'vue';
- import { Message, Conversation, Theme, Plugin, ContentType } from '../../api/dto';
- import { getMessagesByConversation } from '../../api/chat';
- import ChatHeader from './ChatHeader.vue';
- import ChatMessages from './ChatMessages.vue';
- import ChatInput from './ChatInput.vue';
- import { useGlobSetting } from '@jeesite/core/hooks/setting';
- const { ctxAdminPath } = useGlobSetting();
- interface Props {
- currentConversation: Conversation;
- plugins: Plugin[];
- }
- interface Emits {
- (e: 'toggle-theme'): void;
- }
- const props = defineProps<Props>();
- const emit = defineEmits<Emits>();
- const currentTheme = ref<Theme>('dark');
- const messages = ref<Message[]>([]);
- const isLoading = ref(false);
- const chatMessagesRef = ref<InstanceType<typeof ChatMessages>>();
- function toggleTheme() {
- currentTheme.value = currentTheme.value === 'dark' ? 'light' : 'dark';
- document.documentElement.setAttribute('data-theme', currentTheme.value);
- localStorage.setItem('soloncode-theme', currentTheme.value);
- emit('toggle-theme');
- }
- function loadTheme() {
- const savedTheme = localStorage.getItem('soloncode-theme') as Theme | null;
- if (savedTheme) {
- currentTheme.value = savedTheme;
- } else {
- const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
- currentTheme.value = prefersDark ? 'dark' : 'light';
- }
- document.documentElement.setAttribute('data-theme', currentTheme.value);
- }
- async function sendMessage(messageText: string) {
- const userMessage: Message = {
- id: Date.now(),
- role: 'user',
- timestamps: new Date().toLocaleTimeString(),
- contents: [{ type: 'text', text: messageText }],
- };
- messages.value.push(userMessage);
- // 保存用户消息到数据库
- // await saveMessage({
- // conversationId: props.currentConversation.id,
- // role: 'user',
- // timestamps: userMessage.timestamps,
- // contents: userMessage.contents,
- // });
- isLoading.value = true;
- await chatMessagesRef.value?.scrollToBottom();
- try {
- const sessionId = props.currentConversation.id.toString();
- const url = `${ctxAdminPath}/ai/call?prompt=${encodeURIComponent(messageText)}&m=stream`;
- const response = await window.fetch(url, {
- method: 'GET',
- headers: {
- 'X-Session-Id': sessionId,
- },
- });
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- const reader = response.body?.getReader();
- const decoder = new TextDecoder();
- const currentType = ref<ContentType>();
- if (reader) {
- while (true) {
- const { done, value } = await reader.read();
- if (done) return;
- const chunk = decoder.decode(value, { stream: true });
- const lines = chunk.split('\n');
- for (const line of lines) {
- if (line.trim()) {
- try {
- let jsonStr = line.trim();
- if (jsonStr.startsWith('data:')) {
- jsonStr = jsonStr.substring(5).trim();
- }
- if (jsonStr === '[DONE]') {
- // 保存助手消息到数据库
- const assistantMsg = messages.value[messages.value.length - 1];
- if (assistantMsg && assistantMsg.role === 'assistant') {
- // await saveMessage({
- // conversationId: props.currentConversation.id,
- // role: 'assistant',
- // timestamps: assistantMsg.timestamps,
- // contents: assistantMsg.contents,
- // });
- }
- isLoading.value = false;
- await chatMessagesRef.value?.scrollToBottom();
- return;
- }
- const data = JSON.parse(jsonStr);
- const type = data.type as ContentType;
- let text = data.text || '';
- if (text === '') {
- continue;
- }
- if (currentType.value != type) {
- let isAddText = false;
- const addText = '\n```\n\n';
- if (currentType.value && (currentType.value == 'reason' || currentType.value == 'action')) {
- isAddText = true;
- }
- currentType.value = type;
- if (type === 'action') {
- text =
- '```md\n> ⚡ ' + data?.toolName ||
- '工具' + '\n' + JSON.stringify(data.args) + '\n' + text.substring(0, 5) + '...\n```\n\n';
- } else if (type === 'reason') {
- text = '```md\n> 🧠\n' + text;
- } else {
- text = '\n\n' + text;
- }
- if (isAddText) {
- text = addText + text;
- }
- }
- console.log(text);
- if (text || data.toolName || data.args) {
- // 获取或创建助手消息
- const lastMsg = messages.value[messages.value.length - 1];
- if (!lastMsg || lastMsg.role !== 'assistant') {
- const newMsg: Message = {
- id: Date.now() + Math.floor(Math.random() * 1000),
- role: 'assistant',
- timestamps: new Date().toLocaleTimeString(),
- contents: [],
- };
- messages.value.push(newMsg);
- }
- const assistantMsg = messages.value[messages.value.length - 1];
- const lastContent = assistantMsg.contents[assistantMsg.contents.length - 1];
- if (lastContent) {
- lastContent.text += text;
- } else {
- assistantMsg.contents.push({ type: 'text', text });
- }
- await chatMessagesRef.value?.scrollToBottom();
- }
- } catch (e) {
- console.warn('Failed to parse chunk:', line, e);
- }
- }
- }
- }
- }
- } catch (error) {
- console.error('Failed to send message:', error);
- const errorMessage: Message = {
- id: Date.now() + 1,
- role: 'error',
- timestamps: new Date().toLocaleTimeString(),
- contents: [{ type: 'error', text: `请求失败: ${error instanceof Error ? error.message : '未知错误'}` }],
- };
- messages.value.push(errorMessage);
- // 保存错误消息到数据库
- // await saveMessage({
- // conversationId: props.currentConversation.id,
- // role: 'error',
- // timestamps: errorMessage.timestamps,
- // contents: errorMessage.contents,
- // });
- } finally {
- isLoading.value = false;
- await chatMessagesRef.value?.scrollToBottom();
- }
- }
- async function loadSolonClawMessages() {
- // 优先从数据库加载历史消息
- const storedMessages = await getMessagesByConversation('SolonClaw');
- if (storedMessages.length > 0) {
- messages.value = storedMessages.map((msg) => ({
- ...msg,
- contents: msg.contents,
- }));
- } else {
- messages.value = [
- {
- id: 1,
- role: 'assistant',
- timestamps: new Date().toLocaleTimeString(),
- contents: [
- {
- type: 'text',
- text: '🦊 猎影 已启动\n\n我是AI数据研判专家。我可以帮助你:\n\n处理和分析银行账单、第三方支付流水、通讯话单(CDR)、基站轨迹等多源异构数据。\n\n擅长利用图算法、时序分析和异常检测模型从杂乱无章的数据中挖掘出隐蔽的贿赂线索、利益输送链条和攻守同盟关系。\n\n请告诉我你需要什么帮助?',
- },
- ],
- },
- ];
- }
- }
- async function loadConversationMessages(convId: string | number) {
- const storedMessages = await getMessagesByConversation(convId);
- if (storedMessages.length > 0) {
- messages.value = storedMessages.map((msg) => ({
- ...msg,
- contents: msg.contents,
- }));
- } else {
- messages.value = [
- {
- id: 1,
- role: 'assistant',
- timestamps: new Date().toLocaleTimeString(),
- contents: [
- {
- type: 'text',
- text: '你好!我是 猎影 助手。有什么我可以帮助你的吗?',
- },
- ],
- },
- ];
- }
- }
- watch(
- () => props.currentConversation.id,
- (newId) => {
- if (newId === 'SolonClaw' && props.currentConversation.isPermanent) {
- loadSolonClawMessages();
- } else {
- loadConversationMessages(newId);
- }
- },
- { immediate: true },
- );
- onMounted(() => {
- loadTheme();
- });
- </script>
- <template>
- <main class="main-content">
- <ChatHeader
- :title="props.currentConversation.title"
- :status="props.currentConversation.status"
- :theme="currentTheme"
- @toggle-theme="toggleTheme"
- />
- <ChatMessages ref="chatMessagesRef" :messages="messages" :is-loading="isLoading" :theme="currentTheme" />
- <ChatInput @send="sendMessage" />
- </main>
- </template>
- <style scoped>
- .main-content {
- flex: 1;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- height: 100%;
- }
- </style>
|