Skip to main content

Nuclia JavaScript SDK

The Nuclia SDK is an open-source library wrapping the Nuclia API in order to integrate the Nuclia services in your frontend or NodeJS application.

It supports both JavaScript and TypeScript.

We document here all the objects and methods offered by the SDK.

If you are looking for a step-by-step guide to integrate Nuclia in your application, please refer to the SDK guide.

Nuclia

Constructor

new Nuclia(options)

Depending on your use case, you might want to:

  • use the Nuclia SDK to access and manage a Nuclia account, in that 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 KnowledgeBox, in that case, you will need to provide the backend, knowledgeBox and zone options, and you will use knowledge box authentication or no authentication if the knowledge box is public.

Input:

options: Object

  • backend: String The Nuclia backend to use. Example: https://nuclia.cloud/api
  • account: String (optional) The Nuclia account slug. Example: my-account
  • knowledgeBox: String (optional) The Nuclia knowledge box unique id. Example: 17815eb2-06a5-40ee-a5aa-b2f9dbc5da70
  • kbSlug: String (optional) The knowledge box slug. Example: my-kb
  • zone: String (optional) The geographical zone for the regional API calls. Example: europe-1
  • apiKey: String (optional) Allows to make calls to a private Knowledge Box. It can be used in a server-side app, but never in a web app.

Output:

A Nuclia instance.

Example:

const nuclia = new Nuclia({
backend: 'https://nuclia.cloud/api',
knowledgeBox: '17815eb2-06a5-40ee-a5aa-b2f9dbc5da70',
zone: 'europe-1',
});

Properties

  • knowledgeBox: Direct access to the current knowledge box instance (it returns a knowledge box in read mode, and it does not work with account authentication)
  • asyncKnowledgeBox: Similar to the previous property, but the returned object exposes Promises instead of RxJS Observables.
  • auth: Allows to authenticate using username/password or using an API key.
  • db: Allows to access and query the Nuclia database.
  • rest: Allows to make authenticated REST requests to the Nuclia backend.
  • backend: the Nuclia backend URL.
  • regionalBackend: the Nuclia regional backend URL.
  • options: the Nuclia options.

Nuclia.auth

Nuclia.auth manages the 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 needed when using a public knowledge box.

Methods

authenticate(tokens: AuthTokens)

Returns a boolean if successful. Stores authentication tokens in localStorage and triggers isAuthenticated. This method is automatically called when using login. It can be useful when using a custom authentication flow.

Example:

nuclia.auth.authenticate(tokens);

deleteAuthenticatedUser()

Deletes current user account and remove stored tokens.

Output: Observable<void>

Example:

nuclia.auth.deleteAuthenticatedUser().subscribe(() => {
console.log('User deleted');
});

getAuthHeaders()

Returns the authentication header (which will be Authorization for account authentication, or X-STF-Serviceaccount for private knowledge box authentication).

Output: { [key: string]: string }

Example:

const headers = nuclia.auth.getAuthHeaders();

getJWTUser()

Parses JWT token and returns corresponding user information.

Output: JwtUser | null

Example:

const user = nuclia.auth.getJWTUser();
console.log(`Hello ${user?.ext.first_name}!`);

getRefreshToken()

Returns refresh token stored in localStorage.

Output: string

Example:

const refreshToken = nuclia.auth.getRefreshToken();

getToken()

Returns authentication token stored in localStorage.

Output: string

Example:

const token = nuclia.auth.getToken();

hasLoggedOut()

Returns an Observable emitting when the user has logged out.

Output: Observable<boolean>

Example:

nuclia.auth.hasLoggedOut().subscribe((loggedOut) => {
if (loggedOut) {
// do something
}
});

isAuthenticated()

Emits when the authentication status changes.

Output: Observable<boolean>

Example:

nuclia.auth.isAuthenticated().subscribe((isAuthenticated) => {
if (isAuthenticated) {
console.log('You are authenticated');
} else {
console.log('You are not authenticated');
}
});

