feat: add general chat feature (without project/agent concept)
This commit is contained in:
@@ -2,6 +2,7 @@ import { Routes, Route, Navigate } from 'react-router-dom'
|
||||
import MainLayout from './layouts/MainLayout'
|
||||
import HomePage from './pages/HomePage'
|
||||
import AgentChatPage from './pages/AgentChatPage'
|
||||
import ChatPage from './pages/ChatPage'
|
||||
import KnowledgePage from './pages/KnowledgePage'
|
||||
import HistoryPage from './pages/HistoryPage'
|
||||
|
||||
@@ -10,6 +11,7 @@ function App() {
|
||||
<Routes>
|
||||
<Route path="/" element={<MainLayout />}>
|
||||
<Route index element={<HomePage />} />
|
||||
<Route path="chat" element={<ChatPage />} />
|
||||
<Route path="agent/:agentId" element={<AgentChatPage />} />
|
||||
<Route path="knowledge" element={<KnowledgePage />} />
|
||||
<Route path="history" element={<HistoryPage />} />
|
||||
|
||||
139
frontend/src/api/chatApi.ts
Normal file
139
frontend/src/api/chatApi.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* 通用对话API
|
||||
* 无需项目和智能体概念,纯大模型对话
|
||||
*/
|
||||
|
||||
export interface GeneralConversation {
|
||||
id: string
|
||||
userId: string
|
||||
title: string
|
||||
modelName?: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface GeneralMessage {
|
||||
id: string
|
||||
conversationId: string
|
||||
role: 'user' | 'assistant'
|
||||
content: string
|
||||
model?: string
|
||||
tokens?: number
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface SendChatMessageData {
|
||||
content: string
|
||||
modelType: string
|
||||
knowledgeBaseIds?: string[]
|
||||
conversationId?: string
|
||||
}
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
success: boolean
|
||||
data?: T
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息(流式输出)
|
||||
*/
|
||||
export const sendMessageStream = async (
|
||||
data: SendChatMessageData,
|
||||
onChunk: (content: string) => void,
|
||||
onComplete: (conversationId: string) => void,
|
||||
onError: (error: Error) => void
|
||||
) => {
|
||||
try {
|
||||
console.log('🚀 [chatApi] 发送通用对话消息', data)
|
||||
|
||||
const response = await fetch('/api/v1/chat/stream', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) {
|
||||
throw new Error('Response body is null')
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
let conversationId = data.conversationId || ''
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
|
||||
if (done) {
|
||||
break
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() || ''
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmedLine = line.trim()
|
||||
if (!trimmedLine || !trimmedLine.startsWith('data:')) {
|
||||
continue
|
||||
}
|
||||
|
||||
const dataStr = trimmedLine.slice(5).trim()
|
||||
|
||||
if (dataStr === '[DONE]') {
|
||||
console.log('✅ [chatApi] 流式输出完成')
|
||||
onComplete(conversationId)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const chunk = JSON.parse(dataStr)
|
||||
if (chunk.content) {
|
||||
onChunk(chunk.content)
|
||||
}
|
||||
// 从第一个chunk中提取conversationId(如果是新对话)
|
||||
if (!conversationId && chunk.conversationId) {
|
||||
conversationId = chunk.conversationId
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse SSE chunk:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ [chatApi] 发送消息失败:', error)
|
||||
onError(error as Error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取对话列表
|
||||
*/
|
||||
export const getConversations = async (): Promise<ApiResponse<GeneralConversation[]>> => {
|
||||
const response = await fetch('/api/v1/chat/conversations')
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除对话
|
||||
*/
|
||||
export const deleteConversation = async (id: string): Promise<ApiResponse> => {
|
||||
const response = await fetch(`/api/v1/chat/conversations/${id}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
return response.json()
|
||||
}
|
||||
|
||||
export default {
|
||||
sendMessageStream,
|
||||
getConversations,
|
||||
deleteConversation,
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
HomeOutlined,
|
||||
MessageOutlined,
|
||||
ExperimentOutlined,
|
||||
FolderOpenOutlined,
|
||||
HistoryOutlined,
|
||||
@@ -52,6 +53,11 @@ const MainLayout = () => {
|
||||
icon: <HomeOutlined />,
|
||||
label: '首页',
|
||||
},
|
||||
{
|
||||
key: '/chat',
|
||||
icon: <MessageOutlined />,
|
||||
label: '智能问答',
|
||||
},
|
||||
{
|
||||
key: 'agents',
|
||||
icon: <ExperimentOutlined />,
|
||||
|
||||
179
frontend/src/pages/ChatPage.tsx
Normal file
179
frontend/src/pages/ChatPage.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { message } from 'antd'
|
||||
import chatApi, { type GeneralMessage } from '../api/chatApi'
|
||||
import MessageList from '../components/chat/MessageList'
|
||||
import MessageInput from '../components/chat/MessageInput'
|
||||
import ModelSelector, { type ModelType } from '../components/chat/ModelSelector'
|
||||
import { useKnowledgeBaseStore } from '../stores/useKnowledgeBaseStore'
|
||||
|
||||
const ChatPage = () => {
|
||||
const { knowledgeBases, fetchKnowledgeBases } = useKnowledgeBaseStore()
|
||||
|
||||
const [messages, setMessages] = useState<GeneralMessage[]>([])
|
||||
const [selectedModel, setSelectedModel] = useState<ModelType>('deepseek-v3')
|
||||
const [sending, setSending] = useState(false)
|
||||
const [streamingContent, setStreamingContent] = useState('')
|
||||
const [currentConversationId, setCurrentConversationId] = useState<string>()
|
||||
|
||||
// 加载知识库列表
|
||||
useEffect(() => {
|
||||
fetchKnowledgeBases()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// 发送消息(流式)
|
||||
const handleSendMessage = async (content: string, knowledgeBaseIds: string[]) => {
|
||||
if (sending) return
|
||||
|
||||
console.log('🔵 [ChatPage] 发送消息', { content, knowledgeBaseIds, currentConversationId })
|
||||
|
||||
setSending(true)
|
||||
setStreamingContent('')
|
||||
|
||||
// 添加用户消息到列表
|
||||
const userMessage: GeneralMessage = {
|
||||
id: `temp-${Date.now()}`,
|
||||
conversationId: currentConversationId || 'temp',
|
||||
role: 'user',
|
||||
content,
|
||||
createdAt: new Date().toISOString(),
|
||||
}
|
||||
setMessages(prev => [...prev, userMessage])
|
||||
|
||||
try {
|
||||
let fullContent = ''
|
||||
|
||||
await chatApi.sendMessageStream(
|
||||
{
|
||||
content,
|
||||
modelType: selectedModel,
|
||||
knowledgeBaseIds,
|
||||
conversationId: currentConversationId,
|
||||
},
|
||||
// onChunk
|
||||
(chunk) => {
|
||||
fullContent += chunk
|
||||
setStreamingContent(fullContent)
|
||||
},
|
||||
// onComplete
|
||||
(conversationId) => {
|
||||
console.log('✅ [ChatPage] 对话完成', { conversationId })
|
||||
|
||||
// 如果是新对话,保存conversationId
|
||||
if (!currentConversationId && conversationId) {
|
||||
setCurrentConversationId(conversationId)
|
||||
}
|
||||
|
||||
// 添加完整的助手消息
|
||||
const assistantMessage: GeneralMessage = {
|
||||
id: `temp-assistant-${Date.now()}`,
|
||||
conversationId: conversationId || currentConversationId || 'temp',
|
||||
role: 'assistant',
|
||||
content: fullContent,
|
||||
model: selectedModel,
|
||||
createdAt: new Date().toISOString(),
|
||||
}
|
||||
setMessages(prev => [...prev, assistantMessage])
|
||||
setStreamingContent('')
|
||||
setSending(false)
|
||||
},
|
||||
// onError
|
||||
(error) => {
|
||||
console.error('❌ [ChatPage] 发送失败:', error)
|
||||
message.error('发送消息失败:' + error.message)
|
||||
setStreamingContent('')
|
||||
setSending(false)
|
||||
}
|
||||
)
|
||||
} catch (err) {
|
||||
console.error('❌ [ChatPage] 发送消息异常:', err)
|
||||
message.error('发送消息失败')
|
||||
setStreamingContent('')
|
||||
setSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
{/* 顶部工具栏 */}
|
||||
<div style={{
|
||||
padding: '12px 24px',
|
||||
background: '#fff',
|
||||
borderBottom: '1px solid #e8e8e8',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
<div style={{ fontSize: 16, fontWeight: 600 }}>
|
||||
💬 智能问答
|
||||
</div>
|
||||
|
||||
{/* 模型选择器 */}
|
||||
<ModelSelector
|
||||
value={selectedModel}
|
||||
onChange={setSelectedModel}
|
||||
disabled={sending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 聊天区域 */}
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'hidden',
|
||||
minHeight: 0,
|
||||
background: '#fff',
|
||||
}}
|
||||
>
|
||||
{/* 消息列表区域 */}
|
||||
<div style={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
minHeight: 0,
|
||||
overflow: 'hidden',
|
||||
}}>
|
||||
{messages.length === 0 && !sending ? (
|
||||
<div style={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: '#fafafa'
|
||||
}}>
|
||||
<div style={{ textAlign: 'center', color: '#999' }}>
|
||||
<div style={{ fontSize: 48, marginBottom: 16 }}>💬</div>
|
||||
<div style={{ fontSize: 18, fontWeight: 500, marginBottom: 8 }}>
|
||||
与AI自由对话
|
||||
</div>
|
||||
<div style={{ fontSize: 14 }}>
|
||||
直接提问,或使用@知识库引用文献
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<MessageList
|
||||
messages={messages}
|
||||
loading={sending}
|
||||
streamingContent={streamingContent}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 消息输入 */}
|
||||
<MessageInput
|
||||
onSend={handleSendMessage}
|
||||
loading={sending}
|
||||
knowledgeBases={knowledgeBases}
|
||||
placeholder="输入你的问题...(Shift+Enter换行,Enter发送)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ChatPage
|
||||
|
||||
Reference in New Issue
Block a user