Repository: neuml/txtai.js
Branch: master
Commit: 85ea6616ac2a
Files: 23
Total size: 40.1 KB
Directory structure:
gitextract_kxx1s_px/
├── .babelrc
├── .gitignore
├── LICENSE
├── README.md
├── examples/
│ └── node/
│ ├── .babelrc
│ ├── package.json
│ └── src/
│ ├── embeddings.js
│ ├── extractor.js
│ ├── labels.js
│ └── pipelines.js
├── package.json
└── src/
├── api.js
├── embeddings.js
├── extractor.js
├── index.js
├── labels.js
├── segmentation.js
├── similarity.js
├── summary.js
├── textractor.js
├── transcription.js
├── translation.js
└── workflow.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc
================================================
{
"presets": ["@babel/preset-env"],
"plugins": [["@babel/transform-runtime"]]
}
================================================
FILE: .gitignore
================================================
dist
node_modules
package-lock.json
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2020- NeuML LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
<p align="center">
<img src="https://raw.githubusercontent.com/neuml/txtai/master/logo.png"/>
</p>
<p align="center">
<b>JavaScript client for txtai</b>
</p>
<p align="center">
<a href="https://github.com/neuml/txtai.js/releases">
<img src="https://img.shields.io/github/release/neuml/txtai.js.svg?style=flat&color=success" alt="Version"/>
</a>
<a href="https://github.com/neuml/txtai.js/releases">
<img src="https://img.shields.io/github/release-date/neuml/txtai.js.svg?style=flat&color=blue" alt="GitHub Release Date"/>
</a>
<a href="https://github.com/neuml/txtai.js/issues">
<img src="https://img.shields.io/github/issues/neuml/txtai.js.svg?style=flat&color=success" alt="GitHub Issues"/>
</a>
<a href="https://github.com/neuml/txtai.js">
<img src="https://img.shields.io/github/last-commit/neuml/txtai.js.svg?style=flat&color=blue" alt="GitHub Last Commit"/>
</a>
</p>
[txtai](https://github.com/neuml/txtai) is an all-in-one AI framework for semantic search, LLM orchestration and language model workflows.
This repository contains JavaScript bindings for the txtai API.
## Installation
txtai.js can be installed via npm
npm install txtai
## Examples
The examples directory has a series of examples that give an overview of txtai. See the list of examples below.
| Example | Description |
|:----------|:-------------|
| [Introducing txtai](https://github.com/neuml/txtai.js/blob/master/examples/node/src/embeddings.js) | Overview of the functionality provided by txtai |
| [Extractive QA with txtai](https://github.com/neuml/txtai.js/blob/master/examples/node/src/extractor.js) | Extractive question-answering with txtai |
| [Labeling with zero-shot classification](https://github.com/neuml/txtai.js/blob/master/examples/node/src/labels.js) | Labeling with zero-shot classification |
| [Pipelines and workflows](https://github.com/neuml/txtai.js/blob/master/examples/node/src/pipelines.js) | Pipelines and workflows |
txtai.js connects to a txtai api instance. See [this link](https://neuml.github.io/txtai/api/) for details on how to start a new api instance.
Once an api instance is running, do the following to run the examples.
```
git clone https://github.com/neuml/txtai.js
cd txtai.js/examples/node
npm install
npm run build
node dist/embeddings.js
node dist/extractor.js
node dist/labels.js
node dist/pipelines.js
```
================================================
FILE: examples/node/.babelrc
================================================
{
"presets": ["@babel/preset-env"],
"plugins": [["@babel/transform-runtime"]]
}
================================================
FILE: examples/node/package.json
================================================
{
"name": "txtai-node",
"dependencies": {
"sprintf-js": ">=1.1.2",
"txtai": ">=9.9.0"
},
"devDependencies": {
"@babel/cli": ">=7.10.5",
"@babel/core": ">=7.10.5",
"@babel/node": ">=7.10.5",
"@babel/plugin-transform-runtime": ">=7.10.5",
"@babel/preset-env": ">=7.10.5"
},
"scripts": {
"build": "node_modules/@babel/cli/bin/babel.js src -d dist -s --verbose"
}
}
================================================
FILE: examples/node/src/embeddings.js
================================================
import {Embeddings} from "txtai";
import {sprintf} from "sprintf-js";
/**
* Example embeddings functionality.
*
* Implements functionality found in this notebook: https://github.com/neuml/txtai/blob/master/examples/01_Introducing_txtai.ipynb
*/
const run = async () => {
try {
let embeddings = new Embeddings("http://localhost:8000");
let data = ["US tops 5 million confirmed virus cases",
"Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
"Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
"The National Park Service warns against sacrificing slower friends in a bear attack",
"Maine man wins $1M from $25 lottery ticket",
"Make huge profits without work, earn up to $100,000 a day"];
console.log("Running similarity queries");
console.log(sprintf("%-20s %s", "Query", "Best Match"));
console.log("-".repeat(50));
for (let query of ["feel good story", "climate change", "public health story", "war", "wildlife", "asia", "lucky", "dishonest junk"]) {
let results = await embeddings.similarity(query, data);
let uid = results[0].id;
console.log(sprintf("%-20s %s", query, data[uid]))
}
let documents = data.map((text, index) => ({id: index, text: text}));
await embeddings.add(documents);
await embeddings.index();
console.log();
console.log("Building an Embeddings index");
console.log(sprintf("%-20s %s", "Query", "Best Match"));
console.log("-".repeat(50));
for (let query of ["feel good story", "climate change", "public health story", "war", "wildlife", "asia", "lucky", "dishonest junk"]) {
let results = await embeddings.search(query, 1);
let uid = results[0].id;
console.log(sprintf("%-20s %s", query, data[uid]));
}
data[0] = "See it: baby panda born"
await embeddings.delete([5]);
await embeddings.add([{id: 0, text: data[0]}])
await embeddings.upsert();
console.log();
console.log("Test delete/upsert/count");
console.log(sprintf("%-20s %s", "Query", "Best Match"));
console.log("-".repeat(50));
let query = "feel good story";
let results = await embeddings.search(query, 1);
let uid = results[0].id;
console.log(sprintf("%-20s %s", query, data[uid]));
let count = await embeddings.count();
console.log();
console.log(sprintf("Total Count: %d", count));
}
catch (e) {
console.trace(e);
}
};
run();
================================================
FILE: examples/node/src/extractor.js
================================================
import {Extractor} from "txtai";
/**
* Example extractor functionality.
*
* Implements logic found in this notebook: https://github.com/neuml/txtai/blob/master/examples/05_Extractive_QA_with_txtai.ipynb
*/
const run = async () => {
try {
let extractor = new Extractor("http://localhost:8000");
let data = ["Giants hit 3 HRs to down Dodgers",
"Giants 5 Dodgers 4 final",
"Dodgers drop Game 2 against the Giants, 5-4",
"Blue Jays beat Red Sox final score 2-1",
"Red Sox lost to the Blue Jays, 2-1",
"Blue Jays at Red Sox is over. Score: 2-1",
"Phillies win over the Braves, 5-0",
"Phillies 5 Braves 0 final",
"Final: Braves lose to the Phillies in the series opener, 5-0",
"Lightning goaltender pulled, lose to Flyers 4-1",
"Flyers 4 Lightning 1 final",
"Flyers win 4-1"]
// Run series of questions
let questions = ["What team won the game?", "What was score?"];
for (let query of ["Red Sox - Blue Jays", "Phillies - Braves", "Dodgers - Giants", "Flyers - Lightning"]) {
console.log("----" + query + "----");
let queue = questions.map(question => ({name: question, query: query, question: question, snippet: false}));
console.log(await extractor.extract(queue, data));
}
// Ad-hoc questions
let question = "What hockey team won?";
console.log("----" + question + "----");
console.log(await extractor.extract([{name: question, query: question, question: question, snippet: false}], data));
}
catch (e) {
console.trace(e);
}
};
run();
================================================
FILE: examples/node/src/labels.js
================================================
import {Labels} from "txtai";
import {sprintf} from "sprintf-js";
/**
* Example labels functionality.
*
* Implements logic found in this notebook: https://github.com/neuml/txtai/blob/master/examples/07_Apply_labels_with_zero_shot_classification.ipynb
*/
const run = async () => {
try {
let labels = new Labels("http://localhost:8000");
let data = ["Dodgers lose again, give up 3 HRs in a loss to the Giants",
"Giants 5 Cardinals 4 final in extra innings",
"Dodgers drop Game 2 against the Giants, 5-4",
"Flyers 4 Lightning 1 final. 45 saves for the Lightning.",
"Slashing, penalty, 2 minute power play coming up",
"What a stick save!",
"Leads the NFL in sacks with 9.5",
"UCF 38 Temple 13",
"With the 30 yard completion, down to the 10 yard line",
"Drains the 3pt shot!!, 0:15 remaining in the game",
"Intercepted! Drives down the court and shoots for the win",
"Massive dunk!!! they are now up by 15 with 2 minutes to go"];
// List of labels
let tags = ["Baseball", "Football", "Hockey", "Basketball"];
console.log(sprintf("%-75s %s", "Text", "Label"));
console.log("-".repeat(100));
for (let text of data) {
let label = await labels.label(text, tags);
label = tags[label[0].id];
console.log(sprintf("%-75s %s", text, label));
}
tags = ["😀", "😡"];
console.log();
console.log(sprintf("%-75s %s", "Text", "Label"));
console.log("-".repeat(100));
for (let text of data) {
let label = await labels.label(text, tags);
label = tags[label[0].id];
console.log(sprintf("%-75s %s", text, label));
}
}
catch (e) {
console.trace(e);
}
};
run();
================================================
FILE: examples/node/src/pipelines.js
================================================
import {Segmentation, Textractor, Summary, Transcription, Translation, Workflow} from "txtai";
/**
* Example pipeline and workflow functionality.
*
* Uses files from txtai unit tests: https://github.com/neuml/txtai/releases/download/v2.0.0/tests.tar.gz
*/
const run = async () => {
try {
let service = "http://localhost:8000"
let segment = new Segmentation(service);
let sentences = "This is a test. And another test.";
console.log("---- Segmented Text ----");
console.log(await segment.segment(sentences));
let textractor = new Textractor(service);
let text = await textractor.textract("/tmp/txtai/article.pdf")
console.log("\n---- Extracted Text ----");
console.log(text);
let summary = new Summary(service);
let summarytext = await summary.summary(text);
console.log("\n---- Summary Text ----");
console.log(summarytext);
let translate = new Translation(service);
let translation = await translate.translate(summarytext, "es");
console.log("\n---- Summary Text in Spanish ----");
console.log(translation);
let workflow = new Workflow(service);
let output = await workflow.workflow("sumspanish", ["file:///tmp/txtai/article.pdf"]);
console.log("\n---- Workflow [Extract Text->Summarize->Translate] ----");
console.log(output);
let transcribe = new Transcription(service);
let transcription = await transcribe.transcribe("/tmp/txtai/Make_huge_profits.wav")
console.log("\n---- Transcribed Text ----");
console.log(transcription);
}
catch (e) {
console.trace(e);
}
};
run();
================================================
FILE: package.json
================================================
{
"name": "txtai",
"version": "9.9.0",
"author": "NeuML",
"description": "JavaScript client for txtai",
"license": "Apache-2.0",
"keywords": ["search", "nlp", "machine-learning", "similarity"],
"repository": "neuml/txtai.js",
"main": "dist/index.js",
"files": ["dist"],
"dependencies": {
"core-js": ">=3.6.5",
"isomorphic-fetch": ">=2.2.1"
},
"devDependencies": {
"@babel/cli": ">=7.10.5",
"@babel/core": ">=7.10.5",
"@babel/node": ">=7.10.5",
"@babel/plugin-transform-runtime": ">=7.10.5",
"@babel/preset-env": ">=7.10.5"
},
"scripts": {
"build": "node_modules/@babel/cli/bin/babel.js src -d dist -s --verbose"
}
}
================================================
FILE: src/api.js
================================================
// Backwards compatibility
import "core-js/features/promise";
import "isomorphic-fetch";
/**
* Base class for interfacing with a remote txtai service via REST API calls.
*/
class API {
/**
* Creates an API instance.
*
* @param url api url
* @param token api token
*/
constructor(url, token) {
// API url
this.url = url ? url : process.env.TXTAI_API_URL
// API token
this.token = token ? token : process.env.TXTAI_API_TOKEN
}
/**
* Executes a get request.
*
* @param method api method
* @param params query parameters
* @return response
*/
async get(method, params) {
// Build URL
let url = `${this.url}/${method}`;
if (params) {
url += `?${new URLSearchParams(params)}`;
}
// Execute remote call
let res = await fetch(url, {headers: this.headers()});
// Validate response and return JSON
return res.ok ? await res.json() : Promise.reject(`${res.status} ${res.statusText}`);
}
/**
* Executes a post request.
*
* @param method api method
* @param params post parameters
* @return response
*/
async post(method, params) {
// Build URL
let url = `${this.url}/${method}`;
// Default headers
let defaults = {"Content-Type": "application/json"};
// Execute remote call
let res = await fetch(url, {method: "post",
body: JSON.stringify(params),
headers: this.headers(defaults)});
// Validate response and return JSON
return res.ok ? await res.json() : Promise.reject(`${res.status} ${res.statusText}`);
}
/**
* Executes a multipart form post request.
*
* @param method api method
* @param formData FormData object
* @return response
*/
async postForm(method, formData) {
// Build URL
let url = `${this.url}/${method}`;
// Execute remote call (no Content-Type header - browser sets it with boundary)
let res = await fetch(url, {method: "post",
body: formData,
headers: this.headers()});
// Validate response
return res.ok ? Promise.resolve() : Promise.reject(`${res.status} ${res.statusText}`);
}
/**
* Creates default HTTP headers.
*
* @param base base headers
* @return headers
*/
headers(base) {
let headers = base ? base : {};
if (this.token) {
headers["Authorization"] = "Bearer " + this.token;
}
return headers
}
}
export default API;
================================================
FILE: src/embeddings.js
================================================
import API from "./api";
/**
* txtai embeddings instance.
*/
class Embeddings extends API {
/**
* Finds documents in the embeddings model most similar to the input query. Returns
* a list of {id: value, score: value} sorted by highest score, where id is the
* document id in the embeddings model.
*
* @param query query text
* @param limit maximum results (defaults to 10)
* @param weights hybrid score weights, if applicable
* @param index index name, if applicable
* @return list of {id: value, score: value}
*/
async search(query, limit = 10, weights = null, index = null) {
let params = {
query: query,
limit: limit
}
if (weights != null) {
params["weights"] = weights
}
if (index != null) {
params["index"] = index
}
return await this.get("search", params).catch(e => {
throw(e);
});
}
/**
* Finds documents in the embeddings model most similar to the input queries. Returns
* a list of {id: value, score: value} sorted by highest score per query, where id is
* the document id in the embeddings model.
*
* @param queries queries text
* @param limit maximum results (defaults to 10)
* @param weights hybrid score weights, if applicable
* @param index index name, if applicable
* @return list of {id: value, score: value} per query
*/
async batchsearch(queries, limit = 10, weights = null, index = null) {
let params = {
queries: queries,
limit: limit
}
if (weights != null) {
params["weights"] = weights
}
if (index != null) {
params["index"] = index
}
return await this.post("batchsearch", params).catch (e => {
throw(e);
});
}
/**
* Adds a batch of documents for indexing.
*
* @param documents list of {id: value, text: value}
*/
async add(documents) {
await this.post("add", documents).catch(e => {
throw(e);
});
}
/**
* Builds an embeddings index for previously batched documents.
*/
async index() {
await this.get("index", null).catch(e => {
throw(e);
});
}
/**
* Runs an embeddings upsert operation for previously batched documents.
*/
async upsert() {
await this.get("upsert", null).catch(e => {
throw(e);
});
}
/**
* Deletes from an embeddings index. Returns list of ids deleted.
*
* @param ids list of ids to delete
* @return ids deleted
*/
async delete(ids) {
return await this.post("delete", ids).catch(e => {
throw(e);
});
}
/**
* Recreates this embeddings index using config. This method only works if document content storage is enabled.
*
* @param config new config
* @param func optional function to prepare content for indexing
*/
async reindex(config, func = null) {
let params = {
config: config,
}
if (func != null) {
params["function"] = func
}
await this.post("reindex", params).catch(e => {
throw(e);
});
}
/**
* Total number of elements in this embeddings index.
*
* @return number of elements in embeddings index
*/
async count() {
return await this.get("count", null).catch(e => {
throw(e);
});
}
/**
* Computes the similarity between query and list of text. Returns a list of
* {id: value, score: value} sorted by highest score, where id is the index
* in texts.
*
* @param query query text
* @param texts list of text
* @return list of {id: value, score: value}
*/
async similarity(query, texts) {
return await this.post("similarity", {query: query, texts: texts}).catch (e => {
throw(e);
});
}
/**
* Computes the similarity between list of queries and list of text. Returns a list
* of {id: value, score: value} sorted by highest score per query, where id is the
* index in texts.
*
* @param queries queries text
* @param texts list of text
* @return list of {id: value, score: value} per query
*/
async batchsimilarity(queries, texts) {
return await this.post("batchsimilarity", {queries: queries, texts: texts}).catch (e => {
throw(e);
});
}
/**
* Transforms text into an embeddings array.
*
* @param text input text
* @return embeddings array
*/
async transform(text) {
return await this.get("transform", {text: text}).catch(e => {
throw(e);
});
}
/**
* Transforms list of text into embeddings arrays.
*
* @param texts list of text
* @return embeddings array
*/
async batchtransform(texts) {
return await this.post("batchtransform", texts).catch(e => {
throw(e);
});
}
/**
* Adds a batch of binary objects for indexing.
*
* @param data list of binary data (Blob, File, or Buffer objects)
* @param uid list of corresponding ids (optional)
* @param field optional object field name
*/
async addobject(data, uid = null, field = null) {
let formData = new FormData();
for (let i = 0; i < data.length; i++) {
formData.append("data", data[i], `file${i}`);
}
if (uid != null) {
for (let id of uid) {
formData.append("uid", id);
}
}
if (field != null) {
formData.append("field", field);
}
await this.postForm("addobject", formData).catch(e => {
throw(e);
});
}
/**
* Adds a batch of images for indexing.
*
* @param data list of image data (Blob, File, or Buffer objects)
* @param uid list of corresponding ids
* @param field optional object field name
*/
async addimage(data, uid, field = null) {
let formData = new FormData();
for (let i = 0; i < data.length; i++) {
formData.append("data", data[i], data[i].name || `image${i}`);
}
if (uid != null) {
for (let id of uid) {
formData.append("uid", id);
}
}
if (field != null) {
formData.append("field", field);
}
await this.postForm("addimage", formData).catch(e => {
throw(e);
});
}
}
export default Embeddings;
================================================
FILE: src/extractor.js
================================================
import API from "./api";
/**
* txtai extractor instance.
*/
class Extractor extends API {
/**
* Extracts answers to input questions.
*
* @param queue list of {name: value, query: value, question: value, snippet: value}
* @param texts list of text
* @return list of {name: value, answer: value}
*/
async extract(queue, texts) {
return await this.post("extract", {queue: queue, texts: texts}).catch (e => {
throw(e);
});
}
}
export default Extractor;
================================================
FILE: src/index.js
================================================
import Embeddings from "./embeddings";
import Extractor from "./extractor";
import Labels from "./labels";
import Segmentation from "./segmentation";
import Similarity from "./similarity";
import Summary from "./summary";
import Textractor from "./textractor";
import Transcription from "./transcription";
import Translation from "./translation";
import Workflow from "./workflow";
export {
Embeddings,
Extractor,
Labels,
Segmentation,
Similarity,
Summary,
Textractor,
Transcription,
Translation,
Workflow
};
================================================
FILE: src/labels.js
================================================
import API from "./api";
/**
* txtai labels instance.
*/
class Labels extends API {
/**
* Applies a zero shot classifier to text using a list of labels. Returns a list of
* {id: value, score: value} sorted by highest score, where id is the index in labels.
*
* @param text input text
* @param labels list of labels
* @return list of {id: value, score: value} per text element
*/
async label(text, labels) {
return await this.post("label", {text: text, labels: labels}).catch (e => {
throw(e);
});
}
/**
* Applies a zero shot classifier to list of text using a list of labels. Returns a list of
* {id: value, score: value} sorted by highest score, where id is the index in labels per
* text element.
*
* @param texts list of texts
* @param labels list of labels
* @return list of {id: value score: value} per text element
*/
async batchlabel(texts, labels) {
return await this.post("batchlabel", {texts: texts, labels: labels}).catch (e => {
throw(e);
});
}
}
export default Labels;
================================================
FILE: src/segmentation.js
================================================
import API from "./api";
/**
* txtai segmentation instance.
*/
class Segmentation extends API {
/**
* Segments text into semantic units.
*
* @param text input text
* @return segmented text
*/
async segment(text) {
return await this.get("segment", {text: text}).catch (e => {
throw(e);
});
}
/**
* Segments text into semantic units.
*
* @param texts list of texts to segment
* @return list of segmented text
*/
async batchsegment(texts) {
return await this.post("batchsegment", texts).catch (e => {
throw(e);
});
}
}
export default Segmentation;
================================================
FILE: src/similarity.js
================================================
import API from "./api";
/**
* txtai similarity instance.
*/
class Similarity extends API {
/**
* Computes the similarity between query and list of text. Returns a list of
* {id: value, score: value} sorted by highest score, where id is the index
* in texts.
*
* @param query query text
* @param texts list of text
* @return list of {id: value, score: value}
*/
async similarity(query, texts) {
return await this.post("similarity", {query: query, texts: texts}).catch (e => {
throw(e);
});
}
/**
* Computes the similarity between list of queries and list of text. Returns a list
* of {id: value, score: value} sorted by highest score per query, where id is the
* index in texts.
*
* @param queries queries text
* @param texts list of text
* @return list of {id: value, score: value} per query
*/
async batchsimilarity(queries, texts) {
return await this.post("batchsimilarity", {queries: queries, texts: texts}).catch (e => {
throw(e);
});
}
}
export default Similarity;
================================================
FILE: src/summary.js
================================================
import API from "./api";
/**
* txtai summary instance.
*/
class Summary extends API {
/**
* Runs a summarization model against a block of text.
*
* @param text text to summarize
* @param minlength minimum length for summary
* @param maxlength maximum length for summary
* @return summary text
*/
async summary(text, minlength, maxlength) {
let params = {text: text}
if (minlength) {
params.minlength = minlength;
}
if (maxlength) {
params.maxlength = maxlength;
}
return await this.get("summary", params).catch (e => {
throw(e);
});
}
/**
* Runs a summarization model against a block of text.
*
* @param texts list of text to summarize
* @param minlength minimum length for summary
* @param maxlength maximum length for summary
* @return list of summary text
*/
async batchsummary(texts, minlength, maxlength) {
let params = {texts: texts}
if (minlength) {
params.minlength = minlength;
}
if (maxlength) {
params.maxlength = maxlength;
}
return await this.post("batchsummary", params).catch (e => {
throw(e);
});
}
}
export default Summary;
================================================
FILE: src/textractor.js
================================================
import API from "./api";
/**
* txtai textractor instance.
*/
class Textractor extends API {
/**
* Extracts text from a file at path.
*
* @param file file to extract text
* @return extracted text
*/
async textract(file) {
return await this.get("textract", {file: file}).catch (e => {
throw(e);
});
}
/**
* Extracts text from a file at path.
*
* @param files list of files to extract text
* @return list of extracted text
*/
async batchtextract(files) {
return await this.post("batchtextract", files).catch (e => {
throw(e);
});
}
}
export default Textractor;
================================================
FILE: src/transcription.js
================================================
import API from "./api";
/**
* txtai transcription instance.
*/
class Transcription extends API {
/**
* Transcribes audio files to text.
*
* @param file file to transcribe
* @return transcribed text
*/
async transcribe(file) {
return await this.get("transcribe", {file: file}).catch (e => {
throw(e);
});
}
/**
* Transcribes audio files to text.
*
* @param files list of files to transcribe
* @return list of transcribed text
*/
async batchtranscribe(files) {
return await this.post("batchtranscribe", files).catch (e => {
throw(e);
});
}
}
export default Transcription;
================================================
FILE: src/translation.js
================================================
import API from "./api";
/**
* txtai translation instance.
*/
class Translation extends API {
/**
* Translates text from source language into target language.
*
* @param text text to translate
* @param target target language code, defaults to "en"
* @param source source language code, detects language if not provided
* @return translated text
*/
async translate(text, target, source) {
let params = {text: text};
if (target) {
params.target = target;
}
if (source) {
params.source = source;
}
return await this.get("translate", params).catch (e => {
throw(e);
});
}
/**
* Translates text from source language into target language.
*
* @param texts list of text to translate
* @param target target language code, defaults to "en"
* @param source source language code, detects language if not provided
* @return list of translated text
*/
async batchtranslate(texts, target, source) {
let params = {texts: texts};
if (target) {
params.target = target;
}
if (source) {
params.source = source;
}
return await this.post("batchtranslate", files).catch (e => {
throw(e);
});
}
}
export default Translation;
================================================
FILE: src/workflow.js
================================================
import API from "./api";
/**
* txtai workflow instance.
*/
class Workflow extends API {
/**
* Executes a named workflow using elements as input.
*
* @param name workflow name
* @param elements list of elements to run through workflow
* @return list of processed elements
*/
async workflow(name, elements) {
return await this.post("workflow", {name: name, elements: elements}).catch (e => {
throw(e);
});
}
}
export default Workflow;
gitextract_kxx1s_px/
├── .babelrc
├── .gitignore
├── LICENSE
├── README.md
├── examples/
│ └── node/
│ ├── .babelrc
│ ├── package.json
│ └── src/
│ ├── embeddings.js
│ ├── extractor.js
│ ├── labels.js
│ └── pipelines.js
├── package.json
└── src/
├── api.js
├── embeddings.js
├── extractor.js
├── index.js
├── labels.js
├── segmentation.js
├── similarity.js
├── summary.js
├── textractor.js
├── transcription.js
├── translation.js
└── workflow.js
SYMBOL INDEX (46 symbols across 11 files)
FILE: src/api.js
class API (line 8) | class API {
method constructor (line 15) | constructor(url, token) {
method get (line 30) | async get(method, params) {
method post (line 51) | async post(method, params) {
method postForm (line 74) | async postForm(method, formData) {
method headers (line 93) | headers(base) {
FILE: src/embeddings.js
class Embeddings (line 6) | class Embeddings extends API {
method search (line 18) | async search(query, limit = 10, weights = null, index = null) {
method batchsearch (line 47) | async batchsearch(queries, limit = 10, weights = null, index = null) {
method add (line 70) | async add(documents) {
method index (line 79) | async index() {
method upsert (line 88) | async upsert() {
method delete (line 100) | async delete(ids) {
method reindex (line 112) | async reindex(config, func = null) {
method count (line 131) | async count() {
method similarity (line 146) | async similarity(query, texts) {
method batchsimilarity (line 161) | async batchsimilarity(queries, texts) {
method transform (line 173) | async transform(text) {
method batchtransform (line 185) | async batchtransform(texts) {
method addobject (line 198) | async addobject(data, uid = null, field = null) {
method addimage (line 227) | async addimage(data, uid, field = null) {
FILE: src/extractor.js
class Extractor (line 6) | class Extractor extends API {
method extract (line 14) | async extract(queue, texts) {
FILE: src/labels.js
class Labels (line 6) | class Labels extends API {
method label (line 15) | async label(text, labels) {
method batchlabel (line 30) | async batchlabel(texts, labels) {
FILE: src/segmentation.js
class Segmentation (line 6) | class Segmentation extends API {
method segment (line 13) | async segment(text) {
method batchsegment (line 25) | async batchsegment(texts) {
FILE: src/similarity.js
class Similarity (line 6) | class Similarity extends API {
method similarity (line 16) | async similarity(query, texts) {
method batchsimilarity (line 31) | async batchsimilarity(queries, texts) {
FILE: src/summary.js
class Summary (line 6) | class Summary extends API {
method summary (line 15) | async summary(text, minlength, maxlength) {
method batchsummary (line 37) | async batchsummary(texts, minlength, maxlength) {
FILE: src/textractor.js
class Textractor (line 6) | class Textractor extends API {
method textract (line 13) | async textract(file) {
method batchtextract (line 25) | async batchtextract(files) {
FILE: src/transcription.js
class Transcription (line 6) | class Transcription extends API {
method transcribe (line 13) | async transcribe(file) {
method batchtranscribe (line 25) | async batchtranscribe(files) {
FILE: src/translation.js
class Translation (line 6) | class Translation extends API {
method translate (line 15) | async translate(text, target, source) {
method batchtranslate (line 37) | async batchtranslate(texts, target, source) {
FILE: src/workflow.js
class Workflow (line 6) | class Workflow extends API {
method workflow (line 14) | async workflow(name, elements) {
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (44K chars).
[
{
"path": ".babelrc",
"chars": 88,
"preview": "{\n \"presets\": [\"@babel/preset-env\"],\n \"plugins\": [[\"@babel/transform-runtime\"]]\n}\n"
},
{
"path": ".gitignore",
"chars": 36,
"preview": "dist\nnode_modules\npackage-lock.json\n"
},
{
"path": "LICENSE",
"chars": 10754,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 2433,
"preview": "<p align=\"center\">\n <img src=\"https://raw.githubusercontent.com/neuml/txtai/master/logo.png\"/>\n</p>\n\n<p align=\"center"
},
{
"path": "examples/node/.babelrc",
"chars": 88,
"preview": "{\n \"presets\": [\"@babel/preset-env\"],\n \"plugins\": [[\"@babel/transform-runtime\"]]\n}\n"
},
{
"path": "examples/node/package.json",
"chars": 454,
"preview": "{\n \"name\": \"txtai-node\",\n \"dependencies\": {\n \"sprintf-js\": \">=1.1.2\",\n \"txtai\": \">=9.9.0\"\n },\n "
},
{
"path": "examples/node/src/embeddings.js",
"chars": 2749,
"preview": "import {Embeddings} from \"txtai\";\nimport {sprintf} from \"sprintf-js\";\n\n/**\n * Example embeddings functionality.\n * \n * I"
},
{
"path": "examples/node/src/extractor.js",
"chars": 1810,
"preview": "import {Extractor} from \"txtai\";\n\n/**\n * Example extractor functionality.\n * \n * Implements logic found in this notebook"
},
{
"path": "examples/node/src/labels.js",
"chars": 1977,
"preview": "import {Labels} from \"txtai\";\nimport {sprintf} from \"sprintf-js\";\n\n/**\n * Example labels functionality.\n * \n * Implement"
},
{
"path": "examples/node/src/pipelines.js",
"chars": 1717,
"preview": "import {Segmentation, Textractor, Summary, Transcription, Translation, Workflow} from \"txtai\";\n\n/**\n * Example pipeline "
},
{
"path": "package.json",
"chars": 740,
"preview": "{\n \"name\": \"txtai\",\n \"version\": \"9.9.0\",\n \"author\": \"NeuML\",\n \"description\": \"JavaScript client for txtai\",\n"
},
{
"path": "src/api.js",
"chars": 2760,
"preview": "// Backwards compatibility\nimport \"core-js/features/promise\";\nimport \"isomorphic-fetch\";\n\n/**\n * Base class for interfac"
},
{
"path": "src/embeddings.js",
"chars": 6774,
"preview": "import API from \"./api\";\n\n/**\n * txtai embeddings instance. \n */\nclass Embeddings extends API {\n /**\n * Finds doc"
},
{
"path": "src/extractor.js",
"chars": 525,
"preview": "import API from \"./api\";\n\n/**\n * txtai extractor instance. \n */\nclass Extractor extends API {\n /**\n * Extracts an"
},
{
"path": "src/index.js",
"chars": 550,
"preview": "import Embeddings from \"./embeddings\";\nimport Extractor from \"./extractor\";\nimport Labels from \"./labels\";\nimport Segmen"
},
{
"path": "src/labels.js",
"chars": 1144,
"preview": "import API from \"./api\";\n\n/**\n * txtai labels instance. \n */\nclass Labels extends API {\n /**\n * Applies a zero sh"
},
{
"path": "src/segmentation.js",
"chars": 683,
"preview": "import API from \"./api\";\n\n/**\n * txtai segmentation instance. \n */\nclass Segmentation extends API {\n /**\n * Segme"
},
{
"path": "src/similarity.js",
"chars": 1136,
"preview": "import API from \"./api\";\n\n/**\n * txtai similarity instance.\n */\nclass Similarity extends API {\n /**\n * Computes t"
},
{
"path": "src/summary.js",
"chars": 1327,
"preview": "import API from \"./api\";\n\n/**\n * txtai summary instance. \n */\nclass Summary extends API {\n /**\n * Runs a summariz"
},
{
"path": "src/textractor.js",
"chars": 696,
"preview": "import API from \"./api\";\n\n/**\n * txtai textractor instance. \n */\nclass Textractor extends API {\n /**\n * Extracts "
},
{
"path": "src/transcription.js",
"chars": 709,
"preview": "import API from \"./api\";\n\n/**\n * txtai transcription instance. \n */\nclass Transcription extends API {\n /**\n * Tra"
},
{
"path": "src/translation.js",
"chars": 1390,
"preview": "import API from \"./api\";\n\n/**\n * txtai translation instance. \n */\nclass Translation extends API {\n /**\n * Transla"
},
{
"path": "src/workflow.js",
"chars": 508,
"preview": "import API from \"./api\";\n\n/**\n * txtai workflow instance. \n */\nclass Workflow extends API {\n /**\n * Executes a na"
}
]
About this extraction
This page contains the full source code of the neuml/txtai.js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (40.1 KB), approximately 9.8k tokens, and a symbol index with 46 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.