login(username: string, password: string, validation?: string)

Calls the login endpoint for account authentication and emits when done.

It can optionally take a reCaptcha validation code if the Nuclia backend requires it. Once authenticated, the Nuclia SDK will periodically refresh the token before it expires.

Output: Observable<boolean>

Example:

nuclia.auth.login(username, password).subscribe({
next: (success) => {
this.loginError = success ? '' : 'Error';
console.log('logged in', success);
},
error: (error) => {
this.loginError = 'Error';
console.error(error);
},
complete: () => {
this.pending = false;
},
});

logout()

Calls the logout endopint and remove the token stored in localstorage.

Example:

nuclia.auth.logout();

setPassword(password: string)

Sets current user's password.

Output: Observable<boolean>

Example:

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;
},
});

Nuclia.db

Nuclia.db allows to access the Nuclia accounts and/or the Nuclia knowledge boxes.

Methods

createKnowledgeBox(account: string, knowledgeBox: KnowledgeBoxCreation)

Creates a new knowledge box.

Output: Observable<WritableKnowledgeBox>

It requires account authentication.

Parameters:

  • account: the account slug.
  • knowledgeBox: the knowledge box creation object
    • slug: the knowledge box slug, only lowercase letters, numbers, - and _ are allowed.
    • title: the knowledge box title.
    • description: Optional, the knowledge box description.
    • zone: Optional (default to europe-1), the geographical zone for the regional API calls.

Example:

const knowledgeBox = {
slug: 'my-kb',
title: 'My knowledge box',
};
nuclia.db.createKnowledgeBox('my-account', knowledgeBox).subscribe((knowledgeBox) => {
console.log('knowledge box', knowledgeBox);
});

createAccount(account: AccountCreation)

Creates a new account.

Output: Observable<Account>

It requires account authentication.

Parameters:

  • slug: the account slug. A slug can contain only lowercase letters, numbers, - and _.
  • title: the account title.
  • description: the account description (optional).
  • email: owner's email (optional).
  • zone: the geographical zone (optional).

Example:

nuclia.db.createAccount({ slug: 'my-account', title: 'my-account' }).subscribe((account) => {
console.log('account', account);
});

deleteAccount(account: string)

Deletes an account.

Output: Observable<void>

It requires account authentication.

Example:

nuclia.db.deleteAccount('my-account').subscribe(() => {
console.log('account deleted');
});

deleteNUAClient(account: string, client_id: string)

Deletes a NUA client.

It requires account authentication.

Output: Observable<void>

getAccount()

Returns the account defined in the Nuclia options.

Output: Observable<Account>

It requires account authentication.

Example:

nuclia.db.getAccount().subscribe((account) => {
console.log('account', account);
});

getAccount(account?: string)

Returns the account with the given slug.

Output: Observable<Account>

It requires account authentication.

Example:

nuclia.db.getAccount('my-account').subscribe((account) => {
console.log('account', account);
});

getAccounts()

Returns a list of all the accounts.

Output: Observable<Account[]>

It requires account authentication.

Example:

nuclia.db.getAccounts().subscribe((accounts) => {
console.log('accounts', accounts);
});

getAccountStatus(account: string)

Returns account status.

Output: Observable<AccountStatus> ({ available: boolean })

Example:

nuclia.db
.getAccountStatus('my-account')
.pipe(filter((status) => status.available))
.subscribe((status) => {
console.log('account ready');
});

getKnowledgeBox()

Returns the knowledge box defined in the Nuclia options.

Output: Observable<WritableKnowledgeBox>

Example:

nuclia.db.getKnowledgeBox().subscribe((knowledgeBox) => {
console.log('knowledge box', knowledgeBox);
});

getKnowledgeBox(account: string, knowledgeBox: string)

Returns the knowledge box with the given slug.

Output: Observable<WritableKnowledgeBox>

It requires account authentication.

Example:

