import {z} from 'zod' export type ParseMethod = 'default' | 'pypdf' | 'pdfplumber' | 'unstructured' | 'pymupdf' | 'deepdoc'; export type ChunkStrategy = 'recursive' | 'fixed_size' | 'markdown'; export type IngestionConfig = {deepdoc_processing_mode?: (string | null) | undefined, deepdoc_parallel_threads?: (number | null) | undefined, deepdoc_reserve_cpu?: (number | null) | undefined, deepdoc_limiter_capacity?: (number | null) | undefined, deepdoc_pipeline_monitor?: (boolean | null) | undefined, deepdoc_pipeline_s1_workers?: (number | null) | undefined, deepdoc_gpu_sessions?: (number | null) | undefined, embedding_base_url?: (string | null) | undefined, embedding_api_key?: (string | null) | undefined, embedding_timeout_sec?: (number | null) | undefined, rerank_model_id?: (string | null) | undefined, parse_method?: ParseMethod | undefined, chunk_strategy?: ChunkStrategy | undefined, chunk_method?: (string | null) | undefined, chunk_size?: (number | null) | undefined, chunk_overlap?: number | undefined, headers_to_split_on?: (Array> | null) | undefined, separators?: (Array | null) | undefined, use_token_count?: boolean | undefined, tiktoken_encoding?: string | undefined, enable_protected_content?: boolean | undefined, protected_patterns?: (Array | null) | undefined, table_context_size?: number | undefined, image_context_size?: number | undefined, embedding_model_id?: (string | null) | undefined, collection_locked?: boolean | undefined, allow_mixed_parse_methods?: boolean | undefined, skip_config_validation?: boolean | undefined, embedding_batch_size?: number | undefined, embedding_concurrent?: number | undefined, embedding_use_async?: boolean | undefined, max_retries?: number | undefined, retry_delay?: number | undefined}; export type CreateApiApiKbCollectionsCollectionConfigArgs = {collection: string, body: IngestionConfig}; export type CreateApiApiKbCollectionsCollectionConfigOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const documentProcessingStatus = z.enum(["pending", "running", "chunked", "partially_embedded", "success", "failed", "cancelled"]); export const collectionOperationDetail = z.object({doc_id: z.string(), status: documentProcessingStatus, message: z.string().nullable().optional()}); export const collectionOperationResult = z.object({status: z.string(), collection: z.string(), message: z.string(), warnings: z.array(z.string()).optional(), affected_documents: z.array(collectionOperationDetail).optional(), deleted_counts: z.record(z.string(), z.number().int()).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Save Collection Config * * POST /api/kb/collections/{collection}/config */ export const createApiApiKbCollectionsCollectionConfig = async (args: CreateApiApiKbCollectionsCollectionConfigArgs, options: CreateApiApiKbCollectionsCollectionConfigOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/kb/collections/${encodeURIComponent(String(args.collection))}/config${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(collectionOperationResult, await res.json()) };