Compare commits

..
Author SHA1 Message Date
saint 9f933ba023 style: align register layout with login 2026-10-17 11:17:25 +08:00
saint 9db687ee00 feat: connect chat endpoint to verified retrieval 2026-10-17 10:47:33 +08:00
saint af52ee5f58 feat: add local history and error pages 2026-10-17 10:35:18 +08:00
12 changed files with 78 additions and 15 deletions
+24 -5
View File
@@ -1,15 +1,34 @@
from fastapi import APIRouter
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.schemas.chat import ChatRequest, ChatResponse
from app.schemas.retrieval import RetrievalRequest
from app.services.retrieval import retrieve
router = APIRouter(tags=["chat"])
@router.post("/chat", response_model=ChatResponse)
def chat(payload: ChatRequest) -> ChatResponse:
# TODO: retrieval -> context assembly -> LLM -> evidence/source checks
def chat(payload: ChatRequest, db: Session = Depends(get_db)) -> ChatResponse:
"""运行可复核的关键词检索;模型未配置时绝不伪造生成式回答。"""
result = retrieve(db, RetrievalRequest(query=payload.question, top_k=5))
if result.status == "no_evidence":
return ChatResponse(
answer=f"已收到问题:{payload.question}。当前为基础壳子,尚未接入知识检索或大语言模型。",
status="stub",
answer="未检索到可用的已核验知识依据。请补充更具体的关键词,或由管理员补充并审核资料。",
status="no_evidence",
sources=[],
retrieval_run_id=result.run_id,
)
return ChatResponse(
answer=(
f"已检索到 {result.total_hits} 条已核验知识依据。当前尚未配置大语言模型,"
"因此系统仅返回可追溯证据,不生成或改写答案。"
),
status="retrieval_only",
sources=[
{"title": hit.title, "source_url": hit.source_url}
for hit in result.results
],
retrieval_run_id=result.run_id,
)
+5 -1
View File
@@ -1,3 +1,6 @@
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, Field
@@ -12,5 +15,6 @@ class SourcePreview(BaseModel):
class ChatResponse(BaseModel):
answer: str
status: str
status: Literal["retrieval_only", "no_evidence"]
sources: list[SourcePreview] = []
retrieval_run_id: UUID
+3 -1
View File
@@ -271,7 +271,9 @@ def test_all_management_routes_require_admin_and_history_is_private(anonymous_cl
for method, path in paths:
assert c.request(method, path, json={}).status_code == 403, path
assert c.post("/api/retrieval", json={"query": "占位"}).json()["status"] == "no_evidence"
assert c.post("/api/chat", json={"question": "占位"}).json()["status"] == "stub"
response = c.post("/api/chat", json={"question": "占位"})
assert response.status_code == 200
assert response.json()["status"] == "no_evidence"
def test_admin_access_live_role_and_no_csrf_bypass(client, migrated_database):
+18 -2
View File
@@ -59,12 +59,28 @@ def review(client, item, status="verified"):
)
def test_health_docs_and_stub(client):
def test_health_docs_and_chat_without_evidence(client):
assert client.get("/api/health").json()["status"] == "ok"
assert client.get("/api/ready").json()["database"] == "connected"
assert client.get("/docs").status_code == 200
assert "/api/knowledge/{item_id}/review" in client.get("/openapi.json").json()["paths"]
assert client.post("/api/chat", json={"question": "测试"}).json()["status"] == "stub"
response = client.post("/api/chat", json={"question": "测试"})
assert response.status_code == 200
assert response.json()["status"] == "no_evidence"
def test_chat_returns_real_retrieval_evidence_without_generation(client):
item = knowledge(client, title="那拉提测试资料", content="那拉提文旅服务测试依据")
assert review(client, item).status_code == 200
response = client.post("/api/chat", json={"question": "那拉提文旅服务"})
assert response.status_code == 200
body = response.json()
assert body["status"] == "retrieval_only"
assert "不生成" in body["answer"]
assert body["retrieval_run_id"]
assert body["sources"] == [{"title": "那拉提测试资料", "source_url": "https://example.com/"}]
def test_legacy_create_and_missing_evidence(client):
+2 -1
View File
@@ -4,6 +4,7 @@ import { Activity, BookOpen, Bot, CheckCircle2, ChevronRight, Database, FileText
import { createKnowledge, createSource, getHealth, getKnowledge, getSources, type SourceItem } from './api'
import { retrieveHybrid } from './services/hybrid'
import { getCurrentUser } from './services/auth'
import { saveLocalHistory } from './services/localHistory'
import { useRouter } from 'vue-router'
import type { SessionUser } from './types/auth'
type Page='chat'|'knowledge'|'sources'|'evaluation'
@@ -20,7 +21,7 @@ async function saveSource(){error.value='';notice.value='';if(!sourceForm.value.
let sourceSearchTimer:number|undefined
watch(sourceSearch,()=>{window.clearTimeout(sourceSearchTimer);sourceSearchTimer=window.setTimeout(refreshSources,260)})
onMounted(async()=>{try{currentUser.value=await getCurrentUser()}catch{router.replace('/login');return}try{await getHealth();apiStatus.value='已连接'}catch{apiStatus.value='未连接'}if(currentUser.value.role==='admin')await Promise.all([refresh(),refreshSources()])})
async function send(){const q=question.value.trim();if(!q||busy.value)return;messages.value.push({role:'user',content:q});question.value='';busy.value=true;try{const r=await retrieveHybrid({query:q,top_k:5,candidate_k:50});const content=r.status==='no_evidence'?'未检索到可用的已核验知识依据。请调整问题或补充审核后的资料。':`已通过 RRF 混合检索命中 ${r.total_hits} 条依据(关键词 ${r.lexical_total_hits},向量 ${r.vector_total_hits},${r.elapsed_ms.toFixed(1)} ms)。当前仅展示检索证据,尚未接入大语言模型生成回答。`;messages.value.push({role:'assistant',content,sources:r.results.map(hit=>({title:`${hit.title}:${hit.snippet}`,source_url:hit.source_url}))})}catch(e){messages.value.push({role:'assistant',content:e instanceof Error?e.message:'暂时无法连接混合检索服务。'})}finally{busy.value=false}}
async function send(){const q=question.value.trim();if(!q||busy.value)return;messages.value.push({role:'user',content:q});question.value='';busy.value=true;try{const r=await retrieveHybrid({query:q,top_k:5,candidate_k:50});const content=r.status==='no_evidence'?'未检索到可用的已核验知识依据。请调整问题或补充审核后的资料。':`已通过 RRF 混合检索命中 ${r.total_hits} 条依据(关键词 ${r.lexical_total_hits},向量 ${r.vector_total_hits},${r.elapsed_ms.toFixed(1)} ms)。当前仅展示检索证据,尚未接入大语言模型生成回答。`;messages.value.push({role:'assistant',content,sources:r.results.map(hit=>({title:`${hit.title}:${hit.snippet}`,source_url:hit.source_url}))});saveLocalHistory(q,content)}catch(e){const content=e instanceof Error?e.message:'暂时无法连接混合检索服务。';messages.value.push({role:'assistant',content});saveLocalHistory(q,content)}finally{busy.value=false}}
function validUrl(value:string){try{if(value)new URL(value);return true}catch{return false}}
async function save(){
error.value='';notice.value=''
+1 -1
View File
@@ -3,7 +3,7 @@ import type { VectorRetrievalResult } from './services/vectors'
import type { ChunkKeywordResult, HybridResult } from './services/hybrid'
export const getHealth = () => apiRequest<{status:string}>('/api/health')
export const askQuestion = (question:string) => apiRequest<{answer:string;status:string;sources:{title:string;source_url?:string|null}[]}>('/api/chat',{method:'POST',body:JSON.stringify({question})})
export const askQuestion = (question:string) => apiRequest<{answer:string;status:'retrieval_only'|'no_evidence';sources:{title:string;source_url?:string|null}[];retrieval_run_id:string}>('/api/chat',{method:'POST',body:JSON.stringify({question})})
export const getKnowledge = () => apiRequest<{id:number;title:string;category:string;content:string;source_url:string|null;verification_status:string;version:number}[]>('/api/knowledge')
export const createKnowledge = (payload:{title:string;category:string;content:string;source_url?:string;collected_at?:string}) => apiRequest('/api/knowledge',{method:'POST',body:JSON.stringify(payload)},true)
+4 -1
View File
@@ -8,6 +8,8 @@ const router=createRouter({history:createWebHistory(),routes:[
{path:'/',component:App},
{path:'/login',component:()=>import('./views/LoginView.vue'),meta:{public:true}},
{path:'/register',component:()=>import('./views/RegisterView.vue'),meta:{public:true}},
{path:'/403',component:()=>import('./views/ForbiddenView.vue'),meta:{public:true}},
{path:'/history',component:()=>import('./views/HistoryView.vue')},
{path:'/profile',component:()=>import('./views/ProfileView.vue')},
{path:'/settings',component:()=>import('./views/AccountSettingsView.vue')},
{path:'/indexes',component:()=>import('./views/IndexManagementView.vue'),meta:{role:'admin'}},
@@ -17,6 +19,7 @@ const router=createRouter({history:createWebHistory(),routes:[
{path:'/sources',component:()=>import('./views/SourceManagementView.vue'),meta:{role:'admin'}},
{path:'/retrieval-exports',component:()=>import('./views/RetrievalExportView.vue'),meta:{role:'admin'}},
{path:'/admin',component:()=>import('./views/AdminView.vue'),meta:{role:'admin'}},
{path:'/:pathMatch(.*)*',component:()=>import('./views/NotFoundView.vue'),meta:{public:true}},
]})
router.beforeEach(async to=>{if(to.meta.public)return true;try{role=(await getCurrentUser()).role}catch{return {path:'/login',query:{redirect:to.fullPath}}}if(to.meta.role&&role!==to.meta.role)return {path:'/profile',query:{forbidden:'1'}};return true})
router.beforeEach(async to=>{if(to.meta.public)return true;try{role=(await getCurrentUser()).role}catch{return {path:'/login',query:{redirect:to.fullPath}}}if(to.meta.role&&role!==to.meta.role)return {path:'/403'};return true})
export default router
+6
View File
@@ -0,0 +1,6 @@
export type LocalHistoryItem={id:string;question:string;summary:string;created_at:string}
const key='nalati-local-history-v1'
export function readLocalHistory():LocalHistoryItem[]{try{const value=JSON.parse(sessionStorage.getItem(key)||'[]');return Array.isArray(value)?value:[]}catch{return []}}
export function saveLocalHistory(question:string,summary:string){const item:LocalHistoryItem={id:crypto.randomUUID(),question,summary,created_at:new Date().toISOString()};sessionStorage.setItem(key,JSON.stringify([item,...readLocalHistory()].slice(0,100)))}
export function removeLocalHistory(id:string){sessionStorage.setItem(key,JSON.stringify(readLocalHistory().filter(item=>item.id!==id)))}
export function clearLocalHistory(){sessionStorage.removeItem(key)}
+1
View File
@@ -0,0 +1 @@
<template><main><h1>403 无权限</h1><p>当前账户没有访问此页面的权限。管理员能力仍必须由后端授权。</p><RouterLink to="/">返回首页</RouterLink></main></template>
+10
View File
@@ -0,0 +1,10 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { clearLocalHistory, readLocalHistory, removeLocalHistory, type LocalHistoryItem } from '../services/localHistory'
const items=ref<LocalHistoryItem[]>(readLocalHistory()),selected=ref<LocalHistoryItem>()
const empty=computed(()=>!items.value.length)
function refresh(){items.value=readLocalHistory()}
function remove(id:string){removeLocalHistory(id);if(selected.value?.id===id)selected.value=undefined;refresh()}
function clear(){if(window.confirm('确定清除本浏览器的全部本地对话记录吗?')){clearLocalHistory();selected.value=undefined;refresh()}}
</script>
<template><main><RouterLink to="/">返回智能问答</RouterLink><h1>历史对话</h1><p>当前记录仅保存在本浏览器,尚未接入服务器持久化;清除浏览器数据后可能丢失。</p><button :disabled="empty" @click="clear">清除全部本地记录</button><p v-if="empty">暂无本地记录。请先在智能问答页发起提问。</p><table v-else><thead><tr><th>问题</th><th>时间</th><th>操作</th></tr></thead><tbody><tr v-for="item in items" :key="item.id"><td>{{item.question}}</td><td>{{new Date(item.created_at).toLocaleString()}}</td><td><button @click="selected=item">查看</button><button @click="remove(item.id)">删除</button></td></tr></tbody></table><section v-if="selected"><h2>{{selected.question}}</h2><p>{{selected.summary}}</p></section></main></template>
+1
View File
@@ -0,0 +1 @@
<template><main><h1>404 页面不存在</h1><p>请检查地址,或返回智能问答首页。</p><RouterLink to="/">返回首页</RouterLink></main></template>
+2 -2
View File
@@ -5,5 +5,5 @@ import { register } from '../services/auth'
const username=ref(''),password=ref(''),confirmPassword=ref(''),error=ref(''),notice=ref(''),submitting=ref(false),router=useRouter()
async function submit(){if(submitting.value)return;error.value='';notice.value='';if(password.value!==confirmPassword.value){error.value='两次输入的密码不一致。';return}submitting.value=true;try{await register({username:username.value.trim(),password:password.value});notice.value='注册成功,正在跳转登录页…';window.setTimeout(()=>router.push('/login'),500)}catch(cause){error.value=cause instanceof Error?cause.message:'注册失败,请稍后重试。'}finally{submitting.value=false}}
</script>
<template><main class="auth-page"><section class="auth-panel"><RouterLink to="/">边疆红驿</RouterLink><form class="auth-card" @submit.prevent="submit"><p>CREATE ACCOUNT</p><h1>注册账户</h1><span>新注册账户默认为普通用户;管理员权限仅能由后端授权。</span><label>用户名<input v-model.trim="username" autocomplete="username" required minlength="3" maxlength="100" placeholder="至少 3 个字符"/></label><label>密码<input v-model="password" autocomplete="new-password" required minlength="15" type="password" placeholder="至少 15 位密码"/></label><label>确认密码<input v-model="confirmPassword" autocomplete="new-password" required type="password" placeholder="再次输入密码"/></label><p v-if="error" class="auth-error" role="alert">{{error}}</p><p v-if="notice" class="auth-notice" role="status">{{notice}}</p><button :disabled="submitting">{{submitting?'注册中…':'创建账户'}}</button><small>已有账户? <RouterLink to="/login">前往登录</RouterLink></small></form></section><section class="auth-intro"><p>TRUSTWORTHY KNOWLEDGE</p><h2>从可靠资料出发,<br>再开始提问。</h2><span>未审核知识不会进入正式检索;没有可靠依据时,系统会明确说明知识不足。</span></section></main></template>
<style scoped>.auth-page{min-height:100vh;display:grid;grid-template-columns:.9fr 1.1fr;background:#f5f3eb}.auth-intro{padding:12vw;background:#a5423a;color:#fff;display:flex;flex-direction:column;justify-content:center}.auth-intro p,.auth-card>p{letter-spacing:.14em;font-size:11px;font-weight:700;color:#efc9be}.auth-intro h2{font-size:clamp(40px,4.7vw,64px);line-height:1.08;letter-spacing:-.06em;margin:20px 0}.auth-intro span{max-width:410px;line-height:1.9;color:#f6ded7}.auth-panel{padding:34px;display:flex;flex-direction:column;align-items:center;color:#214d3b;font-weight:700}.auth-panel>a{align-self:stretch}.auth-card{width:min(100%,410px);margin:auto 0;padding:34px;border:1px solid #e3e1d8;border-radius:16px;background:#fffefa;box-shadow:0 18px 45px #27332b14;display:grid;gap:14px}.auth-card h1{margin:0;font-size:30px;letter-spacing:-.04em;color:#27332b}.auth-card>span{color:#707a70;font-size:12px;line-height:1.7;font-weight:400}.auth-card label{display:grid;gap:7px;font-size:12px;color:#526052}.auth-card input{padding:12px;border:1px solid #dfe2d8;border-radius:9px;font:inherit;outline-color:#6f967c}.auth-card button{border:0;border-radius:9px;padding:13px;background:#214d3b;color:#fff;font-weight:700}.auth-card small{color:#707a70;font-weight:400}.auth-error,.auth-notice{margin:0;padding:10px;border-radius:8px;font-size:12px}.auth-error{background:#f8e9e4;color:#a5423a}.auth-notice{background:#e8f1e8;color:#356443}@media(max-width:780px){.auth-page{grid-template-columns:1fr}.auth-panel{padding:22px;order:2}.auth-intro{padding:48px 28px;order:1}.auth-card{margin:44px 0}}</style>
<template><main class="auth-page"><section class="auth-panel"><RouterLink to="/">边疆红驿</RouterLink><form class="auth-card" @submit.prevent="submit"><p>CREATE ACCOUNT</p><h1>注册账户</h1><span>新注册账户默认为普通用户;管理员权限仅能由后端授权。</span><label>用户名<input v-model.trim="username" autocomplete="username" required minlength="3" maxlength="100" placeholder="至少 3 个字符"/></label><label>密码<input v-model="password" autocomplete="new-password" required minlength="15" type="password" placeholder="至少 15 位密码"/></label><label>确认密码<input v-model="confirmPassword" autocomplete="new-password" required type="password" placeholder="再次输入密码"/></label><p v-if="error" class="auth-error" role="alert">{{error}}</p><p v-if="notice" class="auth-notice" role="status">{{notice}}</p><button :disabled="submitting">{{submitting?'注册中…':'创建账户'}}</button><small>已有账户? <RouterLink to="/login">前往登录</RouterLink></small></form></section><section class="auth-intro"><p>边疆红驿 · NALATI KNOWLEDGE HUB</p><h2>从可靠资料出发,<br>再开始提问。</h2><span>未审核知识不会进入正式检索;没有可靠依据时,系统会明确说明知识不足。</span></section></main></template>
<style scoped>.auth-page{min-height:100vh;display:grid;grid-template-columns:1.1fr .9fr;background:#f5f3eb}.auth-intro{padding:12vw;background:#214d3b;color:#fff;display:flex;flex-direction:column;justify-content:center;order:0}.auth-intro p,.auth-card>p{letter-spacing:.14em;font-size:11px;font-weight:700;color:#b8d1be}.auth-intro h2{font-size:clamp(42px,5vw,68px);line-height:1.08;letter-spacing:-.06em;margin:20px 0}.auth-intro span{max-width:410px;line-height:1.9;color:#d7e7da}.auth-panel{padding:34px;display:flex;flex-direction:column;align-items:center;color:#214d3b;font-weight:700;order:1}.auth-panel>a{align-self:stretch}.auth-card{width:min(100%,410px);margin:auto 0;padding:34px;border:1px solid #e3e1d8;border-radius:16px;background:#fffefa;box-shadow:0 18px 45px #27332b14;display:grid;gap:16px}.auth-card h1{margin:0;font-size:30px;letter-spacing:-.04em;color:#27332b}.auth-card>span{color:#707a70;font-size:12px;line-height:1.7;font-weight:400}.auth-card label{display:grid;gap:7px;font-size:12px;color:#526052}.auth-card input{padding:12px;border:1px solid #dfe2d8;border-radius:9px;font:inherit;outline-color:#6f967c}.auth-card button{border:0;border-radius:9px;padding:13px;background:#214d3b;color:#fff;font-weight:700}.auth-card small{color:#707a70;font-weight:400}.auth-error,.auth-notice{margin:0;padding:10px;border-radius:8px;font-size:12px;letter-spacing:normal!important}.auth-error{background:#f8e9e4;color:#a5423a}.auth-notice{background:#e8f1e8;color:#356443}@media(max-width:780px){.auth-page{grid-template-columns:1fr}.auth-panel{padding:22px;order:2}.auth-intro{padding:48px 28px;order:1}.auth-card{margin:44px 0}}</style>