nuclia.db.getKnowledgeBox('my-account', 'my-kb').subscribe((knowledgeBox) => {
console.log('knowledge box', knowledgeBox);
});

getKnowledgeBoxes(account: string)

Returns a list of all the knowledge boxes for the given account.

Output: Observable<WritableKnowledgeBox[]>

It requires account authentication.

Example:

nuclia.db.getKnowledgeBoxes('my-account').subscribe((knowledgeBoxes) => {
console.log('knowledge boxes', knowledgeBoxes);
});

getWelcome()

Returns user information.

Output: Observable<Welcome>

  preferences: {
last_login?: string;
email: string;
name?: string;
type: UserType;
language?: Language;
};
accounts: string[];
dependant_accounts: { id: string, slug: string }[];

Example:

nuclia.db.getWelcome().subscribe((welcome) => {
console.log(`Welcome ${welcome.preferences.name}`);
});

modifyAccount(account: string, data: Partial<Account>)

Modifies account properties.

Output: Observable<void>

It requires account authentication.

Example:

nuclia.db.modifyAccount('my-account', { title: 'My account' }).subscribe({
next: () => {
console.log('account modified');
},
error: (error) => {
console.error(error);
},
});

upload(file: FileWithMetadata)

Uploads and push a file to Nuclia Understanding API.

It requires a NUA token.

Parameters:

  • FileWithMetadata: the file to upload. FileWithMetadata is an extension of File with the following properties:
    • md5: the file md5 (optional).
    • payload: not applicable with Nuclia Understanding API (optional).

Output: Observable<ProcessingPushResponse>

ProcessingPushResponse {
seqid: number;
uuid: string;
}

Example:

const file = input.files[0];
nuclia.db.upload(file).subscribe({
next: (response) => {
console.log('file uploaded', response);
},
error: (error) => {
console.error(error);
},
});

pull()

Pulls the latest data from Nuclia Understanding API.

It requires a NUA token.

Output: Observable<ProcessingPullResponse>

ProcessingPullResponse {
status: string;
payload?: string; // protobuf base64 encoded
msgid?: string;
}

See @nuclia/protobuf

createNUAClient(account: string, data: NUAClientPayload)

Creates a NUA client and a NUA token.

It requires account authentication.

Parameters:

  • account: the account slug.
  • data: the NUA client payload:
{
client_id?: string;
contact: string;
description?: string;
title: string;
webhook?: string;
}

Output: Observable<{client_id: string; token: string}>

Example:

nuclia.db
.createNUAClient('my-account', {
contact: 'me@here.net',
client_id: 'my-laptop',
})
.subscribe((response) => {
console.log('NUA client created', response.token);
});

renewNUAClient(account: string, client_id: string)

Renews a NUA token.

It requires account authentication.

Output: Observable<{client_id: string; token: string}>

Nuclia.rest

Nuclia.rest handles the elementary REST requests to the Nuclia backend, setting the appropriate HTTP headers.

On POST, PUT, PATCH and DELETE, 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.

Methods

In the following methods, extraHeaders is an optional parameter that can be used to add headers to the request. The default headers set by Nuclia.rest are:

  • 'content-type': 'application/json',
  • Authorization or X-STF-Serviceaccount depending on the type of authentication. The default headers will be overridden by the extraHeaders ones if they have the same entries.

doNotParse is a boolean that can be used to disable the automatic JSON parsing of the response.

get<T>(path: string, extraHeaders?: { [key: string]: string }, doNotParse?: boolean)

Performs a GET request to the Nuclia backend.

Output: Observable<T>

post<T>(path: string, body: any, extraHeaders?: { [key: string]: string }, doNotParse?: boolean, synchronous?: boolean)

Performs a POST request to the Nuclia backend.

Output: Observable<T>

put<T>(path: string, body: any, extraHeaders?: { [key: string]: string }, doNotParse?: boolean, synchronous?: boolean)

Performs a PUT request to the Nuclia backend.

Output: Observable<T>

