`@xenova/transformers` only ship node.js and browser output, it's not possible to load this in edge runtime and workerd
This reverts commit 34fb1d8992.
We recommend you to understand the basics of Node.js, TypeScript, pnpm, and of course, LLM before contributing.
packages/core which is the main NPM library llamaindex
There are some important folders in the repository:
examples is where the demo code lives
### Turborepo docs
You can checkout how Turborepo works using the default [README-turborepo.md](/README-turborepo.md)
-`packages/*`: Contains the source code of the packages. Each package is a separate npm package.
-`llamaindex`: The starter package for LlamaIndex.TS, which contains the all sub-packages.
-`core`: The core package of LlamaIndex.TS, which contains the abstract classes and interfaces. It is designed for
all JS runtime environments.
-`env`: The environment package of LlamaIndex.TS, which contains the environment-specific classes and interfaces. It
includes compatibility layers for Node.js, Deno, Vercel Edge Runtime, Cloudflare Workers...
-`providers/*`: The providers package of LlamaIndex.TS, which contains the providers for LLM and other services.
-`apps/*`: The applications based on LlamaIndex.TS.
-`next`: Our documentation website based on Next.js.
-`examples`: The code examples of LlamaIndex.TS using Node.js.
## Getting Started
Install NodeJS. Preferably v18 using nvm or n.
Inside the LlamaIndexTS directory:
Make sure you have Node.js LTS (Long-term Support) installed. You can check your Node.js version by running:
```shell
node -v
# v20.x.x
```
npm i -g pnpm ts-node
### Use pnpm
```shell
npm install -g pnpm
```
### Install dependencies
```shell
pnpm install
```
Note: we use pnpm in this repo, which has a lot of the same functionality and CLI options as npm but it does do some things better in a monorepo, like centralizing dependencies and caching.
### Build the packages
PNPM's has documentation on its [workspace feature](https://pnpm.io/workspaces) and Turborepo had some [useful documentation also](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks).
To build all packages, run:
### Running Typescript
When we publish to NPM we will have a tsc compiled version of the library in JS. For now, the easiest thing to do is use ts-node.
### Test cases
To run them, run
```
pnpm run test
```shell
pnpm build
```
To write new test cases write them in [packages/core/src/tests](/packages/core/src/tests)
### Run tests
We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch of built in assertions using the expect function: https://jestjs.io/docs/expect
#### Unit tests
### Demo applications
After build, to run all unit tests, call:
There is an existing ["example"](/examples/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
You can create new demo applications in the apps folder. Just run pnpm init in the folder after you create it to create its own package.json
### Installing packages
To install packages for a specific package or demo application, run
```
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
```shell
pnpm test
```
To install packages for every package or application run
Unit tests are located in the `tests` folder of each package. They are using their own package (e.g. `@llamaindex/core-tests` for `@llamaindex/core`). The tests are importing the package under test and the test package is not published.
#### E2E tests
To run all E2E tests, call:
```shell
pnpm e2e
```
pnpm add -w [NPM Package]
```
All E2E tests are in the `e2e` folder.
### Docs
To contribute to the docs, go to the docs website folder and run the Docusaurus instance.
See the [docs](./apps/next/README.md) for more information.
```bash
cd apps/docs
pnpm install
pnpm start
## Adding a new package
Please follow these steps to add a new package:
1. Only add new packages to the `packages/providers` folder.
2. Use the `package.json` and `tsconfig.json` of an existing packages as template.
3. Reference your new package in the root `tsconfig.json` file
4. Add your package to the `examples/package.json` file if you add a new example.
## Before sending a PR
Before sending a PR, make sure of the following:
1. Tests are all running and you added meaningful tests for your change.
2. If you have a new feature, document it in the `apps/next` docs folder.
3. If you have a new feature, add a new example in the `examples` folder.
4. You have a descriptive changeset for each PR:
### Changesets
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new
changeset, run in the root folder:
```shell
pnpm changeset
```
That should start a webserver which will serve the docs on https://localhost:3000
## Publishing (maintainers only)
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
PR called "Release {version}".
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
the current changesets in the [.changeset](.changeset) folder.
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
This Turborepo includes the following packages/apps:
### Apps and Packages
-`docs`: a [Next.js](https://nextjs.org/) app
-`web`: another [Next.js](https://nextjs.org/) app
-`ui`: a stub React component library shared by both `web` and `docs` applications
-`eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
-`tsconfig`: `tsconfig.json`s used throughout the monorepo
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
### Utilities
This Turborepo has some additional tools already setup for you:
- [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting
- [Prettier](https://prettier.io) for code formatting
### Build
To build all apps and packages, run the following command:
```
cd my-turborepo
pnpm build
```
### Develop
To develop all apps and packages, run the following command:
```
cd my-turborepo
pnpm dev
```
### Remote Caching
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
```
cd my-turborepo
npx turbo login
```
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
LlamaIndex is a data framework for your LLM application.
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in Typescript and Javascript.
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in JS runtime environments with TypeScript support.
Documentation: https://ts.llamaindex.ai/
@@ -19,58 +23,58 @@ Try examples online:
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
## Getting started with an example:
## Compatibility
LlamaIndex.TS requires Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
See our official document: <https://ts.llamaindex.ai/docs/llamaindex/getting_started/>
asyncfunctionmain() {
// Load essay from abramov.txt in Node
constessay=awaitfs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
### Adding provider packages
// Create Document object with essay
constdocument=newDocument({text: essay});
In most cases, you'll also need to install provider packages to use LlamaIndexTS. These are for adding AI models, file readers for ingestion or storing documents, e.g. in vector databases.
// Split text and create embeddings. Store them in a VectorStoreIndex
For example, to use the OpenAI LLM, you would install the following package:
// Query the index
constqueryEngine=index.asQueryEngine();
constresponse=awaitqueryEngine.query({
query:"What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main();
```
Then you can run it using
```bash
pnpx ts-node example.ts
```shell
npm install @llamaindex/openai
pnpm install @llamaindex/openai
yarn add @llamaindex/openai
```
## Playground
@@ -79,56 +83,25 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
## Core concepts for getting started:
- [Document](/packages/core/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
- [Document](/packages/llamaindex/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
- [Node](/packages/core/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
- [Node](/packages/llamaindex/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
- [Embedding](/packages/core/src/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
- [Embedding](/packages/llamaindex/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that question. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/llamaindex/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/llamaindex/src/embeddings)).
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
- [Indices](/packages/llamaindex/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
- [QueryEngine](/packages/core/src/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
- [QueryEngine](/packages/llamaindex/src/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/llamaindex/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/llamaindex/src/engines/query).
- [ChatEngine](/packages/core/src/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
- [ChatEngine](/packages/llamaindex/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/llamaindex/src/engines/chat).
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
## Note: NextJS:
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the following config to your next.config.js to have it use imports/exports in the same way Node does.
```js
exportconstruntime="nodejs";// default
```
```js
// next.config.js
/** @type {import('next').NextConfig} */
constnextConfig={
webpack:(config)=>{
config.resolve.alias={
...config.resolve.alias,
sharp$:false,
"onnxruntime-node$":false,
};
returnconfig;
},
};
module.exports=nextConfig;
```
## Supported LLMs:
- OpenAI GPT-3.5-turbo and GPT-4
- Anthropic Claude Instant and Claude 2
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
- MistralAI Chat LLMs
- [SimplePrompt](/packages/llamaindex/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
## Contributing:
We are in the very early days of LlamaIndex.TS. If you’re interested in hacking on it with us check out our [contributing guide](/CONTRIBUTING.md)
Please see our [contributing guide](CONTRIBUTING.md) for more information.
You are highly encouraged to contribute to LlamaIndex.TS!
import CodeSource from "!raw-loader!../../../../examples/chatEngine";
# Chat Engine
Chat Engine is a class that allows you to create a chatbot from a retriever. It is a wrapper around a retriever that allows you to chat with it in a conversational manner.
A data connector (i.e. `Reader`) ingest data from different data sources and data formats into a simple `Document` representation (text and simple metadata).
[**Documents / Nodes**](./modules/high_level/documents_and_nodes.md): A `Document` is a generic container around any data source - for instance, a PDF, an API output, or retrieved data from a database. A `Node` is the atomic unit of data in LlamaIndex and represents a "chunk" of a source `Document`. It's a rich representation that includes metadata and relationships (to other nodes) to enable accurate and expressive retrieval operations.
Once you've ingested your data, LlamaIndex helps you index data into a format that's easy to retrieve.
Under the hood, LlamaIndex parses the raw documents into intermediate representations, calculates vector embeddings, and stores your data in-memory or to disk.
### Querying Stage
In the querying stage, the query pipeline retrieves the most relevant context given a user query,
and pass that to the LLM (along with the query) to synthesize a response.
This gives the LLM up-to-date knowledge that is not in its original training data,
(also reducing hallucination).
The key challenge in the querying stage is retrieval, orchestration, and reasoning over (potentially many) knowledge bases.
LlamaIndex provides composable modules that help you build and integrate RAG pipelines for Q&A (query engine), chatbot (chat engine), or as part of an agent.
These building blocks can be customized to reflect ranking preferences, as well as composed to reason over multiple knowledge bases in a structured way.
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
Just run
<Tabs>
<TabItem value="1" label="npm" default>
```bash
npx create-llama@latest
```
</TabItem>
<TabItem value="2" label="Yarn">
```bash
yarn create llama
```
</TabItem>
<TabItem value="3" label="pnpm">
```bash
pnpm create llama@latest
```
</TabItem>
</Tabs>
to get started. Once your app is generated, run
```bash npm2yarn
npm run dev
```
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
## Installation from NPM
```bash npm2yarn
npm install llamaindex
```
### Environment variables
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
```bash
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
```
If you want to have it automatically loaded every time, add it to your .zshrc/.bashrc.
WARNING: do not check in your OpenAI key into version control.
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
In a new folder:
```bash npm2yarn
npm install typescript
npm install @types/node
npx tsc --init # if needed
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
const essay = await fs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
// Create Document object with essay
const document = new Document({ text: essay });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query(
"What did the author do in college?",
);
// Output response
console.log(response.toString());
}
main();
```
Then you can run it using
```bash
npx ts-node example.ts
```
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
## 🚀 Why LlamaIndex.TS?
At their core, LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
Applications built on top of LLMs often require augmenting these models with private or domain-specific data. Unfortunately, that data can be distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
That's where **LlamaIndex.TS** comes in.
## 🦙 How can LlamaIndex.TS help?
LlamaIndex.TS provides the following tools:
- **Data loading** ingest your existing `.txt`, `.pdf`, `.csv`, `.md` and `.docx` data directly
- **Data indexes** structure your data in intermediate representations that are easy and performant for LLMs to consume.
- **Engines** provide natural language access to your data. For example:
- Query engines are powerful retrieval interfaces for knowledge-augmented output.
- Chat engines are conversational interfaces for multi-message, "back and forth" interactions with your data.
## 👨👩👧👦 Who is LlamaIndex for?
LlamaIndex.TS provides a core set of tools, essential for anyone building LLM apps with JavaScript and TypeScript.
Our high-level API allows beginner users to use LlamaIndex.TS to ingest and query their data.
For more complex applications, our lower-level APIs allow advanced users to customize and extend any module—data connectors, indices, retrievers, and query engines, to fit their needs.
## Getting Started
`npm install llamaindex`
Our documentation includes [Installation Instructions](./installation.mdx) and a [Starter Tutorial](./starter.md) to build your first application.
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our [End-to-End Tutorials](./end_to_end.md).
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class. Currently, `.txt`, `.pdf`, `.csv`, `.md` and `.docx` files are supported, with more planned in the future!
`Document`s and `Node`s are the basic building blocks of any index. While the API for these objects is similar, `Document` objects represent entire files, while `Node`s are smaller pieces of that original document, that are suitable for an LLM and Q&A.
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
This can be explicitly set in the `ServiceContext` object.
LlamaIndex.TS offers several core modules, seperated into high-level modules for quickly getting started, and low-level modules for customizing key components as you need.
## High-Level Modules
- [**Document**](./high_level/documents_and_nodes.md): A document represents a text file, PDF file or other contiguous piece of data.
- [**Node**](./high_level/documents_and_nodes.md): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
- [**Reader/Loader**](./high_level/data_loader.md): A reader or loader is something that takes in a document in the real world and transforms into a Document class that can then be used in your Index and queries. We currently support plain text files and PDFs with many many more to come.
- [**Indexes**](./high_level/data_index.md): indexes store the Nodes and the embeddings of those nodes.
- [**QueryEngine**](./high_level/query_engine.md): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected nodes from your Index to give the LLM the context it needs to answer your query.
- [**ChatEngine**](./high_level/chat_engine.md): A ChatEngine helps you build a chatbot that will interact with your Indexes.
## Low Level Module
- [**LLM**](./low_level/llm.md): The LLM class is a unified interface over a large language model provider such as OpenAI GPT-4, Anthropic Claude, or Meta LLaMA. You can subclass it to write a connector to your own large language model.
- [**Embedding**](./low_level/embedding.md): An embedding is represented as a vector of floating point numbers. OpenAI's text-embedding-ada-002 is our default embedding model and each embedding it generates consists of 1,536 floating point numbers. Another popular embedding model is BERT which uses 768 floating point numbers to represent each Node. We provide a number of utilities to work with embeddings including 3 similarity calculation options and Maximum Marginal Relevance
- [**TextSplitter/NodeParser**](./low_level/node_parser.md): Text splitting strategies are incredibly important to the overall efficacy of the embedding search. Currently, while we do have a default, there's no one size fits all solution. Depending on the source documents, you may want to use different splitting sizes and strategies. Currently we support spliltting by fixed size, splitting by fixed size with overlapping sections, splitting by sentence, and splitting by paragraph. The text splitter is used by the NodeParser when splitting `Document`s into `Node`s.
- [**Retriever**](./low_level/retriever.md): The Retriever is what actually chooses the Nodes to retrieve from the index. Here, you may wish to try retrieving more or fewer Nodes per query, changing your similarity function, or creating your own retriever for each individual use case in your application. For example, you may wish to have a separate retriever for code content vs. text content.
- [**ResponseSynthesizer**](./low_level/response_synthesizer.md): The ResponseSynthesizer is responsible for taking a query string, and using a list of `Node`s to generate a response. This can take many forms, like iterating over all the context and refining an answer, or building a tree of summaries and returning the root summary.
- [**Storage**](./low_level/storage.md): At some point you're going to want to store your indexes, data and vectors instead of re-running the embedding models every time. IndexStore, DocStore, VectorStore, and KVStore are abstractions that let you do that. Combined, they form the StorageContext. Currently, we allow you to persist your embeddings in files on the filesystem (or a virtual in memory file system), but we are also actively adding integrations to Vector Databases.
The `NodeParser` in LlamaIndex is responbile for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `ServiceContext` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
A query engine wraps a `Retriever` and a `ResponseSynthesizer` into a pipeline, that will use the query string to fetech nodes and then send them to the LLM to generate a response.
The basic concept of the Sub Question Query Engine is that it splits a single query into multiple queries, gets an answer for each of those queries, and then combines those different answers into a single coherent response for the user. You can think of it as the "think this through step by step" prompt technique but iterating over your data sources!
### Getting Started
The easiest way to start trying the Sub Question Query Engine is running the subquestion.ts file in [examples](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
```bash
npx ts-node subquestion.ts
```
### Tools
SubQuestionQueryEngine is implemented with Tools. The basic idea of Tools is that they are executable options for the large language model. In this case, our SubQuestionQueryEngine relies on QueryEngineTool, which as you guessed it is a tool to run queries on a QueryEngine. This allows us to give the model an option to query different documents for different questions for example. You could also imagine that the SubQuestionQueryEngine could use a Tool that searches for something on the web or gets an answer using Wolfram Alpha.
You can learn more about Tools by taking a look at the LlamaIndex Python documentation https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
The ResponseSynthesizer is responsible for sending the query, nodes, and prompt templates to the LLM to generate a response. There are a few key modes for generating a response:
-`Refine`: "create and refine" an answer by sequentially going through each retrieved text chunk.
This makes a separate LLM call per Node. Good for more detailed answers.
-`CompactAndRefine` (default): "compact" the prompt during each LLM call by stuffing as
many text chunks that can fit within the maximum prompt size. If there are
too many chunks to stuff in one prompt, "create and refine" an answer by going through
multiple compact prompts. The same as `refine`, but should result in less LLM calls.
-`TreeSummarize`: Given a set of text chunks and the query, recursively construct a tree
and return the root node as the response. Good for summarization purposes.
-`SimpleResponseBuilder`: Given a set of text chunks and the query, apply the query to each text
chunk while accumulating the responses into an array. Returns a concatenated string of all
responses. Good for when you need to run the same query separately against each text
A retriever in LlamaIndex is what is used to fetch `Node`s from an index using a query string. Aa `VectorIndexRetriever` will fetch the top-k most similar nodes. Meanwhile, a `SummaryIndexRetriever` will fetch all nodes no matter the query.
Storage in LlamaIndex.TS works automatically once you've configured a `StorageContext` object. Just configure the `persistDir` and attach it to an index.
Right now, only saving and loading from disk is supported, with future integrations planned!
LlamaIndex provides **one-click observability** 🔭 to allow you to build principled LLM applications in a production setting.
A key requirement for principled development of LLM applications over your data (RAG systems, agents) is being able to observe, debug, and evaluate
your system - both as a whole and for each component.
This feature allows you to seamlessly integrate the LlamaIndex library with powerful observability/evaluation tools offered by our partners.
Configure a variable once, and you'll be able to do things like the following:
- View LLM/prompt inputs/outputs
- Ensure that the outputs of any component (LLMs, embeddings) are performing as expected
- View call traces for both indexing and querying
Each provider has similarities and differences. Take a look below for the full set of guides for each one!
## OpenLLMetry
[OpenLLMetry](https://github.com/traceloop/openllmetry-js) is an open-source project based on OpenTelemetry for tracing and monitoring
LLM applications. It connects to [all major observability platforms](https://www.traceloop.com/docs/openllmetry/integrations/introduction) and installs in minutes.
موصل البيانات (أي `Reader`) يقوم بتجميع البيانات من مصادر بيانات مختلفة وتنسيقات بيانات مختلفة في تمثيل بسيط للـ `Document` (نص وبيانات تعريفية بسيطة).
[**المستندات / العقد**](./modules/high_level/documents_and_nodes.md): المستند هو حاوية عامة حول أي مصدر بيانات - على سبيل المثال، ملف PDF، نتائج واجهة برمجة التطبيقات، أو بيانات استرداد من قاعدة بيانات. العقد هو الوحدة الذرية للبيانات في LlamaIndex ويمثل "قطعة" من المستند الأصلي. إنه تمثيل غني يتضمن بيانات تعريفية وعلاقات (مع عقد أخرى) لتمكين عمليات الاسترجاع الدقيقة والتعبيرية.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
نقدم العديد من الأمثلة من البداية إلى النهاية باستخدام LlamaIndex.TS في المستودع
تحقق من الأمثلة أدناه أو جربها وأكملها في دقائق مع دروس تفاعلية على Github Codespace المقدمة من Dev-Docs [هنا](https://codespaces.new/team-dev-docs/lits-dev-docs-playground?devcontainer_path=.devcontainer%2Fjavascript_ltsquickstart%2Fdevcontainer.json):
يستخدم هذا المثال العديد من المكونات منخفضة المستوى، مما يزيل الحاجة إلى محرك استعلام فعلي. يمكن استخدام هذه المكونات في أي مكان، في أي تطبيق، أو تخصيصها وتصنيفها الفرعي لتلبية احتياجاتك الخاصة.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
LlamaIndex.TS هو إطار بيانات لتطبيقات LLM لاستيعاب وتنظيم والوصول إلى البيانات الخاصة أو الخاصة بالمجال. في حين أن حزمة Python متاحة أيضًا (انظر [هنا](https://docs.llamaindex.ai/en/stable/)), يوفر LlamaIndex.TS ميزات أساسية في حزمة بسيطة ، محسنة للاستخدام مع TypeScript.
## 🚀 لماذا LlamaIndex.TS؟
في جوهرها ، توفر LLMs واجهة لغة طبيعية بين البشر والبيانات المستنتجة. تأتي النماذج المتاحة على نطاق واسع محملة مسبقًا بكميات هائلة من البيانات المتاحة للجمهور ، من ويكيبيديا وقوائم البريد الإلكتروني إلى الكتب المدرسية وشفرة المصدر.
غالبًا ما تتطلب التطبيقات المبنية على LLMs تعزيز هذه النماذج بالبيانات الخاصة أو الخاصة بالمجال. للأسف ، يمكن توزيع هذه البيانات عبر تطبيقات ومخازن بيانات معزولة. إنها خلف واجهات برمجة التطبيقات ، في قواعد البيانات SQL ، أو محبوسة في ملفات PDF وعروض تقديمية.
هنا يأتي دور **LlamaIndex.TS**.
## 🦙 كيف يمكن أن يساعد LlamaIndex.TS؟
يوفر LlamaIndex.TS الأدوات التالية:
- **تحميل البيانات**: استيعاب البيانات الحالية الخاصة بك بتنسيقات `.txt`, `.pdf`, `.csv`, `.md` و `.docx` مباشرة.
- **فهارس البيانات**: تنظيم البيانات الخاصة بك في تمثيلات وسيطة سهلة وفعالة للاستخدام من قبل LLMs.
- **المحركات**: توفر واجهات الوصول إلى اللغة الطبيعية لبياناتك. على سبيل المثال:
- محركات الاستعلام هي واجهات استرجاع قوية للإخراج المعزز بالمعرفة.
- محركات الدردشة هي واجهات محادثة للتفاعلات "ذهابًا وإيابًا" متعددة الرسائل مع بياناتك.
## 👨👩👧👦 من أجل من هو LlamaIndex؟
يوفر LlamaIndex.TS مجموعة أدوات أساسية ، ضرورية لأي شخص يقوم ببناء تطبيقات LLM باستخدام JavaScript و TypeScript.
يتيح لنا واجهة برمجة التطبيقات على مستوى عالي استخدام LlamaIndex.TS لاستيعاب واستعلام البيانات الخاصة بهم.
بالنسبة للتطبيقات المعقدة أكثر ، تتيح لنا واجهات برمجة التطبيقات على مستوى أدنى للمستخدمين المتقدمين تخصيص وتوسيع أي وحدة - موصلات البيانات والفهارس وأجهزة الاسترجاع ومحركات الاستعلام - لتناسب احتياجاتهم.
## البدء
`npm install llamaindex`
تتضمن وثائقنا [تعليمات التثبيت](./installation.mdx) و[دليل البداية](./starter.md) لبناء تطبيقك الأول.
بمجرد أن تكون جاهزًا وتعمل ، يحتوي [مفاهيم عالية المستوى](./getting_started/concepts.md) على نظرة عامة على الهندسة المعمارية المتعددة المستويات لـ LlamaIndex. لمزيد من الأمثلة العملية التفصيلية ، يمكنك الاطلاع على [دروس النهاية إلى النهاية](./end_to_end.md).
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يدعم LlamaIndex.TS تحميل الملفات بسهولة من المجلدات باستخدام فئة `SimpleDirectoryReader`. حاليًا ، يتم دعم الملفات `.txt` ، `.pdf` ، `.csv` ، `.md` و `.docx` ، مع المزيد المخطط له في المستقبل!
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
`المستندات` و `العقد` هما العناصر الأساسية لأي فهرس. بينما يكون واجهة برمجة التطبيق (API) لهذه الكائنات مشابهة، يُمثل كائن `المستند` ملفات كاملة، بينما تكون `العقد` قطعًا أصغر من ذلك المستند الأصلي، والتي تكون مناسبة لـ LLM و Q&A.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يقوم محرك الاستعلامات بتجميع "Retriever" و "ResponseSynthesizer" في أنبوبة، والتي ستستخدم سلسلة الاستعلام لاسترداد العقد ومن ثم إرسالها إلى LLM لتوليد استجابة.
الفكرة الأساسية لمحرك الاستعلام للأسئلة الفرعية هي تقسيم استعلام واحد إلى استعلامات متعددة، والحصول على إجابة لكل من تلك الاستعلامات، ثم دمج تلك الإجابات المختلفة في استجابة واحدة متسقة للمستخدم. يمكنك أن تفكر فيها كتقنية "فكر في ذلك خطوة بخطوة" ولكن بتكرار مصادر البيانات الخاصة بك!
### البدء
أسهل طريقة لبدء تجربة محرك الاستعلام للأسئلة الفرعية هي تشغيل ملف subquestion.ts في [examples](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
```bash
npx ts-node subquestion.ts
```
"
### الأدوات
يتم تنفيذ محرك الاستعلام للأسئلة الفرعية باستخدام الأدوات. الفكرة الأساسية للأدوات هي أنها خيارات قابلة للتنفيذ لنموذج اللغة الكبيرة. في هذه الحالة، يعتمد محرك الاستعلام للأسئلة الفرعية على أداة QueryEngineTool، والتي كما تخمن هي أداة لتشغيل استعلامات على محرك الاستعلام. يتيح لنا ذلك إعطاء النموذج خيارًا للاستعلام عن وثائق مختلفة لأسئلة مختلفة على سبيل المثال. يمكنك أيضًا أن تتخيل أن محرك الاستعلام للأسئلة الفرعية يمكنه استخدام أداة تبحث عن شيء ما على الويب أو تحصل على إجابة باستخدام Wolfram Alpha.
يمكنك معرفة المزيد عن الأدوات من خلال الاطلاع على وثائق LlamaIndex Python https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يوفر LlamaIndex.TS عدة وحدات أساسية، مقسمة إلى وحدات عالية المستوى للبدء السريع ووحدات منخفضة المستوى لتخصيص المكونات الرئيسية حسب الحاجة.
## وحدات عالية المستوى
- [**المستند**](./high_level/documents_and_nodes.md): يمثل المستند ملف نصي أو ملف PDF أو قطعة بيانات متتابعة أخرى.
- [**العقدة**](./high_level/documents_and_nodes.md): هو البناء الأساسي للبيانات. في أغلب الأحيان، تكون هذه أجزاء من المستند المقسمة إلى قطع قابلة للإدارة وصغيرة بما يكفي ليتم تغذيتها إلى نموذج التضمين و LLM.
- [**القارئ/المحمل**](./high_level/data_loader.md): القارئ أو المحمل هو شيء يأخذ المستند في العالم الحقيقي ويحوله إلى فئة المستند التي يمكن استخدامها في الفهرس الخاص بك والاستعلامات. ندعم حاليًا ملفات النص العادي وملفات PDF والمزيد الكثير.
- [**الفهارس**](./high_level/data_index.md): تخزن الفهارس العقد وتضمينات تلك العقد.
- [**محرك الاستعلامات**](./high_level/query_engine.md): محركات الاستعلامات هي التي تولد الاستعلام الذي تدخله وتعيد لك النتيجة. عمومًا، تجمع محركات الاستعلامات بين تعليمة مسبقة مبنية مع العقد المحددة من الفهرس الخاص بك لتعطي LLM السياق الذي يحتاجه للإجابة على استعلامك.
- [**محرك الدردشة**](./high_level/chat_engine.md): يساعدك محرك الدردشة على بناء روبوت دردشة سيتفاعل مع فهرسك.
## وحدة منخفضة المستوى
- [**LLM**](./low_level/llm.md): فئة LLM هي واجهة موحدة فوق مزود نموذج لغة كبير مثل OpenAI GPT-4 أو Anthropic Claude أو Meta LLaMA. يمكنك توريثها لكتابة موصل إلى نموذج اللغة الخاص بك.
- [**Embedding**](./low_level/embedding.md): يتم تمثيل التضمين كمتجه من الأرقام العائمة. نموذج التضمين الافتراضي لدينا هو text-embedding-ada-002 من OpenAI ويتكون كل تضمين يولده من 1,536 رقمًا عائمًا. نموذج التضمين الشائع الآخر هو BERT الذي يستخدم 768 رقمًا عائمًا لتمثيل كل عقدة. نوفر عددًا من الأدوات للعمل مع التضمين بما في ذلك 3 خيارات لحساب التشابه و Maximum Marginal Relevance.
- [**TextSplitter/NodeParser**](./low_level/node_parser.md): تعتبر استراتيجيات تقسيم النصوص مهمة للغاية لفعالية البحث في التضمين. حاليًا، على الرغم من أن لدينا قيمة افتراضية، إلا أنه لا يوجد حلاً مناسبًا للجميع. اعتمادًا على وثائق المصدر، قد ترغب في استخدام أحجام واستراتيجيات تقسيم مختلفة. حاليًا، ندعم التقسيم حسب الحجم الثابت، التقسيم حسب الحجم الثابت مع أجزاء تتداخل، التقسيم حسب الجملة، والتقسيم حسب الفقرة. يتم استخدام مقسم النصوص بواسطة NodeParser عند تقسيم `Document` إلى `Node`.
- [**Retriever**](./low_level/retriever.md): يقوم Retriever بتحديد العقد التي يتم استردادها من الفهرس. هنا، قد ترغب في محاولة استرداد عدد أكبر أو أقل من العقد لكل استعلام، تغيير وظيفة التشابه الخاصة بك، أو إنشاء استرداد خاص بك لكل حالة استخدام فردية في تطبيقك. على سبيل المثال، قد ترغب في وجود استرداد منفصل لمحتوى الشفرة مقابل محتوى النص.
- [**ResponseSynthesizer**](./low_level/response_synthesizer.md): يتحمل ResponseSynthesizer مسؤولية أخذ سلسلة استعلام واستخدام قائمة من العقد لإنشاء استجابة. يمكن أن يأخذ هذا الشكل العديد من الأشكال، مثل التكرار عبر جميع السياق وتحسين الإجابة، أو بناء شجرة من الملخصات وإرجاع الملخص الجذري.
- [**Storage**](./low_level/storage.md): في نقطة ما، سترغب في تخزين الفهارس والبيانات والمتجهات بدلاً من إعادة تشغيل نماذج التضمين في كل مرة. IndexStore و DocStore و VectorStore و KVStore هي تجريدات تتيح لك ذلك. مجتمعة، تشكل هذه التجريدات سياق التخزين. حاليًا، نسمح لك بالاحتفاظ بالتضمينات الخاصة بك في ملفات على نظام الملفات (أو نظام ملفات افتراضي في الذاكرة)، ولكننا نضيف أيضًا تكاملات مع قواعد بيانات المتجهات.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
`NodeParser` في LlamaIndex مسؤول عن تقسيم كائنات `Document` إلى كائنات `Node` أكثر إدارة. عند استدعاء `.fromDocuments()`, يتم استخدام `NodeParser` من `ServiceContext` للقيام بذلك تلقائيًا بالنسبة لك. بدلاً من ذلك ، يمكنك استخدامه لتقسيم المستندات مسبقًا.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
مركب الاستجابة (ResponseSynthesizer) مسؤول عن إرسال الاستعلام والعقد وقوالب الاستفسار إلى LLM لتوليد استجابة. هناك بعض وسائط رئيسية لتوليد استجابة:
-`تحسين`: "إنشاء وتحسين" إجابة عن طريق المرور تتاليًا عبر كل قطعة نص مُسترجعة. يتم إجراء استدعاء LLM منفصل لكل عقدة. جيد للإجابات المفصلة.
-`مضغوط وتحسين` (الافتراضي): "ضغط" الاستفسار أثناء كل استدعاء LLM عن طريق حشو أكبر عدد ممكن من قطع النص التي يمكن أن تتناسب مع حجم الاستفسار الأقصى. إذا كان هناك الكثير من القطع لتعبئتها في استفسار واحد، "إنشاء وتحسين" إجابة عن طريق المرور بعدة استفسارات مضغوطة. نفس العملية كـ `تحسين`، ولكن يجب أن تؤدي إلى مزيد من استدعاءات LLM أقل.
-`ملخص الشجرة`: بناء شجرة بشكل متكرر بناءً على مجموعة من قطع النص والاستعلام، وإرجاع العقدة الجذرية كاستجابة. جيد لأغراض التلخيص.
-`منشئ الاستجابة البسيط`: تطبيق الاستعلام على كل قطعة نص وتجميع الاستجابات في مصفوفة. يعيد سلسلة متصلة من جميع الاستجابات. جيد عندما تحتاج إلى تشغيل نفس الاستعلام بشكل منفصل على كل قطعة نص.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
الباحث في LlamaIndex هو ما يُستخدم لاسترداد العقد (`Node`) من فهرس باستخدام سلسلة الاستعلام. سيقوم الباحث `VectorIndexRetriever` بجلب أعلى k عقد مشابهة. بينما سيقوم الباحث `SummaryIndexRetriever` بجلب جميع العقد بغض النظر عن الاستعلام.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
بمجرد [تثبيت LlamaIndex.TS باستخدام NPM](installation) وإعداد مفتاح OpenAI الخاص بك، أنت الآن جاهز لبدء تطبيقك الأول:
في مجلد جديد:
```bash npm2yarn
npm install typescript
npm install @types/node
npx tsc --init # إذا لزم الأمر
```
أنشئ ملف `example.ts`. سيقوم هذا الكود بتحميل بعض البيانات المثالية، وإنشاء وثيقة، وفهرسة الوثيقة (مما ينشئ تضمينات باستخدام OpenAI)، ثم إنشاء محرك الاستعلام للإجابة على الأسئلة حول البيانات.
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
async function main() {
// تحميل المقالة من abramov.txt في Node
const essay = await fs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
// إنشاء كائن Document بواسطة المقالة
const document = new Document({ text: essay });
// تقسيم النص وإنشاء التضمينات. تخزينها في VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// استعلام الفهرس
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query("ماذا فعل الكاتب في الكلية؟");
// إخراج الاستجابة
console.log(response.toString());
}
main();
```
ثم يمكنك تشغيله باستخدام
```bash
npx ts-node example.ts
```
هل أنت مستعد للمزيد من التعلم؟ تفضل بزيارة منصة NextJS الخاصة بنا على https://llama-playground.vercel.app/. يمكنك العثور على المصدر على https://github.com/run-llama/ts-playground
Конектор за данни (т.е. `Reader`) поема данни от различни източници на данни и формати на данни и ги превръща в просто представяне на `Document` (текст и прости метаданни).
[**Documents / Nodes**](./modules/high_level/documents_and_nodes.md): `Document` е общ контейнер за всякакъв вид данни - например PDF, изход от API или извлечени данни от база данни. `Node` е атомарната единица от данни в LlamaIndex и представлява "част" от източниковия `Document`. Това е богато представяне, което включва метаданни и връзки (към други възли), за да позволи точни и изразителни операции за извличане.
След като сте поели данните си, LlamaIndex ви помага да индексирате данните във формат, който е лесен за извличане.
Под капака, LlamaIndex анализира суровите документи в промеждинни представяния, изчислява векторни вложения и съхранява данните в паметта или на диска.
"
### Стъпка за заявка
В стъпката за заявка, конвейерът за заявки извлича най-съответния контекст, даден на потребителска заявка,
и го предава на LLM (заедно със заявката), за да синтезира отговор.
Това дава на LLM актуални познания, които не са в неговите оригинални обучаващи данни,
(също така намалява халюцинацията).
Основното предизвикателство в стъпката за заявка е извличането, организирането и резонирането върху (потенциално много) бази от знания.
LlamaIndex предоставя модули, които могат да се комбинират и помагат за създаването и интегрирането на RAG конвейери за Q&A (заявки), чатбот (чат двигател) или като част от агент.
Тези строителни блокове могат да бъдат персонализирани, за да отразяват предпочитанията за ранжиране, както и да бъдат комбинирани, за да резонират върху множество бази от знания по структуриран начин.
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
Включени са няколко примера от начало до край, използвайки LlamaIndex.TS в хранилището
Разгледайте примерите по-долу или ги опитайте и завършете за минути с интерактивни уроци на Github Codespace, предоставени от Dev-Docs [тук](https://codespaces.new/team-dev-docs/lits-dev-docs-playground?devcontainer_path=.devcontainer%2Fjavascript_ltsquickstart%2Fdevcontainer.json):
Създайте списъчен индекс и го заявете. Този пример също използва `LLMRetriever`, който използва LLM, за да избере най-добрите възли за използване при генериране на отговор.
"
## [Запазване / Зареждане на индекс](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/storageContext.ts)
Създайте и заредете векторен индекс. Запазването на диска в LlamaIndex.TS става автоматично, веднага след като е създаден обект за контекст на съхранение.
Използва `SubQuestionQueryEngine`, който разбива сложни заявки на множество въпроси и след това агрегира отговорите на всички под-въпроси.
"
## [Модули с ниско ниво](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/lowlevel.ts)
Този пример използва няколко компонента с ниско ниво, които премахват нуждата от реален двигател за заявки. Тези компоненти могат да се използват навсякъде, във всяко приложение или да бъдат персонализирани и подкласирани, за да отговарят на вашите нужди.
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
Уверете се, че имате NodeJS v18 или по-нова версия.
## Използване на create-llama
Най-лесният начин да започнете с LlamaIndex е чрез използването на `create-llama`. Този инструмент с команден ред ви позволява бързо да започнете да създавате ново приложение LlamaIndex, като всичко е настроено за вас.
Просто изпълнете
<Tabs>
<TabItem value="1" label="npm" default>
```bash
npx create-llama@latest
```
</TabItem>
<TabItem value="2" label="Yarn">
```bash
yarn create llama
```
</TabItem>
<TabItem value="3" label="pnpm">
```bash
pnpm create llama@latest
```
</TabItem>
</Tabs>
за да започнете. След като приложението ви е генерирано, изпълнете
```bash npm2yarn
npm run dev
```
за да стартирате сървъра за разработка. След това можете да посетите [http://localhost:3000](http://localhost:3000), за да видите вашето приложение.
## Инсталация от NPM
```bash npm2yarn
npm install llamaindex
```
### Променливи на средата
Нашият пример използва OpenAI по подразбиране. Ще трябва да настроите вашия Open AI ключ по следния начин:
```bash
export OPENAI_API_KEY="sk-......" # Заменете с вашия ключ от https://platform.openai.com/account/api-keys
```
Ако искате да го зареждате автоматично всеки път, добавете го към вашия .zshrc/.bashrc.
ВНИМАНИЕ: не добавяйте вашия OpenAI ключ в системата за контрол на версиите.
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
LlamaIndex.TS е рамка за данни за приложения на LLM, която позволява внасяне, структуриране и достъп до частни или специфични за домейна данни. Въпреки че има наличен и пакет на Python (вижте [тук](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS предлага основни функции в едно просто пакетиране, оптимизирано за използване с TypeScript.
## 🚀 Защо LlamaIndex.TS?
В основата си, LLM-ите предлагат естествен езиков интерфейс между хората и изводените данни. Широко разпространените модели са предварително обучени на голямо количество публично достъпни данни, от Уикипедия и списания до учебници и изходен код.
Приложенията, построени върху LLM-и, често изискват допълване на тези модели с частни или специфични за домейна данни. За съжаление, тези данни могат да бъдат разпределени в различни приложения и хранилища на данни. Те се намират зад API-и, в SQL бази данни или са затворени в PDF файлове и презентации.
Тук идва **LlamaIndex.TS**.
## 🦙 Как може да помогне LlamaIndex.TS?
LlamaIndex.TS предоставя следните инструменти:
- **Зареждане на данни** - внасяйте вашите съществуващи данни във формат `.txt`, `.pdf`, `.csv`, `.md` и `.docx` директно
- **Индекси на данни** - структурирайте данните си в промежуточни представяния, които са лесни и ефективни за консумация от LLM.
- **Двигатели** - предоставят достъп до вашите данни чрез естествен език. Например:
- Заявителни двигатели са мощни интерфейси за извличане на знания.
- Чат двигатели са разговорни интерфейси за многократни, "напред и назад" взаимодействия с вашите данни.
"
## 👨👩👧👦 За кого е LlamaIndex?
LlamaIndex.TS предоставя основен набор от инструменти, необходими за всеки, който създава LLM приложения с JavaScript и TypeScript.
Нашето API на високо ниво позволява на начинаещите потребители да използват LlamaIndex.TS за внасяне и заявка на техните данни.
За по-сложни приложения нашите API на по-ниско ниво позволяват на напредналите потребители да персонализират и разширят всяко модул - връзки с данни, индекси, извличатели и заявки, за да отговарят на техните нужди.
## Започване
`npm install llamaindex`
Документацията ни включва [Инструкции за инсталиране](./installation.mdx) и [Урок за начинаещи](./starter.md), за да построите първото си приложение.
След като сте готови, [Високо ниво концепции](./getting_started/concepts.md) представя общ преглед на модулната архитектура на LlamaIndex. За повече практически примери, разгледайте нашите [Уроци от начало до край](./end_to_end.md).
## 🗺️ Екосистема
За да изтеглите или допринесете, намерете LlamaIndex на:
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
LlamaIndex.TS поддържа лесно зареждане на файлове от папки с помощта на класа `SimpleDirectoryReader`. В момента се поддържат файлове с разширения `.txt`, `.pdf`, `.csv`, `.md` и `.docx`, с планове за добавяне на още в бъдеще!
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
`Документи` и `Възли` са основните строителни блокове на всяко индексиране. Въпреки че API-то за тези обекти е подобно, обектите `Документ` представляват цели файлове, докато `Възли` са по-малки части от оригиналния документ, които са подходящи за LLM и Q&A.
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
Заявка на двигател обвива `Retriever` и `ResponseSynthesizer` в тръбопровод, който използва низа от заявки, за да извлече възли и след това ги изпраща към LLM, за да генерира отговор.
Основната концепция на Заявка на подзапитване на двигател е, че тя разделя една заявка на множество заявки, получава отговор за всяка от тези заявки и след това комбинира тези различни отговори в един цялостен отговор за потребителя. Можете да си представите това като техника за "мислене стъпка по стъпка", но като итерира върху източниците на данни!
### Започване
Най-лесният начин да започнете да използвате Заявка на подзапитване на двигател е да стартирате файла subquestion.ts в [примерите](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
```bash
npx ts-node subquestion.ts
```
### Инструменти
Заявка на подзапитване на двигател е реализирана с инструменти. Основната идея на инструментите е, че те са изпълними опции за големия езиков модел. В този случай нашият Заявка на подзапитване на двигател разчита на QueryEngineTool, който, както се предполага, е инструмент за изпълнение на заявки върху QueryEngine. Това ни позволява да дадем на модела възможност да заявява различни документи за различни въпроси, например. Също така можем да си представим, че Заявка на подзапитване на двигател може да използва инструмент, който търси нещо в Интернет или получава отговор, използвайки Wolfram Alpha.
Можете да научите повече за инструментите, като разгледате документацията на LlamaIndex Python https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
## API Reference (API справка)
- [RetrieverQueryEngine (Заявка на двигател за извличане)](../../api/classes/RetrieverQueryEngine.md)
- [SubQuestionQueryEngine (Заявка на двигател за подзапитване)](../../api/classes/SubQuestionQueryEngine.md)
- [QueryEngineTool (Инструмент за заявка на двигател)](../../api/interfaces/QueryEngineTool.md)
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
LlamaIndex.TS предлага няколко основни модула, разделени на модули на високо ниво, за бързо стартиране, и модули на ниско ниво, за персонализиране на ключовите компоненти според вашите нужди.
## Модули на високо ниво
- [**Документ**](./high_level/documents_and_nodes.md): Документ представлява текстов файл, PDF файл или друг непрекъснат парче данни.
- [**Възел**](./high_level/documents_and_nodes.md): Основният строителен блок от данни. Най-често това са части от документа, разделени на управляеми парчета, достатъчно малки, за да бъдат подадени на модел за вграждане и LLM.
- [**Четец/Зареждач**](./high_level/data_loader.md): Четецът или зареждачът е нещо, което приема документ от реалния свят и го преобразува в клас Документ, който после може да се използва в индекса и заявките ви. В момента поддържаме обикновени текстови файлове и PDF файлове, с много други, които ще бъдат добавени.
- [**Индекси**](./high_level/data_index.md): Индексите съхраняват Възлите и вгражданията на тези възли.
- [**QueryEngine**](./high_level/query_engine.md): Заявките са това, което генерира заявката, която въвеждате и ви връща резултата. Заявките обикновено комбинират предварително изграден prompt със избрани възли от вашия индекс, за да предоставят на LLM контекста, от който се нуждае, за да отговори на вашата заявка.
- [**ChatEngine**](./high_level/chat_engine.md): ChatEngine ви помага да построите чатбот, който ще взаимодейства с вашите индекси.
## Модули на ниско ниво
- [**LLM**](./low_level/llm.md): Класът LLM е обединен интерфейс над голям доставчик на модели на езика като OpenAI GPT-4, Anthropic Claude или Meta LLaMA. Можете да го наследите, за да напишете конектор към собствен модел на голям език.
- [**Embedding**](./low_level/embedding.md): Вграждането се представя като вектор от числа с плаваща запетая. Нашето вграждане по подразбиране е OpenAI's text-embedding-ada-002 и всяко вграждане, което генерира, се състои от 1,536 числа с плаваща запетая. Друго популярно вграждане е BERT, което използва 768 числа с плаваща запетая, за да представи всеки възел. Предоставяме няколко помощни функции за работа с вграждания, включително 3 опции за изчисляване на подобие и Maximum Marginal Relevance.
- [**TextSplitter/NodeParser**](./low_level/node_parser.md): Стратегиите за разделяне на текст са изключително важни за общата ефективност на търсенето на вграждания. В момента, въпреки че имаме стойност по подразбиране, няма универсално решение. В зависимост от източниците на документите, може да искате да използвате различни размери и стратегии за разделяне. В момента поддържаме разделяне по фиксиран размер, разделяне по фиксиран размер с препокриващи се секции, разделяне по изречение и разделяне по параграф. TextSplitter се използва от NodeParser при разделянето на `Document` на `Node`.
- [**Retriever**](./low_level/retriever.md): Retriever е този, който наистина избира възлите за връщане от индекса. Тук може да желаете да опитате да вземете повече или по-малко възли за всяка заявка, да промените функцията за подобие или да създадете собствен retriever за всеки отделен случай в приложението си. Например може да желаете да имате отделен retriever за съдържание на код срещу текстово съдържание.
- [**ResponseSynthesizer**](./low_level/response_synthesizer.md): ResponseSynthesizer е отговорен за вземането на низ от заявка и използването на списък от `Node`-и за генериране на отговор. Това може да бъде в различни форми, като обхождане на всички контексти и уточняване на отговор, или изграждане на дърво от резюмета и връщане на кореновото резюме.
- [**Storage**](./low_level/storage.md): На някакъв етап ще искате да съхранявате индексите, данните и векторите си, вместо да изпълнявате моделите за вграждане всеки път. IndexStore, DocStore, VectorStore и KVStore са абстракции, които ви позволяват да го направите. Заедно те формират StorageContext. В момента ви позволяваме да запазвате вгражданията си във файлове на файловата система (или виртуална файлова система в паметта), но също така активно добавяме интеграции към Vector Databases.
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
Моделът за вграждане в LlamaIndex е отговорен за създаването на числови представяния на текст. По подразбиране, LlamaIndex използва модела `text-embedding-ada-002` от OpenAI.
Това може да бъде явно зададено в обекта `ServiceContext`.
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
`NodeParser` в LlamaIndex е отговорен за разделянето на обекти от тип `Document` на по-лесни за управление обекти от тип `Node`. Когато извикате `.fromDocuments()`, `NodeParser` от `ServiceContext` се използва автоматично за това. Алтернативно, можете да го използвате, за да разделяте документи предварително.
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
ResponseSynthesizer е отговорен за изпращането на заявката, възлите и шаблоните за подсказки към LLM, за да генерира отговор. Има няколко ключови режима за генериране на отговор:
-`Refine` (Подобряване): "създаване и подобряване" на отговор, като последователно се преминава през всеки извлечен текстов фрагмент. Това прави отделно LLM обаждане за всеки възел. Подходящо за по-подробни отговори.
-`CompactAndRefine` (Компактно и подобряване) (по подразбиране): "компактиране" на подсказката по време на всяко LLM обаждане, като се пълни с колкото може повече текстови фрагменти, които могат да се поберат в максималния размер на подсказката. Ако има твърде много фрагменти, които не могат да се поберат в една подсказка, се "създава и подобрява" отговор, като се преминава през няколко компактни подсказки. Същото като `refine`, но трябва да доведе до по-малко LLM обаждания.
-`TreeSummarize` (Сумиране на дърво): Дадени набор от текстови фрагменти и заявката, рекурсивно се конструира дърво и се връща кореновият възел като отговор. Подходящо за цели на сумиране.
-`SimpleResponseBuilder` (Прост създател на отговори): Дадени набор от текстови фрагменти и заявката, се прилага заявката към всеки текстов фрагмент, като се натрупват отговорите в масив. Връща конкатениран низ от всички отговори. Подходящо, когато трябва да изпълните същата заявка отделно за всеки текстов фрагмент.
- [CompactAndRefine (Компактно и подобряване)](../../api/classes/CompactAndRefine.md)
- [TreeSummarize (Сумиране на дърво)](../../api/classes/TreeSummarize.md)
- [SimpleResponseBuilder (Прост създател на отговори)](../../api/classes/SimpleResponseBuilder.md)
"
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.