gengx
This commit is contained in:
Vendored
+1
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh"><head><script src="/_app-config-5.7.0-7362080d.js"></script><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="renderer" content="webkit"><meta name="description" content="A Modern Back-end Management System"><meta name="keywords" content="Vben Admin Vue3 Vite"><meta name="author" content="Vben"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0"><title>真羊 AI 客服 · 管理后台</title><link rel="icon" href="/favicon.ico"><script>if(window._VBEN_ADMIN_PRO_APP_CONF_){var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?b38e689f40558f20a9a686d7f6f33edf";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()}</script><script type="module" crossorigin src="/jse/index-index-C6SBxvNl.js"></script><link rel="modulepreload" crossorigin href="/js/objectWithoutProperties-BjoYlK0I.js"><link rel="modulepreload" crossorigin href="/js/preload-helper-DaercurD.js"><link rel="modulepreload" crossorigin href="/js/runtime-core.esm-bundler-DkysjgTd.js"><link rel="modulepreload" crossorigin href="/js/objectSpread2-BmonrgTA.js"><link rel="modulepreload" crossorigin href="/js/defu-1oANYd5X.js"><link rel="modulepreload" crossorigin href="/js/merge-C-fCyOMx.js"><link rel="modulepreload" crossorigin href="/js/dist-DUuDCbWu.js"><link rel="modulepreload" crossorigin href="/js/dist-D5mNzO5q.js"><link rel="modulepreload" crossorigin href="/js/module-CyhaP5hi.js"><link rel="modulepreload" crossorigin href="/js/preferences-zaQWU8vR.js"><link rel="modulepreload" crossorigin href="/js/src-DkoRg56f.js"></head><body><script data-app-loading="inject-js">var theme=localStorage.getItem("zhenyang-admin-5.7.0-prod-preferences-theme");document.documentElement.classList.toggle("dark",/dark/.test(theme))</script><style data-app-loading="inject-css">html{line-height:1.15}.loading{position:fixed;top:0;left:0;z-index:9999;display:flex;flex-direction:column;align-items:center;justify-content:center;width:100%;height:100%;overflow:hidden;background-color:#f4f7f9}.loading.hidden{visibility:hidden;pointer-events:none;opacity:0;transition:all .8s ease-out}.dark .loading{background:#0d0d10}.title{margin-top:66px;font-size:28px;font-weight:600;color:rgb(0 0 0 / 85%)}.dark .title{color:#fff}.loader{position:relative;width:48px;height:48px}.loader::before{position:absolute;top:60px;left:0;width:48px;height:5px;content:'';background:hsl(var(--primary,210 100% 50%) / 50%);border-radius:50%;animation:shadow-ani .5s linear infinite}.loader::after{position:absolute;top:0;left:0;width:100%;height:100%;content:'';background:hsl(var(--primary,210 100% 50%));border-radius:4px;animation:jump-ani .5s linear infinite}@keyframes jump-ani{15%{border-bottom-right-radius:3px}25%{transform:translateY(9px) rotate(22.5deg)}50%{border-bottom-right-radius:40px;transform:translateY(18px) scale(1,.9) rotate(45deg)}75%{transform:translateY(9px) rotate(67.5deg)}100%{transform:translateY(0) rotate(90deg)}}@keyframes shadow-ani{0%,100%{transform:scale(1,1)}50%{transform:scale(1.2,1)}}</style><div class="loading" id="__app-loading__"><div class="loader"></div><div class="title">真羊 AI 客服 · 管理后台</div></div><div id="app"></div></body></html>
|
||||
+1
File diff suppressed because one or more lines are too long
+9
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+13
@@ -0,0 +1,13 @@
|
||||
/*!
|
||||
* Vben Admin
|
||||
* Version: 5.7.0
|
||||
* Author: vben
|
||||
* Copyright (C) 2024 Vben
|
||||
* License: MIT License
|
||||
* Description:
|
||||
* Date Created: 2026-10-07
|
||||
* Homepage: https://vben.pro
|
||||
* Contact: ann.vben@gmail.com
|
||||
*/
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["js/bootstrap-BtjqcS5-.js","js/runtime-core.esm-bundler-DkysjgTd.js","js/runtime-dom.esm-bundler-CirRHyjC.js","js/objectSpread2-BmonrgTA.js","js/objectWithoutProperties-BjoYlK0I.js","js/cn-BpFrWzX2.js","js/use-preferences-2Ls4-wCJ.js","js/preferences-zaQWU8vR.js","js/merge-C-fCyOMx.js","js/defu-1oANYd5X.js","js/dist-DUuDCbWu.js","js/dist-D5mNzO5q.js","js/module-CyhaP5hi.js","js/preload-helper-DaercurD.js","js/vue-router-DmVlK1Dq.js","js/rolldown-runtime-hePW80VL.js","js/icon-button-ShH4zO6U.js","js/VisuallyHiddenInput-CDz4_yZw.js","js/vue.runtime.esm-bundler-DXMo22CJ.js","js/Primitive-Bi_oIzTM.js","js/button-Cr_3AtOU.js","js/_plugin-vue_export-helper-BDNMzG2s.js","js/useApi-CROJJdhE-oP73ypFI.js","css/vue-router-CJxWTMt5.css","js/tree-PkikVu7q.js","js/config-Bw_4j2RP.js","js/FormLabel-CiUM-Zyy.js","js/render-content-3dfOk9Gq.js","css/config-CYorFwo-.css","js/src-DkoRg56f.js","js/routes-D8cwqk34.js","js/src-DxaB-oAj.js","js/core-CY2B_m7j.js","js/dayjs.min-DCUUuXM3.js","js/en_US-Cv9hrLhb.js","js/store-B2VrBUyT.js","js/extends-C_p2ba5S.js","js/config-provider-D1kcLCP5.js","js/useConfigInject-z_xeO0pP.js","js/Keyframes-K60KFfv3.js","js/motionUtil-BeNb4tZl.js","js/Portal-jWUJieln.js","js/vue-types-CFReUAWV.js","js/AntdIcon-BN7vh055.js","js/LoadingOutlined-tpSKTswf.js","js/CloseOutlined-BdX5pn5u.js","js/CloseCircleFilled-C9x0ZM0q.js","js/CheckCircleFilled-CvJ3C2gR.js","js/use-access-ObRBpYsT.js","js/loading-Cw3fZBrE.js","css/loading-DXYS4l2z.css","js/src-D78l4oCk.js","js/initDefaultProps-D8Mki4gM.js","js/modal-Ju-U4s3Q.js","js/motion-BmOd6fTF.js","js/raf-CR9Bw2Uc.js","js/omit-C0ksMpVM.js","js/vnode-CRVBf7wj.js","js/style-DuMcmENf.js","js/KeyCode-DNtAKsAc.js","js/pickAttrs-SF6-8m9R.js","js/zoom-C1lAvwDy.js","js/button-B2y2NpJm.js","js/devWarning-DlchpATv.js","js/warning-BLl3S_cO.js","js/createContext-LBMERH-r.js","js/Compact-Icyx2uFm.js","js/_getTag-2z2WZcIh.js","js/isObjectLike-DNah0Hql.js","js/compact-item-BbW5OmKl.js","js/wave-BBnUlIB_.js","js/isVisible-B1N4qR6W.js","js/useState-DlRKQDQX.js","js/styleChecker-CeGG85sE.js","js/ActionButton-DlhIPLDf.js","js/console-DmvFS6DH.js","css/bootstrap-N-yweAqS.css"])))=>i.map(i=>d[i]);
|
||||
import{n as e}from"../js/objectWithoutProperties-BjoYlK0I.js";import{t}from"../js/preload-helper-DaercurD.js";import{n}from"../js/src-DkoRg56f.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function r(e){return e}function i(e){return e}function a(){let e=document.querySelector(`#__app-loading__`);if(e){e.classList.add(`hidden`);let t=document.querySelectorAll(`[data-app-loading^="inject"]`);e.addEventListener(`transitionend`,()=>{e.remove(),t.forEach(e=>e.remove())},{once:!0})}}var o=r({app:{name:`真羊 AI 客服 · 管理后台`,enablePreferences:!1,defaultHomePath:`/model/stats`,enableRefreshToken:!1},copyright:{companyName:`真羊`,companySiteLink:``,date:`2026`,enable:!0,icp:``,icpLink:``}}),s=i({tabLabel:`preferences.antd.tabLabel`,title:`preferences.antd.title`,fields:[{component:`switch`,defaultValue:!0,key:`enableFormFullscreen`,label:`preferences.antd.fields.enableFormFullscreen.label`,tip:`preferences.antd.fields.enableFormFullscreen.tip`},{component:`select`,defaultValue:`single`,key:`tenantMode`,label:`preferences.antd.fields.tenantMode.label`,options:[{label:`preferences.antd.fields.tenantMode.options.single.label`,value:`single`},{label:`preferences.antd.fields.tenantMode.options.multi.label`,value:`multi`}]},{component:`number`,componentProps:{max:200,min:10,step:10},defaultValue:20,key:`defaultTableSize`,label:`preferences.antd.fields.defaultTableSize.label`},{component:`input`,defaultValue:``,key:`reportTitle`,label:`preferences.antd.fields.reportTitle.label`,placeholder:`preferences.antd.fields.reportTitle.placeholder`}]});function c(){return l.apply(this,arguments)}function l(){return l=e(function*(){let r=`zhenyang-admin-5.7.0-prod`;yield n({extension:s,namespace:r,overrides:o});let{bootstrap:i}=yield t(e(function*(){let{bootstrap:e}=yield import(`../js/bootstrap-BtjqcS5-.js`);return{bootstrap:e}}),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76]));yield i(r),a()}),l.apply(this,arguments)}c();
|
||||
@@ -0,0 +1,430 @@
|
||||
"""Tenant-scoped knowledge management routes."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from typing import Any, Literal
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from archive_store import tenant_scope
|
||||
from knowledge_retriever import KnowledgeRetriever, VectorIndex
|
||||
from knowledge_store import KnowledgeStore
|
||||
|
||||
|
||||
class JobBody(BaseModel):
|
||||
source_account_id: str = Field(min_length=1, max_length=64)
|
||||
conversation_id: str = Field(default="", max_length=64)
|
||||
date_from: str = ""
|
||||
date_to: str = ""
|
||||
engine: Literal["rules", "model"] = "rules"
|
||||
model_provider_id: str = Field(default="", max_length=128)
|
||||
model_timeout_seconds: int = Field(default=90, ge=30, le=180)
|
||||
model_concurrency: int = Field(default=4, ge=1, le=16)
|
||||
model_filter: bool = True
|
||||
# 0 = 不限
|
||||
max_messages: int = Field(default=10000, ge=0, le=100000000)
|
||||
max_model_calls: int = Field(default=100, ge=0, le=10000000)
|
||||
staff_confirmed: bool = False
|
||||
auto_watch: bool = False
|
||||
|
||||
|
||||
class JobConfigBody(BaseModel):
|
||||
engine: Literal['rules', 'model']
|
||||
model_provider_id: str = Field(default='', max_length=128)
|
||||
model_timeout_seconds: int = Field(default=90, ge=30, le=180)
|
||||
model_concurrency: int = Field(default=4, ge=1, le=16)
|
||||
model_batch: int | None = Field(default=None, ge=1, le=20)
|
||||
model_filter: bool = True
|
||||
max_model_calls: int = Field(default=100, ge=0, le=10000000)
|
||||
|
||||
|
||||
class RunScopeBody(BaseModel):
|
||||
"""整理范围:不选账号 = 全部授权账号。"""
|
||||
account_ids: list[int] = Field(default_factory=list, max_length=500)
|
||||
date_from: str = ""
|
||||
date_to: str = ""
|
||||
|
||||
|
||||
class RunBody(RunScopeBody):
|
||||
engine: Literal["rules", "model"] = "model"
|
||||
model_provider_id: str = Field(default="", max_length=128)
|
||||
model_timeout_seconds: int = Field(default=90, ge=30, le=180)
|
||||
model_concurrency: int = Field(default=4, ge=1, le=16)
|
||||
model_batch: int = Field(default=8, ge=1, le=20)
|
||||
model_filter: bool = True
|
||||
max_model_calls: int = Field(default=0, ge=0, le=10000000)
|
||||
staff_confirmed: bool = False
|
||||
auto_watch: bool = False
|
||||
|
||||
|
||||
class RunConfigBody(BaseModel):
|
||||
engine: Literal["rules", "model"]
|
||||
model_provider_id: str = Field(default="", max_length=128)
|
||||
model_timeout_seconds: int = Field(default=90, ge=30, le=180)
|
||||
model_concurrency: int = Field(default=4, ge=1, le=16)
|
||||
model_batch: int = Field(default=8, ge=1, le=20)
|
||||
model_filter: bool = True
|
||||
max_model_calls: int = Field(default=0, ge=0, le=10000000)
|
||||
|
||||
|
||||
class KnowledgeConfigBody(BaseModel):
|
||||
default_engine: Literal["rules", "model"] = "model"
|
||||
default_model_provider_id: str = Field(default="", max_length=128)
|
||||
model_concurrency: int = Field(default=4, ge=1, le=16)
|
||||
model_batch: int = Field(default=8, ge=1, le=20)
|
||||
model_filter: bool = True
|
||||
incremental_engine: Literal["rules", "model"] = "rules"
|
||||
|
||||
|
||||
class ModelTestBody(BaseModel):
|
||||
model_provider_id: str = Field(default="", max_length=128)
|
||||
model_timeout_seconds: int = Field(default=90, ge=30, le=180)
|
||||
|
||||
|
||||
class EditBody(BaseModel):
|
||||
revision: int = Field(ge=1)
|
||||
title: str = Field(min_length=1, max_length=160)
|
||||
question: str = Field(min_length=1, max_length=4000)
|
||||
answer: str = Field(min_length=1, max_length=8000)
|
||||
conditions: str = Field(min_length=1, max_length=2000)
|
||||
category: str = Field(default="", max_length=100)
|
||||
kind: Literal["qa", "procedure", "case"] = "qa"
|
||||
valid_until: str = ""
|
||||
|
||||
|
||||
class ActionBody(BaseModel):
|
||||
revision: int = Field(ge=1)
|
||||
confirmed: bool = False
|
||||
restore_revision: int = Field(default=0, ge=0)
|
||||
|
||||
|
||||
class SearchBody(BaseModel):
|
||||
query: str = Field(min_length=2, max_length=2000)
|
||||
|
||||
@field_validator('query', mode='before')
|
||||
@classmethod
|
||||
def trim_query(cls, value):
|
||||
return value.strip() if isinstance(value, str) else value
|
||||
|
||||
|
||||
class ReviewConfirmBody(BaseModel):
|
||||
confirmed: bool = False
|
||||
|
||||
|
||||
class SettingsBody(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
@contextmanager
|
||||
def errors():
|
||||
try:
|
||||
yield
|
||||
except KeyError as exc:
|
||||
raise HTTPException(404, str(exc).strip("'")) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(502, "知识索引服务连接失败,当前知识未发布,请检查服务配置后重试") from exc
|
||||
|
||||
|
||||
def register_knowledge_routes(app, database, require, client_ip, resolve_admin_tenant, current_desktop):
|
||||
store = KnowledgeStore(database)
|
||||
store.initialize()
|
||||
app.state.knowledge_store = store
|
||||
|
||||
def single(principal, account_id):
|
||||
scope = resolve_admin_tenant(principal, account_id)
|
||||
if not isinstance(scope, str) or scope == "*":
|
||||
raise HTTPException(400, "请先选择具体的客户端账号")
|
||||
return scope
|
||||
|
||||
def item_tenant(principal, account_id, item_id):
|
||||
"""单条知识归哪个账号:选了具体账号就是它;「全部账号」下按知识自己的账号,并且必须在授权范围内。
|
||||
不在范围内一律报"不存在",不透露别的账号有哪些知识。"""
|
||||
scope = resolve_admin_tenant(principal, account_id)
|
||||
if isinstance(scope, str) and scope != "*":
|
||||
return scope
|
||||
with database.connect() as db:
|
||||
row = db.execute("SELECT tenant_id FROM knowledge_item WHERE id=?", (item_id,)).fetchone()
|
||||
allowed = tenant_scope(scope)
|
||||
if row is None or not (allowed.everything or row[0] in allowed.tenants):
|
||||
raise HTTPException(404, "知识不存在或不在你的授权范围内")
|
||||
return row[0]
|
||||
|
||||
from knowledge_review import KnowledgeReviewStore
|
||||
reviews = KnowledgeReviewStore(store)
|
||||
|
||||
def run_tenants(principal, account_ids):
|
||||
"""整理范围 → 租户列表。不选账号 = 授权范围内全部有聊天归档的账号。"""
|
||||
if not account_ids:
|
||||
return store.scope_tenants(resolve_admin_tenant(principal, -1)), "全部账号"
|
||||
tenants = []
|
||||
for account_id in dict.fromkeys(account_ids):
|
||||
tenant = resolve_admin_tenant(principal, int(account_id))
|
||||
if isinstance(tenant, str) and tenant != "*":
|
||||
tenants.append(tenant)
|
||||
return tenants, f"{len(tenants)} 个账号"
|
||||
|
||||
# ── 整理批次:一次整理多个账号、全部聊天 ─────────────────────────────────
|
||||
@app.post('/api/v2/knowledge/runs/preview')
|
||||
def preview_run(body: RunScopeBody, principal=Depends(require('knowledge:write', 'im:content:read'))):
|
||||
with errors():
|
||||
tenants, label = run_tenants(principal, body.account_ids)
|
||||
return {**store.preview_run(tenants, body.model_dump()), 'scope_label': label}
|
||||
|
||||
@app.post('/api/v2/knowledge/runs')
|
||||
def create_run(body: RunBody, request: Request, principal=Depends(require('knowledge:write', 'im:content:read'))):
|
||||
with errors():
|
||||
tenants, label = run_tenants(principal, body.account_ids)
|
||||
values = body.model_dump(exclude={'account_ids'})
|
||||
return store.create_run(tenants, values, principal.id, client_ip(request), scope_label=label)
|
||||
|
||||
@app.get('/api/v2/knowledge/runs')
|
||||
def runs(principal=Depends(require('knowledge:read'))):
|
||||
scope = resolve_admin_tenant(principal, -1)
|
||||
return {**store.runs(scope), 'auto': store.auto_summary(scope)}
|
||||
|
||||
@app.put('/api/v2/knowledge/runs/{run_id}/config')
|
||||
def configure_run(run_id: str, body: RunConfigBody, request: Request,
|
||||
principal=Depends(require('knowledge:write', 'im:content:read'))):
|
||||
with errors():
|
||||
return store.configure_run(resolve_admin_tenant(principal, -1), run_id, body.model_dump(),
|
||||
principal.id, client_ip(request))
|
||||
|
||||
@app.post('/api/v2/knowledge/runs/{run_id}/{action}')
|
||||
def run_action(run_id: str, action: str, request: Request,
|
||||
principal=Depends(require('knowledge:write', 'im:content:read'))):
|
||||
with errors():
|
||||
return store.run_action(resolve_admin_tenant(principal, -1), run_id, action, principal.id, client_ip(request))
|
||||
|
||||
@app.get('/api/v2/knowledge/config')
|
||||
def get_config(principal=Depends(require('knowledge:read'))):
|
||||
return store.config()
|
||||
|
||||
@app.put('/api/v2/knowledge/config')
|
||||
def put_config(body: KnowledgeConfigBody, request: Request,
|
||||
principal=Depends(require('knowledge:write', 'im:content:read'))):
|
||||
with errors():
|
||||
return store.save_config(body.model_dump(), principal.id, client_ip(request))
|
||||
|
||||
@app.post('/api/v2/knowledge/models/test')
|
||||
async def test_model(body: ModelTestBody, principal=Depends(require('knowledge:write'))):
|
||||
"""用一条虚构问答试一次整理,确认模型能连通、能按格式输出。不读任何真实聊天。"""
|
||||
from knowledge_model_output import ModelOutputError, normalize_output
|
||||
from knowledge_models import SAMPLE, extract, resolve_model, safe_model_error
|
||||
from model_usage import UsageRecorder
|
||||
options = {'model_provider_id': body.model_provider_id, 'model_timeout_seconds': body.model_timeout_seconds}
|
||||
try:
|
||||
outlet = await asyncio.to_thread(resolve_model, database, options)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
outlet.config = {**outlet.config, 'timeout_ms': body.model_timeout_seconds * 1000}
|
||||
candidate = {**SAMPLE, 'title': SAMPLE['question'], 'conditions': '', 'category': '待分类',
|
||||
'kind': 'qa', 'flags': [], 'sources': []}
|
||||
started = time.monotonic()
|
||||
async with UsageRecorder(database, tenant_id='default', task_id='knowledge-model-test',
|
||||
purpose='knowledge') as recorder:
|
||||
async with httpx.AsyncClient() as client:
|
||||
result, prompt_chars = await extract(client, outlet, candidate, deadline=body.model_timeout_seconds,
|
||||
allow_discard=False, usage_recorder=recorder)
|
||||
reply = {'model_provider_id': outlet.id, 'model_name': outlet.name,
|
||||
'latency_ms': int((time.monotonic() - started) * 1000)}
|
||||
if result.get('error'):
|
||||
return {**reply, 'ok': False, 'error': safe_model_error(result['error'])}
|
||||
try:
|
||||
draft, _, _ = normalize_output(candidate, result.get('text'), prompt_chars)
|
||||
except ModelOutputError as exc:
|
||||
return {**reply, 'ok': False, 'error': f'模型能连通,但输出不符合整理格式:{exc}'}
|
||||
return {**reply, 'ok': True, 'sample': SAMPLE,
|
||||
'draft': {key: draft[key] for key in ('title', 'question', 'answer', 'conditions', 'category', 'kind')}}
|
||||
|
||||
@app.post('/api/v2/knowledge/review-tasks/preview')
|
||||
def preview_reviews(request: Request, account_id: int = -1,
|
||||
principal=Depends(require('knowledge:read', 'knowledge:review', 'im:content:read'))):
|
||||
with errors():
|
||||
return reviews.preview(resolve_admin_tenant(principal, account_id), account_id, principal.id, client_ip(request))
|
||||
|
||||
@app.get('/api/v2/knowledge/review-tasks')
|
||||
def review_tasks(principal=Depends(require('knowledge:read', 'knowledge:review', 'im:content:read'))):
|
||||
return {'items': reviews.jobs(principal.id)}
|
||||
|
||||
@app.get('/api/v2/knowledge/review-tasks/{job_id}/results')
|
||||
def review_results(job_id: str, result: str = 'skipped', page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=30, ge=1, le=100),
|
||||
principal=Depends(require('knowledge:read', 'knowledge:review', 'im:content:read'))):
|
||||
with errors():
|
||||
return reviews.results(job_id, principal.id, resolve_admin_tenant(principal, -1), result, page, page_size)
|
||||
|
||||
@app.get('/api/v2/knowledge/review-tasks/{job_id}')
|
||||
def review_task(job_id: str, principal=Depends(require('knowledge:read', 'knowledge:review', 'im:content:read'))):
|
||||
with errors():
|
||||
return reviews.get(job_id, principal.id)
|
||||
|
||||
@app.post('/api/v2/knowledge/review-tasks/{job_id}/{action}')
|
||||
def review_action(job_id: str, action: str, body: ReviewConfirmBody, request: Request,
|
||||
principal=Depends(require('knowledge:read', 'knowledge:review', 'im:content:read'))):
|
||||
with errors():
|
||||
return reviews.action(job_id, action, principal.id, client_ip(request), body.confirmed)
|
||||
|
||||
@app.get("/api/v2/knowledge/overview")
|
||||
def overview(account_id: int | None = None, principal=Depends(require("knowledge:read"))):
|
||||
scope = resolve_admin_tenant(principal, account_id)
|
||||
ts = tenant_scope(scope)
|
||||
with database.connect() as db:
|
||||
accounts = [dict(r) for r in db.execute(
|
||||
f"SELECT id,tenant_id,display_name,external_account_id FROM archive_source_account WHERE {ts.clause()}", ts.params)]
|
||||
return {"counts": store.stats(scope), "source_accounts": accounts, "watches": store.watches(scope),
|
||||
"settings": store.settings(scope) if isinstance(scope, str) and scope != "*" else None,
|
||||
"semantic_configured": VectorIndex().configured}
|
||||
|
||||
@app.put("/api/v2/knowledge/settings")
|
||||
def settings(body: SettingsBody, request: Request, account_id: int | None = None,
|
||||
principal=Depends(require("knowledge:publish"))):
|
||||
with errors():
|
||||
return store.set_enabled(single(principal, account_id), body.enabled, principal.id, client_ip(request))
|
||||
|
||||
@app.put("/api/v2/knowledge/watch/{source_id}")
|
||||
def watch(source_id: str, body: SettingsBody, request: Request, account_id: int | None = None,
|
||||
principal=Depends(require("knowledge:write", "im:content:read"))):
|
||||
with errors():
|
||||
return store.set_watch(single(principal, account_id), source_id, body.enabled, principal.id, client_ip(request))
|
||||
|
||||
@app.get('/api/v2/knowledge/models')
|
||||
def models(account_id: int | None = None, principal=Depends(require('knowledge:write', 'im:content:read'))):
|
||||
# 模型清单是全局的,「全部账号」下也能选
|
||||
from knowledge_models import model_choices
|
||||
return {'items': model_choices(database)}
|
||||
|
||||
@app.put('/api/v2/knowledge/jobs/{job_id}/config')
|
||||
def job_config(job_id: str, body: JobConfigBody, request: Request, account_id: int | None = None,
|
||||
principal=Depends(require('knowledge:write', 'im:content:read'))):
|
||||
with errors():
|
||||
return store.configure_job(single(principal, account_id), job_id, body.model_dump(), principal.id, client_ip(request))
|
||||
|
||||
@app.get("/api/v2/knowledge/jobs")
|
||||
def jobs(account_id: int | None = None, include_auto: bool = False, principal=Depends(require("knowledge:read"))):
|
||||
return {"items": store.jobs(resolve_admin_tenant(principal, account_id), include_auto=include_auto)}
|
||||
|
||||
@app.post("/api/v2/knowledge/jobs/preview")
|
||||
def preview_job(body: JobBody, account_id: int | None = None,
|
||||
principal=Depends(require("knowledge:write", "im:content:read"))):
|
||||
with errors():
|
||||
return store.preview_job(single(principal, account_id), body.model_dump())
|
||||
|
||||
@app.post("/api/v2/knowledge/jobs")
|
||||
def create_job(body: JobBody, request: Request, account_id: int | None = None,
|
||||
principal=Depends(require("knowledge:write", "im:content:read"))):
|
||||
with errors():
|
||||
return store.create_job(single(principal, account_id), body.model_dump(), principal.id, client_ip(request))
|
||||
|
||||
@app.post("/api/v2/knowledge/jobs/{job_id}/{action}")
|
||||
def job_action(job_id: str, action: str, request: Request, account_id: int | None = None,
|
||||
principal=Depends(require("knowledge:write", "im:content:read"))):
|
||||
with errors():
|
||||
return store.job_action(single(principal, account_id), job_id, action, principal.id, client_ip(request))
|
||||
|
||||
@app.get("/api/v2/knowledge/items")
|
||||
def items(account_id: int | None = None, status: str = "", query: str = "",
|
||||
page: int = Query(default=1, ge=1), page_size: int = Query(default=30, ge=1, le=100),
|
||||
principal=Depends(require("knowledge:read"))):
|
||||
result = store.list_items(resolve_admin_tenant(principal, account_id), status, query, page, page_size)
|
||||
# 「全部账号」下列表混着多个账号的知识:每条带上所属账号,点开就能直接看、直接审
|
||||
with database.connect() as db:
|
||||
labels = store._tenant_labels(db, {item["tenant_id"] for item in result["items"]})
|
||||
for item in result["items"]:
|
||||
item.update(account_id=labels[item["tenant_id"]]["account_id"], account_label=labels[item["tenant_id"]]["label"])
|
||||
return result
|
||||
|
||||
@app.get("/api/v2/knowledge/items/{item_id}")
|
||||
def detail(item_id: str, account_id: int | None = None, principal=Depends(require("knowledge:read"))):
|
||||
with errors():
|
||||
tenant = item_tenant(principal, account_id, item_id)
|
||||
item = store.detail(tenant, item_id, sources="im:content:read" in principal.permissions)
|
||||
with database.connect() as db:
|
||||
label = store._tenant_labels(db, [tenant])[tenant]
|
||||
return {**item, "account_id": label["account_id"], "account_label": label["label"]}
|
||||
|
||||
@app.put("/api/v2/knowledge/items/{item_id}")
|
||||
def edit(item_id: str, body: EditBody, request: Request, account_id: int | None = None,
|
||||
principal=Depends(require("knowledge:write", "im:content:read"))):
|
||||
with errors():
|
||||
return store.save(item_tenant(principal, account_id, item_id), item_id, body.model_dump(), principal.id,
|
||||
client_ip(request))
|
||||
|
||||
@app.post("/api/v2/knowledge/items/{item_id}/{action}")
|
||||
def transition(item_id: str, action: str, body: ActionBody, request: Request,
|
||||
account_id: int | None = None, principal=Depends(require("knowledge:read"))):
|
||||
permission = "knowledge:publish" if action in {"publish", "disable"} else (
|
||||
"knowledge:write" if action in {"restore", "delete"} else "knowledge:review")
|
||||
if permission not in principal.permissions or "im:content:read" not in principal.permissions:
|
||||
raise HTTPException(403, "缺少知识操作或来源正文查看权限")
|
||||
tenant = item_tenant(principal, account_id, item_id)
|
||||
with errors():
|
||||
if action == 'delete':
|
||||
if not body.confirmed:
|
||||
raise ValueError('请确认删除已驳回知识,原始聊天归档会保留')
|
||||
return store.delete_rejected(tenant, item_id, body.revision, principal.id, client_ip(request))
|
||||
if action == "publish":
|
||||
return store.publish(tenant, item_id, body.revision, principal.id, client_ip(request))
|
||||
if action == "restore":
|
||||
with database.connect() as db:
|
||||
store._item(db, tenant, item_id)
|
||||
previous = db.execute("SELECT snapshot_json FROM knowledge_revision WHERE item_id=? AND revision=? "
|
||||
"ORDER BY created_at DESC LIMIT 1", (item_id, body.restore_revision)).fetchone()
|
||||
if previous is None:
|
||||
raise KeyError("历史版本不存在")
|
||||
values = json.loads(previous[0])
|
||||
values["revision"] = body.revision
|
||||
return store.save(tenant, item_id, values, principal.id, client_ip(request))
|
||||
return store.transition(tenant, item_id, body.revision, action, principal.id, client_ip(request), body.confirmed)
|
||||
|
||||
@app.post("/api/v2/knowledge/search")
|
||||
def search(body: SearchBody, account_id: int | None = None, principal=Depends(require("knowledge:read"))):
|
||||
return KnowledgeRetriever(store).search(single(principal, account_id), body.query)
|
||||
|
||||
@app.get("/api/v2/knowledge/retrievals")
|
||||
def retrievals(account_id: int | None = None, principal=Depends(require("knowledge:read", "stats:read"))):
|
||||
scope = tenant_scope(resolve_admin_tenant(principal, account_id))
|
||||
with database.connect() as db:
|
||||
rows = db.execute(f"SELECT * FROM knowledge_retrieval_log WHERE {scope.clause()} "
|
||||
"ORDER BY created_at DESC LIMIT 100", scope.params).fetchall()
|
||||
return {"items": [{**dict(r), "hits": json.loads(r["hits_json"])} for r in rows]}
|
||||
|
||||
@app.get("/api/v2/knowledge/export")
|
||||
def export(request: Request, account_id: int | None = None,
|
||||
principal=Depends(require("knowledge:read", "knowledge:export"))):
|
||||
tenant = single(principal, account_id)
|
||||
with database.connect() as db:
|
||||
database._audit(db, principal.id, "knowledge.export", f"tenant={tenant}", client_ip(request))
|
||||
|
||||
def stream():
|
||||
cursor = ""
|
||||
while True:
|
||||
with database.connect() as db:
|
||||
rows = db.execute("SELECT * FROM knowledge_item WHERE tenant_id=? AND status='published' AND id>? "
|
||||
"AND (valid_until='' OR valid_until>=?) ORDER BY id LIMIT 200",
|
||||
(tenant, cursor, KnowledgeRetriever._today())).fetchall()
|
||||
if not rows:
|
||||
return
|
||||
cursor = rows[-1]["id"]
|
||||
rows = [r for r in rows if store._fresh(db, r["id"], tenant)]
|
||||
for row in rows:
|
||||
yield json.dumps({"schema_version": "knowledge-v1", **{k: row[k] for k in
|
||||
("id", "revision", "title", "question", "answer", "conditions", "category", "kind", "valid_until")}},
|
||||
ensure_ascii=False) + "\n"
|
||||
return StreamingResponse(stream(), media_type="application/x-ndjson",
|
||||
headers={"Content-Disposition": 'attachment; filename="knowledge.jsonl"'})
|
||||
|
||||
@app.get("/api/v2/knowledge/desktop/summary")
|
||||
def desktop_summary(account: Any = Depends(current_desktop)):
|
||||
tenant = str(account["tenant_id"])
|
||||
counts = store.stats(tenant)
|
||||
return {"published": counts.get("published", 0), "enabled": bool(store.settings(tenant)["enabled"])}
|
||||
|
||||
return store
|
||||
Reference in New Issue
Block a user