patch<T>(path: string, body: any, extraHeaders?: { [key: string]: string }, doNotParse?: boolean, synchronous?: boolean)

Performs a PATCH request to the Nuclia backend.

Output: Observable<T>

delete(path: string, extraHeaders?: { [key: string]: string }, synchronous?: boolean)

Performs a DELETE request to the Nuclia backend.

Output: Observable<void>

head(path: string, extraHeaders?: { [key: string]: string })

Performs a HEAD request to the Nuclia backend.

Output: Observable<Response>

getFullUrl(path: string)

Returns the full URL of the given path, using the regional or the global Nuclia backend according the path.

Output: string

Example:

nuclia.rest.getFullUrl('/account/my-account');
// https://nuclia.cloud/api/v1/account/my-account

getObjectURL(filePath: string)

Downloads the file, converts it to a Blob and returns its blob: URL.

Output: Observable<string>

getZones()

Returns a dictionary giving the geographical zones available slugs by unique ids.

Output: Observable<{ [key: string]: string }>

KnowledgeBox

Properties

  • id: the knowledge box unique id.

  • zone: the geographical zone for the regional API calls.

  • path: the knowledge box path on the regional API

    Example: /v1/kb/3cce4a71-9cb9-4fda-beee-8a1512616bf0

  • fullpath: the knowledge box fullpath on the regional API

    Example: https://europe-1.nuclia.cloud/api/v1/kb/3cce4a71-9cb9-4fda-beee-8a1512616bf0

Methods

counters()

Returns total elements stored in the knowledge box.

Output:

Observable<{
resources: number;
paragraphs: number;
fields: number;
sentences: number;
}>;

getEntities()

Returns all the entities groups in the knowledge box.

Output: Observable<Entities>

  • Entities : {[key: string]: EntitiesGroup}
  • EntitiesGroup : {title: string; color?: string; entities: { [entityName: string]: Entity }}

An Entity is a dictionary with the following properties:

  • value: string
  • merged: optional, boolean
  • represents: optional, string[]

Example:

nuclia.knowledgeBox.getEntities().subscribe((entities) => {
console.log('entities', entities);
});

getEntitiesGroup(groupId: string)

Returns the entities group with the given id.

Output: Observable<EntitiesGroup> EntitiesGroup : {title: string; color?: string; entities: { [entityName: string]: Entity }}

Example:

nuclia.knowledgeBox.getEntitiesGroup('countries').subscribe((entitiesGroup) => {
console.log('entities group', entitiesGroup);
});

getLabels()

Returns all the labels in the knowledge box.

Output: Observable<Labels>

  • Labels : {[key: string]: LabelSet}
  • LabelSet : {title: string; color?: string; labels: Label[]}
  • Label : {title: string; related?: string; text?: string; uri?: string;}

Example:

nuclia.knowledgeBox.getLabels().subscribe((labels) => {
console.log('labels', labels);
});

getResource(uuid: string, show: ResourceProperties[], extracted: ExtractedDataTypes[])

Retrieve a resource from the knowledge box.

Parameters:

  • uuid: the resource uuid.

  • show: optional, ResourceProperties[]. It defines which properties are returned. Default takes all the properties:

    • ResourceProperties.BASIC
    • ResourceProperties.ORIGIN
    • ResourceProperties.RELATIONS
    • ResourceProperties.VALUES
    • ResourceProperties.EXTRACTED
    • ResourceProperties.ERRORS
  • extracted: optional, ExtractedDataTypes[]. It defines which extracted data are returned (it is ignored if ResourceProperties.EXTRACTED is not in the returned properties). Default takes the following:

    • ExtractedDataTypes.TEXT
    • ExtractedDataTypes.METADATA
    • ExtractedDataTypes.LINK
    • ExtractedDataTypes.FILE

    Other possible values are ExtractedDataTypes.LARGE_METADATA and ExtractedDataTypes.VECTOR (Note: they might significantly increase the response size).

