feat: add skill and assistant knowledge bases
This commit is contained in:
1 parent
dd0ee282df
commit
fbd8dec48f
45 files changed
+5262
-21
No files matched your search
@@ -0,0 +1,177 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/assistant-knowledge`;
|
||||
|
||||
export interface AssistantKnowledgeBase {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AssistantWikiPage {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
page_type: string;
|
||||
content_markdown: string;
|
||||
summary: string;
|
||||
current_revision_id?: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AssistantWikiRevision {
|
||||
id: string;
|
||||
page_id: string;
|
||||
revision_no: number;
|
||||
summary: string;
|
||||
content_markdown: string;
|
||||
change_type: string;
|
||||
created_by?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AssistantKnowledgeSource {
|
||||
id: string;
|
||||
source_type: "weknora" | "skill" | "local_file";
|
||||
source_name: string;
|
||||
source_key: string;
|
||||
status: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AssistantImportJob {
|
||||
id: string;
|
||||
source_id: string;
|
||||
trigger: string;
|
||||
status: string;
|
||||
phase: string;
|
||||
counts: Record<string, number>;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
const detail = data && typeof data === "object" && "detail" in data
|
||||
? (data as { detail: unknown }).detail
|
||||
: `请求失败 (${response.status})`;
|
||||
throw new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export async function getAssistantKnowledgeBase() {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase | null }>(await apiFetch(`${BASE()}/base`));
|
||||
return data.base;
|
||||
}
|
||||
|
||||
export async function initializeAssistantKnowledgeBase(name = "知识梳理") {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase }>(
|
||||
await apiFetch(`${BASE()}/base/initialize`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name }),
|
||||
}),
|
||||
);
|
||||
return data.base;
|
||||
}
|
||||
|
||||
export async function listAssistantWikiPages(q = "") {
|
||||
const params = new URLSearchParams();
|
||||
if (q.trim()) params.set("q", q.trim());
|
||||
return (await readJson<{ pages: AssistantWikiPage[] }>(await apiFetch(`${BASE()}/wiki-pages?${params}`))).pages;
|
||||
}
|
||||
|
||||
export async function listAssistantKnowledgeSources() {
|
||||
return (await readJson<{ sources: AssistantKnowledgeSource[] }>(await apiFetch(`${BASE()}/sources`))).sources;
|
||||
}
|
||||
|
||||
export async function listAssistantImportJobs() {
|
||||
return (await readJson<{ jobs: AssistantImportJob[] }>(await apiFetch(`${BASE()}/import-jobs`))).jobs;
|
||||
}
|
||||
|
||||
export async function listAssistantWikiRevisions(slug: string) {
|
||||
return (await readJson<{ revisions: AssistantWikiRevision[] }>(
|
||||
await apiFetch(`${BASE()}/wiki-pages/${encodeURIComponent(slug)}/revisions`),
|
||||
)).revisions;
|
||||
}
|
||||
|
||||
export async function rollbackAssistantWikiRevision(slug: string, revisionId: string) {
|
||||
return readJson<AssistantWikiRevision>(
|
||||
await apiFetch(
|
||||
`${BASE()}/wiki-pages/${encodeURIComponent(slug)}/revisions/${encodeURIComponent(revisionId)}/rollback`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function uploadAssistantKnowledgeFiles(files: File[]) {
|
||||
const form = new FormData();
|
||||
files.forEach((file) => form.append("files", file));
|
||||
return readJson<{ batch_id: string; jobs: AssistantImportJob[] }>(
|
||||
await apiFetch(`${BASE()}/imports/files`, { method: "POST", body: form }),
|
||||
);
|
||||
}
|
||||
|
||||
export async function exportLlmWikiToAssistant(mappingId: string) {
|
||||
return readJson<AssistantImportJob>(
|
||||
await apiFetch(
|
||||
`${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(mappingId)}/export-to-assistant`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function reimportAssistantKnowledgeSource(sourceId: string) {
|
||||
return readJson<AssistantImportJob>(
|
||||
await apiFetch(`${BASE()}/sources/${encodeURIComponent(sourceId)}/reimport`, {
|
||||
method: "POST",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteAssistantKnowledgeSource(sourceId: string) {
|
||||
const response = await apiFetch(`${BASE()}/sources/${encodeURIComponent(sourceId)}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!response.ok) await readJson(response);
|
||||
}
|
||||
|
||||
const KEY = "assistant-knowledge";
|
||||
|
||||
export function useAssistantKnowledgeBase() {
|
||||
return useQuery({ queryKey: [KEY, "base"], queryFn: getAssistantKnowledgeBase });
|
||||
}
|
||||
|
||||
export function useAssistantWikiPages(query = "") {
|
||||
return useQuery({ queryKey: [KEY, "pages", query], queryFn: () => listAssistantWikiPages(query) });
|
||||
}
|
||||
|
||||
export function useAssistantKnowledgeSources() {
|
||||
return useQuery({ queryKey: [KEY, "sources"], queryFn: listAssistantKnowledgeSources });
|
||||
}
|
||||
|
||||
export function useAssistantImportJobs() {
|
||||
return useQuery({ queryKey: [KEY, "jobs"], queryFn: listAssistantImportJobs });
|
||||
}
|
||||
|
||||
export function useAssistantKnowledgeActions() {
|
||||
const client = useQueryClient();
|
||||
const invalidate = () => client.invalidateQueries({ queryKey: [KEY] });
|
||||
return {
|
||||
initialize: useMutation({ mutationFn: initializeAssistantKnowledgeBase, onSuccess: invalidate }),
|
||||
upload: useMutation({ mutationFn: uploadAssistantKnowledgeFiles, onSuccess: invalidate }),
|
||||
reimportSource: useMutation({ mutationFn: reimportAssistantKnowledgeSource, onSuccess: invalidate }),
|
||||
deleteSource: useMutation({ mutationFn: deleteAssistantKnowledgeSource, onSuccess: invalidate }),
|
||||
rollback: useMutation({
|
||||
mutationFn: ({ slug, revisionId }: { slug: string; revisionId: string }) =>
|
||||
rollbackAssistantWikiRevision(slug, revisionId),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/skill-knowledge`;
|
||||
|
||||
export type SkillKnowledgeTargetType = "weknora" | "assistant";
|
||||
export type SkillKnowledgeTargetMode =
|
||||
| "wiki"
|
||||
| "document"
|
||||
| "faq"
|
||||
| "conversation_archive"
|
||||
| "readonly_sidecar"
|
||||
| "assistant";
|
||||
|
||||
export interface SkillKnowledgeTarget {
|
||||
target_type: SkillKnowledgeTargetType;
|
||||
target_mode: SkillKnowledgeTargetMode;
|
||||
target_id: string;
|
||||
target_name: string;
|
||||
remote_business_key?: string | null;
|
||||
readonly?: boolean;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeBinding {
|
||||
id: string;
|
||||
skill_name: string;
|
||||
target_type: SkillKnowledgeTargetType;
|
||||
target_mode: SkillKnowledgeTargetMode;
|
||||
target_id: string;
|
||||
target_name: string;
|
||||
remote_business_key?: string | null;
|
||||
remote_refs?: Array<{
|
||||
provider: string;
|
||||
remote_kind: string;
|
||||
remote_id: string;
|
||||
slug?: string;
|
||||
}>;
|
||||
status: string;
|
||||
active: boolean;
|
||||
auto_sync_enabled: boolean;
|
||||
synced_digest?: string | null;
|
||||
last_synced_at?: string | null;
|
||||
last_error_message?: string | null;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeSyncItem {
|
||||
id: string;
|
||||
job_id: string;
|
||||
binding_id: string;
|
||||
skill_name: string;
|
||||
target_type: SkillKnowledgeTargetType;
|
||||
target_mode: SkillKnowledgeTargetMode;
|
||||
target_id: string;
|
||||
status: string;
|
||||
phase: string;
|
||||
progress: number;
|
||||
attempts: number;
|
||||
last_error_message?: string | null;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeJob {
|
||||
id: string;
|
||||
status: string;
|
||||
total_count: number;
|
||||
success_count: number;
|
||||
partial_failed_count: number;
|
||||
failed_count: number;
|
||||
review_mode: "required" | "auto_high_confidence" | "off";
|
||||
created_at: string;
|
||||
completed_at?: string | null;
|
||||
items?: SkillKnowledgeSyncItem[];
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeReview {
|
||||
id: string;
|
||||
job_id: string;
|
||||
item_id: string;
|
||||
binding_id: string;
|
||||
object_type: "entity" | "relation" | "wiki" | "alignment";
|
||||
object_key: string;
|
||||
original: Record<string, unknown>;
|
||||
edited?: Record<string, unknown> | null;
|
||||
status: string;
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeAutoSyncSettings {
|
||||
watch_enabled: boolean;
|
||||
schedule_enabled: boolean;
|
||||
schedule_cron: string;
|
||||
debounce_seconds: number;
|
||||
write_remote_enabled: boolean;
|
||||
review_mode: "required" | "auto_high_confidence" | "off";
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
const detail =
|
||||
data && typeof data === "object" && "detail" in data
|
||||
? JSON.stringify((data as { detail: unknown }).detail)
|
||||
: `请求失败 (${response.status})`;
|
||||
throw new Error(detail.replace(/^"|"$/g, ""));
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export async function listSkillKnowledgeBindings(
|
||||
skillNames?: string[],
|
||||
): Promise<SkillKnowledgeBinding[]> {
|
||||
const params = new URLSearchParams();
|
||||
for (const name of skillNames ?? []) params.append("skill_names", name);
|
||||
const response = await apiFetch(`${BASE()}/bindings?${params.toString()}`);
|
||||
return (await readJson<{ bindings: SkillKnowledgeBinding[] }>(response)).bindings;
|
||||
}
|
||||
|
||||
export async function createSkillKnowledgeJob(input: {
|
||||
skill_names: string[];
|
||||
targets: SkillKnowledgeTarget[];
|
||||
force?: boolean;
|
||||
review_mode?: "required" | "auto_high_confidence" | "off";
|
||||
}): Promise<SkillKnowledgeJob> {
|
||||
return readJson(
|
||||
await apiFetch(`${BASE()}/sync-jobs`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function listSkillKnowledgeJobs(): Promise<SkillKnowledgeJob[]> {
|
||||
const response = await apiFetch(`${BASE()}/sync-jobs`);
|
||||
return (await readJson<{ jobs: SkillKnowledgeJob[] }>(response)).jobs;
|
||||
}
|
||||
|
||||
export async function getSkillKnowledgeJob(id: string): Promise<SkillKnowledgeJob> {
|
||||
return readJson(await apiFetch(`${BASE()}/sync-jobs/${encodeURIComponent(id)}`));
|
||||
}
|
||||
|
||||
export async function listSkillKnowledgeReviews(): Promise<SkillKnowledgeReview[]> {
|
||||
const response = await apiFetch(`${BASE()}/reviews?status=pending`);
|
||||
return (await readJson<{ reviews: SkillKnowledgeReview[] }>(response)).reviews;
|
||||
}
|
||||
|
||||
export async function reviewSkillKnowledge(input: {
|
||||
review_ids: string[];
|
||||
action: "approve" | "reject";
|
||||
edits?: Record<string, Record<string, unknown>>;
|
||||
reason?: string;
|
||||
}) {
|
||||
return readJson<{ updated: number; resumed_item_ids: string[] }>(
|
||||
await apiFetch(`${BASE()}/reviews/actions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function retrySkillKnowledgeItem(itemId: string) {
|
||||
return readJson<SkillKnowledgeSyncItem>(
|
||||
await apiFetch(`${BASE()}/sync-items/${encodeURIComponent(itemId)}/retry`, {
|
||||
method: "POST",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function detachSkillKnowledgeBinding(
|
||||
bindingId: string,
|
||||
deleteContributions: boolean,
|
||||
) {
|
||||
return readJson<SkillKnowledgeBinding>(
|
||||
await apiFetch(`${BASE()}/bindings/${encodeURIComponent(bindingId)}/detach`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ delete_contributions: deleteContributions }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function resyncSkillKnowledgeBinding(bindingId: string) {
|
||||
return readJson<SkillKnowledgeJob>(
|
||||
await apiFetch(`${BASE()}/bindings/${encodeURIComponent(bindingId)}/resync`, {
|
||||
method: "POST",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function setSkillKnowledgeBindingAutoSync(
|
||||
bindingId: string,
|
||||
enabled: boolean,
|
||||
) {
|
||||
return readJson<SkillKnowledgeBinding>(
|
||||
await apiFetch(
|
||||
`${BASE()}/bindings/${encodeURIComponent(bindingId)}/${enabled ? "enable" : "disable"}-auto-sync`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSkillKnowledgeAutoSyncSettings() {
|
||||
return readJson<SkillKnowledgeAutoSyncSettings>(
|
||||
await apiFetch(`${BASE()}/auto-sync-settings`),
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateSkillKnowledgeAutoSyncSettings(
|
||||
input: Partial<SkillKnowledgeAutoSyncSettings>,
|
||||
) {
|
||||
return readJson<SkillKnowledgeAutoSyncSettings>(
|
||||
await apiFetch(`${BASE()}/auto-sync-settings`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const KEY = "skill-knowledge";
|
||||
|
||||
export function useSkillKnowledgeBindings(skillNames?: string[]) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "bindings", ...(skillNames ?? [])],
|
||||
queryFn: () => listSkillKnowledgeBindings(skillNames),
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeJobs() {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "jobs"],
|
||||
queryFn: listSkillKnowledgeJobs,
|
||||
refetchInterval: (query) =>
|
||||
(query.state.data ?? []).some((job) => ["queued", "running"].includes(job.status))
|
||||
? 1500
|
||||
: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeReviews() {
|
||||
return useQuery({ queryKey: [KEY, "reviews"], queryFn: listSkillKnowledgeReviews });
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeAutoSyncSettings() {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "auto-sync-settings"],
|
||||
queryFn: getSkillKnowledgeAutoSyncSettings,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeActions() {
|
||||
const client = useQueryClient();
|
||||
const invalidate = () => client.invalidateQueries({ queryKey: [KEY] });
|
||||
return {
|
||||
createJob: useMutation({ mutationFn: createSkillKnowledgeJob, onSuccess: invalidate }),
|
||||
review: useMutation({ mutationFn: reviewSkillKnowledge, onSuccess: invalidate }),
|
||||
retry: useMutation({ mutationFn: retrySkillKnowledgeItem, onSuccess: invalidate }),
|
||||
resync: useMutation({ mutationFn: resyncSkillKnowledgeBinding, onSuccess: invalidate }),
|
||||
setAutoSync: useMutation({
|
||||
mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) =>
|
||||
setSkillKnowledgeBindingAutoSync(id, enabled),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
updateAutoSyncSettings: useMutation({
|
||||
mutationFn: updateSkillKnowledgeAutoSyncSettings,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
detach: useMutation({
|
||||
mutationFn: ({ id, deleteContributions }: { id: string; deleteContributions: boolean }) =>
|
||||
detachSkillKnowledgeBinding(id, deleteContributions),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
};
|
||||
}
|
||||
+21
-1
@@ -1,4 +1,4 @@
|
||||
import { AlertCircle, Edit3, FileText, Loader2, RefreshCw, Trash2 } from "lucide-react";
|
||||
import { AlertCircle, Database, Edit3, FileText, Loader2, RefreshCw, Trash2 } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Navigate, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
@@ -14,6 +14,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownCodeEditor } from "@/components/wiki/MarkdownCodeEditor";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { buildWeKnoraWikiPagePath } from "@/core/llmwiki/source-links";
|
||||
import {
|
||||
createLlmWikiWeKnoraEmbedSession,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
useLlmWikiWikiPage,
|
||||
useLlmWikiRuntime,
|
||||
} from "@/strategy-components/api/llmwiki";
|
||||
import { exportLlmWikiToAssistant } from "@/strategy-components/api/assistant-knowledge";
|
||||
|
||||
const LIST_PATH = "/page/workspace/knowledge";
|
||||
|
||||
@@ -104,6 +106,7 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
const [frameSrc, setFrameSrc] = useState("");
|
||||
const [frameVersion, setFrameVersion] = useState(0);
|
||||
const [frameError, setFrameError] = useState<string | null>(null);
|
||||
const [assistantImporting, setAssistantImporting] = useState(false);
|
||||
const runtime = useLlmWikiRuntime();
|
||||
const details = useLlmWikiKnowledgeBase(knowledgeBaseId || null, !!knowledgeBaseId);
|
||||
|
||||
@@ -255,6 +258,23 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{getStoredAuth()?.system_role === "admin" && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={assistantImporting}
|
||||
onClick={() => {
|
||||
setAssistantImporting(true);
|
||||
void exportLlmWikiToAssistant(knowledgeBaseId)
|
||||
.then(() => toast.success("已导入到助手知识库“知识梳理”"))
|
||||
.catch((error: unknown) => toast.error(error instanceof Error ? error.message : String(error)))
|
||||
.finally(() => setAssistantImporting(false));
|
||||
}}
|
||||
>
|
||||
{assistantImporting ? <Loader2 className="mr-2 size-4 animate-spin" /> : <Database className="mr-2 size-4" />}
|
||||
导入到助手知识库
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
|
||||
Reference in new issue
Block a user