import { Observable, RetryConfig, Subject } from 'rxjs'; import { JSONSchema4 } from 'json-schema'; type AccountTypes = 'stash-trial' | 'v3starter' | 'v3fly' | 'v3growth' | 'v3pro' | 'v3enterprise' | 'cowork' | 'stash-basic' | 'stash-team'; interface Account { blocked_features: BlockedFeature[]; blocking_state?: AccountBlockingState; can_manage_account: boolean; config?: AccountConfig; current_agents?: number; current_kbs?: number; current_memories?: number; current_users?: number; domain?: string; description?: string; eula_accepted?: boolean; id: string; limits?: AccountLimits; max_agents: number; max_kbs: number; max_memories: number; /** @deprecated */ max_arags: number; max_users: number | null; saml_entity_id?: string; saml_sso_url?: string; saml_x509_cert?: string; saml_config?: SamlConfig; slug: string; title: string; trial_expiration_date?: string; creation_date: string; type: AccountTypes; workflow?: WorkflowType; } interface AccountConfig { g_speech_to_text: boolean; indexer_slow_replicas: number; max_dedicated_processors: number; } type UploadLimitsEntries = 'upload_limit_max_media_file_size' | 'upload_limit_max_non_media_file_size'; type UploadLimits = { [key in UploadLimitsEntries]: number; }; type NullableUploadLimits = { [key in UploadLimitsEntries]: number | null; }; type UsageLimitsEntries = 'monthly_limit_docs_no_media_processed' | 'monthly_limit_hosted_answers_generated' | 'monthly_limit_hosted_searches_performed' | 'monthly_limit_media_seconds_processed' | 'monthly_limit_paragraphs_processed' | 'monthly_limit_paragraphs_stored' | 'monthly_limit_self_hosted_answers_generated' | 'monthly_limit_self_hosted_searches_performed' | 'storage_limit_max_bytes_per_kb' | 'storage_limit_max_resources_per_kb'; type UsageLimits = { [key in UsageLimitsEntries]: number; }; type NullableUsageLimits = { [key in UsageLimitsEntries]: number | null; }; interface AccountLimits { upload: UploadLimits; usage: UsageLimits; } interface AccountLimitsPatchPayload { upload: NullableUploadLimits; usage: NullableUsageLimits; } declare enum AccountBlockingState { UNBLOCKED = "unblocked", QUOTA = "quota", MANAGER = "manager" } declare enum BlockedFeature { UPLOAD = "upload", PROCESSING = "processing", SEARCH = "search", GENERATIVE = "generative", TRAINING = "training", PUBLIC_UPLOAD = "public_upload", PUBLIC_PROCESSING = "public_processing", PUBLIC_SEARCH = "public_search", PUBLIC_GENERATIVE = "public_generative" } type WorkflowType = 'classic' | 'cowork'; interface AccountCreation { slug?: string; title: string; description?: string; email?: string; eula_accepted?: boolean; zone?: string; workflow?: WorkflowType; campaign_id?: string; } interface SamlConfig { domains: string[]; entity_id: string; sso_url: string; x509_cert: string; idp_initiated_target?: string; authn_context?: 'exact' | 'minimum' | 'better' | 'maximum'; } interface AccountModification { title?: string; description?: string; eula_accepted?: boolean; saml_config?: SamlConfig | null; slug?: string; workflow?: WorkflowType; } interface AccountStatus { available: boolean; } type UsageAggregation = 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year' | 'millennium'; interface CommonMetricDetails { identifier: { [key: string]: string | null; }; raw_usage: { search: number | null; input: number | null; output: number | null; image: number | null; storage: number | null; external_requests: number | null; }; } interface UsageMetric { name: string; value: number; details: CommonMetricDetails[]; } interface NucliaTokensDetails extends CommonMetricDetails { identifier: { type: string; source: string; version: string; model: string | null; service: string; }; nuclia_tokens: { search: number | null; input: number | null; output: number | null; image: number | null; storage: number | null; external_requests: number | null; }; nuclia_tokens_billed: { search: number | null; input: number | null; output: number | null; image: number | null; storage: number | null; external_requests: number | null; }; requests: { api: number | null; chrome_extension: number | null; dashboard: number | null; desktop: number | null; internal: number | null; web: number | null; widget: number | null; }; } interface NucliaTokensMetric extends UsageMetric { name: 'nuclia_tokens'; value: number; details: NucliaTokensDetails[]; } interface UsagePoint { timestamp: string; metrics: (UsageMetric | NucliaTokensMetric)[]; } declare enum UsageType { PRE_PROCESSING_TIME = "pre_processing_time", SLOW_PROCESSING_TIME = "slow_processing_time", RESOURCES_PROCESSED = "resources_processed", BYTES_PROCESSED = "bytes_processed", CHARS_PROCESSED = "chars_processed", MEDIA_SECONDS_PROCESSED = "media_seconds_processed", MEDIA_FILES_PROCESSED = "media_files_processed", PAGES_PROCESSED = "pages_processed", PARAGRAPHS_PROCESSED = "paragraphs_processed", TRAIN_SECONDS = "train_seconds", SEARCHES_PERFORMED = "searches_performed", SUGGESTIONS_PERFORMED = "suggestions_performed", AI_TOKENS_USED = "ai_tokens_used", NUCLIA_TOKENS = "nuclia_tokens_billed" } interface Welcome { preferences: WelcomeUser; accounts: string[]; create: boolean; dependant_accounts: { id: string; slug: string; }[]; } interface WelcomeUser { last_login?: string; email: string; name?: string; type: UserType; language?: Language; } interface SignUpInfo { company: string; email: string; fullname: string; workflow?: WorkflowType; } type UserType = 'ROOT' | 'DEALER' | 'MANAGER' | 'SALES' | 'READONLY' | 'USER' | 'ADMIN'; type Language = 'CA' | 'ES' | 'EN'; interface NUAClientPayload { allow_kb_management?: boolean; client_id?: string; contact: string; description?: string; processing_webhook?: { uri: string; headers?: { [key: string]: string; }; }; title: string; tokens_limit?: number | null; /** @deprecated */ webhook?: string; } interface NUAClientEditPayload { title?: string; contact?: string; tokens_limit?: number | null; } interface NUAClient extends NUAClientPayload { client_id: string; created: string; internal_id: string; partitions: 0; zone: string; } interface NUAClientResponse { client_id: string; internal_id: string; token: string; } interface ProcessingPushResponse { seqid: number; account_seq: number; uuid: string; } interface ProcessingPullResponse { status: string; payload?: string; msgid?: string; } interface LearningConfigurations { [key: string]: LearningConfiguration; } interface LearningConfigurationOption { value: string; name: string; user_key?: string; user_prompt?: string; provider?: string; description?: string; } interface LearningConfiguration { options?: LearningConfigurationOption[]; schema?: LearningConfigurationSchema; schemas?: { [key: string]: LearningConfigurationSchema; }; default: string; create: boolean; update: boolean; } declare function normalizeSchemaProperty(config: LearningConfigurations): LearningConfigurations; declare function improveSchemaNames(config: LearningConfigurations): LearningConfigurations; declare const USER_PROMPTS = "user_prompts"; declare const SUMMARY_PROMPT = "summary_prompt"; interface LearningConfigurationProperty { title: string; type: string; widget?: string; info?: string; examples?: string[]; default?: any; description?: string; anyOf?: { type: string; }[]; $ref?: string; values?: { value: string; label: string; }[]; } interface LearningConfigurationSchema { title: string; type: 'integer' | 'number' | 'string' | 'boolean'; properties: { [key: string]: LearningConfigurationProperty; }; required?: string[]; $defs?: { [key: string]: LearningConfigurationSchema; }; enum?: number[]; titles?: string[]; } declare function getLearningConfigPropType(property: LearningConfigurationProperty): string; declare function getSubSchema(schema: LearningConfigurationSchema, property: LearningConfigurationProperty): LearningConfigurationSchema | undefined; type LearningConfigurationSet = { id: string; data: LearningConfiguration; }[]; interface LearningConfigurationUserKeys { [key: string]: { [key: string]: { title: string; required: boolean; textarea: boolean; }; }; } interface PredictedToken { text: string; ner: string; start: number; end: number; } declare enum ResourceProperties { BASIC = "basic", ORIGIN = "origin", RELATIONS = "relations", VALUES = "values", EXTRACTED = "extracted", ERRORS = "errors", EXTRA = "extra", SECURITY = "security" } interface KbIndex { account_id: string; kb_id: string; kb_mode: KnowledgeBoxMode; zone_id: string; } interface Ner { text: string; ner: string; start: number; end: number; } interface TokenSearch { tokens: Ner[]; time: number; } interface SentenceSearch { data: number[]; time: number; } interface QueryInfo { language: string; stop_words: string[]; semantic_threshold: number; visual_llm: boolean; max_context: number; entities?: TokenSearch; sentence?: SentenceSearch; query: string; } declare enum ModelType { GENERATIVE = "GENERATIVE", NER = "NER", RESOURCE_LABELER = "RESOURCE_LABELER", CLASSIFIER = "CLASSIFIER", ANONYMIZER = "ANONYMIZER", VISUAL_LABELER = "VISUAL_LABELER", SUMMARY = "SUMMARY", DUMMY = "DUMMY", PARAGRAPH_LABELER = "PARAGRAPH_LABELER", EMBEDDINGS = "EMBEDDINGS", RELATIONS = "RELATIONS" } declare enum AssumeRole { NONE = 0, BEDROCK = 1 } interface BaseCustomModel { model_id: string | null; account: string | null; model_types?: ModelType[]; trained_date: string | null; location: string | null; trained_kbid: string | null; } interface CustomModelItem extends BaseCustomModel { title: string | null; } interface CustomModel extends BaseCustomModel { log: string | null; kbids: string[]; openai_compat: any; } interface ModelConfigurationItem { id: string; default_model_id: string; description?: string; assume_role?: AssumeRole; kbids?: string[]; nua_client_ids?: string[]; } interface ModelConfiguration extends ModelConfigurationItem { user_keys?: any; user_prompts?: any; } type ModelConfigurationCreation = Omit; type KnowledgeBoxMode = 'kb' | 'agent' | 'agent_no_memory' | 'agents'; interface NuaGuardPolicy { id: string; name: string; description?: string; instruction: string; query: string; target: 'QUERY'; zone: string; enabled: boolean; blocking: boolean; } type NuaGuardPolicyPayload = Omit; type NuaGuardPolicyResponse = Omit; type NotificationType = 'resource_written' | 'resource_processed' | 'resource_indexed'; type NotificationOperation = 'created' | 'modified' | 'deleted'; interface BaseNotificationData { resource_uuid: string; resource_title: string; seqid: number; } interface ResourceWrittenData extends BaseNotificationData { operation: NotificationOperation; error: boolean; } interface ResourceProcessedData extends BaseNotificationData { ingestion_succeeded: boolean; processing_errors: boolean; } interface NotificationMessage { type: NotificationType; data: BaseNotificationData | ResourceWrittenData | ResourceProcessedData; } declare function getAllNotifications(nuclia: INuclia, path: string, controller: AbortController): Observable; interface IResource { id: string; slug?: string; title?: string; summary?: string; icon?: string; metadata?: Metadata; usermetadata?: UserMetadata; fieldmetadata?: UserFieldMetadata[]; computedmetadata?: ComputedMetadata; extra?: ExtraMetadata; origin?: Origin; security?: Security; created?: string; modified?: string; thumbnail?: string; last_seqid?: number; last_account_seq?: number; queue?: 'private' | 'shared'; hidden?: boolean; relations?: Relation[] | null; data?: ResourceData; } type ResourceData = { files?: { [key: string]: FileFieldData; }; links?: { [key: string]: LinkFieldData; }; texts?: { [key: string]: TextFieldData; }; conversations?: { [key: string]: ConversationFieldData; }; generics?: { [key: string]: GenericFieldData; }; key_values?: { [key: string]: KeyValueFieldData; }; }; interface ICreateResource { title?: string; summary?: string; slug?: string; icon?: string; metadata?: Metadata; usermetadata?: UserMetadata; fieldmetadata?: UserFieldMetadata[]; origin?: Origin; extra?: ExtraMetadata; files?: { [key: string]: FileField; }; links?: { [key: string]: LinkField; }; texts?: { [key: string]: TextField; }; conversations?: { [key: string]: ConversationField; }; security?: Security; hidden?: boolean; processing_options?: ProcessingOptions; } declare enum FIELD_TYPE { text = "text", file = "file", link = "link", conversation = "conversation", generic = "generic", key_value = "key_value" } declare enum RESOURCE_STATUS { PENDING = "PENDING", PROCESSED = "PROCESSED", ERROR = "ERROR", DELETED = "DELETED" } interface Metadata { metadata?: object; language?: string; languages?: string[]; status?: RESOURCE_STATUS; } interface UserMetadata { classifications?: UserClassification[]; relations?: Relation[]; } interface ExtraMetadata { metadata: object; } type RelationType = 'ABOUT' | 'CHILD' | 'COLAB' | 'ENTITY' | 'OTHER' | 'SYNONYM'; type RelationEntityType = 'entity' | 'label' | 'resource' | 'user'; interface Relation { relation: RelationType; label?: string; metadata?: RelationMetadata; from?: RelationEntity; to: RelationEntity; } interface RelationEntity { value: string; type: RelationEntityType; group?: string; } interface RelationMetadata { paragraph_id?: string; source_start?: number; source_end?: number; to_start?: number; to_end?: number; data_augmentation_task_id?: string; } interface Origin { source_id?: string; url?: string; created?: string; modified?: string; metadata?: { [key: string]: string; }; tags?: string[]; collaborators?: string[]; filename?: string; related?: string[]; source?: 'WEB' | 'DESKTOP' | 'API'; path?: string; } interface Security { access_groups: string[]; } interface ProcessingOptions { ml_text?: boolean; } interface IError { body: string; code: number; code_str?: string; created?: string; severity: SEVERITY; } declare enum SEVERITY { ERROR = "ERROR", WARNING = "WARNING" } interface IFieldDataBase { extracted?: ExtractedData; error?: IError; errors?: IError[]; status?: string | null; } interface IFieldData extends IFieldDataBase { value?: TextField | FileField | LinkField | ConversationField | ConversationFieldPages; } interface FieldId { field_type: FIELD_TYPE; field_id: string; } interface FieldFullId extends FieldId { resourceId: string; } interface ResourceField extends IFieldData, FieldId { } declare class FileFieldData implements IFieldData { value?: FileField; extracted?: FileFieldExtractedData; error?: IError; errors?: IError[]; status?: string | null; } interface FileField { added?: string; file?: CloudLink; language?: string; password?: string; external?: boolean; extract_strategy?: string; split_strategy?: string; } interface FileFieldExtractedData extends ExtractedData { file?: FileExtractedData; } interface FileExtractedData { language?: string; md5?: string; metadata?: { [id: string]: string; }; nested?: { [id: string]: string; }; file_generated?: { [id: string]: CloudLink; }; file_rows_previews?: { [id: string]: RowsPreview; }; file_preview?: CloudLink; file_pages_previews?: FilePages; file_thumbnail?: CloudLink; field?: string; icon?: string; nested_position?: { [id: string]: NestedPosition; }; nested_list_position?: { [id: string]: { positions: NestedPosition[]; }; }; } interface NestedPosition { start?: number; end?: number; page?: number; } interface Row { cell?: string[]; } interface Sheet { rows?: Row[]; } interface RowsPreview { sheets?: { [id: string]: Sheet; }; } interface WriteFileField { language?: string[]; file: FileB64; } interface PagePositions { start?: number; end?: number; } interface PageStructure { page: { width: number; height: number; }; tokens: PageToken[]; } interface PageToken { x: number; y: number; width: number; height: number; text: string; line: number; } interface FilePages { pages?: CloudLink[]; positions?: PagePositions[]; structures?: PageStructure[]; } interface FileB64 { filename: string; content_type?: string; payload: string; md5: string; } interface LinkField { added?: string; headers?: { [id: string]: string; }; cookies?: { [id: string]: string; }; uri?: string; language?: string; localstorage?: { [id: string]: string; }; css_selector?: string | null; xpath?: string | null; extract_strategy?: string; split_strategy?: string; } declare class TextFieldData implements IFieldData { value?: TextField; extracted?: ExtractedData; error?: IError; errors?: IError[]; status?: string | null; } type TextFormat = 'PLAIN' | 'MARKDOWN' | 'KEEP_MARKDOWN' | 'HTML' | 'RST'; type TextFieldFormat = TextFormat | 'JSON' | 'JSONL'; interface TextField { body: string; format?: TextFieldFormat; md5?: string; extract_strategy?: string; split_strategy?: string; } interface ExtractedData { text?: ExtractedText; metadata?: FieldComputedMetadata; question_answers?: QuestionAnswers; } interface ExtractedText { text?: string; split_text?: { [id: string]: string; }; deleted_splits?: string[]; } interface FieldComputedMetadata { metadata: FieldMetadata; split_metadata?: { [id: string]: FieldMetadata; }; deleted_splits?: string[]; } interface FieldMetadata { links: string[]; paragraphs: Paragraph[]; ner: { [id: string]: string; }; classifications: Classification[]; last_index?: string; last_understanding?: string; last_extract?: string; last_summary?: string; thumbnail?: CloudLink; language?: string; summary?: string; positions?: EntityPositions; entities: FieldEntities; relations?: Relation[]; } interface EntityPositions { [entityId: string]: EntityPosition; } interface EntityPosition { entity: string; position: { start: number; end: number; }[]; } interface FieldEntities { [key: string]: { entities: FieldEntity[]; }; } interface FieldEntity { text: string; label: string; positions: { start: number; end: number; }[]; } interface QuestionAnswers { question_answers: { question_answer: QuestionAnswer[]; }; split_question_answers?: { [key: string]: { question_answer: QuestionAnswer[]; }; }; deleted_splits?: string[]; } interface QuestionAnswer { question: Question; answers: Answer[]; } interface Question { text: string; language?: string; ids_paragraphs: string[]; } type Answer = Question; declare const DEFAULT_NER_KEY = "processor"; interface UserFieldMetadata { field: { field: string; field_type: string; }; paragraphs?: ParagraphClassification[]; selections?: PageSelections[]; } interface PageSelections { page: number; visual: VisualSelection[]; } interface VisualSelection { label: string; top: number; left: number; right: number; bottom: number; token_ids: number[]; } interface TokenAnnotation { token: string; klass: string; start: number; end: number; } interface ParagraphClassification { classifications: Classification[]; key: string; } interface Classification { labelset: string; label: string; immutable?: boolean; } interface UserClassification extends Classification { cancelled_by_user?: boolean; } type TypeParagraph = 'TEXT' | 'OCR' | 'INCEPTION' | 'DESCRIPTION' | 'TITLE' | 'TRANSCRIPT' | 'TABLE'; interface Paragraph { start?: number; end?: number; start_seconds?: number[]; end_seconds?: number[]; kind?: TypeParagraph; classifications?: Classification[]; sentences?: Sentence[]; key?: string; order?: number; page?: { page?: number; page_with_visual?: boolean; }; representation?: { is_a_table: boolean; reference_file?: string; }; } interface Sentence { start?: number; end?: number; key?: string; } interface CloudLink { filename?: string; md5?: string; uri?: string; size?: number; content_type?: string; extra_headers?: { [key: string]: string; }; } declare class LinkFieldData implements IFieldData { value?: LinkField; extracted?: LinkFieldExtractedData; error?: IError; errors?: IError[]; status?: string | null; } interface LinkFieldExtractedData extends ExtractedData { link?: LinkExtractedData; } interface LinkExtractedData { date?: string; language?: string; title?: string; metadata?: { [id: string]: string; }; link_thumbnail?: CloudLink; link_preview?: CloudLink; field?: string; link_image?: CloudLink; description?: string; type?: string; embed?: string; file_generated?: { [id: string]: CloudLink; }; } interface PositionedNER { entity: string; family: string; start: number; end: number; } interface ComputedMetadata { field_classifications: FieldClassification[]; } interface FieldClassification { field: FieldId; classifications: Classification[]; } declare class ConversationFieldData implements IFieldData { value?: ConversationField | ConversationFieldPages; extracted?: ExtractedData; error?: IError; errors?: IError[]; status?: string | null; } interface GenericFieldData extends IFieldDataBase { value?: string; } type AnyFieldData = FileFieldData | TextFieldData | LinkFieldData | ConversationFieldData | GenericFieldData | KeyValueFieldData; interface ConversationField { messages: Message[]; } interface ConversationFieldPages { pages?: number; size?: number; total?: number; extract_strategy?: string; split_strategy?: string; } interface Message { ident: string; content: MessageContent; timestamp?: string; who?: string; to?: string[]; type?: 'QUESTION' | 'ANSWER'; } interface MessageContent { text: string; format?: TextFormat; attachments_fields?: MessageAttachment[]; } interface MessageAttachment { field_id: string; field_type: string; split?: string; } declare enum ResourceFieldProperties { VALUE = "value", EXTRACTED = "extracted", ERROR = "error" } declare enum ExtractedDataTypes { TEXT = "text", METADATA = "metadata", SHORTENED_METADATA = "shortened_metadata", LARGE_METADATA = "large_metadata", VECTOR = "vectors", LINK = "link", FILE = "file", QUESTION_ANSWERS = "question_answers" } interface TaskResults { results: { [key: string]: AugmentedField; }; } interface AugmentedField { metadata: FieldMetadata; applied_data_augmentation: AppliedDataAugmentation; input_nuclia_tokens: number; output_nuclia_tokens: number; time: number; } interface AppliedDataAugmentation { changed?: boolean; qas?: { question_answer: QuestionAnswer[]; }; new_text_fields?: { text_field: TextField; destination: string; }[]; } /** A closed-bound range value for `range: true` fields (integer, float, or date). */ interface KVRange { lower: number | string; upper: number | string; } type KVValue = string | string[] | number | boolean | KVRange; type KVFieldType = 'text' | 'integer' | 'float' | 'boolean' | 'date'; interface KVSchemaField { key: string; type: KVFieldType; description?: string; required: boolean; range: boolean; repeated: boolean; } interface KVSchema { id: string; description?: string; fields: KVSchemaField[]; } interface KBKVSchemas { schemas: { [id: string]: KVSchema; }; } interface UpdateKVSchema { description?: string; fields?: KVSchemaField[]; } interface KeyValueField { data: Record; } interface KeyValueFieldData extends IFieldDataBase { value?: KeyValueField; } interface UploadResponse { resource?: string; field?: string; progress?: number; failed?: boolean; completed?: boolean; conflict?: boolean; limitExceeded?: boolean; blocked?: boolean; } interface UploadStatus { files: FileUploadStatus[]; progress: number; completed: boolean; uploaded: number; failed: number; conflicts?: number; limitExceeded?: number; blocked?: number; } interface FileUploadStatus { file: File; progress: number; uploaded: boolean; failed: boolean; conflicts?: boolean; limitExceeded?: boolean; blocked?: boolean; } interface FileWithMetadata extends File { lang?: string; md5?: string; payload?: ICreateResource; contentType?: string; processing?: string; split?: string; } interface FileMetadata { lang?: string; contentType?: string; filename?: string; md5?: string; rslug?: string; processing?: string; split?: string; } declare const upload: (nuclia: INuclia, path: string, data: File | FileWithMetadata | ArrayBuffer, TUS: boolean, metadata?: FileMetadata) => Observable; declare const uploadFile: (nuclia: INuclia, path: string, buffer: ArrayBuffer, metadata?: FileMetadata, maxWaitOn429?: number) => Observable; declare const TUSuploadFile: (nuclia: INuclia, path: string, buffer: ArrayBuffer, metadata?: FileMetadata, creationPayload?: ICreateResource, maxWaitOn429?: number) => Observable; declare const batchUpload: (nuclia: INuclia, path: string, files: FileList | File[] | FileWithMetadata[], isResource?: boolean) => Observable; declare const uploadToProcess: (nuclia: INuclia, nuaKey: string, file: File, metadata?: FileMetadata) => Observable; declare const getFileMetadata: (metadata: FileMetadata | undefined) => { [key: string]: string; }; declare namespace Ask { interface Entry { question: string; answer: Answer; } enum Features { KEYWORD = "keyword", SEMANTIC = "semantic", RELATIONS = "relations" } interface Answer { type: 'answer'; text: string; id: string; sources?: Search.FindResults; prequeries?: { [key: string]: Omit; }; citations?: Citations; citation_footnote_to_context?: CitationFootnotes; jsonAnswer?: any; incomplete?: boolean; inError?: boolean; error?: string; metadata?: { /** @deprecated */ tokens?: AskTokens; timings?: AskTimings; }; promptContext?: string[]; augmentedContext?: AugmentedContext; reasoning?: string; consumption?: Consumption; } enum Author { USER = "USER", NUCLIA = "NUCLIA" } interface ContextEntry { author: Author; text: string; } interface AskResponseItem { item: RetrievalAskResponseItem | AnswerAskResponseItem | AnswerJsonResponseItem | MetadataAskResponseItem | CitationsAskResponseItem | CitationFootnotesAskResponseItem | PrequeriesResponseItem | StatusAskResponseItem | ErrorAskResponseItem | RelationsAskResponseItem | DebugAskResponseItem | AugmentedContextAskResponseItem | ReasoningAskResponseItem | ConsumptionAskResponseItem; } interface RetrievalAskResponseItem { type: 'retrieval'; results: Search.FindResults; } interface AnswerAskResponseItem { type: 'answer'; text: string; } interface ReasoningAskResponseItem { type: 'reasoning'; text: string; } interface AnswerJsonResponseItem { type: 'answer_json'; object: any; } interface MetadataAskResponseItem { type: 'metadata'; /** @deprecated */ tokens: AskTokens; timings: AskTimings; } interface CitationsAskResponseItem { type: 'citations'; citations: Citations; } interface CitationFootnotesAskResponseItem { type: 'footnote_citations'; footnote_to_context: CitationFootnotes; } interface PrequeriesResponseItem { type: 'prequeries'; results: { [key: string]: Omit; }; } interface StatusAskResponseItem { type: 'status'; code: string; status: string; details?: string; } interface ErrorAskResponseItem { type: 'error'; error: string; } interface RelationsAskResponseItem { type: 'relations'; relations: Search.Relations; } interface ConsumptionAskResponseItem { type: 'consumption'; normalized_tokens: TokenConsumption; customer_key_tokens: TokenConsumption; } interface DebugAskResponseItem { type: 'debug'; metadata: { [key: string]: any; }; } interface AugmentedContextAskResponseItem { type: 'augmented_context'; augmented: AugmentedContext; } interface AskTokens { input: number; output: number; input_nuclia: number; output_nuclia: number; } interface AskTimings { generative_first_chunk?: number; generative_total?: number; } interface AskResponse { answer: string; status: string; retrieval_results: Search.FindResults; retrieval_best_matches: string[]; prequeries: { [key: string]: Omit; }; learning_id: string; relations: Search.Relations; citations: Citations; citation_footnote_to_context: CitationFootnotes; prompt_context?: string[]; metadata: MetadataAskResponseItem; answer_json?: any; error_details?: string; augmented_context?: AugmentedContext; reasoning?: string; consumption?: Consumption; } interface PredictAnswerResponseItem { chunk: TextPredictAnswerResponseItem | StatusPredictAnswerResponseItem | JsonPredictAnswerResponseItem | ReasoningAskResponseItem; } interface TextPredictAnswerResponseItem { type: 'text'; text: string; } interface StatusPredictAnswerResponseItem { type: 'status'; code: string; } interface JsonPredictAnswerResponseItem { type: 'object'; object: any; } interface AugmentedContext { fields: { [key: string]: AugmentedContextText; }; paragraphs: { [key: string]: AugmentedContextText; }; } interface AugmentedContextText { id: string; text: string; parent?: string; position?: { index: number; start: number; end: number; start_seconds?: number[]; end_seconds?: number[]; page_number?: number; }; augmentation_type: RagStrategyName.FULL_RESOURCE | RagStrategyName.HIERARCHY | RagStrategyName.METADATAS | RagStrategyName.NEIGHBOURING_PARAGRAPHS | RagStrategyName.CONVERSATION; } } interface Citations { [paragraphId: string]: [number, number][]; } interface CitationFootnotes { [blockId: string]: string; } interface Consumption { normalized_tokens: TokenConsumption; customer_key_tokens: TokenConsumption; } interface TokenConsumption { input: number; output: number; image: number; } interface PredictAnswerOptions { retrieval?: boolean; system?: string; chat_history?: Ask.ContextEntry[]; context?: Ask.ContextEntry[]; query_context?: string[] | { [key: string]: string; }; query_context_order?: { [key: string]: number; }; truncate?: boolean; user_prompt?: { prompt: string; }; citations?: boolean; citation_threshold?: number; generative_model?: string; max_tokens?: number; query_context_images?: { content_type: string; b64encoded: string; }; prefer_markdown?: boolean; json_schema?: object; format_prompt?: boolean; rerank_context?: boolean; reasoning?: ReasoningParam; } type ResourceStatus = 'PENDING' | 'PROCESSED' | 'ERROR'; type SortOrder = 'asc' | 'desc'; declare enum SortField { created = "created", modified = "modified", title = "title" } interface SortOption { field: SortField; limit?: number; order?: SortOrder; } declare enum FilterOperator { all = "all", any = "any", none = "none", not_all = "not_all" } type Filter = { [operator in FilterOperator]?: string[]; }; interface Prompts { system?: string; user?: string; rephrase?: string; } interface MinScore { bm25?: number; semantic?: number; } interface RankFusion { name: 'rrf'; boosting: { semantic: number; }; } interface BaseSearchOptions { fields?: string[]; filters?: string[] | Filter[]; filter_expression?: FilterExpression; keyword_filters?: string[] | Filter[]; min_score?: number | MinScore; range_creation_start?: string; range_creation_end?: string; range_modification_start?: string; range_modification_end?: string; show?: ResourceProperties[]; /** @deprecated */ extracted?: ExtractedDataTypes[]; field_type_filter?: FIELD_TYPE[]; resource_filters?: string[]; highlight?: boolean; rephrase?: boolean; vectorset?: string; debug?: boolean; show_hidden?: boolean; audit_metadata?: { [key: string]: string; }; top_k?: number; reranker?: Reranker; rank_fusion?: RankFusion; security?: { groups: string[]; }; search_configuration?: string; } type ReasoningParam = boolean | { display: boolean; effort: 'low' | 'medium' | 'high'; budget_tokens: number; }; interface Routing { generative_model?: string; rules: { search_config: string; prompt: string; }[]; direct_answer?: string; } interface ChatOptions extends BaseSearchOptions { synchronous?: boolean; prompt?: string | Prompts; /** * It will return the text blocks that have been effectively used to build each section of the answer. */ citations?: boolean | 'none' | 'default' | 'llm_footnotes'; rag_strategies?: RAGStrategy[]; rag_images_strategies?: RAGImageStrategy[]; generative_model?: string; /** * Defines the maximum number of tokens that the model will take as context. */ max_tokens?: number | { context?: number; answer?: number; }; prefer_markdown?: boolean; answer_json_schema?: object; extra_context?: string[]; citation_threshold?: number; features?: Ask.Features[]; extra_context_images?: { content_type: string; b64encoded: string; }[]; query_image?: { content_type: string; b64encoded: string; }; reasoning?: ReasoningParam; show_consumption?: boolean; agentic_config_id?: string; } interface SearchOptions extends BaseSearchOptions { faceted?: string[]; sort?: SortOption; offset?: number; /** * @deprecated use top_k */ page_number?: number; /** * @deprecated use top_k */ page_size?: number; with_status?: ResourceStatus; with_duplicates?: boolean; rephrase_prompt?: string; features?: Search.Features[]; } interface CatalogQuery { field: 'title' | 'slug'; match: 'exact' | 'words' | 'fuzzy' | 'starts_with' | 'ends_with' | 'contains'; query: string; } interface CatalogOptions extends Omit { hidden?: boolean; page_number?: number; page_size?: number; filter_expression?: { resource: ResourceFilterExpression; }; } interface SuggestOptions { highlight?: boolean; show_hidden?: boolean; security?: { groups: string[]; }; } interface And { and: T[]; } interface Or { or: T[]; } interface Not { not: T; } interface ResourceFilter { prop: 'resource'; id?: string; slug?: string; } interface FieldFilter { prop: 'field'; type: FIELD_TYPE; name?: string; } interface KeywordFilter { prop: 'keyword'; word: string; } interface DateCreatedFilter { prop: 'created'; since?: string; until?: string; } interface DateModifiedFilter { prop: 'modified'; since?: string; until?: string; } interface LabelFilter { prop: 'label'; labelset: string; label?: string; } interface ResourceMimetypeFilter { prop: 'resource_mimetype'; type: string; subtype?: string; } interface FieldMimetypeFilter { prop: 'field_mimetype'; type: string; subtype?: string; } interface EntityFilter { prop: 'entity'; subtype: string; value?: string; } interface LanguageFilter { prop: 'language'; language: string; only_primary?: boolean; } interface OriginTagFilter { prop: 'origin_tag'; tag: string; } interface OriginMetadataFilter { prop: 'origin_metadata'; field: string; value?: string; } interface OriginPathFilter { prop: 'origin_path'; prefix?: string; } interface OriginSourceFilter { prop: 'origin_source'; id?: string; } interface OriginCollaboratorFilter { prop: 'origin_collaborator'; collaborator: string; } interface StatusFilter { prop: 'status'; status: RESOURCE_STATUS; } interface GeneratedFilter { prop: 'generated'; by: string; da_task?: string; } interface KindFilter { prop: 'kind'; kind: TypeParagraph; } interface KeyValueFilter { schema_id: string; key: string; } interface KeyValueEqualFilter extends KeyValueFilter { eq?: boolean | number | string; } interface KeyValueRangeFilter extends KeyValueFilter { gte?: number | string; lte?: number | string; } interface KeyValueContainsFilter extends KeyValueFilter { eq?: boolean | number | string; contains?: number | string; } interface FilterExpression { field?: FieldFilterExpression; paragraph?: ParagraphFilterExpression; operator?: 'and' | 'or'; key_value?: KeyValueFilterExpression; } type FieldFilterExpression = And | Or | Not | ResourceFilter | FieldFilter | KeywordFilter | DateCreatedFilter | DateModifiedFilter | LabelFilter | ResourceMimetypeFilter | FieldMimetypeFilter | EntityFilter | LanguageFilter | OriginTagFilter | OriginMetadataFilter | OriginPathFilter | OriginSourceFilter | OriginCollaboratorFilter | GeneratedFilter; type ParagraphFilterExpression = And | Or | Not | LabelFilter | KindFilter; type ResourceFilterExpression = And | Or | Not | ResourceFilter | DateCreatedFilter | DateModifiedFilter | LabelFilter | ResourceMimetypeFilter | LanguageFilter | OriginTagFilter | OriginMetadataFilter | OriginPathFilter | OriginSourceFilter | OriginCollaboratorFilter | StatusFilter; type KeyValueFilterExpression = And | Or | Not | KeyValueEqualFilter | KeyValueRangeFilter | KeyValueContainsFilter; declare enum SHORT_FIELD_TYPE { text = "t", file = "f", link = "u", generic = "a", conversation = "c", key_value = "kv" } declare enum Reranker { NOOP = "noop", PREDICT = "predict" } declare namespace Search { enum Features { KEYWORD = "keyword", SEMANTIC = "semantic", FULLTEXT = "fulltext", RELATIONS = "relations" } enum ResourceFeatures { KEYWORD = "keyword", SEMANTIC = "semantic", RELATIONS = "relations" } enum SuggestionFeatures { PARAGRAPH = "paragraph", ENTITIES = "entities" } interface FindResults { type: 'findResults'; resources?: { [id: string]: FindResource; }; next_page: boolean; page_number: number; page_size: number; query: string; total: number; relations?: Relations; searchId?: string; rephrased_query?: string; } interface FindResource extends IResource { fields: { [id: string]: FindField; }; } interface FindField { paragraphs: { [id: string]: FindParagraph; }; } enum FindScoreType { VECTOR = "VECTOR", BM25 = "BM25", BOTH = "BOTH", RERANKER = "RERANKER" } interface FindParagraph { order: number; score: number; score_type: FindScoreType; text: string; id: string; labels: string[]; position: { index: number; start: number; end: number; start_seconds?: number[]; end_seconds?: number[]; page_number?: number; }; fuzzy_result: boolean; page_with_visual: boolean; is_a_table: boolean; reference: string; } interface Results { type: 'searchResults'; resources?: { [id: string]: IResource; }; sentences?: Sentences; paragraphs?: Paragraphs; fulltext?: Fulltext; relations?: Relations; } interface Pagination { total: number; page_number: number; page_size: number; next_page: boolean; } interface FieldResult extends IResource { paragraphs?: FindParagraph[]; field?: FieldId; fieldData?: IFieldData; } interface Suggestions { type: 'suggestions'; paragraphs?: Paragraphs; entities?: EntitySuggestions; } interface EntitySuggestions { total?: number; entities?: { value: string; family: string; }[]; } interface Sentences extends Pagination { results: Sentence[]; facets: FacetsResult; } interface Fulltext extends Pagination { results: FulltextResource[]; facets: FacetsResult; } interface Paragraphs extends Pagination { results: Paragraph[]; facets: FacetsResult; } interface Relations { entities: { [key: string]: { related_to: Relation[]; }; }; } interface Relation { entity: string; entity_type: RelationEntityType; relation: RelationType; relation_label: string; direction: 'in' | 'out'; } interface FacetsResult { [key: string]: { [value: string]: number; }; } interface Paragraph { order: number; score: number; rid: string; field_type: SHORT_FIELD_TYPE; field: string; text: string; labels: string[]; start_seconds?: number[]; end_seconds?: number[]; position?: { page_number: number; start: number; end: number; index: number; }; } interface Sentence { score: number; rid: string; field_type: SHORT_FIELD_TYPE; field: string; text: string; position?: { page_number?: number; start: number; end: number; index: number; }; } interface FulltextResource { score: number; rid: string; field_type: string; field: string; } } interface ReadableResource extends IResource { } /** * Implements all the read operations on resources. * * A resource allows you to store content in the Knowledge Box. * A single resource might contain several fields. * * Fields have different types: files, links, texts, conversations, etc. */ declare class ReadableResource implements IResource { data: ResourceData; private fieldTextsCache; /** * Note: Usually you will not need to create a `Resource` object yourself. * It is returned by the `getResource` method of the `KnowledgeBox` object. */ constructor(data: IResource); getFields(types?: (keyof ResourceData)[]): T[]; getFieldData(type: keyof ResourceData, fieldId: string): T | undefined; /** Returns the summaries generated by Nuclia for every resource fields. */ getExtractedSummaries(): string[]; /** Returns the texts generated by Nuclia for every resource fields. */ getExtractedTexts(): ExtractedText[]; /** Returns the files contained in the resource. */ getFiles(): CloudLink[]; /** Returns the thumbnails generated by Nuclia for every resource fields. */ getThumbnails(): CloudLink[]; /** Returns the entities extracted from the resource. */ getNamedEntities(): { [key: string]: string[]; }; getClassifications(): Classification[]; getPositionedNamedEntities(fieldType: keyof ResourceData, fieldId: string): PositionedNER[]; private formatTitle; getParagraphText(fieldType: FIELD_TYPE, fieldId: string, paragraph: Paragraph, split?: string): string; getSentenceText(fieldType: FIELD_TYPE, fieldId: string, sentence: Sentence, split?: string): string; private getFieldText; } /** Extends `ReadableResource` and implements all the write operations. */ declare class Resource extends ReadableResource implements IResource { kb: string; uuid: string; private nuclia; get kbPath(): string; get path(): string; constructor(nuclia: INuclia, kb: string, data: IResource); /** * Modifies the resource attributes. * * Example: ```ts nuclia.db .getKnowledgeBox('my-account', 'my-kb') .pipe( switchMap((knowledgeBox) => knowledgeBox.getResource('my-resource')), switchMap((resource) => resource.modify({ description: 'new description' })), ) .subscribe(() => { console.log('resource modified'); }); ``` */ modify(data: Partial, synchronous?: boolean): Observable; /** Deletes the resource. */ delete(synchronous?: boolean): Observable; /** Triggers a resource reprocessing. */ reprocess(): Observable; getField(type: FIELD_TYPE, field: string, show?: ResourceFieldProperties[], extracted?: ExtractedDataTypes[], page?: number | 'last' | undefined): Observable; /** Returns the thumbnails generated by Nuclia for every resource fields as `blob:` URLs. */ getThumbnailsUrl(): Observable; /** Deletes the field with the given type and id. */ deleteField(type: FIELD_TYPE, field: string, synchronous?: boolean): Observable; /** * Adds or updates a field in the resource. * * Example: ```ts nuclia.db .getKnowledgeBox('my-account', 'my-kb') .pipe( switchMap((knowledgeBox) => knowledgeBox.getResource('my-resource').pipe( switchMap((resource) => resource.setField(FIELD_TYPE.text, 'my-field', { body: '*my text*', format: 'MARKDOWN', }), ), ), ), ) .subscribe(() => { console.log('field added'); }); ``` */ setField(type: FIELD_TYPE, field: string, data: TextField | LinkField | FileField | ConversationField): Observable; patchField(type: FIELD_TYPE, field: string, data: { extract_strategy?: string; }): Observable; /** Appends messages to a conversation field */ appendMessages(field: string, messages: Message[]): Observable; /** * Uploads a file in the resource. The field will be stored in the indicated field. * * Example: ```ts nuclia.db .getKnowledgeBox('my-account', 'my-kb') .pipe( switchMap((knowledgeBox) => knowledgeBox.getResource('my-resource')), switchMap((resource) => resource.upload(fileInputElement.files[0])), ) .subscribe(() => { console.log('file uploaded'); }); ``` */ upload(field: string, file: File, TUS?: boolean, metadata?: FileMetadata): Observable; upload(field: string, buffer: ArrayBuffer, TUS?: boolean, metadata?: FileMetadata): Observable; /** * Uploads a list of files in the resource. It automatically creates a new field for each file (named according to the filename). * It uses the [TUS](https://tus.io/) protocol to upload the files. */ batchUpload(files: FileList | File[]): Observable; /** Performs a search operation in the resource (similar as `find()` but results are not nested). */ search(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable; /** Performs a find operation in the resource. */ find(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable; /** * Retrieves a generative answer for the given query based on * the results of a search operation performed on the resource. */ ask(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions): Observable; ask(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions, callback?: (answer: Ask.Answer | IErrorResponse) => void): Observable; /** * Retrieves a generative answer for the given query using the entire resource as context * (the resource's text might be shorten if too large). */ askToResource(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions): Observable; askToResource(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions, callback?: (answer: Ask.Answer | IErrorResponse) => void): Observable; setLabels(fieldId: string, fieldType: string, paragraphId: string, labels: Classification[]): Observable; /** * Run tasks on the resource and return the results * (the results are not stored within the resource). */ runTasks(agent_ids?: string[]): Observable; } declare const deDuplicateList: (a: any[]) => any[]; declare const setLabels: (fieldId: string, fieldType: string, paragraphId: string, labels: Classification[], allEntries: UserFieldMetadata[]) => UserFieldMetadata[]; declare const sliceUnicode: (str: string | string[] | undefined, start?: number, end?: number) => string; declare const lengthUnicode: (str: string | undefined) => number; declare const retry429Config: (maxWaitOn429?: number) => RetryConfig; /** Agentic RAG * * The Agentic class allows to define a pipeline of actions to be executed in sequence. * Each action can be of different types: * - predict: ask a question to the LLM model and extract information in a JSON response * - find: search for a set of results based on a query * - ask: perform a Nuclia RAG call based on a query * - web: fetch a web page and extract information based on CSS selectors * - api: call an API and extract information based on a JSON path * - user: wait for a user entry * * Example: * ```typescript * const agentic = nucliaApi.knowledgeBox.createAgenticRAGPipeline({ START: { action: { type: 'predict', query: 'Does the following question refers to a specific reference document? QUESTION: "{{query}}"', outputs: { reference: { type: 'string', description: 'The name of the reference document if any, and just an empty string if none.', }, }, }, next: [ { stepId: 'finddoc', if: '`{{START.reference}}` !== ""' }, { stepId: 'domain', if: '`{{START.reference}}` == ""' }, ], }, finddoc: { action: { type: 'find', query: '{{START.reference}}', features: [Search.Features.KEYWORD], options: { fields: ['a/title'], }, }, next: [{ stepId: 'domain' }], }, domain: { action: { type: 'predict', query: 'What is the domain of the question among the following categories: "ART", "SCIENCE" ? QUESTION: "{{query}}"', outputs: { domain: { type: 'string', description: 'The domain of the question.' }, }, }, next: [{ stepId: 'answer' }], }, answer: { action: { type: 'ask', query: '{{query}}', options: { filters: ['/classification.labels/domain/{{domain.domain}}'], resource_filters: ['{{finddoc.results.resources.[0].id}}'], }, }, }, }); agentic .run({ query, }) .subscribe((res) => console.log(agentic.context)); agentic.status.subscribe((res) => console.log(res)); * ``` */ declare namespace Agentic { interface Output { type: 'string' | 'number' | 'boolean'; description: string; required?: boolean; } interface OutputArray { type: 'array'; items: Output; required?: boolean; } interface PredictAction { type: 'predict'; query: string; context?: string[]; outputs: { [id: string]: Output | OutputArray; }; } interface FindAction { type: 'find'; query: string; features?: Search.Features[]; options: SearchOptions; } interface AskAction { type: 'ask'; query: string; features?: Ask.Features[]; options?: ChatOptions; outputs?: { [id: string]: Output | OutputArray; }; } interface WebAction { type: 'web'; url: string; headers?: { [id: string]: string; }; outputs: { [id: string]: string; }; } interface APIAction { type: 'api'; url: string; method: 'GET' | 'POST'; headers?: { [id: string]: string; }; body?: any; outputs: { [id: string]: string; }; } interface UserEventAction { type: 'user'; label: string; help?: string; inputType: 'boolean' | 'choice' | 'text'; } type Action = PredictAction | FindAction | AskAction | WebAction | APIAction | UserEventAction; interface Step { action: Action; next?: { if?: string; stepId: string; }[]; statusMessage?: string; } interface Event { stepId: string; status: 'running' | 'done' | 'error'; message?: string; } type Steps = { [stepId: string]: Step; }; class Pipeline { private _kb; private _steps; kb: KnowledgeBox; steps: { [stepId: string]: Step; }; context: { [id: string]: any; }; private _events; events: Observable<{ stepId: string; params: UserEventAction; }>; userResponses: Subject<{ stepId: string; value: boolean | string | string[]; }>; private _status; status: Observable; constructor(_kb: KnowledgeBox, _steps: Steps); run(initialContext: object): Observable; private runStep; private runSingleStep; private runPredictAction; private runFindAction; private runAskAction; private runWebAction; private runAPIAction; private runUserAction; private format; private formatObject; } } declare function getObjectValue(obj: object, path: string): any; declare function format(expression: string, context: any, skipMissing?: boolean): string | undefined; declare function formatObject(obj: any, context: any): any; declare function evaluateExpression(expression: string, context: any): T | undefined; declare function ask(nuclia: INuclia, kbid: string, path: string, query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions): Observable; declare function predictAnswer(nuclia: INuclia, path: string, question: string, options?: PredictAnswerOptions, synchronous?: boolean): Observable; declare const LABEL_FILTER_PREFIX = "classification.labels"; declare const NER_FILTER_PREFIX = "entities"; declare const MIME_FILTER_PREFIX = "icon"; declare const PATH_FILTER_PREFIX = "origin.path"; declare const MIME_FACETS: string[]; declare const LANGUAGE_FACET: string[]; declare const MAX_FACETS_PER_REQUEST = 50; declare const CREATION_START_PREFIX = "/creation/start/"; declare const CREATION_END_PREFIX = "/creation/end/"; declare const HIDDEN_PREFIX = "/hidden/"; declare function getFilterFromLabel(label: Classification): string; declare function getLabelFromFilter(filter: string): Classification; declare function getFilterFromLabelSet(labelSet: string): string; declare function getLabelSetFromFilter(filter: string): string; declare function getFilterFromEntity(entity: { family: string; entity: string; }): string; declare function getEntityFromFilter(filter: string): { family: string; entity: string; }; declare function getDateFromFilter(dateFilter: string): string; declare function getFilterFromDate(date: string, type: 'start' | 'end'): string; declare function getVisibilityFromFilter(filter: string): boolean; declare function getFilterFromVisibility(hidden: boolean): string; declare function trimLabelSets(labelSets: LabelSets, classifications: Classification[]): LabelSets; declare const find: (nuclia: INuclia, kbid: string, path: string, query: string, features?: (Search.Features | Search.ResourceFeatures)[], options?: SearchOptions, useGet?: boolean) => Observable; declare const search: (nuclia: INuclia, kbid: string, path: string, query: string, features?: Search.Features[] | Search.ResourceFeatures[], options?: SearchOptions, useGet?: boolean) => Observable; declare const catalog: (nuclia: INuclia, kbid: string, query: string | CatalogQuery, options?: CatalogOptions, useGet?: boolean) => Observable; declare const suggest: (nuclia: INuclia, path: string, query: string, inTitleOnly: boolean, features: Search.SuggestionFeatures[], options?: SuggestOptions) => Observable; declare namespace Widget { type FilterType = 'labels' | 'entities' | 'created' | 'labelFamilies' | 'mime' | 'path'; type FilterSelectionType = { [key in FilterType]: boolean; }; type WidgetFeedback = 'none' | 'answer' | 'answerAndResults'; interface SearchBoxConfig { filter: boolean; filterLogic: 'and' | 'or' | 'and-or'; setPreselectedFilters: boolean; suggestions: boolean; highlight: boolean; suggestResults: boolean; autocompleteFromNERs: boolean; preselectedFilters: string; preselectedFilterExpression: string; filters: FilterSelectionType; labelSetsExcludedFromFilters: string; initialFilters: string | undefined; labelFilterCounts: boolean; rephraseQuery: boolean; useRephrasePrompt: boolean; rephrasePrompt: string; generateAnswerWith: 'only-semantic' | 'semantic-and-full-text'; showHiddenResources: boolean; semanticReranking: boolean; rrfBoosting: boolean; rrfSemanticBoosting?: number; vectorset: string; useSearchResults: boolean; limitParagraphs: boolean; paragraphsLimit: number | null; useSecurityGroups: boolean; securityGroups: string; } interface RagStrategiesConfig { includeTextualHierarchy: boolean; metadatasRagStrategy: boolean; metadatas: { [key in RAG_METADATAS]: boolean; } | undefined; graphRagStrategy: boolean; graph: { hops: number | null; top_k: number | null; /** @deprecated * Use exclude_processor_relations */ agentic_graph_only?: boolean; exclude_processor_relations?: boolean; relation_text_as_paragraphs: boolean; generative_relation_ranking: boolean; suggest_query_entity_detection: boolean; } | undefined; includeNeighbouringParagraphs: boolean; precedingParagraphs: number | null; succeedingParagraphs: number | null; entireResourceAsContext: boolean; maxNumberOfResources: number | null; excludeFilter: string; includeRemaining: boolean; fieldsAsContext: boolean; fieldIds: string; dataAugmentationFieldPrefixes: string; conversationalRagStrategy: boolean; conversationOptions: { attachmentsText: boolean; attachmentsImages: boolean; full: boolean; }; maxMessages: number | null; includePageImages: boolean; maxNumberOfImages: number | null; includeParagraphImages: boolean; } interface GenerativeAnswerConfig { generateAnswer: boolean; generativeModel: string; usePrompt: boolean; prompt: string; useSystemPrompt: boolean; systemPrompt: string; askSpecificResource: boolean; specificResourceSlug: string; showReasoning: boolean; reasoningEffort: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'; reasoningBudget: number; limitTokenConsumption: boolean; tokenConsumptionLimit: number | null; outputTokenConsumptionLimit: number | null; preferMarkdown: boolean; useImages: boolean; imageUsage: 'query' | 'context'; ragStrategies: RagStrategiesConfig; } interface ResultDisplayConfig { displayResults: boolean; showResultType: 'citations' | 'all-resources' | 'llmCitations'; displayMetadata: boolean; hideAnswer: boolean; metadatas?: string[]; displayThumbnails: boolean; noScroll: boolean; showAttachedImages: boolean; displayFieldList: boolean; relations: boolean; relationGraph: boolean; jsonOutput: boolean; jsonSchema: string; customizeThreshold: boolean; citationThreshold: number; sortResults: boolean; } interface RoutingConfig { useRouting: boolean; routing?: Routing; } interface SearchAPIConfig { id: string; value: SearchConfig; type: 'api'; } type TypedSearchConfiguration = SearchConfiguration & { type: 'config'; }; type AnySearchConfiguration = TypedSearchConfiguration | SearchAPIConfig; interface AgenticSearchConfig { configId?: string; transport?: 'http' | 'websocket'; searchConfigId?: string; config?: AgenticConfig; } interface StandardSearchFields { searchBox: SearchBoxConfig; generativeAnswer: GenerativeAnswerConfig; resultDisplay: ResultDisplayConfig; routing: RoutingConfig; } interface SearchConfiguration extends Partial { id: string; searchMode?: 'agentic' | 'simple-rag' | 'search'; agentic?: AgenticSearchConfig; } type StandardSearchConfiguration = SearchConfiguration & StandardSearchFields; type StandardTypedSearchConfiguration = StandardSearchConfiguration & { type: 'config'; }; interface WidgetConfiguration { widgetMode: 'page' | 'popup' | 'chat' | 'floating-chat'; darkMode: 'light' | 'dark'; customizePlaceholder: boolean; placeholder: string; customizeChatPlaceholder: boolean; chatPlaceholder: string; customizeCopyDisclaimer: boolean; copyDisclaimer: string; customizeNotEnoughDataMessage: boolean; notEnoughDataMessage: string; hideLogo: boolean; permalink: boolean; displaySearchButton: boolean; chatSubmitButton?: boolean; navigateToLink: boolean; navigateToFile: boolean; navigateToOriginURL: boolean; hideDownload: boolean; openNewTab: boolean; noChatHistory: boolean; persistChatHistory: boolean; speech: boolean; speechSynthesis: boolean; feedback: WidgetFeedback; lang: string; customizeTextBlocksVisibility: boolean; textBlocksVisibility: 'expanded' | 'collapsed'; customizeCitationVisibility: boolean; citationVisibility: 'expanded' | 'collapsed'; hideReset: boolean; fabPosition: 'bottom-right' | 'bottom-left'; fabSize: 'small' | 'medium' | 'large'; fabOffsetBottom: number; fabOffsetSide: number; panelWidth: number; panelHeight: number; } interface Widget { slug: string; name: string; creationDate: string; searchConfigId?: string; widgetConfig?: WidgetConfiguration; raoWidgetConfig?: RaoWidgetConfiguration; } interface RaoWidgetConfiguration { workflow: string; darkMode?: 'light' | 'dark'; } interface RaoWidget { slug: string; name: string; creationDate: string; widgetConfig: RaoWidgetConfiguration; } interface WidgetFeatures { filter?: boolean; highlight?: boolean; navigateToFile?: boolean; navigateToLink?: boolean; navigateToOriginURL?: boolean; permalink?: boolean; relations?: boolean; suggestions?: boolean; autocompleteFromNERs?: boolean; displayMetadata?: boolean; answers?: boolean; hideLogo?: boolean; hideResults?: boolean; hideThumbnails?: boolean; displayFieldList?: boolean; knowledgeGraph?: boolean; /** * @deprecated use semanticOnly */ noBM25forChat?: boolean; citations?: boolean; llmCitations?: boolean; rephrase?: boolean; debug?: boolean; preferMarkdown?: boolean; openNewTab?: boolean; orFilterLogic?: boolean; andOrFilterLogic?: boolean; labelFilterCounts?: boolean; noChatHistory?: boolean; showHidden?: boolean; showAttachedImages?: boolean; speech?: boolean; speechSynthesis?: boolean; semanticOnly?: boolean; expandCitations?: boolean; collapseCitations?: boolean; expandTextBlocks?: boolean; collapseTextBlocks?: boolean; displaySearchButton?: boolean; chatSubmitButton?: boolean; hideDownload?: boolean; disableRAG?: boolean; persistChatHistory?: boolean; hideAnswer?: boolean; contextImages?: boolean; queryImage?: boolean; sortResults?: boolean; noScroll?: boolean; hideReset?: boolean; } } declare const NUCLIA_STANDARD_SEARCH_CONFIG_ID = "nuclia-standard"; declare const INITIAL_CITATION_THRESHOLD = 0.4; declare const DEFAULT_SEARCH_BOX_CONFIG: Widget.SearchBoxConfig; declare const DEFAULT_GENERATIVE_ANSWER_CONFIG: Widget.GenerativeAnswerConfig; declare const DEFAULT_RESULT_DISPLAY_CONFIG: Widget.ResultDisplayConfig; declare const DEFAULT_ROUTING_CONFIG: Widget.RoutingConfig; declare const NUCLIA_STANDARD_SEARCH_CONFIG: Widget.StandardTypedSearchConfiguration; declare function parseRAGStrategies(ragStrategies: string): RAGStrategy[]; declare function parseRAGImageStrategies(ragImageStrategies: string): RAGImageStrategy[]; declare function parsePreselectedFilters(preselectedFilters: string): string[] | Filter[]; declare function getWidgetParameters(searchConfig: Widget.SearchConfiguration, widgetOptions: Widget.WidgetConfiguration): { fab_position: "bottom-right" | "bottom-left"; fab_size: "medium" | "small" | "large"; fab_offset_bottom: number; fab_offset_side: number; panel_width: number; panel_height: number; placeholder: string; chat_placeholder: string; copy_disclaimer: string; lang: string; not_enough_data_message: string; mode: string; feedback: Widget.WidgetFeedback; agentic_config_id?: string; agentic_transport?: "http" | "websocket"; search_config_id?: string; features: string; } | { fab_position?: undefined; fab_size?: undefined; fab_offset_bottom?: undefined; fab_offset_side?: undefined; panel_width?: undefined; panel_height?: undefined; placeholder: string; chat_placeholder: string; copy_disclaimer: string; lang: string; not_enough_data_message: string; mode: string; feedback: Widget.WidgetFeedback; agentic_config_id?: string; agentic_transport?: "http" | "websocket"; search_config_id?: string; features: string; } | { fab_position: "bottom-right" | "bottom-left"; fab_size: "medium" | "small" | "large"; fab_offset_bottom: number; fab_offset_side: number; panel_width: number; panel_height: number; placeholder: string; chat_placeholder: string; copy_disclaimer: string; lang: string; not_enough_data_message: string; mode: string; feedback: Widget.WidgetFeedback; features: string; prompt: string; system_prompt: string; rephrase_prompt: string; filters: string; labelsets_excluded_from_filters: string; initial_filters: string; preselected_filters: string; filter_expression: string; rag_strategies: string; rag_images_strategies: string; ask_to_resource: string; reasoning: string; routing: string; max_tokens: string | undefined; max_output_tokens: string | undefined; max_paragraphs: string | undefined; generativemodel: string; vectorset: string; json_schema: string; metadata: string; reranker: string | undefined; rrf_boosting: string; citation_threshold: string | undefined; security_groups: string | undefined; } | { fab_position?: undefined; fab_size?: undefined; fab_offset_bottom?: undefined; fab_offset_side?: undefined; panel_width?: undefined; panel_height?: undefined; placeholder: string; chat_placeholder: string; copy_disclaimer: string; lang: string; not_enough_data_message: string; mode: string; feedback: Widget.WidgetFeedback; features: string; prompt: string; system_prompt: string; rephrase_prompt: string; filters: string; labelsets_excluded_from_filters: string; initial_filters: string; preselected_filters: string; filter_expression: string; rag_strategies: string; rag_images_strategies: string; ask_to_resource: string; reasoning: string; routing: string; max_tokens: string | undefined; max_output_tokens: string | undefined; max_paragraphs: string | undefined; generativemodel: string; vectorset: string; json_schema: string; metadata: string; reranker: string | undefined; rrf_boosting: string; citation_threshold: string | undefined; security_groups: string | undefined; }; declare function getFeatures(config: Widget.SearchConfiguration, widgetOptions: Widget.WidgetConfiguration): string; declare function getPreselectedFilterValue(config: Widget.SearchBoxConfig): string; declare function getRagStrategies(ragStrategiesConfig: Widget.RagStrategiesConfig): { ragStrategies: string; ragImagesStrategies: string; }; declare function getJsonSchemaValue(config: Widget.ResultDisplayConfig): string | undefined; /** * Currently in our models, there are more FIELD_TYPEs than ResourceData keys, so we need the switch for typing reason */ declare const getDataKeyFromFieldType: (fieldType: FIELD_TYPE) => keyof ResourceData | null; declare function longToShortFieldType(fieldType: FIELD_TYPE): SHORT_FIELD_TYPE; declare function shortToLongFieldType(shortType: SHORT_FIELD_TYPE): FIELD_TYPE | null; declare function getFieldTypeFromString(type: string): FIELD_TYPE | null; declare namespace Memory { interface Metadata { } interface KnowledgeGraph { } interface Reason { } interface NucliaDBMemoryConfig { key?: string | null; url: string; kbid: string; internal: boolean; } interface MemoryConfig { nucliadb?: NucliaDBMemoryConfig | null; } interface Rule { prompt?: string | null; } interface Rules { rules: (Rule | string)[]; } interface Facets { chunks: Record; fields: Record; } interface Source { id: string; description: string; labels: Record; facets_native: any; paragraph_facets: Record; learning_configuration: any; } interface Answer { answer: string; original_question_uuid?: string | null; actual_question_uuid?: string | null; module: string; agent_path: string; } interface Citations { metadata: { [block: string]: { chunk_index: number | null; context_id: string; origin_urls: string[]; }; }; } interface Step { original_question_uuid?: string | null; actual_question_uuid?: string | null; module: string; title: string; value?: string | null; agent_path: string; reason?: string | null; timeit: number; input_nuclia_tokens?: number | null; output_nuclia_tokens?: number | null; error?: string | null; } interface ChunkImages { table?: string | null; chunk?: string | null; page?: string | null; } interface Chunk { chunk_id: string; title?: string | null; source?: string | null; text: string; labels: string[]; url: string[]; metadata?: { [key: string]: any; } | null; action?: string | null; origin_url?: string | null; origin_agent?: string | null; } interface Context { id: string; actual_question_uuid?: string | null; agent: string; chunks: Chunk[]; citations: string[] | null; images: Record; missing?: string | null; original_question_uuid?: string | null; question: string; source: string; structured: string[]; summary: string; title?: string | null; agent_id: string; } interface HistoryQuestionAnswer { question: string; answer: string; } interface DataVisualization { type: 'vega_lite'; vega_lite_obj: { [key: string]: any; }; } class StepUtils { static toString(step: Step): string; static toMarkdown(step: Step): string; } class ChunkUtils { static render(chunk: Chunk): string; } class ContextUtils { static context(context: Context): string; static contextMarkdown(context: Context): string; static stats(context: Context): Record; } } declare enum InteractionOperation { question = 0, quit = 1 } declare enum AnswerOperation { answer = 0, quit = 1, start = 2, done = 3, error = 4, agent_request = 5, answer_chunk = 6, reasoning = 7 } interface InteractionRequest { question: string; headers: Record; operation: InteractionOperation; chat_history?: HistoryEntry[]; streaming?: boolean; } interface InteractionOptions { chat_history?: HistoryEntry[]; streaming?: boolean; } type HistoryEntry = { question: string; answer: string; }; interface ARAGException { detail: string; } interface ValidationFeedbackSchema { call_tool: boolean; } interface PromptFeedbackSchema { prompt_id: string; data: any; } interface Feedback { request_id: string; feedback_id: string; question: string; module: string; agent_id: string; data: any; timeout_ms: number; response_schema?: JSONSchema4; get_credentials?: { [key: string]: string; }; credentials?: OAuthCredentials; } interface StreamingChunk { text: string; last: boolean; } interface OAuthRedirection { oauth_url: string; } interface OAuthCredentials { [key: string]: { [key: string]: any; }; } interface AragResponse { type: 'answer'; answer: AragAnswer; } interface AragAnswer { exception: ARAGException | null; answer: string | null; answer_citations: Memory.Citations | null; agent_request: string | null; generated_text: string | null; step: Memory.Step | null; possible_answer: Memory.Answer | null; context: Memory.Context | null; operation: AnswerOperation; seqid: number | null; original_question_uuid: string | null; actual_question_uuid: string | null; feedback: Feedback | null; oauth: OAuthRedirection | null; data_visualizations: Memory.DataVisualization[] | null; streaming_response_chunk: StreamingChunk | null; reasoning: StreamingChunk | null; } declare function mapErrorResponseFromAnswer(message: AragAnswer): IErrorResponse; type AgenticConfigSchema = LearningConfigurationSchema; interface AgenticConfigDefaults { rephraseModel?: string; summarizeModel?: string; smartAgentExecutorModel?: string; smartAgentPlannerModel?: string; smartAgentContextValidationModel?: string; } declare function getAgenticConfigDefaults(schema: AgenticConfigSchema): AgenticConfigDefaults; interface HistoryConfig { history?: boolean; } interface AgenticRephraseConfig extends HistoryConfig { ask_to?: string; prompt?: string; model?: AgenticModelConfig; } type AgenticSmartAgentMode = 'reactive' | 'plan_execute'; interface AgenticSmartAgentModels { context_validation?: AgenticModelConfig; planner?: AgenticModelConfig; executor?: AgenticModelConfig; } interface AgenticSmartAgentConfig extends HistoryConfig { mode?: AgenticSmartAgentMode; extra_prompt?: string; models?: AgenticSmartAgentModels; /** IDs of sources (defined via the sources API) used by this smart agent. */ sources?: string[]; } interface AgenticSummarizeConfig extends HistoryConfig { user_prompt?: string; system_prompt?: string; conversational?: boolean; model?: AgenticModelConfig; } interface AgenticConfig { title?: string; rephrase?: AgenticRephraseConfig; smart_agent?: AgenticSmartAgentConfig; summarize?: AgenticSummarizeConfig; } interface AgenticModelConfig { model_id: string; reasoning?: 'enabled' | 'disabled'; advanced_reasoning?: { effort?: ReasoningEffort; budget_tokens?: number; }; } type AgenticConfigs = { [id: string]: AgenticConfig; }; interface NucliaDBSource { type: 'nucliadb'; description?: string; filter_expression?: FilterExpression; labels?: string[]; resource_filters?: string[]; } interface PerplexitySource { type: 'perplexity'; description?: string; enabled_domains?: string[]; } type GoogleTimeRange = 'past_day' | 'past_week' | 'past_month' | 'past_year'; interface GoogleSource { type: 'google'; description?: string; time_range?: GoogleTimeRange; exclude_domains?: string[]; } interface MCPSource { type: 'mcp'; description?: string; uri: string; headers?: { [key: string]: string; }; tool_choice_model?: string; valid_headers?: string[]; } interface SyncSource { type: 'sync'; source_id?: string; description?: string; connection?: string; params?: { [key: string]: unknown; }; } type AgenticSource = NucliaDBSource | PerplexitySource | GoogleSource | MCPSource | SyncSource; type AgenticSources = { [id: string]: AgenticSource; }; type TaskName = 'labeler' | 'llm-graph' | 'synthetic-questions' | 'ask' | 'llama-guard' | 'prompt-guard' | 'semantic-model-migrator'; type ApplyOption = 'ALL' | 'EXISTING' | 'NEW'; /** * Minimum definition of a task. */ interface TaskDefinition { name: TaskName; data_augmentation: boolean; description?: string; can_cleanup?: boolean; } /** * Full definition of a task, including its schema. */ interface TaskFullDefinition extends TaskDefinition { validation: { $defs: { [property: string]: any; }; properties: { [property: string]: any; }; required: string[]; title: string; type: 'object'; }; } /** * Whether the task applies to the text blocks only or to the full field. */ declare enum TaskApplyTo { TEXT_BLOCKS = 0, FULL_FIELD = 1 } /** * Definition of the operation done by the task */ interface Operation { label?: LabelOperation; graph?: GraphOperation; qa?: QAOperation; prompt_guard?: GuardOperation; llama_guard?: GuardOperation; ask?: AskOperation; extract?: null; } interface BaseOperation { triggers?: TaskTrigger[]; } interface LabelOperation extends BaseOperation { labels?: { label: string; examples?: string[]; description?: string; }[]; ident?: string; multiple?: boolean; description?: string; paragraph_filter_expression_json?: string; } interface GraphOperation extends BaseOperation { ident?: string; entity_defs?: EntityDefinition[]; examples?: GraphExtractionExample[]; } interface EntityDefinition { label: string; description?: string; } interface GraphExtractionExample { entities: EntityExample[]; relations: RelationExample[]; text: string; } interface EntityExample { name: string; label: string; } interface RelationExample { source: string; target: string; label: string; } interface QAOperation extends BaseOperation { generate_answers_prompt?: string; question_generator_prompt?: string; summary_prompt?: string; system_question_generator_prompt?: string; max_questions?: number; } interface AskOperation extends BaseOperation { question?: string; destination?: string; json?: boolean; user_prompt?: string; store_as_key_value?: boolean; kv_schema_id?: string; } interface GuardOperation extends BaseOperation { enabled?: boolean; } interface TaskTrigger { url?: string; headers?: { [key: string]: string; }; params?: { [key: string]: string; }; } /** * Configuration of the LLM used for the task */ interface LLMConfig { model?: string; keys?: { [model: string]: any; }; prompts?: { [model: string]: { prompt: string; system?: string; } | null; }; reasoning_config?: ReasoningConfig; } type TaskParameters = DataAugmentationParameters | SemanticModelMigration; /** * Parameters used to configure data augmentation tasks */ interface DataAugmentationParameters { name: string; filter: { contains?: string[]; contains_operator?: 0 | 1; resource_type?: string[]; field_types?: string[]; labels?: string[]; labels_operator?: 0 | 1; not_field_types?: string[]; apply_to_agent_generated_fields?: boolean; }; llm: LLMConfig; on?: TaskApplyTo; operations?: Operation[]; filter_expression_json?: string; } interface SemanticModelMigration { semantic_model_id: string; hf_embedding_key?: any; } interface TaskStatus { task: TaskDefinition; source: string; kbid: string; dataset_id?: string; account_id: string; nua_client_id?: string; user_id: string; id: string; parameters: TaskParameters; timestamp: string; stopped: boolean; stopped_at: string; failed: boolean; retries: number; } /** * Task running as a batch on all the resources existing on the moment the task is launched. * Once the task is completed, it stops. */ interface TaskOnBatch extends TaskStatus { scheduled: boolean; completed: boolean; scheduled_at: string; completed_at: string; cleanup_parent_task_id?: string; task_config_id?: string; } /** * Task configured to run on new resources. * The task never ends unless the user stops it. */ interface TaskOnGoing extends TaskStatus { defined_at: string; enabled: boolean; } /** * TaskListResponse provides: * - **tasks**: list of all the available task and their schema * - **running**: list of tasks running on existing resources * - **configs**: list of tasks running on new resources * - **done**: list of finished tasks which were running on existing resources */ interface TaskListResponse { tasks: TaskFullDefinition[]; running: TaskOnBatch[]; configs: TaskOnGoing[]; done: TaskOnBatch[]; } /** * Response from start and stop endpoints. */ interface StartStopTaskResponse { task: string; status: string; id: string; } /** * Response from inspect endpoint. */ interface InspectTaskResponse { request?: TaskOnBatch; config?: TaskOnGoing; } declare class TaskManager { kb: WritableKnowledgeBox; nuclia: INuclia; constructor(kb: WritableKnowledgeBox, nuclia: INuclia); /** * List the available tasks on a KB and get the list of tasks running and done. * * @param count How many finished task to return. By default, the server is returning 10. */ getTasks(count?: number): Observable; /** * Delete a task so it is not listed anymore in getTasks. * If the task is currently running, you should stop it before deleting it. * @param taskId */ deleteTask(taskId: string, clean?: boolean): Observable; /** * Start a new task * @param name Name of the task * @param parameters Parameters configuring the task * @param apply Apply the task to: * - EXISTING: only the resources already existing in the KB. * - NEW: only the resources created in the KB after the task is started * - ALL: all the existing and new resources of the KB */ startTask(name: TaskName, parameters?: TaskParameters, apply?: ApplyOption, enabled?: boolean, uuid_task?: string): Observable; /** * Stop a running task. * @param taskId */ stopTask(taskId: string): Observable; /** * Restart a running task. * @param taskId */ restartTask(taskId: string): Observable; /** * Remove the data generated by a task * @param taskId */ cleanTask(taskId: string): Observable; /** * Get the status of a tasks * * @param taskId */ getTask(taskId: string): Observable; /** * Edit a tasks * @param taskId * @param parameters Parameters configuring the task */ editTask(taskId: string, parameters: TaskParameters): Observable; /** * Enable or disable a tasks * @param enabled */ enableTask(taskId: string, enabled: boolean): Observable; } interface Metric { name: string; min: number; max: number; average: number; } interface RemiScoresResponseItem { timestamp: string; metrics: Metric[]; } interface RemiScore { answer_relevance: { score: number; reason: string; }; context_relevance: number[]; groundedness: number[]; } interface RemiQueryResponse { data: RemiQueryResponseItem[]; has_more: boolean; } interface RemiQueryResponseItem { id: number; question: string; answer: string; date?: string | null; remi?: RemiScore; } interface RemiQueryResponseContextDetails extends RemiQueryResponseItem { context: { text: string; text_block_id: string | null; }[]; } /** * NO_CONTEXT means there was no answer to the query */ type RemiAnswerStatus = 'SUCCESS' | 'ERROR' | 'NO_CONTEXT'; interface RemiQueryCriteria { context_relevance?: { value: number; operation: 'gt' | 'lt' | 'eq'; aggregation: 'average' | 'min' | 'max'; }; feedback_good?: boolean; status?: RemiAnswerStatus; month: string; from_date?: string; to_date?: string; pagination?: { limit?: number; starting_after?: number; ending_before?: number; }; } interface SearchMetricsItem { timestamp: string; search: number; chat: number; } declare enum EventType { VISITED = "visited", MODIFIED = "modified", DELETED = "deleted", NEW = "new", STARTED = "started", STOPPED = "stopped", SEARCH = "search", PROCESSED = "processed", CHAT = "chat", ASK = "ask", SUGGEST = "suggest", INDEXED = "indexed", RETRIEVE = "retrieve", AUGMENT = "augment" } type DownloadFormat = 'application/x-ndjson' | 'text/csv'; interface ActivityLogDownloadQuery { year_month: string; show?: string[] | 'all'; filters: ActivityLogFilters | ActivityLogSearchFilters | ActivityLogChatFilters | ActivityLogAskFilters; email_address?: string; notify_via_email?: boolean; } interface ActivityLogDownload { request_id: string; download_type: string; download_format: DownloadFormat; event_type: EventType; requested_at: string; kb_id: string; download_url: string | null; } /** Generic query base — parameterized by show-field type and filters type. */ interface ActivityLogQueryBase { year_month: string; pagination?: ActivityLogPagination; show?: S[] | 'all'; filters: F; } type ActivityLogBaseQuery = ActivityLogQueryBase; type ActivityLogSearchQuery = ActivityLogQueryBase; type ActivityLogChatQuery = ActivityLogQueryBase; type ActivityLogAskQuery = ActivityLogQueryBase; type ActivityLogQuery = ActivityLogBaseQuery | ActivityLogSearchQuery | ActivityLogAskQuery | ActivityLogChatQuery; type ActivityLogResponseItemUnion = ActivityLogResponseItem | ActivityLogResponseSearchItem | ActivityLogResponseChatItem | ActivityLogResponseAskItem; interface ActivityLogResponseItem { id: number; date: string | null; user_id: string | null; user_type: string | null; client_type: string | null; total_duration: number | null; audit_metadata: Record | null; resource_id: string | null; nuclia_tokens: number | null; } interface ActivityLogPagination { limit?: number; starting_after?: number; ending_before?: number; } interface ActivityLogFilters { id?: ActivityLogFilter; date?: ActivityLogFilter; user_id?: ActivityLogFilter; user_type?: ActivityLogFilter; client_type?: ActivityLogFilter; total_duration?: ActivityLogFilter; nuclia_tokens?: ActivityLogFilter; audit_metadata?: AuditMetadataFilter; } declare const ACTIVITY_LOG_SHOW_FIELDS: readonly ["id", "date", "user_id", "user_type", "client_type", "total_duration", "audit_metadata", "resource_id", "nuclia_tokens"]; type ActivityLogShowFields = (typeof ACTIVITY_LOG_SHOW_FIELDS)[number]; interface ActivityLogResponseSearchItem extends ActivityLogResponseItem { question: string | null; resources_count: number | null; filter: string | null; retrieval_rephrased_question: string | null; vectorset: string | null; security: unknown; min_score_bm25: number | null; min_score_semantic: number | null; result_per_page: number | null; retrieval_time: number | null; } interface ActivityLogSearchFilters extends ActivityLogFilters { question?: ActivityLogStringFilter; resources_count?: ActivityLogFilter; vectorset?: ActivityLogStringFilter; min_score_bm25?: ActivityLogFilter; min_score_semantic?: ActivityLogFilter; result_per_page?: ActivityLogFilter; retrieval_time?: ActivityLogFilter; } declare const ACTIVITY_LOG_SEARCH_SHOW_FIELDS: readonly ["id", "date", "user_id", "user_type", "client_type", "total_duration", "audit_metadata", "resource_id", "nuclia_tokens", "question", "token_details", "resources_count", "filter", "retrieval_rephrased_question", "vectorset", "security", "min_score_bm25", "min_score_semantic", "result_per_page", "retrieval_time"]; type ActivityLogSearchShowFields = (typeof ACTIVITY_LOG_SEARCH_SHOW_FIELDS)[number]; /** @deprecated Use {@link ActivityLogSearchShowFields} instead. */ type ActivityLogSearchShowField = ActivityLogSearchShowFields; interface ActivityLogResponseChatItem extends ActivityLogResponseItem { question: string | null; rephrased_question: string | null; answer: string | null; learning_id: string | null; retrieved_context: unknown; chat_history: unknown; feedback_good: boolean | null; feedback_comment: string | null; feedback_good_all: boolean | null; feedback_good_any: boolean | null; feedback: unknown; model: string | null; rag_strategies_names: string[] | null; rag_strategies: unknown; /** AnswerStatusCode: '0'=SUCCESS, '-1'=ERROR, '-2'=NO_CONTEXT, '-3'=NO_RETRIEVAL_DATA. Null on resource events. */ status: string | null; generative_answer_first_chunk_time: number | null; generative_reasoning_first_chunk_time: number | null; generative_answer_time: number | null; remi_scores: number | null; user_request: string | null; reasoning: string | null; } interface ActivityLogChatFilters extends ActivityLogSearchFilters { rephrased_question?: ActivityLogStringFilter; answer?: ActivityLogStringFilter; learning_id?: ActivityLogStringFilter; feedback_good?: ActivityLogFilter; feedback_good_all?: ActivityLogFilter; feedback_good_any?: ActivityLogFilter; feedback_comment?: ActivityLogStringFilter; model?: ActivityLogStringFilter; /** AnswerStatusCode: '0'=SUCCESS, '-1'=ERROR, '-2'=NO_CONTEXT, '-3'=NO_RETRIEVAL_DATA */ status?: ActivityLogFilter; generative_answer_first_chunk_time?: ActivityLogFilter; generative_reasoning_first_chunk_time?: ActivityLogFilter; generative_answer_time?: ActivityLogFilter; reasoning?: ActivityLogStringFilter; } declare const ACTIVITY_LOG_CHAT_SHOW_FIELDS: readonly ["id", "date", "user_id", "user_type", "client_type", "total_duration", "audit_metadata", "resource_id", "nuclia_tokens", "question", "token_details", "rephrased_question", "answer", "learning_id", "retrieved_context", "chat_history", "feedback_good", "feedback_comment", "feedback_good_all", "feedback_good_any", "feedback", "model", "rag_strategies_names", "rag_strategies", "status", "generative_answer_first_chunk_time", "generative_reasoning_first_chunk_time", "generative_answer_time", "remi_scores", "user_request", "reasoning"]; type ActivityLogChatShowFields = (typeof ACTIVITY_LOG_CHAT_SHOW_FIELDS)[number]; /** @deprecated Use {@link ActivityLogChatShowFields} instead. */ type ActivityLogChatShowField = ActivityLogChatShowFields; interface ActivityLogResponseAskItem extends ActivityLogResponseChatItem { resources_count: number | null; filter: string | null; retrieval_rephrased_question: string | null; vectorset: string | null; security: unknown; min_score_bm25: number | null; min_score_semantic: number | null; result_per_page: number | null; retrieval_time: number | null; } interface ActivityLogAskFilters extends ActivityLogChatFilters { resources_count?: ActivityLogFilter; vectorset?: ActivityLogStringFilter; min_score_bm25?: ActivityLogFilter; min_score_semantic?: ActivityLogFilter; result_per_page?: ActivityLogFilter; retrieval_time?: ActivityLogFilter; } declare const ACTIVITY_LOG_ASK_SHOW_FIELDS: readonly ["id", "date", "user_id", "user_type", "client_type", "total_duration", "audit_metadata", "resource_id", "nuclia_tokens", "question", "token_details", "rephrased_question", "answer", "learning_id", "retrieved_context", "chat_history", "feedback_good", "feedback_comment", "feedback_good_all", "feedback_good_any", "feedback", "model", "rag_strategies_names", "rag_strategies", "status", "generative_answer_first_chunk_time", "generative_reasoning_first_chunk_time", "generative_answer_time", "remi_scores", "user_request", "reasoning", "resources_count", "filter", "retrieval_rephrased_question", "vectorset", "security", "min_score_bm25", "min_score_semantic", "result_per_page", "retrieval_time"]; type ActivityLogAskShowFields = (typeof ACTIVITY_LOG_ASK_SHOW_FIELDS)[number]; /** @deprecated Use {@link ActivityLogAskShowFields} instead. */ type ActivityLogAskShowField = ActivityLogAskShowFields; interface ActivityLogFilter { eq?: T; gt?: T; ge?: T; lt?: T; le?: T; ne?: T; isnull?: boolean; } interface ActivityLogStringFilter extends ActivityLogFilter { like?: string; ilike?: string; } interface AuditMetadataFilter extends ActivityLogStringFilter { key: string; } /** * Backward-compatible alias — the "widest" response item containing all possible fields. * Prefer the specific response types (ActivityLogResponseItem, ActivityLogResponseSearchItem, etc.) * when the event type is known. */ type ActivityLogItem = ActivityLogResponseAskItem; declare class ActivityMonitor { kb: WritableKnowledgeBox; nuclia: INuclia; constructor(kb: WritableKnowledgeBox, nuclia: INuclia); /** * Get the evolution of REMi scores of a KB on the specified time range. * * @param from Timestamp of the moment from which we want the metrics. * @param to Timestamp of the moment until which we want the metrics. When not provided, the metrics are returned "until now". * @param aggregation Define how the metrics are aggregated. By default, the endpoint returns only one point aggregating all the data for the specified date range. But you can have one point by: * - "hour" * - "day" * - "week" * - "month" * - "quarter" * - "year" * - "millennium" (used by default) */ getRemiScores(from: string, to?: string, aggregation?: UsageAggregation): Observable; /** * Get a list of RAG requests and their scores (if any) that matches a REMi scores query or a status. * * @param criteria Object representing the query to be done. It currently supports querying on context relevance, answer status or answer feedback. */ queryRemiScores(criteria: RemiQueryCriteria): Observable; /** * Get the RAG request (question and answer), the REMi scores and the full contexts list for a specific item coming from `queryRemiScores` method. * * @param eventId Identifier of an item from `queryRemiScores` response. */ getFullContexts(eventId: number): Observable; /** * Create a URL to download activity log data * * @param eventType * @param query * @param format */ createActivityLogDownload(eventType: EventType, query: ActivityLogDownloadQuery, format: DownloadFormat): Observable; /** * Get the status of a download request * * @param requestId */ getDownloadStatus(requestId: string): Observable; /** * Get the list of months with available activity log data for a specific event type * * @param eventType */ getMonthsWithActivity(eventType: EventType): Observable<{ downloads: string[]; }>; /** * Retrieve statistics for search and ask requests * * @param from Timestamp of the moment from which we want the metrics. * @param to Timestamp of the moment until which we want the metrics. When not provided, the metrics are returned "until now". * @param aggregation Define how the metrics are aggregated. By default, the endpoint returns only one point aggregating all the data for the specified date range. */ getSearchMetrics(from: string, to?: string, aggregation?: UsageAggregation): Observable; /** * Query activity logs with live pagination. * Returns an array of log items parsed from the NDJSON response. * * @param eventType The event type to query (ask, search, chat, new, modified, processed, etc.) * @param query Query body: year_month (required), optional pagination, show, filters */ queryActivityLogs(eventType: EventType, query: ActivityLogQuery): Observable; } declare class SyncManager implements ISyncManager { kb: IWritableKnowledgeBox; nuclia: INuclia; constructor(kb: IWritableKnowledgeBox, nuclia: INuclia); createOAuthExternalConnection(provider: string): Observable; createExternalConnection(provider: string, credentials: ExternalConnectionCredentials): Observable; getExternalConnection(id: string): Observable; getAssumeRoleInfo(): Observable; createConfig(config: SyncConfigurationCreate): Observable; getConfigs(): Observable; getConfig(id: string): Observable; deleteConfig(id: string): Observable; getConfigJobs(id: string, pagination?: JobPagination): Observable; getJobLogs(jobId: string, pagination?: JobPagination, filters?: LogFilters): Observable; syncConfig(id: string, full_sync?: boolean): Observable; browse(externalConnectorId: string, options: BrowseOptions): Observable; resolveSite(connectionId: string, siteUrl: string): Observable; updateConfig(id: string, config: SyncConfigurationUpdate): Observable; } type KBStates = 'PUBLISHED' | 'PRIVATE'; type KBRoles = 'SOWNER' | 'SCONTRIBUTOR' | 'SMEMBER'; declare enum LabelSetKind { RESOURCES = "RESOURCES", PARAGRAPHS = "PARAGRAPHS" } interface IKnowledgeBoxBase { id: string; slug: string; title: string; state?: KBStates; description?: string; zone: string; created?: string; allowed_origins?: string[] | null; allowed_ip_addresses?: string[] | null; search_configs?: { [key: string]: any; }; hidden_resources_enabled?: boolean; hidden_resources_hide_on_creation?: boolean; enforce_security?: boolean; external_index_provider?: string; } interface IKnowledgeBoxStandalone { slug: string; uuid: string; config?: { slug?: string; title?: string; description?: string; hidden_resources_enabled?: boolean; hidden_resources_hide_on_creation?: boolean; }; } interface IKnowledgeBoxItem extends IKnowledgeBoxBase { role_on_kb?: KBRoles; } interface IStandaloneKb { slug: string; uuid: string; } interface FullKbUser { id: string; name: string; email: string; role: KBRoles; } interface KbUser { id: string; role: KBRoles; } interface KbUserPayload { add?: KbUser[]; update?: KbUser[]; delete?: string[]; } interface InviteKbData { email: string; role: KBRoles; came_from?: string; } interface KbInvite { email: string; role: KBRoles; expires: string; } interface IKnowledgeBox extends IKnowledgeBoxBase { get path(): string; get fullpath(): string; getEntities(): Observable; getEntitiesGroup(groupId: string): Observable; getFacets(facets: string[]): Observable; getLabels(): Observable; getResource(uuid: string, show?: ResourceProperties[], extracted?: ExtractedDataTypes[]): Observable; getFullResource(uuid: string): Observable; getResourceBySlug(slug: string, show?: ResourceProperties[], extracted?: ExtractedDataTypes[]): Observable; getFullResourceBySlug(slug: string): Observable; createAgenticRAGPipeline(steps: Agentic.Steps): Agentic.Pipeline; ask(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions): Observable; ask(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions, callback?: (answer: Ask.Answer | IErrorResponse) => void): Observable; askViaWS(agenticConfigId: string, question: string, keepOpen?: boolean, searchConfiguration?: string, groups?: string[], chatHistory?: HistoryEntry[]): Observable; find(query: string, features?: Search.Features[], options?: SearchOptions): Observable; search(query: string, features?: Search.Features[], options?: SearchOptions): Observable; summarize(ressourceIds: string[]): Observable; tokens(text: string): Observable; predictAnswer(question: string, options?: PredictAnswerOptions): Observable; generate(question: string, context: string[]): Observable<{ answer: string; cannotAnswer: boolean; }>; generateJSON(question: string, json_schema: object, context: string[]): Observable<{ answer: object; success: boolean; }>; rephrase(question: string, user_context?: string[], rephrase_prompt?: string): Observable; generateRandomQuestionAboutResource(resource: Resource): Observable; catalog(query: string, options?: CatalogOptions): Observable; suggest(query: string, inTitleOnly?: boolean, features?: Search.SuggestionFeatures[], options?: SuggestOptions): Observable; feedback(answerId: string, good: boolean, feedback?: string, text_block_id?: string): Observable; counters(): Observable; listResources(page?: number, size?: number): Observable; getTempToken(payload?: any, ignoreExpiration?: boolean): Observable; getConfiguration(): Observable<{ [id: string]: any; }>; getLearningSchema(): Observable; getGenerativeProviders(): Observable; getUsers(accountSlug: string): Observable; listenToAllNotifications(): Observable; listenToProcessingNotifications(): Observable; listenToResourceOperationNotifications(): Observable; stopListeningToNotifications(): void; processingStatus(cursor?: string, scheduled?: boolean, limit?: number): Observable<{ cursor: string; results: ProcessingStatus[]; }>; getSearchConfig(id: string): Observable; getExtractStrategies(): Observable; getSplitStrategies(): Observable; getSearchConfigs(): Observable; getAgenticConfig(id: string): Observable; listAgenticConfigs(): Observable; getAgenticSource(id: string): Observable; listAgenticSources(): Observable; getProcessingHook(): Observable; } interface IWritableKnowledgeBox extends IKnowledgeBox { admin?: boolean; contrib?: boolean; activityMonitor?: ActivityMonitor; taskManager: TaskManager; syncManager: SyncManager; modify(data: Partial): Observable; publish(published: boolean): Observable; delete(): Observable; setLabelSet(setId: string, labelSet: LabelSet): Observable; deleteLabelSet(setId: string): Observable; createResource(resource: IResource, synchronous: boolean): Observable<{ uuid: string; }>; createLinkResource(link: LinkField, metadata?: UserMetadata, synchronous?: boolean, origin?: Origin): Observable<{ uuid: string; }>; upload(file: File | FileWithMetadata, TUS?: boolean, metadata?: FileMetadata): Observable; upload(buffer: ArrayBuffer, TUS?: boolean, metadata?: FileMetadata): Observable; upload(data: File | FileWithMetadata | ArrayBuffer, TUS?: boolean, metadata?: FileMetadata): Observable; batchUpload(files: FileList | File[] | FileWithMetadata[]): Observable; getServiceAccounts(): Observable; createServiceAccount(data: ServiceAccountCreation): Observable; deleteServiceAccount(serviceAccountId: string): Observable; createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{ token: string; }>; createKey(serviceAccountId: string, expires: string): Observable<{ token: string; }>; deleteKey(serviceAccountId: string, serviceAccountKeyId: string): Observable; setConfiguration(config: { [id: string]: any; }): Observable; updateUsers(data: KbUserPayload): Observable; inviteToKb(data: InviteKbData): Observable; addVectorset(model: string): Observable; removeVectorset(model: string): Observable; createExtractStrategy(config: ExtractConfig): Observable; deleteExtractStrategy(id: string): Observable; createSplitStrategy(strategy: SplitStrategy): Observable; deleteSplitStrategy(id: string): Observable; createSearchConfig(id: string, config: SearchConfig): Observable; updateSearchConfig(id: string, config: SearchConfig): Observable; deleteSearchConfig(id: string): Observable; createAgenticConfig(id: string, config: AgenticConfig): Observable; updateAgenticConfig(id: string, config: AgenticConfig): Observable; deleteAgenticConfig(id: string): Observable; createAgenticSource(id: string, source: AgenticSource): Observable; updateAgenticSource(id: string, source: AgenticSource): Observable; deleteAgenticSource(id: string): Observable; updateProcessingHook(data: ProcessingHook): Observable; deleteProcessingHook(): Observable; deleteAllResources(filter: DeleteResourcesFilter): Observable; } interface KnowledgeBoxCreation { slug: string; title: string; zone?: string; description?: string; learning_configuration?: { [configId: string]: any; }; external_index_provider?: any; enforce_security?: boolean; } interface Entities { [key: string]: BaseEntitiesGroup; } interface Entity { value: string; merged?: boolean; represents?: string[]; } interface BaseEntitiesGroup { title?: string; color?: string; custom?: boolean; } interface EntitiesGroup extends BaseEntitiesGroup { entities: { [key: string]: Entity; }; } interface Label { title: string; related?: string; text?: string; uri?: string; } interface LabelSet { title: string; color: string; multiple: boolean; kind: LabelSetKind[]; labels: Label[]; } interface LabelSets { [id: string]: LabelSet; } declare enum RAG_METADATAS { ORIGIN = "origin", LABELS = "classification_labels", NERS = "ners", EXTRA = "extra_metadata" } declare enum RagStrategyName { FIELD_EXTENSION = "field_extension", FULL_RESOURCE = "full_resource", HIERARCHY = "hierarchy", METADATAS = "metadata_extension", NEIGHBOURING_PARAGRAPHS = "neighbouring_paragraphs", PREQUERIES = "prequeries", CONVERSATION = "conversation", GRAPH = "graph_beta" } interface Prequery { request: SearchOptions & { query: string; features?: Search.Features[]; }; weight?: number; id?: string; } interface FieldExtensionStrategy { name: RagStrategyName.FIELD_EXTENSION; fields?: string[]; data_augmentation_field_prefixes?: string[]; } interface FullResourceStrategy { name: RagStrategyName.FULL_RESOURCE; count?: number; include_remaining_text_blocks?: boolean; apply_to?: { exclude: string[]; }; } interface HierarchyStrategy { name: RagStrategyName.HIERARCHY; count?: number; } interface MetadatasStrategy { name: RagStrategyName.METADATAS; types: RAG_METADATAS[]; } interface NeighbouringParagraphsStrategy { name: RagStrategyName.NEIGHBOURING_PARAGRAPHS; before: number; after: number; } interface PrequeriesStrategy { name: RagStrategyName.PREQUERIES; queries: Prequery[]; } interface ConversationalStrategy { name: RagStrategyName.CONVERSATION; attachments_text: boolean; attachments_images: boolean; full: boolean; max_messages?: number; } interface GraphStrategy { name: RagStrategyName.GRAPH; hops: number; top_k: number; /** @deprecated * Use exclude_processor_relations */ agentic_graph_only?: boolean; exclude_processor_relations?: boolean; relation_ranking?: 'generative' | 'reranker'; relation_text_as_paragraphs?: boolean; query_entity_detection?: 'predict' | 'suggest'; } type RAGStrategy = FieldExtensionStrategy | FullResourceStrategy | HierarchyStrategy | MetadatasStrategy | NeighbouringParagraphsStrategy | PrequeriesStrategy | ConversationalStrategy | GraphStrategy; declare enum RagImageStrategyName { PAGE_IMAGE = "page_image", PARAGRAPH_IMAGE = "paragraph_image" } interface PageImageStrategy { name: RagImageStrategyName.PAGE_IMAGE; count?: number; } interface ParagraphImageStrategy { name: RagImageStrategyName.PARAGRAPH_IMAGE; } type RAGImageStrategy = PageImageStrategy | ParagraphImageStrategy; interface Counters { resources: number; paragraphs: number; fields: number; sentences: number; index_size: number; } interface ResourceList { resources: Resource[]; pagination: ResourcePagination; } interface ResourcePagination { page: number; size: number; last: boolean; } interface EventList { events: Event[]; pagination: ResourcePagination; } type Event = { [key: string]: any; }; interface ServiceAccountKey { id: string; created: string; expires: string; } interface ServiceAccount { id: string; title: string; role: KBRoles; keys?: ServiceAccountKey[]; } interface ServiceAccountCreation { title: string; role: KBRoles; } interface SentenceToken { text: string; ner: string; start: number; end: number; } interface ProcessingStatus { completed: boolean; completed_at?: string | null; failed: boolean; kbid: string; processing_id: string; resource_id: string; retries: number; schedule_eta: number; schedule_order: number; scheduled: boolean; scheduled_at: string; timestamp: string; title: string; } interface ResourceBaseNotification { resourceId: string; resourceTitle: string; timestamp: string; success: boolean; } interface ResourceOperationNotification extends ResourceBaseNotification { operation: NotificationOperation; } type ResourceProcessingNotification = ResourceBaseNotification; type ExtractStrategies = { [id: string]: ExtractConfig; }; interface ExtractConfig { name?: string; vllm_config?: ExtractVLLMConfig; ai_tables?: ExtractVLLMConfig; split?: { max_paragraph?: number; }; max_parallel_llm_calls?: number; } interface ExtractLLMConfig { generative_model?: string; generative_provider?: string; generative_prompt_id?: string; user_keys?: any; reasoning_config?: ReasoningConfig; } interface ExtractVLLMConfig { llm?: ExtractLLMConfig; rules?: string[]; merge_pages?: boolean; max_pages_to_merge?: number; } type SplitStrategies = { [id: string]: SplitStrategy; }; interface SplitStrategy { name?: string; max_paragraph?: number; custom_split?: CustomSplitStrategy; llm_split?: SplitLLMConfig; manual_split?: { splitter: string; }; } interface SplitLLMConfig { llm?: ExtractLLMConfig; rules?: string[]; } declare enum CustomSplitStrategy { NONE = 0, MANUAL = 1, LLM = 2 } type SearchConfigs = { [key: string]: SearchConfig; }; type SearchConfig = AskConfig | FindConfig; interface AskConfig { kind: 'ask'; config: ChatOptions; } interface FindConfig { kind: 'find'; config: SearchOptions; } interface GenerativeProviders { [key: string]: GenerativeProvider; } interface GenerativeProvider { title: string; enterprise_readiness: boolean; models: { [key: string]: ModelInfo; }; } interface ModelInfo { name: string; title: string; description?: string; config: ModelConfig; features: ModelFeatures; metadata: ModelMetadata; } interface ModelConfig { input_tokens: { min?: number; max: number; }; output_tokens: { min?: number; max: number; default_max?: number; }; prompt_id?: string; driver?: string; max_images?: string; assume_role?: number; } interface ModelFeatures { reasoning?: { default: number | ReasoningEffort; available_efforts?: ReasoningEffort; }; tools?: any; structured_output?: any; vision?: any; streaming?: any; system_message?: any; text_extraction?: any; custom_keys?: any; file_input?: any; image_generation?: any; } interface ModelMetadata { data_region?: string; data_residency_status?: DataResidencyStatus; deployed_region?: string; deprecated?: boolean; shut_down_date?: string; superseded_by?: string; stability?: ModelStability; knowledge_cutoff_date?: string; release_date?: string; } declare enum ModelStability { STABLE = "stable", PREVIEW = "preview" } declare enum ReasoningEffort { MINIMAL = "minimal", LOW = "low", MEDIUM = "medium", HIGH = "high", NONE = "none", XHIGH = "xhigh" } declare enum NumericReasoningEffort { MINIMAL = 0, LOW = 1, MEDIUM = 2, HIGH = 3, NONE = 4, XHIGH = 5 } interface ReasoningConfig { budget_tokens?: number; effort?: NumericReasoningEffort; } declare enum DataResidencyStatus { UNKNOWN = "unknown", GUARANTEED = "guaranteed", NOT_GUARANTEED = "not_guaranteed" } interface ProcessingHook { uri: string; headers?: { [key: string]: string; }; } interface DeleteResourcesFilter { filter_expression: { resource: ResourceFilterExpression; }; } interface DeletedResources { delete_id: string; resources: string[]; } interface AWSS3AccessKeysCredentials { access_key_id: string; secret_access_key: string; } interface AzureCertificateCredentials { tenant_id: string; client_id: string; pfx_base64: string; pfx_password: string; } interface ShareFileAPIKeyCredentials { api_key: string; subdomain: string; } type ExternalConnectionCredentials = { [key: string]: string; }; interface ISyncManager { kb: IWritableKnowledgeBox; nuclia: INuclia; createOAuthExternalConnection(provider: string): Observable; createExternalConnection(provider: string, credentials: { [key: string]: string; }): Observable; getExternalConnection(id: string): Observable; getAssumeRoleInfo(): Observable; createConfig(config: SyncConfigurationCreate): Observable; getConfigs(): Observable; getConfig(id: string): Observable; deleteConfig(id: string): Observable; getConfigJobs(id: string, pagination?: JobPagination): Observable; getJobLogs(jobId: string, pagination?: JobPagination, filters?: LogFilters): Observable; syncConfig(id: string, full_sync?: boolean): Observable; browse(externalConnectorId: string, options: BrowseOptions): Observable; resolveSite(connectionId: string, siteUrl: string): Observable; updateConfig(id: string, config: SyncConfigurationUpdate): Observable; } interface OAuthUrl { authorize_url: string; } interface ExternalConnection { id: string; kb_id: string; created_at: string; updated_at: string; created_by: string; provider: string; capabilities: BrowseCapabilities; } interface AssumeRoleInfo { external_id: string; role_name: string; aws_account_id: string; } interface BrowseCapabilities { has_sites: boolean; requires_site_search: boolean; requires_site_url_resolution: boolean; } interface SyncConfiguration extends SyncConfigurationOptions { id: string; name: string; kb_id: string; created_at: string; updated_at: string; sync_root_path: string; drive_id?: string; drive_type?: string; sharepoint_site_pages_site_id?: string; sync_interval_minutes: number; last_sync_run: string | null; created_by: string; external_connection: { id: string; provider: string; }; provider: string; } interface SyncConfigurationCreate extends SyncConfigurationOptions { name: string; folder_id?: string; sync_root_path?: string; drive_id?: string; sharepoint_site_pages_site_id?: string; external_connection_id: string; } type INullable = { [P in keyof T]: T[P] | null; }; interface SyncConfigurationUpdate extends INullable { name?: string; } interface SyncConfigurationOptions { file_filter?: FileFilter; labels?: { labelset: string; label: string; }[]; modified_time_range?: ModifiedTimeRange; extract_strategy?: string; } interface FileFilter { mode: 'include' | 'exclude'; extensions?: string[]; glob_patterns?: string[]; } interface ModifiedTimeRange { from?: string; to?: string; } interface JobsPage { items: Job[]; next_cursor?: string; } interface Job { id: string; created_at: string; finished_at: string | null; config_id: string; status: 'pending' | 'in_progress' | 'completed' | 'failed'; options: { full_sync: boolean; }; } interface JobLogsPage { items: JobLog[]; next_cursor?: string; } type LogLevel = 'INFO' | 'WARNING' | 'ERROR' | 'EXCEPTION' | 'CRITICAL'; interface JobLog { level: LogLevel; message: string; timestamp: string; [key: string]: unknown; } interface JobPagination { limit?: number; cursor?: string; order?: 'asc' | 'desc'; } interface LogFilters { level?: LogLevel; start_date?: string; end_date?: string; } interface BrowseOptions { drive_id?: string; folder_id?: string; path?: string; page_token?: string; site_id?: string; site_search?: string; } interface StorageStructure { sites?: StorageSite[]; drives?: StorageDrive[]; folders?: StorageFolder[]; next_page_token: string; } interface StorageDrive { id: string; name: string; drive_type?: string; web_url?: string; } interface StorageFolder { id: string; name: string; path: string; web_url?: string; } interface StorageSite { id: string; name: string; web_url?: string; } declare enum TrainingType { classifier = "classifier", resource_labeler = "resource-labeler", paragraph_labeler = "paragraph-labeler", ner = "ner" } declare enum TrainingStatus { finished = "finished", not_running = "not_running", running = "running", started = "started", stopped = "stopped" } declare enum TrainingExecutionStatus { succeeded = "succeeded", failed = "failed", stopped = "stopped" } interface TrainingLastExecution { start: string; end: string; status: TrainingExecutionStatus; } interface TrainingTask { task: string; status: TrainingStatus; last_execution?: TrainingLastExecution; } interface TrainingExecutions { items: TrainingExecution[]; pagination: { page: number; size: number; last: boolean; }; } interface TrainingExecution { id: string; task: string; start: string; end: string; status: TrainingExecutionStatus; } interface TrainingExecutionWithDuration extends TrainingExecution { duration: string; } declare class Training { kb: WritableKnowledgeBox; nuclia: INuclia; constructor(kb: WritableKnowledgeBox, nuclia: INuclia); start(type: TrainingType, params?: { valid_nertags?: string[]; valid_labelsets?: string[]; }): Observable; stop(type: TrainingType): Observable; getStatus(type: TrainingType): Observable; getExecutions(page?: number): Observable; hasModel(type: TrainingType): Observable; } interface KnowledgeBox extends IKnowledgeBox { } /** * Provides access to all the Knowledge Box contents and services in read mode. * * For any Knowledge Box operation that requires write access, you need to use `WritableKnowledgeBox` instead. */ declare class KnowledgeBox implements IKnowledgeBox { accountId: string; protected nuclia: INuclia; private tempTokenReplay; private tempTokenExpiration; private notifications?; private notificationsController?; private resourceProcessingStatus; private resourceOperationStatus; /** * The Knowledge Box path on the regional API. * * Example: `/v1/kb/3cce4a71-9cb9-4fda-beee-8a1512616bf0` */ get path(): string; /** * The Knowledge Box fullpath on the regional API. * * Example: `https://europe-1.dp.progress.cloud/api/v1/kb/3cce4a71-9cb9-4fda-beee-8a1512616bf0` */ get fullpath(): string; constructor(nuclia: INuclia, account: string, data: IKnowledgeBoxBase | IKnowledgeBoxStandalone); /** Returns all the NER families defined in the Knowledge Box. */ getEntities(): Observable; /** Returns the NER family with the given id. */ getEntitiesGroup(groupId: string): Observable; /** Returns all the labels defined in the Knowledge Box. */ getLabels(): Observable; /** Returns all the KV schemas defined in the Knowledge Box. */ getKVSchemas(): Observable; /** Returns the KV schema with the given id. */ getKVSchema(id: string): Observable; /** * Get the total amount of matches in the Knowledge Box for specific criteria (facets) passed in argument * @param facets List of facets to request * @returns An observable containing an object where each key is a string and maps to an object containing values and their corresponding counts. */ getFacets(facets: string[]): Observable; /** * Retrieves a resource from the Knowledge Box. * * - `show` defines which properties are returned. Default retrieves only the basic metadata. * - `extracted` defines which extracted data are returned. * It is ignored if `ResourceProperties.EXTRACTED` is not in the returned properties. * Default is an empty array. * * Example: ```ts nuclia.db .getKnowledgeBox() .pipe(switchMap((knowledgeBox) => knowledgeBox.getResource('09a94719a6444c5a9689394f6ed9baf6'))) .subscribe((resource) => { console.log('resource', resource); }); ``` */ getResource(uuid: string, show?: ResourceProperties[], extracted?: ExtractedDataTypes[]): Observable; /** * Retrieves a resource from the Knowledge Box with all its attached metadata and content. */ getFullResource(uuid: string): Observable; getResourceBySlug(slug: string, show?: ResourceProperties[], extracted?: ExtractedDataTypes[]): Observable; getFullResourceBySlug(slug: string): Observable; private _getResource; private _getPath; getResourceFromData(data: IResource): Resource; createAgenticRAGPipeline(steps: Agentic.Steps): Agentic.Pipeline; /** * Retrieves a generative answer for the given query. * * The generative answer is a text that is generated chunk by chunk by the language model. * It is retrieved through a readable HTTP stream, so the `chat()` method returns an `Observable` * emitting a value each time a new chunk is available. * The `incomplete` attribute of the emitted value indicates if the asnwer is complete or not. * * Example: ```ts nuclia.knowledgeBox .ask('where does the Little Prince live') .pipe(filter((answer) => !answer.incomplete)) .subscribe((answer) => { console.log(answer.text); }); ``` */ ask(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions): Observable; ask(query: string, context?: Ask.ContextEntry[], features?: Ask.Features[], options?: ChatOptions, callback?: (answer: Ask.Answer | IErrorResponse) => void): Observable; /** * Performs a find operation in the Knowledge Box, which is the recommended way to search for results. * * Example: ```ts nuclia.knowledgeBox .find('where does the Little Prince live') .subscribe((searchResult) => { console.log('search result', searchResult); }); ``` */ find(query: string, features?: Search.Features[], options?: SearchOptions): Observable; /** * Performs a search operation in the knowledge box. * * It is similar to `find()` but the results are not nested. * * Example: ```ts nuclia.knowledgeBox .search('where does the Little Prince live', [Search.Features.KEYWORD]) .subscribe((searchResult) => { console.log('search result', searchResult); }); ``` */ search(query: string, features?: Search.Features[], options?: SearchOptions): Observable; /** * Summarize resources. * * It reads the resources text content and return a global summary about them and one summery per resource. * * The optional `user_prompt` parameter allows you to specify a text that will be used to generate the summary, * and must use the `{text}` placeholder to indicate where the resource text should be inserted * (example: 'Make a one-line summary of the following text: {text}'). * * Example: ```ts nuclia.knowledgeBox .summarize(['09a94719a6444c5a9689394f6ed9baf6']) .subscribe((summary) => { console.log('Summary', summary); }); ``` */ summarize(ressourceIds: string[], user_prompt?: string, generative_model?: string): Observable; /** * Performs a tokenization of the given text. * * Example: ```ts nuclia.knowledgeBox .tokens('Does James Joyce live in Dublin?') .subscribe((tokens) => { console.log('tokens', tokens); }); ``` */ tokens(text: string): Observable; /** * Performs a question answering operation * * Example: ```ts nuclia.knowledgeBox .predictAnswer('Who is Eric from Toronto?')) .subscribe((answer) => { if (answer.type !== 'error') { console.log('answer', answer.text); } }); ``` */ predictAnswer(question: string, options?: PredictAnswerOptions, synchronous?: boolean): Observable; /** * Performs a question answering operation based on a given context. * * Example: ```ts nuclia.knowledgeBox .generate('Who is Eric from Toronto?', [ 'Eric is a taxi driver', 'Eric was born in France', 'Eric lives in Toronto', ])) .subscribe(({ answer }) => { console.log('answer', answer); }); ``` */ generate(question: string, context?: string[]): Observable<{ answer: string; cannotAnswer: boolean; }>; /** * Performs a question answering operation using a JSON schema. * * Example: ```ts nuclia.knowledgeBox .generateJSON( 'Who is Eric from Toronto?', { name: 'info', parameters: { properties: { location: { title: 'Location', description: 'The location of the person', type: 'string', }, name: { title: 'Name', description: 'The name of the person', type: 'string', }, }, required: ['name', 'location'], }, }, [ 'Eric is a taxi driver', 'Eric was born in France', 'Eric lives in Toronto', ], )).subscribe((answer) => { console.log('location', answer.answer.location); }); ``` */ generateJSON(question: string, json_schema: object, context?: string[]): Observable<{ answer: object; success: boolean; }>; /** * Performs a question rephrasing operation. * It returns a rephrased question that can be used as input for the `generate()` method. * Example: ```ts nuclia.knowledgeBox .rephrase('Eric lives Toronto') .subscribe((rephrased) => { console.log('rephrased', rephrased); // Where does Eric live? }); ``` */ rephrase(question: string, user_context?: string[], rephrase_prompt?: string): Observable; /** * Generates a random question about the given resource. * It picks an entities relation from the extracted metadata and generates a question about it. * It returns an empty string if no question can be generated. * Example: ```ts nuclia.knowledgeBox .getResource('09a94719a6444c5a9689394f6ed9baf6', [ResourceProperties.EXTRACTED], [ExtractedDataTypes.METADATA]) .pipe( switchMap((resource) => knowledgeBox.generateRandomQuestionAboutResource(resource)), ) .subscribe((question) => { console.log('question', question); }); ``` */ generateRandomQuestionAboutResource(resource: Resource): Observable; catalog(query: string | CatalogQuery, options?: CatalogOptions): Observable; /** Suggests paragraphs based on the given query. */ suggest(query: string, inTitleOnly?: boolean, features?: Search.SuggestionFeatures[], options?: SuggestOptions): Observable; feedback(answerId: string, good: boolean, feedback?: string, text_block_id?: string): Observable; /** Returns totals for each kind of contents stored in the Knowledge Box (resources, fields, paragraphs, vectors) */ counters(): Observable; /** Lists all the resources stored in the Knowledge Box. */ listResources(page?: number, size?: number): Observable; /** * Returns an ephemeral token. * Requires account id and zone to be set in the Nuclia options (except when working with a local NucliaDB instance). * * This is useful when displaying a clickable link to a file in a private Knowledge Box * (the token will authorize the request even though there are no authentication headers). * * Example: ```ts const downloadLink = `${nuclia.rest.getFullpath(filePath)}?eph-token=${nuclia.knowledgeBox.getTempToken()}`; ``` * @param payload Optional payload to provide extra data for the token generation * @param ignoreExpiration Optional By default, a temp token is valid for 5min and the same token returned if this method is called several times during this time. * Passing ignoreExpiration flag to true will ignore this expiration delay and will always return a new token. */ getTempToken(payload?: any, ignoreExpiration?: boolean): Observable; private _getTempToken; getConfiguration(): Observable<{ [id: string]: any; }>; getLearningSchema(): Observable; getGenerativeProviders(): Observable; getUsers(): Observable; getInvites(): Observable; /** * Start listening to all the notifications sent by the Knowledge Box. */ listenToAllNotifications(): Observable; /** * Stop listening the notifications sent by the Knowledge Box. */ stopListeningToNotifications(): void; /** * Start listening to the Knowledge Box notifications, and returns the list of notifications corresponding to the different operations affecting the resources: * created, modified, deleted. * The notification contains the resource id, title, a timestamp and a flag indicating if the operation was successful or not. */ listenToResourceOperationNotifications(): Observable; /** * Start listening to the Knowledge Box notifications, and returns the list of notifications for resources which have processing completed (either successfully or not). * Notifications are sent anytime processing is completed, and processing is done anytime the resource is created or modified (like when a summary is added to the resource for example). */ listenToProcessingNotifications(): Observable; processingStatus(cursor?: string, scheduled?: boolean, limit?: number): Observable<{ cursor: string; results: ProcessingStatus[]; }>; getExtractStrategies(): Observable; getSplitStrategies(): Observable; getSearchConfig(id: string): Observable; getSearchConfigs(): Observable; getAgenticConfig(id: string): Observable; listAgenticConfigs(): Observable; getAgenticConfigsSchema(): Observable; getAgenticSource(id: string): Observable; listAgenticSources(): Observable; /** * Asks a question using an agentic pipeline (Rephrase → SmartAgent → Summarize) over WebSocket. * * Requires an `agentic_config_id` that has been created via `createAgenticConfig()`. * Set `keepOpen: true` to keep the connection open for follow-up questions. */ askViaWS(agenticConfigId: string, question: string, keepOpen?: boolean, searchConfiguration?: string, groups?: string[], chatHistory?: HistoryEntry[]): Observable; getProcessingHook(): Observable; } /** Extends `KnowledgeBox` with all the write operations. */ declare class WritableKnowledgeBox extends KnowledgeBox implements IWritableKnowledgeBox { /** True if the current user is an administrator of the Knowledge Box. */ admin?: boolean; /** True if the current user is a contributor of the Knowledge Box. */ contrib?: boolean; private _training?; private _activityMonitor?; private _taskManager?; private _syncManager?; /** * Entry point to task manager */ get taskManager(): TaskManager; get syncManager(): ISyncManager; /** * @deprecated */ get training(): Training; get activityMonitor(): ActivityMonitor; /** * Modifies the Knowledge Box properties. * * Example: ```ts nuclia.db.getKnowledgeBox("my-account", "my-kb").pipe( switchMap((knowledgeBox) => knowledgeBox.modify({title: "My new title"}), ).subscribe(() => { console.log("knowledge box modified"); }); ``` */ modify(data: Partial): Observable; /** Deletes the Knowledge Box. */ delete(): Observable; protected getKbEndpointAndZone(): { endpoint: string; zone: string | undefined; }; /** Publishes or unpublishes the Knowledge Box. */ publish(published: boolean): Observable; /** * Creates or updates a label set. * * Example: ```ts nuclia.db .getKnowledgeBox('my-account', 'my-kb') .pipe( switchMap((knowledgeBox) => knowledgeBox.setLabelSet('status', { title: 'Status', color: '#ff0000', labels: [{ title: 'Major' }, { title: 'Minor' }, { title: 'Critical' }], }), ), ) .subscribe(() => { console.log('label set set'); }); ``` */ setLabelSet(setId: string, labelSet: LabelSet): Observable; /** Deletes a label set. */ deleteLabelSet(setId: string): Observable; /** Creates and indexes a new resource in the Knowledge Box. */ createResource(resource: ICreateResource, synchronous?: boolean): Observable<{ uuid: string; }>; /** * Creates a new link resource in the Knowledge Box more easily than using `createResource`. * * Example: ```ts nuclia.db .getKnowledgeBox('my-account', 'my-kb') .pipe( switchMap((knowledgeBox) => knowledgeBox.createLinkResource( { uri: 'https://en.wikipedia.org/wiki/Hedy_Lamarr', }, { classifications: [{ labelset: 'Genius', label: 'Inventor' }] }, ), ), ) .subscribe(() => { console.log('resource created'); }); ``` */ createLinkResource(link: LinkField, metadata?: UserMetadata, synchronous?: boolean, origin?: Origin, slug?: string): Observable<{ uuid: string; }>; /** Checks if a resource exists for the given slug. */ hasResource(slug: string): Observable; /** * Creates a resource or updates it if it already exists */ createOrUpdateResource(data: ICreateResource, synchronous?: boolean): Observable<{ uuid: string; } | void>; /** * Uploads a file to the Knowledge Box and automatically creates a new resource to store the file. * The resource path is returned in the `resource` property of the `UploadResult` * (and `field` provides the path to the `FileField`). * * Example: ```ts nuclia.db .getKnowledgeBox('my-account', 'my-kb') .pipe(switchMap((knowledgeBox) => knowledgeBox.upload(fileInputElement.files[0]))) .subscribe(() => { console.log('file uploaded'); }); ``` */ upload(file: File | FileWithMetadata, TUS?: boolean, metadata?: FileMetadata): Observable; upload(buffer: ArrayBuffer, TUS?: boolean, metadata?: FileMetadata): Observable; /** * Uploads a list of files to the Knowledge Box. It automatically creates a new resource for each file * and uses the [TUS](https://tus.io/) protocol to upload the files. */ batchUpload(files: FileList | File[] | FileWithMetadata[]): Observable; getServiceAccounts(): Observable; createServiceAccount(data: ServiceAccountCreation): Observable; deleteServiceAccount(saId: string): Observable; createKey(saId: string, expires: string): Observable<{ token: string; }>; createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{ token: string; }>; deleteKey(saId: string, saKeyId: string): Observable; setConfiguration(config: { [id: string]: any; }): Observable; /** * Update the list of users of the Knowledge Box, providing the list of users (id and role) to add and/or update, and the list of user ids to delete. * @param data */ updateUsers(data: KbUserPayload): Observable; /** * Invite a user to the Knowledge Box * @param data */ inviteToKb(data: InviteKbData): Observable; deleteInvite(email: string): Observable; /** * Add an embedding model to the Knowledge box * @param model */ addVectorset(model: string): Observable; /** * Remove an embedding model from the Knowledge box * @param model */ removeVectorset(model: string): Observable; createExtractStrategy(config: ExtractConfig): Observable; deleteExtractStrategy(id: string): Observable; createSplitStrategy(strategy: SplitStrategy): Observable; deleteSplitStrategy(id: string): Observable; createSearchConfig(id: string, config: SearchConfig): Observable; updateSearchConfig(id: string, config: SearchConfig): Observable; deleteSearchConfig(id: string): Observable; createAgenticConfig(id: string, config: AgenticConfig): Observable; updateAgenticConfig(id: string, config: AgenticConfig): Observable; deleteAgenticConfig(id: string): Observable; createAgenticSource(id: string, source: AgenticSource): Observable; updateAgenticSource(id: string, source: AgenticSource): Observable; deleteAgenticSource(id: string): Observable; /** Creates a new KV schema in the Knowledge Box. */ createKVSchema(schema: KVSchema): Observable; /** Updates an existing KV schema. Only description and fields can be changed; id is immutable. */ updateKVSchema(id: string, update: UpdateKVSchema): Observable; /** Deletes a KV schema from the Knowledge Box. */ deleteKVSchema(id: string): Observable; updateProcessingHook(data: ProcessingHook): Observable; deleteProcessingHook(): Observable; deleteAllResources(filter: DeleteResourcesFilter): Observable; } /** * Sets up the onopen / onmessage / onerror / onclose handlers on an already-created WebSocket. * * Shared by `RetrievalAgent._interactThroughWs()` and `KnowledgeBox.askViaWS()`. * Both callers own the Subject and the WebSocket; this function only wires the handlers. * * @param ws The WebSocket instance to attach handlers to. * @param message The initial message sent on open. * @param subject The Subject that receives parsed AragAnswer emissions. * @param onUnexpectedClose Called when the socket closes with a non-1000 code before receiving * a DONE operation. The caller decides whether to reconnect (RetrievalAgent) * or emit an error and complete (KnowledgeBox). */ declare function setupAgenticWSHandlers(ws: WebSocket, message: InteractionRequest, subject: Subject, onUnexpectedClose?: (event: CloseEvent, lastMessage?: AragAnswer) => void, closeOnDone?: boolean): void; type InternetProviderType = 'brave' | 'perplexity' | 'tavily' | 'google'; type GuardrailsProviderType = 'alinia'; type ProviderType = InternetProviderType | GuardrailsProviderType | 'cypher' | 'nucliadb' | 'sync' | 'sql' | 'mcpsse' | 'mcpstdio' | 'mcphttp'; type AragModule = 'historical' | 'rephrase' | 'pre_conditional' | 'preprocess_alinia' | 'context_conditional' | 'basic_ask' | 'ask' | 'advanced_ask' | 'brave' | 'perplexity' | 'tavily' | 'google' | 'sql' | 'pandas' | 'snowflake' | 'cypher' | 'mcp' | 'restricted' | 'sparql' | 'summarize' | 'generate' | 'post_conditional' | 'remi' | 'external' | 'restart' | 'postprocess_alinia' | 'data_viz' | 'smart' | 'static' | 'sync'; declare function getCategoryFromModule(module: AragModule): 'preprocess' | 'context' | 'generation' | 'postprocess' | undefined; declare const PREPROCESS_MODULES: AragModule[]; type PreprocessModule = (typeof PREPROCESS_MODULES)[number]; declare function isPreprocessModule(x: any): x is PreprocessModule; declare const CONTEXT_MODULE: AragModule[]; type ContextModule = (typeof CONTEXT_MODULE)[number]; declare function isContextModule(x: any): x is ContextModule; declare const GENERATION_MODULE: AragModule[]; type GenerationModule = (typeof GENERATION_MODULE)[number]; declare function isGenerationModule(x: any): x is GenerationModule; declare const POSTPROCESS_MODULE: AragModule[]; type PostprocessModule = (typeof POSTPROCESS_MODULE)[number]; declare function isPostprocessModule(x: any): x is PostprocessModule; interface IDriver { /** * Driver identifier, to be used in path URLs (endpoints) */ id: string; /** * Driver configuration identifier, to be used in agent configuration */ identifier: string; provider: ProviderType; name: string; config: BraveConfig | CypherConfig | NucliaDBConfig | SyncConfig | PerplexityConfig | TavilyConfig | GoogleConfig | SqlConfig | McpSseConfig | McpStdioConfig | McpHttpConfig; } type DriverCreation = Omit; type Driver = BraveDriver | CypherDriver | NucliaDBDriver | PerplexityDriver | TavilyDriver | GoogleDriver | SqlDriver | McpSseDriver | McpStdioDriver | McpHttpDriver | SyncDriver | AliniaDriver; type InternetDriver = BraveDriver | PerplexityDriver | TavilyDriver | GoogleDriver; interface BraveDriver extends IDriver { provider: 'brave'; config: BraveConfig; } interface GoogleDriver extends IDriver { provider: 'google'; config: GoogleConfig; } interface CypherDriver extends IDriver { provider: 'cypher'; config: CypherConfig; } interface NucliaDBDriver extends IDriver { provider: 'nucliadb'; config: NucliaDBConfig; } interface PerplexityDriver extends IDriver { provider: 'perplexity'; config: PerplexityConfig; } interface TavilyDriver extends IDriver { provider: 'tavily'; config: TavilyConfig; } interface SqlDriver extends IDriver { provider: 'sql'; config: SqlConfig; } interface McpSseDriver extends IDriver { provider: 'mcpsse'; config: McpSseConfig; } interface McpStdioDriver extends IDriver { provider: 'mcpstdio'; config: McpStdioConfig; } interface McpHttpDriver extends IDriver { provider: 'mcphttp'; config: McpHttpConfig; } interface SyncDriver extends IDriver { provider: 'sync'; config: SyncConfig; } interface SyncDriver extends IDriver { provider: 'sync'; config: SyncConfig; } interface AliniaDriver extends IDriver { provider: 'alinia'; config: AliniaConfig; } interface InternetConfig { key: string; } interface BraveConfig extends InternetConfig { endpoint?: string; } interface GoogleConfig { vertexai?: boolean; api_key?: string; credentials?: string; project?: string; location?: string; } interface CypherConfig { username: string; password: string; url: string; timeout: number | null; enhanced_schema: boolean; database: string | null; config: { [property: string]: string | number | null; }; } interface NucliaDBConfig { url: string; manager: string; key?: string; description: string; kbid: string; filters: string[]; filter_expression?: FilterExpression; } type PerplexityConfig = InternetConfig; type TavilyConfig = InternetConfig; interface SqlConfig { dsn: string; sql_schema: string | null; } interface McpSseConfig { uri: string; key: string | null; headers: { [property: string]: string; }; timeout: number; sse_read_timeout: number; } interface McpStdioConfig { command: string; args: string[]; env: { [property: string]: string; }; cwd?: string; encoding?: string; encoding_error_handler?: 'strict' | 'ignore' | 'replace'; } interface McpHttpConfig { } interface SyncConfig extends NucliaDBConfig { connection_ids: string[]; } interface SyncConfig { } interface AliniaConfig { key: string; } type ISession = IResource; /** * Implements all the read operation on sessions. * * A session allows you to store content in the Retrieval Agent. * A single sessio might contain several fields. * * Fields have different types: files, links, texts, conversations, etc. */ declare class ReadableSession extends ReadableResource implements ISession { } /** * Extends `ReadableSession` and implements all the write operations. */ declare class Session extends Resource implements ISession { } type IRetrievalAgentBase = IKnowledgeBoxBase; type IRetrievalAgentItem = IKnowledgeBoxItem; type SessionProperties = ResourceProperties; type SessionPagination = ResourcePagination; interface RetrievalAgentCreation { slug: string; title: string; mode: 'agent' | 'agent_no_memory'; } interface SessionList { sessions: Session[]; pagination: SessionPagination; } interface SessionCreationResponse { uuid: string; elapsed: number; seqid: number; } interface SessionCreation { slug: string; name: string; summary: string; data: string; format: 'PLAIN' | 'HTML' | 'RST' | 'MARKDOWN' | 'JSON' | 'KEEP_MARKDOWN' | 'JSONL' | 'PLAIN_BLANKLINE_SPLIT'; } interface IRetrievalAgent extends Omit { getSession(uuid: string, show?: SessionProperties[], extracted?: ExtractedDataTypes[]): Observable; listSessions(page?: number, size?: number): Observable; createSession(session: SessionCreation): Observable; interact(sessionId: string, question: string, workflowId?: string, method?: 'POST' | 'WS', headers?: { [key: string]: string; }): Observable<{ type: 'answer'; answer: AragAnswer; } | IErrorResponse>; stopInteraction(sessionId: string): void; inviteToAgent(data: InviteKbData): Observable; getDrivers(provider?: ProviderType): Observable; addDriver(driver: DriverCreation): Observable; patchDriver(driver: Driver): Observable; deleteDriver(driverId: string): Observable; getRules(workflowId?: string): Observable<(Memory.Rule | string)[]>; setRules(rules: string[], workflowId?: string): Observable; getPreprocess(workflowId?: string): Observable; addPreprocess(agent: PreprocessAgentCreation, workflowId?: string): Observable<{ id: string; }>; patchPreprocess(agent: PreprocessAgent, workflowId?: string): Observable; deletePreprocess(agentId: string, workflowId?: string): Observable; getContext(workflowId?: string): Observable; addContext(agent: ContextAgentCreation, workflowId?: string): Observable<{ id: string; }>; patchContext(agent: ContextAgent, workflowId?: string): Observable; deleteContext(agentId: string, workflowId?: string): Observable; getGeneration(workflowId?: string): Observable; addGeneration(agent: GenerationAgentCreation, workflowId?: string): Observable<{ id: string; }>; patchGeneration(agent: GenerationAgent, workflowId?: string): Observable; deleteGeneration(agentId: string, workflowId?: string): Observable; getPostprocess(workflowId?: string): Observable; addPostprocess(agent: PostprocessAgentCreation, workflowId?: string): Observable<{ id: string; }>; patchPostprocess(agent: PostprocessAgent, workflowId?: string): Observable; deletePostprocess(agentId: string, workflowId?: string): Observable; getSchemas(): Observable; getFullSchemas(): Observable; requestActivityDownload(options: DownloadOptions): Observable; getDownloads(): Observable; getDownload(requestId: string): Observable; getWorkflows(): Observable; createWorkflow(data: Workflow): Observable; patchWorkflow(workflowId: string, data: Omit): Observable; deleteWorkflow(workflowId: string): Observable; } interface BaseAgent { module: AragModule; id?: string; rules?: string[] | null; title?: string; model?: string; validate_model?: string; } interface BasePreprocessAgent extends BaseAgent { module: PreprocessModule; } interface BaseContextAgent extends BaseAgent { module: ContextModule; } interface BaseGenerationAgent extends BaseAgent { module: GenerationModule; } interface BasePostprocessAgent extends BaseAgent { module: PostprocessModule; } type SomeAgent = BasePreprocessAgent | BaseContextAgent | BaseGenerationAgent | BasePostprocessAgent | PreprocessAgent | ContextAgent | GenerateAgent | PostprocessAgent; interface PreprocessAgent extends BaseAgent { id: string; module: PreprocessModule; } interface ContextAgent extends BaseAgent { id: string; module: ContextModule; } interface GenerationAgent extends BaseAgent { id: string; module: GenerationModule; } interface PostprocessAgent extends BaseAgent { id: string; module: PostprocessModule; } type PreprocessAgentCreation = HistoricalAgentCreation | RephraseAgentCreation | PreprocessAliniaCreation; type ContextAgentCreation = SqlAgentCreation | TavilyAgentCreation | PerplexityAgentCreation | BraveAgentCreation | GoogleAgentCreation | McpAgentCreation | CypherAgentCreation | AskAgentCreation | BasicAskAgentCreation | ContextConditionalAgentCreation | RestrictedAgentCreation | SparqlAgentCreation | SyncAgentCreation; type GenerationAgentCreation = SummarizeAgentCreation | GenerateAgentCreation; type PostprocessAgentCreation = RestartAgentCreation | RemiAgentCreation | ExternalAgentCreation | PostprocessAliniaCreation; interface HistoricalAgentCreation { module: 'historical'; all: boolean; } interface RephraseAgentCreation { module: 'rephrase'; kb: string; rids?: string[]; labels?: string[]; synonyms?: boolean; extend?: boolean; session_info?: boolean; history?: boolean; model?: string; split_question?: boolean; } interface SqlAgentCreation { module: 'sql'; source: string; description?: string | null; sqlschema?: string | null; retries?: number; ignore_tables: string[]; include_tables: string[]; sample_rows_in_table_info?: number; indexes_in_table_info?: boolean; custom_table_info?: { [property: string]: unknown; }; view_support?: boolean; max_string_length?: number; lazy_table_reflection?: boolean; conversion_model?: string; } interface TavilyAgentCreation { module: 'tavily'; source: string; } interface PerplexityAgentCreation { module: 'perplexity'; source: string; domain: string[]; top_k: number; related_questions: boolean; images: boolean; } interface BraveAgentCreation { module: 'brave'; source: string; domain: string | null; country: string | null; } interface McpAgentCreation { module: 'mcp'; source: string; transport: 'SSE' | 'STDIO'; fallback?: BaseContextAgent | null; summarize_model?: string; tool_choice_model?: string; } interface CypherAgentCreation { module: 'cypher'; source: string; exclude_types?: string[]; include_types?: string[]; allow_dangerous_requests?: boolean; top_k?: number; model?: string; } interface BasicAskAgentCreation { module: 'basic_ask'; sources: string[]; fallback?: BaseContextAgent | null; summarize_model?: string; generative_model?: string; } interface SyncAgentCreation { module: 'sync'; sources: string[]; fallback?: BaseContextAgent | null; generative_model?: string; } interface AskAgentCreation { module: 'ask'; sources: string[]; fallback?: BaseContextAgent | null; pre_queries?: string[]; filters?: string[]; security_groups?: string[]; rephrase_semantic_custom_prompt?: string; rephrase_lexical_custom_prompt?: string; keywords_custom_prompt?: string; visual_enable_prompt?: string; date_range_enabled?: boolean; before?: number; after?: number; extra_fields: string[]; full_resource: boolean; vllm: boolean; query_entities?: { name: string; type?: string; subtype?: string; }[]; retrieve_related?: string; configuration_model?: string; configuration_json_model?: string; ai_parameter_search?: boolean; } interface BaseConditionalAgentCreation { prompt?: string; then: (PreprocessAgent | ContextAgent | PostprocessAgent)[]; else_: (PreprocessAgent | ContextAgent | PostprocessAgent)[]; } interface PreConditionalAgentCreation extends BaseConditionalAgentCreation { module: 'pre_conditional'; then: PreprocessAgent[]; else_: PreprocessAgent[]; } interface ContextConditionalAgentCreation extends BaseConditionalAgentCreation { module: 'context_conditional'; then: ContextAgent[]; else_: ContextAgent[]; } interface PostConditionalAgentCreation extends BaseConditionalAgentCreation { module: 'post_conditional'; then: PostprocessAgent[]; else_: PostprocessAgent[]; } interface RestrictedAgentCreation { module: 'restricted'; code: string; } interface GoogleAgentCreation { module: 'google'; source: string; gen_model_id?: string; } interface SparqlAgentCreation { module: 'sparql'; } interface SummarizeAgentCreation { module: 'summarize'; prompt?: string; model?: string; images?: boolean; conversational?: boolean; } interface GenerateAgentCreation { module: 'generate'; prompt?: string; model?: string; images?: boolean; generate_image?: boolean; } interface RestartAgentCreation { module: 'restart'; prompt: string; model: string; retries?: number; } interface RemiAgentCreation { module: 'remi'; then?: PostprocessAgentCreation[]; else_?: PostprocessAgentCreation[]; } interface ExternalAgentCreation { module: 'external'; url: string; prompt?: string; method?: 'POST' | 'GET' | 'PATCH'; description?: string; call_schema?: unknown; call_obj?: unknown; headers?: { [name: string]: string; }; model?: string; context: boolean; } type GuardrailsPreconfig = 'INAPPROPRIATE' | 'COMPLIANCE' | 'FINANCIAL_COMPLIANT' | 'CUSTOM'; interface BaseAliniaAgentCreation { preconfig: GuardrailsPreconfig; metadata: { user_id: string | number | null; environment: string | null; } | null; detection_config: object | null; } interface PreprocessAliniaCreation extends BaseAliniaAgentCreation { module: 'preprocess_alinia'; preconfig: 'INAPPROPRIATE' | 'CUSTOM'; } interface PostprocessAliniaCreation extends BaseAliniaAgentCreation { module: 'postprocess_alinia'; preconfig: GuardrailsPreconfig; } interface HistoricalAgent extends PreprocessAgent, HistoricalAgentCreation { module: 'historical'; } interface RephraseAgent extends PreprocessAgent, RephraseAgentCreation { module: 'rephrase'; rules: string[]; } interface SqlAgent extends ContextAgent, SqlAgentCreation { module: 'sql'; } interface TavilyAgent extends ContextAgent, TavilyAgentCreation { module: 'tavily'; } interface PerplexityAgent extends ContextAgent, PerplexityAgentCreation { module: 'perplexity'; } interface McpAgent extends ContextAgent, McpAgentCreation { module: 'mcp'; } interface BraveAgent extends ContextAgent, BraveAgentCreation { module: 'brave'; } interface CypherAgent extends ContextAgent, CypherAgentCreation { module: 'cypher'; } interface BasicAskAgent extends ContextAgent, BasicAskAgentCreation { module: 'basic_ask'; } interface AskAgent extends ContextAgent, AskAgentCreation { module: 'ask'; } interface SyncAgent extends ContextAgent, SyncAgentCreation { module: 'sync'; } interface PreConditionalAgent extends PreprocessAgent, PreConditionalAgentCreation { module: 'pre_conditional'; } interface ContextConditionalAgent extends ContextAgent, ContextConditionalAgentCreation { module: 'context_conditional'; } interface PostConditionalAgent extends PostprocessAgent, PostConditionalAgentCreation { module: 'post_conditional'; } interface RestrictedAgent extends ContextAgent, RestrictedAgentCreation { module: 'restricted'; } interface GoogleAgent extends ContextAgent, GoogleAgentCreation { module: 'google'; } interface SparkleAgent extends ContextAgent, SparqlAgentCreation { module: 'sparql'; } interface GenerateAgent extends GenerationAgent, GenerateAgentCreation { module: 'generate'; } interface SummarizeAgent extends GenerationAgent, SummarizeAgentCreation { module: 'summarize'; } interface RestartAgent extends PostprocessAgent, RestartAgentCreation { module: 'restart'; model: string; } interface RemiAgent extends PostprocessAgent, RemiAgentCreation { module: 'remi'; } interface ExternalAgent extends PostprocessAgent, ExternalAgentCreation { module: 'external'; } interface PreprocessAliniaAgent extends PreprocessAgent, PreprocessAliniaCreation { module: 'preprocess_alinia'; } interface PostprocessAliniaAgent extends PostprocessAgent, PostprocessAliniaCreation { module: 'postprocess_alinia'; } interface ARAGSchemas { agents: { context: { [id: string]: ARAGAgent; }; generation: { [id: string]: ARAGAgent; }; preprocess: { [id: string]: ARAGAgent; }; postprocess: { [id: string]: ARAGAgent; }; }; drivers: { [id: string]: ARAGDriver; }; } interface ARAGAgent { id: string; agent_type: keyof ARAGSchemas['agents']; title: string; description: string; config_schema: JSONSchema4; } interface ARAGDriver { id: string; title: string; description: string; config_schema: JSONSchema4; } interface ExportOptions { passphrase: string; } interface ImportOptions { file: File; passphrase: string; overwrite?: boolean; } interface DownloadOptions { format: 'csv' | 'ndjson'; year?: number; month?: number; session_id?: string; } interface DownloadStatus { id: string; type: string; status: 'pending' | 'ready'; download_url?: string; query: { [key: string]: any; }; } interface Workflow { id: string; name: string; description?: string; parameters?: { [key: string]: any; }; rules?: (string | { prompt?: string; })[]; required?: string[]; } /** * Provides access to all the Retrieval Agent contents and services. */ declare class RetrievalAgent extends WritableKnowledgeBox implements IRetrievalAgent { private wsConnections; private oauthCredentials; /** * The Retrieval Agent path on the regional API. */ get path(): string; /** * The Retrieval Agent fullpath on the regional API. */ get fullpath(): string; /** * Retrieves a session from the Retrieval Agent. * * Example: ```ts nuclia.db .getRetrievalAgent() .pipe(switchMap((agent) => agent.getSession('09a94719a6444c5a9689394f6ed9baf6'))) .subscribe((session) => { console.log('session', session); }); ``` */ getSession(sessionId: string): Observable; /** * List all the sessions stored in the Retrieval Agent. * @param page Page index (0 by default) * @param size Page size * @returns Paginated sessions list */ listSessions(page?: number, size?: number): Observable; /** * Create sessions on the retrieval agent * @param session * @returns */ createSession(session: SessionCreation): Observable; interact(sessionId: string, question: string, workflowId?: string, method?: 'POST' | 'WS', headers?: { [key: string]: string; }, options?: InteractionOptions): Observable; stopInteraction(sessionId: string): void; sendMessage(sessionId: string, requestId: string, message: any): void; wsOpeningCount: number; private _interactThroughWs; private openWebSocket; /** * Interact with the session with an HTTP POST request. * @param sessionId Session identifier * @param question Question to send to the agent * @param workflowId Workflow identifier * @returns */ private _interactThroughPost; private getInteractionPath; private getWsPath; private getWsUrl; getAgentTempToken(agent_session: string, ttl?: number): Observable; /** * Invite a user to the Retrieval Agent. * @param data * @returns */ inviteToAgent(data: InviteKbData): Observable; /** * Get the list of drivers of the Retrieval Agent * @param provider Optional parameter allowing to filter the drivers to get only the ones corresponding to the given provider type */ getDrivers(provider?: ProviderType): Observable; /** * Add driver to the Retrieval Agent * @param driver BraveDriver | CypherDriver | NucliaDBDriver | PerplexityDriver | TavilyDriver | SqlDriver | McpDriver */ addDriver(driver: DriverCreation): Observable; /** * Edit driver * @param driver BraveDriver | CypherDriver | NucliaDBDriver | PerplexityDriver | TavilyDriver | SqlDriver | McpDriver */ patchDriver(driver: Driver): Observable; /** * Delete driver * @param driverId Identifier of the driver to delete */ deleteDriver(driverId: string): Observable; /** * Get the list of rules of a workflow * @param workflowId */ getRules(workflowId?: string): Observable<(Memory.Rule | string)[]>; /** * Set the list of rules of a workflow * @param rules List of rules to set * @param workflowId */ setRules(rules: string[], workflowId?: string): Observable; /** * Get the list of preprocess agents from a workflow. * @param workflowId * @returns the list of preprocess agents */ getPreprocess(workflowId?: string): Observable; /** * Add a preprocess agent to a workflow. * @param agent data representing the preprocess agent to add * @param workflowId * @returns An observable providing the created agent id. */ addPreprocess(agent: PreprocessAgentCreation, workflowId?: string): Observable<{ id: string; }>; /** * Edit an existing preprocess agent. * @param agent Modified preprocess agent to be saved. * @param workflowId */ patchPreprocess(agent: PreprocessAgent, workflowId?: string): Observable; /** * Delete a preprocess agent from a workflow. * @param agentId Identifier of the preprocess agent to delete * @param workflowId */ deletePreprocess(agentId: string, workflowId?: string): Observable; /** * Get the list of context agents from a workflow. * @param workflowId * @returns The list of context agents */ getContext(workflowId?: string): Observable; /** * Add a context agent to a workflow. * @param agent data representing the context agent to add * @param workflowId * @returns An observable providing the created agent id. */ addContext(agent: ContextAgentCreation, workflowId?: string): Observable<{ id: string; }>; /** * Edit an existing context agent. * @param agent Modified context agent to be saved * @param workflowId */ patchContext(agent: ContextAgent, workflowId?: string): Observable; /** * Delete a context agent from a workflow. * @param agentId Identifier of the agent to delete. * @param workflowId */ deleteContext(agentId: string, workflowId?: string): Observable; /** * Get the list of generation agents from a workflow. * @param workflowId * @returns The list of generation agents */ getGeneration(workflowId?: string): Observable; /** * Add a generation agent to a workflow. * @param agent data representing the generation agent to add. * @param workflowId * @returns An observable providing the created agent id. */ addGeneration(agent: GenerationAgentCreation, workflowId?: string): Observable<{ id: string; }>; /** * Edit an existing generation agent. * @param agent Modified generation agent to be saved * @param workflowId */ patchGeneration(agent: GenerationAgent, workflowId?: string): Observable; /** * Delete a generation agent from a workflow. * @param agentId Identifier of the agent to delete * @param workflowId */ deleteGeneration(agentId: string, workflowId?: string): Observable; /** * Get the list of postprocess agents from a workflow. * @param workflowId * @returns The list of postprocess agents */ getPostprocess(workflowId?: string): Observable; /** * Add a postprocess agent to a workflow. * @param agent data representing the postprocess agent to add * @param workflowId * @returns An observable providing the created agent id. */ addPostprocess(agent: PostprocessAgentCreation, workflowId?: string): Observable<{ id: string; }>; /** * Edit an existing postprocess agent. * @param agent Modified postprocess agent to be saved * @param workflowId */ patchPostprocess(agent: PostprocessAgent, workflowId?: string): Observable; /** * Delete a postprocess agent from a workflow. * @param agentId Identifier of the agent to delete * @param workflowId */ deletePostprocess(agentId: string, workflowId?: string): Observable; /** * Get the agents and drivers schemas */ getSchemas(): Observable; /** @deprecated * Use getSchemas */ getFullSchemas(): Observable; /** * Request the export of a Retrieval Agent. * @param options Export options */ export(options: ExportOptions): Observable; /** * Import a Retrieval Agent. * @param options Import options */ import(options: ImportOptions): Observable; /** * Request the download of activity data * @param options Download options */ requestActivityDownload(options: DownloadOptions): Observable; /** * Get the status of all downloads */ getDownloads(): Observable; /** * Get the status of a download * @param requestId */ getDownload(requestId: string): Observable; /** * Get the list of workflows */ getWorkflows(): Observable; /** * Create a new workflow */ createWorkflow(data: Workflow): Observable; /** * Edit an existing workflow */ patchWorkflow(workflowId: string, data: Omit): Observable; /** * Delete a workflow */ deleteWorkflow(workflowId: string): Observable; } /** Allows you to access Nuclia accounts and/or Nuclia Knowledge Boxes. */ declare class Db implements IDb { private nuclia; constructor(nuclia: INuclia); /** Returns a list of all the accounts which are accessible for the current authenticated user. */ getAccounts(): Observable; /** * Returns a list of all the KB indexes (account id, kb id, zone id) for the provided account slug. * @param accountSlug */ getKbIndexes(accountSlug: string): Observable; /** Creates a new account. */ createAccount(account: AccountCreation): Observable; /** * Modifies account properties. * * Example: ```ts nuclia.db.modifyAccount('my-account', { title: 'My account' }).subscribe({ next: () => { console.log('account modified'); }, error: (error) => { console.error(error); }, }); ``` */ modifyAccount(accountSlug: string, data: AccountModification): Observable; /** Deletes an account. Optionally pass an OTP code (from email verification) via the x-otp-email header. */ deleteAccount(accountSlug: string, otpCode?: string): Observable; /** * Returns account status. * * Example: ```ts nuclia.db .getAccountStatus('my-account') .pipe(filter((status) => status.available)) .subscribe((status) => { console.log('account ready'); }); ``` */ getAccountStatus(accountSlug: string): Observable; /** * Returns user information. * * Example: ```ts nuclia.db.getWelcome().subscribe((welcome) => { console.log(`Welcome ${welcome.preferences.name}`); }); ``` */ getWelcome(): Observable; /** * Returns sign up information. */ getSignupInfo(signup_token: string): Observable; /** * Returns the account with the given id or slug, or the one defined in the Nuclia options * if no id nor slug is provided. */ getAccount(): Observable; getStandaloneKbs(): Observable; private _getKnowledgeBoxes; /** Skips the warm-up call if the origin is already known for this zone (e.g. seeded by getAccountZones). */ private ensureZoneOriginReady; private _getKnowledgeBoxesForZone; /** * Returns a list of all the Knowledge Boxes for the given account. Account slug and id can be provided in the Nuclia options or as parameters. */ getKnowledgeBoxes(): Observable; getKnowledgeBoxes(accountSlug: string, accountId: string, includeSearchConfigs?: boolean): Observable; /** * Returns the list of Knowledge Boxes for the given account id and zone. * @param accountId * @param zone */ getKnowledgeBoxesForZone(accountId: string, zone: string, includeSearchConfigs?: boolean): Observable; /** * Returns a list of all the Retrieval Agents for the given account. Account slug and id can be provided in the Nuclia options or as parameters. */ getRetrievalAgents(): Observable; getRetrievalAgents(accountSlug: string, accountId: string, mode?: KnowledgeBoxMode, includeSearchConfigs?: boolean): Observable; /** * Returns the list of Retrieval Agents for the given account id and zone. * @param accountId * @param zone */ getRetrievalAgentsForZone(accountId: string, zone: string, mode?: KnowledgeBoxMode, includeSearchConfigs?: boolean): Observable; /** * Returns the Knowledge Box corresponding to the account id, Knowledge Box id and zone provided as parameters or the ones defined in the Nuclia options * if no parameters are provided. * Zone is mandatory except if the Knowledge Box is from a local NucliaDB instance. */ getKnowledgeBox(): Observable; getKnowledgeBox(accountId: string, knowledgeBoxId: string, zone?: string): Observable; getRetrievalAgent(): Observable; getRetrievalAgent(accountId: string, retrievalAgentId: string, zone?: string): Observable; /** * Creates a new Knowledge Box. * Zone parameter is mandatory. * Example: ```ts const knowledgeBox = { slug: 'my-kb', title: 'My knowledge box', }; nuclia.db.createKnowledgeBox('my-account-id', 'europe-1', knowledgeBox).subscribe((knowledgeBox) => { console.log('knowledge box', knowledgeBox); }); ``` */ createKnowledgeBox(accountId: string, knowledgeBox: KnowledgeBoxCreation, zone: string): Observable; /** * Creates a new Retrieval Agent. ```ts const retrievalAgent = { slug: 'my-arag', title: 'My retrieval agent', mode: 'agent' }; nuclia.db.createRetrievalAgent('my-account-id', 'europe-1', retrievalAgent).subscribe((retrievalAgent) => { console.log('retrieval agent', retrievalAgent); }); */ createRetrievalAgent(accountId: string, retrievalAgent: RetrievalAgentCreation, zone: string): Observable; /** * Get usage metric for the account. * @param accountId Account identifier * @param from Timestamp of the moment from which we want the metrics. * @param to Timestamp of the moment until which we want the metrics. When not provided, the metrics are returned "until now". * @param knowledgeBoxId Knowledge Box identifier to get the metrics for a specific Knowledge Box (returns the metrics aggregated for all the Knowledge Boxes of the account by default) * @param aggregation Define how the metrics are aggregated. By default, the endpoint returns only one point aggregating all the data for the specified date range. But you can have one point by: * - "hour" * - "day" * - "week" * - "month" * - "quarter" * - "year" * - "millennium" (used by default) * @param nuaKeyId NUA key identifier to get the metrics for a specific NUA key. */ getUsage(accountId: string, from: string, to?: string, knowledgeBoxId?: string, aggregation?: UsageAggregation, nuaKeyId?: string): Observable; /** * Uploads and pushes a file to Nuclia Understanding API. * * _Requires a NUA token._ * * Example: ```ts const file = input.files[0]; nuclia.db.upload(file).subscribe({ next: (response) => { console.log('file uploaded', response); }, error: (error) => { console.error(error); }, }); ``` */ upload(file: FileWithMetadata): Observable; /** * Pulls the latest data from Nuclia Understanding API. * * _Requires a NUA token._ */ pull(): Observable; getNUAActivity(accountId: string, client_id: string, zoneSlug: string, pageIndex?: number): Observable; /** Returns the list of NUA clients for the given account and zone. */ getNUAClientsForZone(accountId: string, zoneSlug: string): Observable; getNUAClients(accountId: string): Observable; getNUAClient(accountId: string, internalId: string, zone: string): Observable; hasNUAClient(): boolean; getNUAKey(): string; getNUAHeader(): { 'x-nuclia-nuakey': string; }; /** * Creates a NUA client and a NUA token. * Zone parameter must be provided except when working with a local NucliaDB instance. * @param accountId Account identifier * @param data NUA client data */ createNUAClient(accountId: string, data: NUAClientPayload): Observable; createNUAClient(accountId: string, data: NUAClientPayload, zone: string): Observable; /** * Edit a NUA key * @param accountId Account identifier * @param internalId NUA client internal identifier * @param data */ editNUAClient(accountId: string, internalId: string, data: NUAClientEditPayload, zone: string): Observable; /** * Renews a NUA token. * Zone parameter must be provided except when working with a local NucliaDB instance. */ renewNUAClient(accountId: string, internalId: string): Observable; renewNUAClient(accountId: string, internalId: string, zone: string): Observable; /** * Deletes a NUA client. * Zone parameter must be provided except when working with a local NucliaDB instance. */ deleteNUAClient(accountId: string, internalId: string): Observable; deleteNUAClient(accountId: string, internalId: string, zone: string): Observable; /** * Get NUA guardrail policies for the given account. * @param accountId * @returns */ getNuaGuardPolicies(accountId: string): Observable; /** * Get NUA guardrail policies for the given account and zone. * @param accountId * @param zone * @returns */ getNuaGuardPoliciesForZone(accountId: string, zone: string): Observable; /** * Get the NUA guardrail policy matching the given guardrail ID on the given account and zone. * @param guardId * @param accountId * @param zone * @returns */ getNuaGuardPolicy(guardId: string, accountId: string, zone: string): Observable; /** * Create a NUA guardrail policy on the given account and zone. * @param accountId * @param zone * @param data * @returns */ createNuaGuardPolicy(accountId: string, zone: string, data: NuaGuardPolicyPayload): Observable; /** * Edit the NUA guardrail matching the given identifier and the given account and zone. * @param guardId * @param accountId * @param zone * @param data * @returns */ editNuaGuardPolicy(guardId: string, accountId: string, zone: string, data: Partial): Observable; /** * Delete a NUA guardrail policy from the given account and zone. * @param guardId * @param accountId * @param zone * @returns */ deleteNuaGuardPolicy(guardId: string, accountId: string, zone: string): Observable; /** * Get learning configuration schema. * This method is requiring account id and zone parameters. */ getLearningSchema(accountId: string, zone: string): Observable; /** * Extract NER tokens from a text. */ predictTokens(text: string): Observable; /** * Generate an answer from a question and a context. */ predictAnswer(question: string, context: string[], model?: string): Observable; /** * Analyse a sentence, returning the language, the entities intent and the embeddings. */ predictQuery(text: string, rephrase?: boolean, model?: string, rephrase_prompt?: string): Observable; /** * Generate a summary from a text. * * The optional `user_prompt` parameter allows you to provide a custom prompt to the model, * it must use the `{text}` placeholder to indicate where the resource text should be inserted * (example: 'Make a one-line summary of the following text: {text}'). */ predictSummarize(text: string, user_prompt?: string, model?: string, summary_kind?: 'simple' | 'extended'): Observable; /** * Get an account user by their id * @param accountSlug * @param userId */ getAccountUser(accountSlug: string, userId: string): Observable>; /** * Get the list of all users of an account * @param accountSlug */ getAccountUsers(accountSlug: string): Observable; /** * Add and/or delete users from an account * @param accountSlug * @param users */ setAccountUsers(accountSlug: string, users: AccountUsersPayload): Observable; /** * Invite a user to an account * @param accountSlug * @param data */ inviteToAccount(accountSlug: string, data: InviteAccountUserPayload): Observable; /** * List pending account invitations * @param accountId */ getAccountInvitations(accountId: string): Observable; /** * Delete account invitation * @param accountId * @param email */ deleteAccountInvitation(accountId: string, email: string): Observable; /** * Get the list of custom models of an account */ getModels(accountId: string, zone: string): Observable; /** * Get a custom models */ getModel(modelId: string, accountId: string, zone: string): Observable; /** * Add a custom model to a Knowledge Box */ addModelToKb(modelId: string, accountId: string, kbId: string, zone: string): Observable; /** * Add a custom model to a Knowledge Box */ deleteModelFromKb(modelId: string, accountId: string, kbId: string, zone: string): Observable; /** * Get the list of model configurations of an account */ getModelConfigurations(accountId: string, zone: string): Observable; /** * Get a model configuration */ getModelConfiguration(modelId: string, accountId: string, zone: string): Observable; /** * Creates a new model configuration */ createModelConfiguration(model: ModelConfigurationCreation, accountId: string, zone: string): Observable<{ id: string; }>; /** * Updates a model configuration */ updateModelConfiguration(model: ModelConfigurationCreation, modelId: string, accountId: string, zone: string): Observable; /** * Deletes a model configuration */ deleteModelConfiguration(modelId: string, accountId: string, zone: string): Observable; } interface INuclia { options: NucliaOptions; auth: IAuthentication; rest: IRest; db: IDb; events?: IEvents; get backend(): string; get regionalBackend(): string; get knowledgeBox(): KnowledgeBox; } interface IEvents { emit(eventName: string, data: T): void; on(eventName: string): Observable; log(eventName: string, data: any): void; dump(): Observable<{ [name: string]: any; }>; } interface IAuthentication { isAuthenticated(): Observable; hasLoggedOut(): Observable; logout(): void; getAuthHeaders(): { [key: string]: string; }; getAuthHeaders(method: string, path: string): { [key: string]: string; }; getToken(force?: boolean): string; getRefreshToken(): string; authenticate(tokens: AuthTokens): boolean; setPassword(password: string): Observable; deleteAuthenticatedUser(): Observable; requestEmailOtp(): Observable; getJWTUser(): JwtUser | null; getAuthInfo(includeIP?: boolean): Observable; redirectToOAuth(queryParams?: { [key: string]: string | boolean; }, oauthUrlParams?: { [key: string]: string; }): void; processAuthorizationResponse(authCode: string, returnedState: string): Observable<{ success: boolean; state: any; }>; getAuthUrl(): string; validateMagicToken(token: string, zone?: string): Observable; } interface IRest { get(path: string, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, zoneSlug?: string): Observable; post(path: string, body: any, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, synchronous?: boolean, zoneSlug?: string): Observable; put(path: string, body: any, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, synchronous?: boolean, zoneSlug?: string): Observable; patch(path: string, body: any, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, synchronous?: boolean, zoneSlug?: string): Observable; delete(path: string, extraHeaders?: { [key: string]: string; }, synchronous?: boolean, zoneSlug?: string, body?: any, doNotParse?: boolean): Observable; head(path: string, extraHeaders?: { [key: string]: string; }): Observable; getZones(): Observable<{ [key: string]: string; }>; getZoneSlug(zoneId: string): Observable; getAccountZones(accountIdOrSlug: string): Observable<{ [key: string]: string; }>; getZoneOrigin(slug: string): string | null | undefined; setZoneOrigins(origins: { [slug: string]: string | null; }): void; getFullUrl(path: string): string; getObjectURL(path: string): Observable; getStreamedResponse(path: string, body: any, extraHeaders?: { [key: string]: string; }): Observable<{ data: Uint8Array; incomplete: boolean; headers: Headers; }>; getStreamMessages(path: string, controller: AbortController): Observable<{ data: Uint8Array; headers: Headers; }>; checkAuthorization(path: string): Observable<{ allowed: boolean; roles: (KBRoles | NucliaDBRole)[]; }>; getHeaders(method: string, path: string, extraHeaders?: { [key: string]: string; }, synchronous?: boolean, formData?: boolean): { [key: string]: string; }; getWsUrl(path: string, ephemeralToken: string): string; } interface IDb { getAccounts(): Observable; getKbIndexes(accountSlug: string): Observable; createAccount(account: AccountCreation): Observable; getAccountStatus(accountSlug: string): Observable; modifyAccount(accountSlug: string, data: AccountModification): Observable; deleteAccount(accountSlug: string, otpCode?: string): Observable; getWelcome(): Observable; getSignupInfo(signup_token: string): Observable; getAccount(): Observable; getAccount(accountIdOrSlug?: string): Observable; getStandaloneKbs(): Observable; getKnowledgeBoxes(): Observable; getKnowledgeBoxes(accountSlug: string, accountId: string, includeSearchConfigs?: boolean): Observable; getKnowledgeBoxesForZone(accountId: string, zone: string, includeSearchConfigs?: boolean): Observable; getKnowledgeBox(): Observable; getKnowledgeBox(accountId: string, knowledgeBoxId: string, zone?: string): Observable; createKnowledgeBox(accountId: string, knowledgeBox: KnowledgeBoxCreation, zone?: string): Observable; getRetrievalAgents(): Observable; getRetrievalAgents(accountSlug: string, accountId: string, mode?: KnowledgeBoxMode, includeSearchConfigs?: boolean): Observable; getRetrievalAgentsForZone(accountId: string, zone: string, mode?: KnowledgeBoxMode, includeSearchConfigs?: boolean): Observable; getRetrievalAgent(): Observable; getRetrievalAgent(accountId: string, retrievalAgentId: string, zone?: string): Observable; createRetrievalAgent(accountId: string, retrievalAgent: RetrievalAgentCreation, zone: string): Observable; getUsage(accountId: string, from: string, to?: string, knowledgeBox?: string, aggregation?: UsageAggregation, nuaKeyId?: string): Observable; upload(file: File): Observable; pull(): Observable; getNUAClients(accountId: string): Observable; getNUAClientsForZone(accountId: string, zoneSlug: string): Observable; getNUAClient(accountId: string, client_id: string, zone: string): Observable; createNUAClient(accountId: string, data: NUAClientPayload): Observable; createNUAClient(accountId: string, data: NUAClientPayload, zone: string): Observable; editNUAClient(accountId: string, internalId: string, data: NUAClientEditPayload, zone: string): Observable; renewNUAClient(accountId: string, internalId: string): Observable; renewNUAClient(accountId: string, internalId: string, zone: string): Observable; deleteNUAClient(accountId: string, internalId: string): Observable; deleteNUAClient(accountId: string, internalId: string, zone: string): Observable; hasNUAClient(): boolean; getNUAActivity(accountId: string, client_id: string, zoneSlug: string, pageIndex?: number): Observable; getLearningSchema(accountId: string, zone: string): Observable; predictTokens(text: string): Observable; predictAnswer(question: string, context: string[], model?: string): Observable; predictQuery(text: string, rephrase?: boolean, model?: string, rephrase_prompt?: string): Observable; predictSummarize(text: string, user_prompt?: string, model?: string, summary_kind?: 'simple' | 'extended'): Observable; getAccountUser(accountSlug: string, userId: string): Observable>; getAccountUsers(accountSlug: string): Observable; setAccountUsers(accountSlug: string, users: AccountUsersPayload): Observable; inviteToAccount(accountSlug: string, data: InviteAccountUserPayload): Observable; getAccountInvitations(accountId: string): Observable; deleteAccountInvitation(accountId: string, email: string): Observable; getModels(accountId: string, zone: string): Observable; getModel(modelId: string, accountId: string, zone: string): Observable; addModelToKb(modelId: string, accountId: string, kbId: string, zone: string): Observable; deleteModelFromKb(modelId: string, accountId: string, kbId: string, zone: string): Observable; getModelConfigurations(accountId: string, zone: string): Observable; getModelConfiguration(modelId: string, accountId: string, zone: string): Observable; createModelConfiguration(model: ModelConfigurationCreation, accountId: string, zone: string): Observable<{ id: string; }>; updateModelConfiguration(model: ModelConfigurationCreation, modelId: string, accountId: string, zone: string): Observable; deleteModelConfiguration(modelId: string, accountId: string, zone: string): Observable; getNuaGuardPolicies(accountId: string): Observable; getNuaGuardPoliciesForZone(accountId: string, zone: string): Observable; getNuaGuardPolicy(guardId: string, accountId: string, zone: string): Observable; createNuaGuardPolicy(accountId: string, zone: string, data: NuaGuardPolicyPayload): Observable; editNuaGuardPolicy(guardId: string, accountId: string, zone: string, data: Partial): Observable; deleteNuaGuardPolicy(guardId: string, accountId: string, zone: string): Observable; } interface NucliaOptions { /** * The Nuclia backend to use. * * Example: `https://accounts.progress.cloud/api` */ backend: string; /** * The geographical zone for the regional API calls. * * Example: `europe-1` */ zone?: string; /** * The regional base doamin prefix. * * Example: `europe-1` */ regionalPrefix?: string; /** * Allows you to make calls to a private Knowledge Box. * * It can be used in a server-side app, but never in a web app. */ apiKey?: string; /** * Allows you to make calls the NUA processing. */ nuaKey?: string; /** * The Nuclia account slug. * * Example: `my-account` */ account?: string; accountType?: AccountTypes; /** * The Nuclia account id. */ accountId?: string; /** * The Nuclia Knowledge Box unique id. * * Example: `17815eb2-06a5-40ee-a5aa-b2f9dbc5da70` */ knowledgeBox?: string; /** * The Knowledge Box slug. * * Example: `my-kb` */ kbSlug?: string; client?: string; /** Indicates if you are using a proxy. */ proxy?: boolean; /** * Indicates if the Knowledge Box is public or not. * * Set it to `false` when using a private Knowledge Box. */ public?: boolean; /** * OAuth parameters. */ oauth?: { client_id: string; }; /** * Allow to modify the headers for the REST calls. */ modifyHeaders?: (headers: { [key: string]: string; }) => { [key: string]: string; }; } type PromiseMapper = { [K in keyof T]: T[K] extends (...args: infer A) => Observable ? (...args: A) => Promise : T[K]; }; interface IErrorResponse { status: number; detail: string; type: 'error'; body?: any; } type AccountRoles = 'AOWNER' | 'AMEMBER'; interface FullAccountUser { id: string; name: string; email: string; role: AccountRoles; } interface AccountUser { id: string; role: AccountRoles; } interface AccountUsersPayload { add?: AccountUser[]; delete?: string[]; } interface InviteAccountUserPayload { email: string; role?: AccountRoles; came_from?: string; } interface PendingInvitation { email: string; role: AccountRoles; expires: string; } interface JwtUser { client_id: string; exp: number; ext: { first_name: string; type: string; last_verified_at?: number; }; iat: number; iss: string; jti: string; sub: string; nbf: number; scp: string[]; } declare class JwtHelper { token: string; constructor(token: string); urlBase64Decode(str: string): string; private b64decode; private b64DecodeUnicode; decodeToken(token?: string): any; getJWTUser(token?: string): JwtUser | null; getTokenExpirationDate(token?: string): Date | null; isTokenExpired(token?: string, offsetSeconds?: number): boolean; } interface AuthTokens { access_token: string; refresh_token: string; id_token?: string; } type NucliaDBRole = 'READER' | 'WRITER' | 'MANAGER'; interface AuthInfo { auth: string; ip_info?: IPAddressInfo; } interface IPAddressInfo { client?: string; available?: { [key: string]: string; }; } type MagicActionType = 'create' | 'edit' | 'login' | 'gosetpassword' | 'goaccount' | 'goselectaccount' | 'gosetupaccount' | 'startonboarding' | 'join_regional_kb' | 'redict_to_kb' | 'account_ready_please_login'; interface MagicAction { action: MagicActionType; token?: AuthTokens; account?: string; path?: string; id?: string; then?: string; join_kb_token?: string; kb?: string; login_token?: AuthTokens; zone?: string; consent_url?: string; came_from?: string; needs_initial_setpassword?: boolean; } /** * It manages authentication to the Nuclia backend. * It can be based on login/password for account authentication, * or on an API key for private Knowledge Box authentication. * Authentication is not necessary when using a public Knowledge Box. */ declare class Authentication implements IAuthentication { private nuclia; private _isAuthenticated; private timerSubscription?; constructor(nuclia: INuclia); /** * Returns the authentication header (which will be `Authorization` for account authentication, or `X-NUCLIA-SERVICEACCOUNT` for private Knowledge Box authentication). * * Example: ```ts const headers = nuclia.auth.getAuthHeaders(); ``` */ getAuthHeaders(): { [key: string]: string; }; getAuthHeaders(method: string, path: string): { [key: string]: string; }; private getNucliaDbRole; /** * Emits when the authentication status changes. * * Example: ```ts nuclia.auth.isAuthenticated().subscribe((isAuthenticated) => { if (isAuthenticated) { console.log('You are authenticated'); } else { console.log('You are not authenticated'); } }); ``` */ isAuthenticated(): Observable; /** * Returns an `Observable` emitting when the user has logged out. * * Example: ```ts nuclia.auth.hasLoggedOut().subscribe((loggedOut) => { if (loggedOut) { // do something } }); ``` */ hasLoggedOut(): Observable; getAuthUrl(): string; getHydraUrl(): string; redirectToOAuth(queryParams?: { [key: string]: string | boolean; }, oauthUrlParams?: { [key: string]: string; }): void; processAuthorizationResponse(authCode: string, returnedState: string): Observable<{ success: boolean; state: any; }>; private exchangeAuthorizationCode; private generateSecureToken; private generateCodeVerifier; private base64URLEncode; private generateCodeChallenge; /** * Returns a boolean if successful. Stores authentication tokens in localStorage and triggers `isAuthenticated`. * * This method is automatically called when using `login` and can be useful when using a custom authentication flow. * * Example: ```ts nuclia.auth.authenticate(tokens); ``` */ authenticate(tokens: AuthTokens): boolean; /** Calls the logout endpoint and removes the token stored in localStorage. */ logout(): void; refresh(): Observable; /** Returns authentication token stored in localStorage. */ getToken(force?: boolean): string; /** * Sets the current user’s password. * * Example: ```ts nuclia.auth.setPassword(password).subscribe({ next: (success) => { this.passwordError = success ? '' : 'Error'; console.log('password set', success); }, error: (error) => { this.passwordError = 'Error'; console.error(error); }, complete: () => { this.pending = false; }, }); ``` */ setPassword(password: string): Observable; /** * Deletes current user account and removes stored tokens. * * Example: ```ts nuclia.auth.deleteAuthenticatedUser().subscribe(() => { console.log('User deleted'); }); ``` */ deleteAuthenticatedUser(): Observable; /** * Requests an email OTP for the currently authenticated user. * Used to verify identity when deleting an account via email-based providers. * * Example: ```ts nuclia.auth.requestEmailOtp().subscribe(() => { console.log('OTP sent'); }); ``` */ requestEmailOtp(): Observable; /** Returns authentication information */ getAuthInfo(includeIP?: boolean): Observable; /** * Parses JWT token and returns corresponding user information. * * Example: ```ts const user = nuclia.auth.getJWTUser(); console.log(`Hello ${user?.ext.first_name}!`); ``` */ getJWTUser(): JwtUser | null; /** Returns refresh token stored in localStorage. */ getRefreshToken(): string; private storeTokens; private checkTokenExpiration; private fetch; validateMagicToken(token: string, zone?: string): Observable; } declare class Events implements IEvents { private messages; private logs; emit(eventName: string, data: T): void; on(eventName: string): Observable; log(eventName: string, data: any): void; dump(): Observable<{ [name: string]: any; }>; } declare class Nuclia implements INuclia { /** Nuclia configuration options */ options: NucliaOptions; /** Allows you to authenticate using username/password or using an API key. */ auth: IAuthentication; /** Allows you to make authenticated REST requests to the Nuclia backend. */ rest: IRest; /** Allows you to access and query the Nuclia database. */ db: IDb; events: Events; private readKb?; private _arag?; /** The Nuclia global backend URL. */ get backend(): string; /** The Nuclia regional backend URL. */ get regionalBackend(): string; /** * Direct access to the current Knowledge Box instance * (it returns a Knowledge Box in read mode, and does not work with account authentication). */ get knowledgeBox(): KnowledgeBox; /** * Direct access to the current Retrieval Agent instance */ get arag(): RetrievalAgent; /** Similar to `knowledgeBox`, but the returned object exposes `Promises` instead of RxJS `Observables`. */ get asyncKnowledgeBox(): PromiseMapper; /** * Depending on your use case, you might want to: * * - Use the Nuclia SDK to access and manage a Nuclia account. In this case you will need to provide the `backend` and `account` options, and you will use **account authentication**. * - Use the Nuclia SDK to use a Nuclia Knowledge Box. In this case you will need to provide the `backend`, `knowledgeBox` and `zone` options. You will also either use **knowledge box authentication**, or **no authentication** if the Knowledge Box is public. * * Example: ```ts const nuclia = new Nuclia({ backend: 'https://accounts.progress.cloud/api', knowledgeBox: '17815eb2-06a5-40ee-a5aa-b2f9dbc5da70', zone: 'europe-1', }); ``` */ constructor(options: NucliaOptions); } declare function replaceSubdomainInUrl(mainBackend: string, prefix?: string): string; /** * Canonical global backend used by the SDK. * * Legacy deployments may still pass `rag.` as backend. * Global endpoints must target `accounts.`, so we normalize here. */ declare function normalizeGlobalBackendUrl(url: string): string; declare function setZoneInRegionalUrl(url: string, zone?: string, regionalPrefix?: string): string; declare const ABORT_STREAMING_REASON = "Stop listening to streaming"; /** * Handles the elementary REST requests to the Nuclia backend, setting the appropriate HTTP headers. * * Its main methods implement the corresponding HTTP verbs (`GET` is `get()`, POST is `post()`, etc.) * For each of them, `extraHeaders` is an optional parameter that can be used to add headers to the request. * * On POST, PUT, PATCH and DELETE, the `synchronous` parameter will make the call synchronous, * meaning the response will be returned only when the operation is fully completed. It is `false` by default. * * * The default headers set by `Nuclia.rest` are: * * - `'content-type': 'application/json'` * - `Authorization` or `X-NUCLIA-SERVICEACCOUNT` depending on the type of authentication. * * The default headers will be overridden by `extraHeaders` if they have the same entries. * * `doNotParse` is a boolean that can be used to disable the automatic JSON parsing of the response. */ declare class Rest implements IRest { private nuclia; private zones?; /** Cached per account so concurrent per-zone callers of `getAccountZones()` share a single request. */ private accountZones; private zoneOrigins?; private streamErrorAt?; private webSockets; constructor(nuclia: INuclia); get(path: string, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, zoneSlug?: string): Observable; post(path: string, body: any, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, synchronous?: boolean, zoneSlug?: string): Observable; put(path: string, body: any, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, synchronous?: boolean, zoneSlug?: string): Observable; patch(path: string, body: any, extraHeaders?: { [key: string]: string; }, doNotParse?: boolean, synchronous?: boolean, zoneSlug?: string): Observable; delete(path: string, extraHeaders?: { [key: string]: string; }, synchronous?: boolean, zoneSlug?: string, body?: any, doNotParse?: boolean): Observable; head(path: string, extraHeaders?: { [key: string]: string; }): Observable; getHeaders(method: string, path: string, extraHeaders?: { [key: string]: string; }, synchronous?: boolean, formData?: boolean): { [key: string]: string; }; private fetch; /** * Returns the full URL of the given path, using the regional or the global Nuclia backend according to the path or the provided zone slug (if any). */ getFullUrl(path: string, zoneSlug?: string, insertAuthorizer?: boolean): string; /** * Check if the user has access to the given endpoint, and return the corresponding roles. * */ checkAuthorization(endpoint: string): Observable<{ allowed: boolean; roles: (KBRoles | NucliaDBRole)[]; }>; /** Builds the id-to-slug zone map from a zone list and seeds the origin cache as a side effect. */ private toZoneMap; /** Returns a dictionary giving the geographical zones available slugs by unique ids. */ getZones(): Observable<{ [key: string]: string; }>; getZoneSlug(zoneId: string): Observable; /** Zone id to slug map, scoped to the account's own zones (unlike `getZones()`, which is global). */ getAccountZones(accountIdOrSlug: string): Observable<{ [key: string]: string; }>; /** Returns the custom origin URL for the given zone slug, or null/undefined if not set. */ getZoneOrigin(slug: string): string | null | undefined; /** * Merges the provided slug→origin map into the cached zoneOrigins. * Uses "prefer non-null" semantics: a non-null incoming value always wins; * an incoming null/undefined does not overwrite an already-known non-null origin. */ setZoneOrigins(origins: { [slug: string]: string | null; }): void; /** * Downloads the file, converts it to a BLOB and returns its `blob:` URL. * * Use carefully with big files as it can impact the memory. */ getObjectURL(path: string): Observable; /** * Call an endpoint streaming its response by batch of data, * concatenate the data with the batch received previously until the response is marked as completed and then close the connection. * @param path * @param body body to be passed as parameter to the POST request made */ getStreamedResponse(path: string, body: unknown, extraHeaders?: { [key: string]: string; }): Observable<{ data: Uint8Array; incomplete: boolean; headers: Headers; }>; /** * Call a long polling HTTP endpoint streaming its response until the connection times out. * This method is keeping the connection alive by calling the endpoint again when it times out until the provided controller receives an abort signal * (or if the endpoint returns an error unrelated to the timeout). * * @param path * @param controller */ getStreamMessages(path: string, controller: AbortController): Observable<{ data: Uint8Array; headers: Headers; }>; private fetchStream; private _readStreamChunk; private concat; getWsUrl(path: string, ephemeralToken: string): string; } export { ABORT_STREAMING_REASON, ACTIVITY_LOG_ASK_SHOW_FIELDS, ACTIVITY_LOG_CHAT_SHOW_FIELDS, ACTIVITY_LOG_SEARCH_SHOW_FIELDS, ACTIVITY_LOG_SHOW_FIELDS, AccountBlockingState, ActivityMonitor, Agentic, AnswerOperation, Ask, AssumeRole, Authentication, BlockedFeature, CREATION_END_PREFIX, CREATION_START_PREFIX, ConversationFieldData, CustomSplitStrategy, DEFAULT_GENERATIVE_ANSWER_CONFIG, DEFAULT_NER_KEY, DEFAULT_RESULT_DISPLAY_CONFIG, DEFAULT_ROUTING_CONFIG, DEFAULT_SEARCH_BOX_CONFIG, DataResidencyStatus, Db, EventType, ExtractedDataTypes, FIELD_TYPE, FileFieldData, FilterOperator, HIDDEN_PREFIX, INITIAL_CITATION_THRESHOLD, InteractionOperation, JwtHelper, KnowledgeBox, LABEL_FILTER_PREFIX, LANGUAGE_FACET, LabelSetKind, LinkFieldData, MAX_FACETS_PER_REQUEST, MIME_FACETS, MIME_FILTER_PREFIX, Memory, ModelStability, ModelType, NER_FILTER_PREFIX, NUCLIA_STANDARD_SEARCH_CONFIG, NUCLIA_STANDARD_SEARCH_CONFIG_ID, Nuclia, NumericReasoningEffort, PATH_FILTER_PREFIX, RAG_METADATAS, RESOURCE_STATUS, RagImageStrategyName, RagStrategyName, ReadableResource, ReadableSession, ReasoningEffort, Reranker, Resource, ResourceFieldProperties, ResourceProperties, Rest, RetrievalAgent, SEVERITY, SHORT_FIELD_TYPE, SUMMARY_PROMPT, Search, Session, SortField, SyncManager, TUSuploadFile, TaskApplyTo, TaskManager, TextFieldData, Training, TrainingExecutionStatus, TrainingStatus, TrainingType, USER_PROMPTS, UsageType, Widget, WritableKnowledgeBox, ask, batchUpload, catalog, deDuplicateList, evaluateExpression, find, format, formatObject, getAgenticConfigDefaults, getAllNotifications, getCategoryFromModule, getDataKeyFromFieldType, getDateFromFilter, getEntityFromFilter, getFeatures, getFieldTypeFromString, getFileMetadata, getFilterFromDate, getFilterFromEntity, getFilterFromLabel, getFilterFromLabelSet, getFilterFromVisibility, getJsonSchemaValue, getLabelFromFilter, getLabelSetFromFilter, getLearningConfigPropType, getObjectValue, getPreselectedFilterValue, getRagStrategies, getSubSchema, getVisibilityFromFilter, getWidgetParameters, improveSchemaNames, isContextModule, isGenerationModule, isPostprocessModule, isPreprocessModule, lengthUnicode, longToShortFieldType, mapErrorResponseFromAnswer, normalizeGlobalBackendUrl, normalizeSchemaProperty, parsePreselectedFilters, parseRAGImageStrategies, parseRAGStrategies, predictAnswer, replaceSubdomainInUrl, retry429Config, search, setLabels, setZoneInRegionalUrl, setupAgenticWSHandlers, shortToLongFieldType, sliceUnicode, suggest, trimLabelSets, upload, uploadFile, uploadToProcess }; export type { ARAGAgent, ARAGDriver, ARAGException, ARAGSchemas, AWSS3AccessKeysCredentials, Account, AccountConfig, AccountCreation, AccountLimits, AccountLimitsPatchPayload, AccountModification, AccountRoles, AccountStatus, AccountTypes, AccountUser, AccountUsersPayload, ActivityLogAskFilters, ActivityLogAskQuery, ActivityLogAskShowField, ActivityLogAskShowFields, ActivityLogBaseQuery, ActivityLogChatFilters, ActivityLogChatQuery, ActivityLogChatShowField, ActivityLogChatShowFields, ActivityLogDownload, ActivityLogDownloadQuery, ActivityLogFilter, ActivityLogFilters, ActivityLogItem, ActivityLogPagination, ActivityLogQuery, ActivityLogQueryBase, ActivityLogResponseAskItem, ActivityLogResponseChatItem, ActivityLogResponseItem, ActivityLogResponseItemUnion, ActivityLogResponseSearchItem, ActivityLogSearchFilters, ActivityLogSearchQuery, ActivityLogSearchShowField, ActivityLogSearchShowFields, ActivityLogShowFields, ActivityLogStringFilter, AgenticConfig, AgenticConfigDefaults, AgenticConfigSchema, AgenticConfigs, AgenticModelConfig, AgenticRephraseConfig, AgenticSmartAgentConfig, AgenticSmartAgentMode, AgenticSmartAgentModels, AgenticSource, AgenticSources, AgenticSummarizeConfig, AliniaConfig, AliniaDriver, And, Answer, AnyFieldData, AppliedDataAugmentation, ApplyOption, AragAnswer, AragModule, AragResponse, AskAgent, AskAgentCreation, AskConfig, AskOperation, AssumeRoleInfo, AuditMetadataFilter, AugmentedField, AuthInfo, AuthTokens, AzureCertificateCredentials, BaseAgent, BaseAliniaAgentCreation, BaseConditionalAgentCreation, BaseContextAgent, BaseEntitiesGroup, BaseGenerationAgent, BaseNotificationData, BasePostprocessAgent, BasePreprocessAgent, BaseSearchOptions, BasicAskAgent, BasicAskAgentCreation, BraveAgent, BraveAgentCreation, BraveConfig, BraveDriver, BrowseCapabilities, BrowseOptions, CatalogOptions, CatalogQuery, ChatOptions, CitationFootnotes, Citations, Classification, CloudLink, CommonMetricDetails, ComputedMetadata, Consumption, ContextAgent, ContextAgentCreation, ContextConditionalAgent, ContextConditionalAgentCreation, ContextModule, ConversationField, ConversationFieldPages, ConversationalStrategy, Counters, CustomModel, CustomModelItem, CypherAgent, CypherAgentCreation, CypherConfig, CypherDriver, DataAugmentationParameters, DateCreatedFilter, DateModifiedFilter, DeleteResourcesFilter, DeletedResources, DownloadFormat, DownloadOptions, DownloadStatus, Driver, DriverCreation, Entities, EntitiesGroup, Entity, EntityDefinition, EntityExample, EntityFilter, EntityPosition, EntityPositions, Event, EventList, ExportOptions, ExternalAgent, ExternalAgentCreation, ExternalConnection, ExternalConnectionCredentials, ExtraMetadata, ExtractConfig, ExtractLLMConfig, ExtractStrategies, ExtractVLLMConfig, ExtractedData, ExtractedText, Feedback, FieldClassification, FieldComputedMetadata, FieldEntities, FieldEntity, FieldExtensionStrategy, FieldFilter, FieldFilterExpression, FieldFullId, FieldId, FieldMetadata, FieldMimetypeFilter, FileB64, FileExtractedData, FileField, FileFieldExtractedData, FileFilter, FileMetadata, FilePages, FileUploadStatus, FileWithMetadata, Filter, FilterExpression, FindConfig, FullAccountUser, FullKbUser, FullResourceStrategy, GenerateAgent, GenerateAgentCreation, GeneratedFilter, GenerationAgent, GenerationAgentCreation, GenerationModule, GenerativeProvider, GenerativeProviders, GenericFieldData, GoogleAgent, GoogleAgentCreation, GoogleConfig, GoogleDriver, GoogleSource, GoogleTimeRange, GraphExtractionExample, GraphOperation, GraphStrategy, GuardOperation, GuardrailsPreconfig, GuardrailsProviderType, HierarchyStrategy, HistoricalAgent, HistoricalAgentCreation, HistoryEntry, IAuthentication, ICreateResource, IDb, IDriver, IError, IErrorResponse, IEvents, IFieldData, IFieldDataBase, IKnowledgeBox, IKnowledgeBoxBase, IKnowledgeBoxItem, IKnowledgeBoxStandalone, INuclia, IPAddressInfo, IResource, IRest, IRetrievalAgent, IRetrievalAgentBase, IRetrievalAgentItem, ISession, IStandaloneKb, ISyncManager, IWritableKnowledgeBox, ImportOptions, InspectTaskResponse, InteractionOptions, InteractionRequest, InternetConfig, InternetDriver, InternetProviderType, InviteAccountUserPayload, InviteKbData, Job, JobLog, JobLogsPage, JobPagination, JobsPage, JwtUser, KBKVSchemas, KBRoles, KBStates, KVFieldType, KVRange, KVSchema, KVSchemaField, KVValue, KbIndex, KbInvite, KbUser, KbUserPayload, KeyValueContainsFilter, KeyValueEqualFilter, KeyValueField, KeyValueFieldData, KeyValueFilterExpression, KeyValueRangeFilter, KeywordFilter, KindFilter, KnowledgeBoxCreation, KnowledgeBoxMode, LLMConfig, Label, LabelFilter, LabelOperation, LabelSet, LabelSets, Language, LanguageFilter, LearningConfiguration, LearningConfigurationOption, LearningConfigurationProperty, LearningConfigurationSchema, LearningConfigurationSet, LearningConfigurationUserKeys, LearningConfigurations, LinkExtractedData, LinkField, LinkFieldExtractedData, LogFilters, MCPSource, MagicAction, MagicActionType, McpAgent, McpAgentCreation, McpHttpConfig, McpHttpDriver, McpSseConfig, McpSseDriver, McpStdioConfig, McpStdioDriver, Message, MessageAttachment, MessageContent, Metadata, MetadatasStrategy, Metric, MinScore, ModelConfig, ModelConfiguration, ModelConfigurationCreation, ModelConfigurationItem, ModelFeatures, ModelInfo, ModelMetadata, ModifiedTimeRange, NUAClient, NUAClientEditPayload, NUAClientPayload, NUAClientResponse, NeighbouringParagraphsStrategy, Ner, NestedPosition, Not, NotificationMessage, NotificationOperation, NotificationType, NuaGuardPolicy, NuaGuardPolicyPayload, NuaGuardPolicyResponse, NucliaDBConfig, NucliaDBDriver, NucliaDBRole, NucliaDBSource, NucliaOptions, NucliaTokensDetails, NucliaTokensMetric, NullableUploadLimits, NullableUsageLimits, OAuthCredentials, OAuthRedirection, OAuthUrl, Operation, Or, Origin, OriginCollaboratorFilter, OriginMetadataFilter, OriginPathFilter, OriginSourceFilter, OriginTagFilter, PageImageStrategy, PagePositions, PageSelections, PageStructure, PageToken, Paragraph, ParagraphClassification, ParagraphFilterExpression, ParagraphImageStrategy, PendingInvitation, PerplexityAgent, PerplexityAgentCreation, PerplexityConfig, PerplexityDriver, PerplexitySource, PositionedNER, PostConditionalAgent, PostConditionalAgentCreation, PostprocessAgent, PostprocessAgentCreation, PostprocessAliniaAgent, PostprocessAliniaCreation, PostprocessModule, PreConditionalAgent, PreConditionalAgentCreation, PredictAnswerOptions, PredictedToken, PreprocessAgent, PreprocessAgentCreation, PreprocessAliniaAgent, PreprocessAliniaCreation, PreprocessModule, PrequeriesStrategy, Prequery, ProcessingHook, ProcessingOptions, ProcessingPullResponse, ProcessingPushResponse, ProcessingStatus, PromiseMapper, PromptFeedbackSchema, Prompts, ProviderType, QAOperation, QueryInfo, Question, QuestionAnswer, QuestionAnswers, RAGImageStrategy, RAGStrategy, RankFusion, ReasoningConfig, ReasoningParam, Relation, RelationEntity, RelationEntityType, RelationExample, RelationMetadata, RelationType, RemiAgent, RemiAgentCreation, RemiAnswerStatus, RemiQueryCriteria, RemiQueryResponse, RemiQueryResponseContextDetails, RemiQueryResponseItem, RemiScore, RemiScoresResponseItem, RephraseAgent, RephraseAgentCreation, ResourceBaseNotification, ResourceData, ResourceField, ResourceFilter, ResourceFilterExpression, ResourceList, ResourceMimetypeFilter, ResourceOperationNotification, ResourcePagination, ResourceProcessedData, ResourceProcessingNotification, ResourceStatus, ResourceWrittenData, RestartAgent, RestartAgentCreation, RestrictedAgent, RestrictedAgentCreation, RetrievalAgentCreation, Routing, Row, RowsPreview, SamlConfig, SearchConfig, SearchConfigs, SearchMetricsItem, SearchOptions, Security, SemanticModelMigration, Sentence, SentenceSearch, SentenceToken, ServiceAccount, ServiceAccountCreation, ServiceAccountKey, SessionCreation, SessionCreationResponse, SessionList, SessionPagination, SessionProperties, ShareFileAPIKeyCredentials, Sheet, SignUpInfo, SomeAgent, SortOption, SortOrder, SparkleAgent, SparqlAgentCreation, SplitLLMConfig, SplitStrategies, SplitStrategy, SqlAgent, SqlAgentCreation, SqlConfig, SqlDriver, StartStopTaskResponse, StatusFilter, StorageDrive, StorageFolder, StorageSite, StorageStructure, StreamingChunk, SuggestOptions, SummarizeAgent, SummarizeAgentCreation, SyncAgent, SyncAgentCreation, SyncConfig, SyncConfiguration, SyncConfigurationCreate, SyncConfigurationOptions, SyncConfigurationUpdate, SyncDriver, SyncSource, TaskDefinition, TaskFullDefinition, TaskListResponse, TaskName, TaskOnBatch, TaskOnGoing, TaskParameters, TaskResults, TaskStatus, TaskTrigger, TavilyAgent, TavilyAgentCreation, TavilyConfig, TavilyDriver, TextField, TextFieldFormat, TextFormat, TokenAnnotation, TokenConsumption, TokenSearch, TrainingExecution, TrainingExecutionWithDuration, TrainingExecutions, TrainingLastExecution, TrainingTask, TypeParagraph, UpdateKVSchema, UploadLimits, UploadLimitsEntries, UploadResponse, UploadStatus, UsageAggregation, UsageLimits, UsageLimitsEntries, UsageMetric, UsagePoint, UserClassification, UserFieldMetadata, UserMetadata, UserType, ValidationFeedbackSchema, VisualSelection, Welcome, WelcomeUser, Workflow, WorkflowType, WriteFileField };