Output: Observable<IResource>

Example:

nuclia.db
.getKnowledgeBox()
.pipe(switchMap((knowledgeBox) => knowledgeBox.getResource('09a94719a6444c5a9689394f6ed9baf6')))
.subscribe((resource) => {
console.log('resource', resource);
});

getTempToken()

Returns an ephemeral token. It is useful when displaying a clickable link to a file.

Output: string

Example:

const downloadLink = `${nuclia.rest.getFullpath(filePath)}?eph-token=${nuclia.knowledgeBox.getTempToken()}`;

listResources(page?: number, size?: number)

List all the resources stored in the knowledge box.

Output: Observable<ResourceList>

ResourceList {
resources: Resource[];
pagination: ResourcePagination;
}

search(query: string, features: Search.Features[], options?: SearchOptions)

Performs a search in the knowledge box.

Parameters:

  • query: the search query.
  • features: optional, Search.Features[]. It defines which features are returned in each result. Default is []. Possible values are:
    • PARAGRAPH
    • DOCUMENT
    • RELATIONS
    • VECTOR
  • options: optional
    • highlight: boolean. If true, the matching words are marked in paragraphs text. Default is false (optional).
    • inTitleOnly: boolean. If true, the search is performed only in the title. Default is false (optional).

Output: Observable<SearchResult>

Example:

nuclia.knowledgeBox
.search('where does the Little Prince live', [Search.Features.PARAGRAPH])
.subscribe((searchResult) => {
console.log('search result', searchResult);
});

suggest(query: string)

Suggests paragraphs based on the given query.

Output: Observable<{error?: boolean; paragraphs?: Paragraphs;}[]>

getWidgets()

Returns all the widgets in the knowledge box.

Output: Observable<Widgets>

  • Widgets: {[key: string]: Widget}
  • Widget:
    • id: string
    • mode: 'button' | 'input' | 'form'`
    • description: optional, string`
    • features: { useFilters: boolean; suggestEntities: boolean; suggestSentences: boolean; suggestParagraphs: boolean; }
    • filters: optional, string[]
    • topEntities: optional, string[]
    • style: optional, { [key: string]: string }

Example:

nuclia.knowledgeBox.getWidgets().subscribe((widgets) => {
console.log('widgets', widgets);
});

getWidget(widgetId: string)

Returns the widget with the given id.

Output: Observable<Widget>

Example:

nuclia.knowledgeBox.getWidget('my-widget').subscribe((widget) => {
console.log('widget', widget);
});

WritableKnowledgeBox

It extends KnowledgeBox with the following properties and methods:

Properties

  • slug: knowledge box slug.
  • title: knowledge box title.
  • state: 'PUBLISHED' or 'PRIVATE'
  • description: knowledge box description.
  • admin: boolean, true if the current user is an administrator of the knowledge box.
  • contrib: boolean, true if the current user is a contributor.

Methods

modify(data: Partial<IKnowledgeBox>)

Modify the knowledge box properties.

It requires account authentication.

Output: Observable<void>

Example:

