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.
Here we'll document 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 this case you will need to provide the
backend
andaccount
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
andzone
options. You will also either 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
: (optional) String the Nuclia account slug. Example:my-account
knowledgeBox
: (optional) String the Nuclia Knowledge Box unique id. Example:17815eb2-06a5-40ee-a5aa-b2f9dbc5da70
kbSlug
: (optional) String the Knowledge Box slug. Example:my-kb
zone
: (optional) String the geographical zone for the regional API calls. Example:europe-1
apiKey
: (optional) 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.
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 does not work with account authentication).asyncKnowledgeBox
: Similar to the previous property, but the returned object exposesPromises
instead of RxJSObservables
.auth
: Allows you to authenticate using username/password or using an API key.db
: Allows you to access and query the Nuclia database.rest
: Allows you 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 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.
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
and can be useful when using a custom authentication flow.
Example:
nuclia.auth.authenticate(tokens);
deleteAuthenticatedUser()
Deletes current user account and removes 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
emission 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 removes the token stored in localStorage.
Example:
nuclia.auth.logout();
setPassword(password: string)
Sets the 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 you to access Nuclia accounts and/or Nuclia Knowledge Boxes.
Methods
createKnowledgeBox(account: string, knowledgeBox: KnowledgeBoxCreation)
Creates a new Knowledge Box.
Output: Observable<WritableKnowledgeBox>
Requires account authentication.
Parameters:
account
: Account slug.knowledgeBox
: Knowledge Box creation object.slug
: Knowledge Box slug: only lowercase letters, numbers,-
and_
are allowed.title
: Knowledge Box title.description
: (optional) Knowledge Box description.zone
: (optional) Geographical zone for the regional API calls. Defaults toeurope-1
.
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>
Requires account authentication.
Parameters:
slug
: Account slug. A slug can contain only lowercase letters, numbers,-
and_
.title
: Account title.description
: Account description (optional).email
: (optional) Owner's email.zone
: (optional) Geographical zone.
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>
Requires account authentication.
Example:
nuclia.db.deleteAccount('my-account').subscribe(() => {
console.log('account deleted');
});
deleteNUAClient(account: string, client_id: string)
Deletes a NUA client.
Requires account authentication.
Output: Observable<void>
getAccount()
Returns the account defined in the Nuclia options.
Output: Observable<Account>
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>
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[]>
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>
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[]>
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>
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 pushes a file to Nuclia Understanding API.
Requires a NUA token.
Parameters:
FileWithMetadata
: the file to upload.FileWithMetadata
is an extension ofFile
with the following properties:md5
: (optional) the file md5.payload
: (optional) not applicable with Nuclia Understanding API.
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.
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.
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.
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, 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.
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
orX-STF-Serviceaccount
depending on the type of authentication. The default headers will be overridden byextraHeaders
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 APIExample:
/v1/kb/3cce4a71-9cb9-4fda-beee-8a1512616bf0
fullpath
: the Knowledge Box fullpath on the regional APIExample:
https://europe-1.nuclia.cloud/api/v1/kb/3cce4a71-9cb9-4fda-beee-8a1512616bf0
Methods
counters()
Returns all the 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
: stringmerged
: (optional) booleanrepresents
: (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[])
Retrieves a resource from the Knowledge Box.
Parameters:
uuid
: the resource uuidshow
: (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 ifResourceProperties.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
andExtractedDataTypes.VECTOR
(Note: they may 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. This 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)
Lists 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[]
and possible values are:PARAGRAPH
DOCUMENT
RELATIONS
VECTOR
options
: (optional)highlight
: (optional) Boolean. If true, the matching words are marked in the paragraph text. Default isfalse
.inTitleOnly
: (optional) Boolean. If true, the search is performed only in the title. Default isfalse
.
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
: stringmode
: '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 to the Knowledge Box.
Methods
modify(data: Partial<IKnowledgeBox>)
Modifies the Knowledge Box properties.
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)
Publishes or unpublishes the Knowledge Box.
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()
Deletes the Knowledge Box.
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)
Adds or modifies the entities group with the given id.
Requires account authentication or an API key with contributor access.
Parameters:
groupId
: entities group idgroup
:title
: stringcolor
: (optional) stringentities
:{ [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)
Deletes an entities group.
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)
Adds or modifies the label set with the given id.
Requires account authentication or an API key with contributor access.
Parameters:
setId
: label set idlabelSet
:title
: stringcolor
: (optional) stringlabels
:{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)
Deletes a label set.
Requires account authentication or an API key with contributor access.
Parameters:
setId
: 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)
Creates and indexes a new resource in the Knowledge Box.
Requires account authentication or an API key with contributor access.
Parameters:
title
: (optional) stringsummary
: (optional) stringicon
: (optional) stringmetadata
: (optional) metadatausermetadata
: (optional) user metadataorigin
: (optional) originfiles
: (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');
});
createLinkResource(link: LinkField, metadata?: UserMetadata)
Creates a new link resource in the Knowledge Box more easily than using createResource
.
Requires account authentication or an API key with contributor access.
Parameters:
link
:added
: (optional) stringheaders
: (optional) { [id: string]: string }cookies
: (optional) { [id: string]: string }uri
: (optional) stringlocalstorage
: (optional) { [id: string]: string }
metadata
: (optional) user metadata
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>)
Adds or modifies the widget with the given id.
Requires account authentication or an API key with contributor access.
Parameters:
id
: stringwidget
:id
: stringmode
: '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)
Deletes the widget with the given id.
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)
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
).
Requires account authentication or an API key with contributor access.
Parameters:
data
: The file to upload. It can be either aFile
object (as provided by an HTML input file element) or anArrayBuffer
object.TUS
: (optional)boolean
. Iftrue
, the file will be uploaded using the TUS protocol. Default isfalse
.metadata
: (optional)FileMetadata
. It defines the file metadata. It can contain the following properties:contentType
: stringfilename
: string
Output: Observable<UploadResponse>
An UploadResponse
object might contain the following properties:
resource
: stringfield
: stringprogress
: number (percentage)failed
: booleancompleted
: 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)
Uploads a list of files to the Knowledge Box. It automatically creates a new resource for each file and uses the TUS protocol to upload the files.
Requires account authentication or an API key with contributor access.
Parameters:
files
: a list of files to upload. It can be either aFileList
object (as provided by an HTML input multiple file element), or a list ofFile
.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 you to store content in the Knowledge Box. A single resource might contain several fields.
Fields have different types: files, links, texts, conversations, etc.
Properties
uuid
: stringkb
: parent Knowledge Box
Methods
Constructor
new Resource(nuclia: INuclia, kb: string, uuid: string, data: IResource)
Usually you will not 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.
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()
Deletes the resource.
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.
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()
Returns 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()
Returns 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()
Returns the texts generated by Nuclia for each resource field.
Output: ExtractedText[]
.
An ExtractedText
object might contain the following properties:
text
: stringsplit_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()
Returns the files contained in the resource.
Output: CloudLink[]
A CloudLink
object might contain the following properties:
uri
: stringsize
: numbercontent_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.
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
: (optional)Search.ResourceFeatures[]
. It defines which features are returned in each result. Default is[]
and possible values are:PARAGRAPH
RELATIONS
VECTOR
highlight
: (optional) boolean. If true, the matching words are marked in paragraphs text. Default isfalse
.
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.
Requires account authentication or an API key with contributor access.
Parameters:
field
: stringdata
: The file to upload. It can be either aFile
object (as provided by an HTML input file element) or anArrayBuffer
object.TUS
: (optional)boolean
. Iftrue
, the file will be uploaded using the TUS protocol. Default isfalse
.metadata
: (optional)FileMetadata
. It defines the file metadata and can contain the following properties:contentType
: stringfilename
: string
Output: Observable<UploadResponse>
An UploadResponse
object might contain the following properties:
resource
: stringfield
: stringprogress
: number (percentage)failed
: booleancompleted
: 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[])
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 protocol to upload the files.
Requires account authentication or an API key with contributor access.
Parameters:
files
: a list of files to upload. It can be either aFileList
object (as provided by an HTML input multiple file element), or a list ofFile
.
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);
}
});