knowledge-service.ts
Overview
knowledge-service.ts is a service module that provides a comprehensive API client layer for managing knowledge bases, documents, chunks, tags, and related data within an application. It acts as an abstraction over HTTP requests to backend endpoints, centralizing and standardizing interactions with knowledge-related APIs.
This file defines a collection of REST API method configurations and exports a registered service instance (kbService) with strongly-typed method keys for convenient use. Additionally, it exports several helper functions for tag management, knowledge graph operations, dataset listing, and document filtering.
The module plays a pivotal role in the system by enabling frontend or other clients to perform CRUD operations and other business logic on knowledge bases, documents, and their components seamlessly.
Detailed Explanation
1. Imported Interfaces and Utilities
Interfaces provide typings for request bodies and parameters:
IRenameTag: Interface describing the shape of a tag rename operation.IFetchDocumentListRequestBody,IFetchKnowledgeListRequestBody,IFetchKnowledgeListRequestParams: Interfaces for request payloads related to fetching knowledge and document lists.
Utilities:
api: Centralized API endpoint definitions.registerServer: Utility to register and type API methods.request,post: HTTP request wrappers for making GET, POST, DELETE calls.
2. methods Object
This object maps method names to their corresponding API endpoint URLs and HTTP methods. It is organized into domains:
Knowledge Base (KB) Management:
createKb,updateKb,rmKb,get_kb_detail,getList
Document Management:
get_document_list,document_change_status,document_rm,document_rename,document_create,document_run,document_change_parser,document_thumbnails,document_upload,web_crawl,document_infos,setMeta,document_delete,upload_and_parse
Chunk Management:
chunk_list,create_chunk,set_chunk,get_chunk,switch_chunk,rm_chunk
Other Utilities:
retrieval_test,knowledge_graph,listTagByKnowledgeIds,getMeta,retrievalTestShare
Dataset Filters:
documentFilter
Each entry contains:
url: The endpoint URL imported fromapi.method: The HTTP method used to call the endpoint (get,post, ordelete).
3. kbService
const kbService = registerServer<keyof typeof methods>(methods, request);
Uses
registerServerutility to create a strongly-typed service object.This object exposes all the methods defined in
methodswith their respective HTTP calls.This abstraction allows consumers to call e.g.
kbService.createKb({ ... })without manually specifying URLs or methods.
4. Exported Helper Functions
These functions provide more specific API interactions that often require parameters or more complex request bodies:
listTag
export const listTag = (knowledgeId: string) => request.get(api.listTag(knowledgeId));
Fetches tags associated with a specific knowledge base ID.
Parameters:
knowledgeId- string identifier of the knowledge base.Returns: Promise resolving to the list of tags.
removeTag
export const removeTag = (knowledgeId: string, tags: string[]) => post(api.removeTag(knowledgeId), { tags });
Removes specified tags from a knowledge base.
Parameters:
knowledgeId: string - knowledge base ID.tags: string[] - array of tags to remove.
Returns: Promise resolving with the removal operation result.
renameTag
export const renameTag = (knowledgeId: string, { fromTag, toTag }: IRenameTag) => post(api.renameTag(knowledgeId), { fromTag, toTag });
Renames a tag within a knowledge base.
Parameters:
knowledgeId: string - knowledge base ID.Object implementing
IRenameTaginterface with:fromTag: string - current tag name.toTag: string - new tag name.
Returns: Promise resolving with the rename operation result.
getKnowledgeGraph
export function getKnowledgeGraph(knowledgeId: string) {
return request.get(api.getKnowledgeGraph(knowledgeId));
}
Retrieves the knowledge graph data for a knowledge base.
Parameters:
knowledgeId: string.Returns: Promise resolving with the graph data.
deleteKnowledgeGraph
export function deleteKnowledgeGraph(knowledgeId: string) {
return request.delete(api.getKnowledgeGraph(knowledgeId));
}
Deletes the knowledge graph associated with the knowledge base.
Parameters:
knowledgeId: string.Returns: Promise resolving with the deletion result.
listDataset
export const listDataset = (
params?: IFetchKnowledgeListRequestParams,
body?: IFetchKnowledgeListRequestBody,
) => request.post(api.kb_list, { data: body || {}, params });
Lists datasets (knowledge bases) with optional filtering.
Parameters:
params: optional query parameters.body: optional POST body with filters.
Returns: Promise resolving with the list of knowledge bases.
listDocument
export const listDocument = (
params?: IFetchKnowledgeListRequestParams,
body?: IFetchDocumentListRequestBody,
) => request.post(api.get_document_list, { data: body || {}, params });
Lists documents with optional filtering.
Parameters: same as
listDatasetbut for documents.Returns: Promise resolving with the document list.
documentFilter
export const documentFilter = (kb_id: string) =>
request.post(api.get_dataset_filter, { kb_id });
Fetches filters applicable to documents within a knowledge base.
Parameters:
kb_id: string.Returns: Promise resolving with filter data.
Important Implementation Details
Centralized API Endpoints: All endpoint URLs are imported from a single
apiutility, ensuring ease of maintenance and consistency.Dynamic Service Registration: The use of
registerServercreates a typed service from themethodsconfig, reducing boilerplate and improving developer experience.Separation of Concerns: The file cleanly separates raw API methods (
kbService) from higher-level utility functions that require parameters or specialized payloads.Combination of HTTP verbs: The service uses GET, POST, and DELETE methods appropriately based on the action semantics.
Interaction With Other System Parts
API Layer: Depends on centralized API endpoint definitions (
api).Request Layer: Uses HTTP request utilities (
request,post) to perform HTTP calls.Interfaces: Relies on TypeScript interfaces for type safety in requests.
Frontend or Client: This module is the main interface for frontend components or other client modules to interact with the knowledge management backend.
Data Flow:
Frontend invokes methods from
kbServiceor helper functions.These methods perform HTTP calls to backend APIs.
Responses provide data for UI rendering or further processing.
Usage Examples
import kbService, { listTag, renameTag } from '@/services/knowledge-service';
// Create a new knowledge base
kbService.createKb({ name: 'New KB', description: 'Sample knowledge base' })
.then(response => console.log('Created:', response));
// List tags for a knowledge base
listTag('kb123')
.then(tags => console.log('Tags:', tags));
// Rename a tag
renameTag('kb123', { fromTag: 'oldTag', toTag: 'newTag' })
.then(() => console.log('Tag renamed successfully'));
Mermaid Class Diagram
classDiagram
class kbService {
<<registered service>>
+createKb(data)
+updateKb(data)
+rmKb(data)
+get_kb_detail(params)
+getList(data)
+get_document_list(params)
+document_change_status(data)
+document_rm(data)
+document_rename(data)
+document_create(data)
+document_run(data)
+document_change_parser(data)
+document_thumbnails(params)
+document_upload(data)
+web_crawl(data)
+document_infos(data)
+setMeta(data)
+chunk_list(data)
+create_chunk(data)
+set_chunk(data)
+get_chunk(params)
+switch_chunk(data)
+rm_chunk(data)
+retrieval_test(data)
+knowledge_graph(params)
+document_delete(params)
+upload_and_parse(data)
+listTagByKnowledgeIds(params)
+documentFilter(data)
+getMeta(params)
+retrievalTestShare(data)
}
class HelperFunctions {
+listTag(knowledgeId)
+removeTag(knowledgeId, tags)
+renameTag(knowledgeId, {fromTag, toTag})
+getKnowledgeGraph(knowledgeId)
+deleteKnowledgeGraph(knowledgeId)
+listDataset(params?, body?)
+listDocument(params?, body?)
+documentFilter(kb_id)
}
kbService <.. HelperFunctions : uses
Summary
The knowledge-service.ts file is a core service module that encapsulates all knowledge base and document management HTTP interactions. It provides a strongly-typed, well-organized, and reusable API layer that facilitates CRUD and advanced operations on knowledge entities, chunks, tags, and retrieval tests. By centralizing endpoint calls and request configurations, it improves maintainability and developer productivity across the application.