nuclia.db.getKnowledgeBox("my-account", "my-kb").pipe(
switchMap((knowledgeBox) => knowledgeBox.modify({title: "My new title"}),
).subscribe(() => {
console.log("knowledge box modified");
});

publish(published: boolean)

Publish or unpublish the knowledge box.

It requires account authentication.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(switchMap((knowledgeBox) => knowledgeBox.publish(true)))
.subscribe(() => {
console.log('knowledge box published');
});

delete()

Delete the knowledge box.

It requires account authentication.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(switchMap((knowledgeBox) => knowledgeBox.delete()))
.subscribe(() => {
console.log('knowledge box deleted');
});

setEntitiesGroup(groupId: string, group: EntitiesGroup)

Add or modify the entities group with the given id.

It requires account authentication or an API key with contributor access.

Parameters:

  • groupId: the entities group id.
  • group:
    • title: string
    • color: optional, string
    • entities: { [entityName: string]: Entity }

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(
switchMap((knowledgeBox) =>
knowledgeBox.setEntitiesGroup('countries', {
title: 'Countries',
color: '#ff0000',
entities: {
fr: { value: 'France' },
de: { value: 'Germany' },
it: { value: 'Italy' },
},
}),
),
)
.subscribe(() => {
console.log('entities group set');
});

deleteEntitiesGroup(groupId: string)

Delete an entities group.

It requires account authentication or an API key with contributor access.

Parameters:

  • groupId: the entities group id.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(switchMap((knowledgeBox) => knowledgeBox.deleteEntitiesGroup('countries')))
.subscribe(() => {
console.log('entities group deleted');
});

setLabelSet(setId: string, labelSet: LabelSet)

Add or modify the label set with the given id.

It requires account authentication or an API key with contributor access.

Parameters:

  • setId: the label set id.
  • labelSet:
    • title: string
    • color: optional, string
    • labels: {title: string; related?: string; text?: string; uri?: string;}[]

Output: Observable<void>

Example:

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');
});

deleteLabelSet(setId: string)

Delete a label set.

It requires account authentication or an API key with contributor access.

Parameters:

  • setId: the label set id.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(switchMap((knowledgeBox) => knowledgeBox.deleteLabelSet('status')))
.subscribe(() => {
console.log('label set deleted');
});

createResource(resource: ICreateResource)

Create and index a new resource in the knowledge box.

It requires account authentication or an API key with contributor access.

Parameters:

TO BE COMPLETED

  • title: optional, string
  • summary: optional, string
  • icon: optional, string
  • metadata: optional, Metadata
  • usermetadata: optional, UserMetadata
  • origin: optional, Origin
  • files: optional, { [key: string]: FileField }
  • links: optional, { [key: string]: LinkField }
  • texts: optional, { [key: string]: TextField }

Output: Observable<{ uuid: string }>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(
switchMap((knowledgeBox) =>
knowledgeBox.createResource({
title: 'My new resource',
summary: 'This is my new resource',
}),
),
)
.subscribe(() => {
console.log('resource created');
});

Create a new link resource in the knowledge box in a simpler way than using createResource.

It requires account authentication or an API key with contributor access.

Parameters:

  • link:
    • added: optional, string
    • headers: optional, { [id: string]: string }
    • cookies: optional, { [id: string]: string }
    • uri: optional, string
    • localstorage: optional, { [id: string]: string }
  • metadata: optional, UserMetadata

Output: Observable<{ uuid: string }>

Example:

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');
});

saveWidget(id: string, widget: Partial<Widget>)

Add or modify the widget with the given id.

It requires account authentication or an API key with contributor access.

Parameters:

  • id: string
  • widget:
    • id: string
    • mode: 'button' | 'input' | 'form'`
    • description: optional, string`
    • features: { useFilters: boolean; suggestEntities: boolean; suggestSentences: boolean; suggestParagraphs: boolean; }
    • filters: optional, string[]
    • topEntities: optional, string[]
    • style: optional, { [key: string]: string }

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(
switchMap((knowledgeBox) =>
knowledgeBox.saveWidget('my-widget', {
mode: 'button',
features: {
useFilters: true,
suggestEntities: true,
suggestSentences: true,
suggestParagraphs: true,
},
}),
),
)
.subscribe(() => {
console.log('widget saved');
});

deleteWidget(widgetId: string)

Delete the widget with the given id.

It requires account authentication or an API key with contributor access.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(switchMap((knowledgeBox) => knowledgeBox.deleteWidget('my-widget')))
.subscribe(() => {
console.log('widget deleted');
});

upload(data: File | ArrayBuffer, TUS?: boolean, metadata?: FileMetadata)

Upload a file to the knowledge box. It 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).

It requires account authentication or an API key with contributor access.

Parameters:

  • data: the file to upload. It can be either a File object (as provided by an HTML input file element) or an ArrayBuffer object.
  • TUS: optional, boolean. If true, the file will be uploaded using the TUS protocol. Default is false.
  • metadata: optional, FileMetadata. It defines the file metadata. It can contain the following properties:
    • contentType: string
    • filename: string

Output: Observable<UploadResponse>

An UploadResponse object might contain the following properties:

  • resource: string
  • field: string
  • progress: number (percentage)
  • failed: boolean
  • completed: boolean

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(switchMap((knowledgeBox) => knowledgeBox.upload(fileInputElement.files[0])))
.subscribe(() => {
console.log('file uploaded');
});

batchUpload(files: FileList | File[], creationPayload?: ICreateResource)

Upload a list of files to the knowledge box. It automatically creates a new resource for each file. It uses the TUS protocol to upload the files.

It requires account authentication or an API key with contributor access.

Parameters:

  • files: a list of files to upload. It can be either a FileList object (as provided by an HTML input multiple file element), or a list of File.
  • creationPayload: optional, ICreateResource. It defines the default payload to create the resources that will contains the files.

Output: Observable<{ progress: number; completed: boolean; uploaded: number; failed: number }>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(switchMap((knowledgeBox) => knowledgeBox.upload(fileInputElement.files[0])))
.subscribe((res) => {
if (res.completed) {
console.log(`Uploaded completed, ${res.uploaded} files uploaded, ${res.failed} failed`);
} else {
console.log('upload progress', res.progress);
}
});

Resource

A resource allows to store content in the knowledge box. A single resource might contain several fields.

Fields have different types: files, links, texts, conversations, etc. (TO BE COMPLETED)

Properties

  • uuid: string
  • kb: parent knowledge box

Methods

Constructor

new Resource(nuclia: INuclia, kb: string, uuid: string, data: IResource)

Usually, you don't need to create a Resource object yourself. It is returned by the getResource method of the KnowledgeBox object.

addField(type: FIELD_TYPE, field: string, data: TextField | LinkField | FileField | KeywordSetField)

Adds a field to the resource.

It requires account authentication or an API key with contributor access.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(
switchMap((knowledgeBox) =>
knowledgeBox.getResource('my-resource').pipe(
switchMap((resource) =>
resource.addField(FIELD_TYPE.text, 'my-field', {
body: '*my text*',
format: 'MARKDOWN',
}),
),
),
),
)
.subscribe(() => {
console.log('field added');
});

delete()

Delete the resource.

It requires account authentication or an API key with contributor access.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(
switchMap((knowledgeBox) => knowledgeBox.getResource('my-resource')),
switchMap((resource) => resource.delete()),
)
.subscribe(() => {
console.log('resource deleted');
});

deleteField(type: FIELD_TYPE, field: string)

Deletes the field with the given type and name.

It requires account authentication or an API key with contributor access.

Output: Observable<void>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(
switchMap((knowledgeBox) => knowledgeBox.getResource('my-resource')),
switchMap((resource) => resource.deleteField(FIELD_TYPE.text, 'my-field')),
)
.subscribe(() => {
console.log('field deleted');
});

getField(type: FIELD_TYPE, field: string)

Gets a field of the resource.

Output: Observable<ResourceField>

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(map((resource) => resource.getField(FIELD_TYPE.text, 'my-field')))
.subscribe((field) => {
console.log('field', field);
});

getFields()

Return all the fields contained in the resource.

Output: Observable<IFieldData[]>

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(map((resource) => resource.getFields()))
.subscribe((fields) => {
console.log('fields', fields);
});

getExtractedSummaries()

Return the summaries generated by Nuclia for each resource field.

Output: string[]

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(map((resource) => resource.getExtractedSummaries()))
.subscribe((summaries) => {
console.log('summaries', summaries);
});

getExtractedTexts()

Return the texts generated by Nuclia for each resource field.

Output: ExtractedText[].

An ExtractedText object might contain the following properties:

  • text: string
  • split_text: { [id: string]: string }
  • deleted_splits: string[]

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(map((resource) => resource.getExtractedTexts()))
.subscribe((extractedTexts) => {
console.log('extractedTexts', extractedTexts);
});

getFiles()

Return the files contained in the resource.

Output: CloudLink[]

A CloudLink object might contain the following properties:

  • uri: string
  • size: number
  • content_type: string

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(map((resource) => resource.getFiles()))
.subscribe((files) => {
console.log('files', files);
});

getNamedEntities()

Return the entities extracted from the resource.

Output: { [key: string]: string[] }

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(map((resource) => resource.getNamedEntities()))
.subscribe((entities) => {
console.log('entities', entities);
});

getThumbnails()

Returns the thumbnails generated by Nuclia for each resource field.

Output: CloudLink[]

CloudLink {
uri?: string;
size?: number;
content_type?: string;
}

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(map((resource) => resource.getThumbnails()))
.subscribe((thumbnails) => {
console.log('thumbnails', thumbnails);
});

getThumbnailsUrl()

Returns the thumbnails generated by Nuclia for each resource field as blob: URLs.

Output: Observable<string[]>

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(switchMap((resource) => resource.getThumbnailsUrl()))
.subscribe((thumbnails) => {
container.innerHtml = thumbnails.map((thumbnail) => `<img src="${thumbnail}" />`).join('');
});

modify(data: Partial<IResource>)

Modifies the resource attributes.

It requires account authentication or an API key with contributor access.

Output: Observable<void>

Example:

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');
});

reprocess()

Reprocesses the resource.

Output: Observable<void>

search(query: string, features: Search.ResourceFeatures[] = [], highlight = false)

Searches in the resource.

Parameters:

  • query: the search query.
  • features: Search.ResourceFeatures[] (optional). It defines which features are returned in each result. Default is []. Possible values are:
    • PARAGRAPH
    • RELATIONS
    • VECTOR
    • highlight: boolean (optional). If true, the matching words are marked in paragraphs text. Default is false.

Output: Observable<SearchResult>

Example:

nuclia.knowledgeBox
.getResource('my-resource')
.pipe(switchMap((resource) => resource.search('my query', [Search.ResourceFeatures.PARAGRAPH])))
.subscribe((result) => {
console.log('result', result);
});

upload(field: string, data: File | ArrayBuffer, TUS?: boolean, metadata?: FileMetadata)

Uploads a file in the resource. The field will be stored in the indicated field.

It requires account authentication or an API key with contributor access.

Parameters:

  • field: string
  • data: the file to upload. It can be either a File object (as provided by an HTML input file element) or an ArrayBuffer object.
  • TUS: optional, boolean. If true, the file will be uploaded using the TUS protocol. Default is false.
  • metadata: optional, FileMetadata. It defines the file metadata. It can contain the following properties:
    • contentType: string
    • filename: string

Output: Observable<UploadResponse>

An UploadResponse object might contain the following properties:

  • resource: string
  • field: string
  • progress: number (percentage)
  • failed: boolean
  • completed: boolean

Example:

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');
});

batchUpload(files: FileList | File[])

Upload a list of files in teh resource. It automatically creates a new field for each file (named according the filename). It uses the TUS protocol to upload the files.

It requires account authentication or an API key with contributor access.

Parameters:

  • files: a list of files to upload. It can be either a FileList object (as provided by an HTML input multiple file element), or a list of File.

Output: Observable<{ progress: number; completed: boolean; uploaded: number; failed: number }>

Example:

nuclia.db
.getKnowledgeBox('my-account', 'my-kb')
.pipe(
switchMap((knowledgeBox) => knowledgeBox.getResource('my-resource')),
switchMap((resource) => resource.upload(fileInputElement.files[0])),
)
.subscribe((res) => {
if (res.completed) {
console.log(`Uploaded completed, ${res.uploaded} files uploaded, ${res.failed} failed`);
} else {
console.log('upload progress', res.progress);
}
});