Compare commits

...

72 Commits

Author SHA1 Message Date
github-actions[bot] 0e980d962d Release 0.5.2 (#1035)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-12 11:44:32 -07:00
Alex Yang 3ed6acc6a6 chore: bump cloud api (#1036) 2024-07-12 11:21:37 -07:00
Parham Saidi 56746c240f fix: bedrock handle empty content and added max tokens export (#1034) 2024-07-12 09:47:49 -07:00
Alex Yang 5c1c2c7f5b ci: only commit lock file (#1031) 2024-07-10 10:17:35 -07:00
github-actions[bot] a699086f46 Release 0.5.1 (#1028)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-09 15:36:20 -07:00
Alex Yang 454c204112 chore: bump version (#1029) 2024-07-09 13:42:09 -07:00
Julius Lipp 277468160d feat: add mixedbread ai integration (#953) 2024-07-09 09:36:43 -07:00
Ranjan Mangla a0f424e592 fix: corrected the regex in the ReactAgent (#1022)
Signed-off-by: ranjanmangla1 <ranjanmangla1@gmail.com>
2024-07-09 08:55:38 -07:00
github-actions[bot] 3ae832ca28 Release 0.5.0 (#1024)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: himself65 <himself65@users.noreply.github.com>
2024-07-08 17:16:46 -07:00
Alex Yang 16ef5dd631 feat: simplify callback manager (#1027) 2024-07-08 16:44:54 -07:00
Alex Yang c4bd0a5215 refactor: move llm & callback manager to core module (#1026) 2024-07-08 15:48:59 -07:00
Alex Yang f5c8ca7dfb chore: use bunchee bundler for all (#1025) 2024-07-08 09:45:55 -07:00
Sacha Bron 36ddec44af fix: typo in custom page separator parameter for LlamaParse (#1023) 2024-07-08 09:27:51 -07:00
github-actions[bot] c147d8a271 Release 0.4.14 (#1021)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-05 15:26:31 -07:00
Alex Yang 1c444d58b6 feat(cloud): update openapi.json (#1020) 2024-07-05 15:01:22 -07:00
github-actions[bot] 1f910f7566 Release 0.4.13 (#1016)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-05 11:44:37 -07:00
Thuc Pham 99826cff43 fix: missing dispatch retrieve event on llamacloud retriever (#1018) 2024-07-05 20:43:26 +07:00
Fabian Wimmer e8f8bea969 feat: add boundingBox and targetPages to LlamaParseReader (#1017) 2024-07-05 14:32:26 +07:00
Fabian Wimmer 304484b77a feat: add ignoreErrors flag to LlamaParse (#959)
Co-authored-by: Marcus Schiesser <marcus.schiesser@googlemail.com>
2024-07-04 20:51:05 +07:00
abgita 29fed77d58 Fixed a typo in the retriever description (#1009) 2024-07-04 20:15:20 +07:00
Alex Yang db070588c8 ci: fix setup pnpm (#1014) 2024-07-03 12:11:48 -07:00
github-actions[bot] 76deca7fea Release 0.4.12 (#1013)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-03 10:24:22 -07:00
Alex Yang f326ab86d2 chore: bump version 2024-07-03 10:20:46 -07:00
Cássio de Freitas e Silva ca8d9709e0 feat: add support for Meta LLMs in AWS Bedrock (#960) 2024-07-03 01:27:58 -07:00
github-actions[bot] e0af059221 Release 0.4.11 (#1008)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-02 15:07:03 -07:00
Alex Yang 8bf5b4acfd fix: llama parse input spreadsheet (#1007) 2024-07-02 14:48:51 -07:00
Alex Yang 93a003baa0 ci: pre release (#1005) 2024-07-02 00:40:45 -07:00
github-actions[bot] 5d9b0bd3f0 Release 0.4.10 (#1003)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-01 23:59:52 -07:00
Alex Yang 9a5525e1b3 refactor(core): migrate llms type (#1002) 2024-07-01 20:13:35 -07:00
Peron 7dce3d28d3 fix: disable External Filters for Gemini (#994)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-07-01 18:28:22 -07:00
github-actions[bot] d4c1482c1c Release 0.4.9 (#1001)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-01 17:20:47 -07:00
Alex Yang 3a96a483a6 fix: anthropic image input (#999) 2024-07-01 16:03:30 -07:00
Alex Yang 7467fce2d4 docs: remove cloudflare worker section (#1000) 2024-07-01 16:01:55 -07:00
github-actions[bot] 06af08cac4 Release 0.4.8 (#998)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-01 15:07:50 -07:00
Alex Yang 83ebdfb1c5 fix: next.js binding (#997) 2024-07-01 14:52:57 -07:00
github-actions[bot] 835b1ac000 Release 0.4.7 (#986)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-28 22:58:14 -07:00
Alex Yang f10b41dbc1 chore: fix release files (#991) 2024-06-28 13:36:55 -07:00
Wassim Chegham 41fe871e2f feat: add support for azure dynamic session tool (#942)
Co-authored-by: Marcus Schiesser <marcus.schiesser@googlemail.com>
2024-06-27 13:18:05 -07:00
Alex Yang 321c39ddc7 fix: generate api as class (#988) 2024-06-27 09:58:00 -07:00
Alex Yang f7f1af0139 fix: llamacloud sdk edge case (#985) 2024-06-26 23:10:04 -07:00
github-actions[bot] a8c9c279d6 Release 0.4.6 (#981)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-26 17:22:28 -07:00
Alex Yang eece129831 feat: migrate @llamaindex/cloud package (#984) 2024-06-26 16:51:47 -07:00
Alex Yang 80e4f51a83 fix: remove check-minor-version.mjs
We no longer need that
2024-06-26 15:31:08 -07:00
Alex Yang 22ff0837c3 feat: init @llamaindex/core (#938) 2024-06-26 15:28:57 -07:00
Alex Yang 74d7e05bcb ci: continue when commit lockfile error (#982) 2024-06-26 11:06:06 -07:00
Parham Saidi 1feb23bb83 feat: added Gemini tool calling support (#973) 2024-06-26 10:49:11 -07:00
Marcus Schiesser 08c55ec258 fix: Add metadata to PDFs and use Uint8Array for readers content (#980) 2024-06-26 10:16:23 -07:00
github-actions[bot] 394e797567 Release 0.4.5 (#979)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-26 17:42:19 +07:00
Parham Saidi 6c3e5d08b8 fix: switch to correct reference for a static function (#978) 2024-06-26 17:35:22 +07:00
github-actions[bot] 6e19482814 Release 0.4.4 (#977)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-26 14:46:48 +07:00
Marcus Schiesser 42eb73a08f fix: IngestionPipeline not working without vectorStores (#976) 2024-06-26 14:30:58 +07:00
github-actions[bot] 4b59ffee45 Release 0.4.3 (#971)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-25 15:38:10 -07:00
Alex Yang d4e853c8b5 fix: stronger type declaration (#975) 2024-06-25 15:22:13 -07:00
Alex Yang a94b8ec3d2 chore: fix misc (#974) 2024-06-25 14:41:26 -07:00
Alex Yang ed57e6b7be docs: remove i18n temporary (#972) 2024-06-25 14:00:07 -07:00
Alex Yang 05f006e7e1 chore: fix llamaindex version 2024-06-25 12:21:22 -07:00
Alex Yang c3aed72c29 chore: skip install when releasing new version 2024-06-25 12:08:53 -07:00
Alex Yang 7deba94e6b chore: fix lock file 2024-06-25 11:57:04 -07:00
github-actions[bot] d15811f09f Release 0.4.2 (#966)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-25 11:23:01 -07:00
Tasmiyah Iqbal 2ef62a93bb feat: added support for embeddings via HuggingFace Inference API (#929) 2024-06-25 11:16:41 -07:00
Fabian Wimmer 9015aea527 docs: LlamaParse JSON + SimpleDirectoryReader (#970) 2024-06-25 11:16:27 -07:00
Emanuel Ferreira 4bb401e6f9 feat: upgrade llamacloud index (#944)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-06-25 10:52:06 -07:00
Parham Saidi a87a4d1222 feat: tool calling for Bedrock's Claude and General LLM Agent (#955) 2024-06-25 10:51:40 -07:00
Marcus Schiesser d27ad16335 test: add e2e test for nextjs/node with tokenizer (#963) 2024-06-25 10:02:01 -07:00
Marcus Schiesser 20498a2bce fix: use tiktoken instead of tiktoken/lite (#967) 2024-06-25 09:51:08 -07:00
Andy Garvin 0730140e62 fix: include node relationships when converting jsonToDoc (#968) 2024-06-25 22:59:16 +07:00
Andy Garvin 810711d355 docs: change references from core package to llamaindex (#969) 2024-06-25 22:55:37 +07:00
Marcus Schiesser f3b34b457c docs: add changeset (#965) 2024-06-25 21:36:00 +07:00
Fabian Wimmer 6f4b9f3372 docs: fix broken links, add API References (#962) 2024-06-24 19:10:16 -07:00
Fabian Wimmer 01658fdb31 docs: update data loaders (#961) 2024-06-24 10:45:17 -07:00
Alex Yang 66c26d9cce fix: json import (#958) 2024-06-21 11:27:08 -07:00
Marcus Schiesser a4060a7914 docs: update anthropic examples to use claude 3.5 (#954) 2024-06-21 17:27:56 +07:00
1580 changed files with 25098 additions and 90106 deletions
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
+28
View File
@@ -0,0 +1,28 @@
name: Publish Preview
on: [pull_request]
jobs:
pre_release:
name: Pre Release
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm run build
- name: Pre Release
run: pnpx pkg-pr-new publish ./packages/*
-36
View File
@@ -1,36 +0,0 @@
name: Publish
on:
push:
branches:
- main
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Publish @llamaindex/env
run: npx jsr publish
working-directory: packages/env
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Publish @llamaindex/core
run: npx jsr publish --allow-slow-types
working-directory: packages/llamaindex
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
+14 -1
View File
@@ -15,7 +15,7 @@ jobs:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -55,3 +55,16 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
# Refs: https://github.com/changesets/changesets/issues/421
- name: Update lock file
continue-on-error: true
run: pnpm install --lockfile-only
- name: Commit lock file
continue-on-error: true
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "chore: update lock file"
branch: changeset-release/main
file_pattern: "pnpm-lock.yaml"
+12 -5
View File
@@ -23,7 +23,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -45,7 +45,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -60,7 +60,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -91,12 +91,13 @@ jobs:
- cloudflare-worker-agent
- nextjs-agent
- nextjs-edge-runtime
- nextjs-node-runtime
# - waku-query-engine
runs-on: ubuntu-latest
name: Build LlamaIndex Example (${{ matrix.packages }})
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -115,7 +116,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -127,6 +128,12 @@ jobs:
run: pnpm run build
- name: Copy examples
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
- name: Pack @llamaindex/cloud
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/cloud
- name: Pack @llamaindex/core
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/core
- name: Pack @llamaindex/env
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/env
+3
View File
@@ -48,3 +48,6 @@ playwright/.cache/
# intellij
**/.idea
# generated API
packages/cloud/src/client
+3 -3
View File
@@ -6,7 +6,7 @@ This is a monorepo built with Turborepo
Right now there are two packages of importance:
packages/core which is the main NPM library llamaindex
packages/llamaindex which is the main NPM library llamaindex
examples is where the demo code lives
@@ -41,7 +41,7 @@ To run them, run
pnpm run test
```
To write new test cases write them in [packages/core/src/tests](/packages/llamaindex/src/tests)
To write new test cases write them in [packages/llamaindex/tests](/packages/llamaindex/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
@@ -56,7 +56,7 @@ You can create new demo applications in the apps folder. Just run pnpm init in t
To install packages for a specific package or demo application, run
```
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
pnpm add [NPM Package] --filter [package or application i.e. llamaindex or docs]
```
To install packages for every package or application run
+1 -35
View File
@@ -76,7 +76,7 @@ main();
node --import tsx ./main.ts
```
### Next.js
### React Server Component (Next.js, Waku, Redwood.JS...)
First, you will need to add a llamaindex plugin to your Next.js project.
@@ -154,40 +154,6 @@ export async function chatWithAgent(
}
```
### Cloudflare Workers
```ts
// src/index.ts
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const { setEnvs } = await import("@llamaindex/env");
// set environment variables so that the OpenAIAgent can use them
setEnvs(env);
const { OpenAIAgent } = await import("llamaindex");
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: "Hello? What is the weather today?",
});
const textEncoder = new TextEncoder();
const response = responseStream.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(textEncoder.encode(chunk.response.delta));
},
}),
);
return new Response(response);
},
};
```
## Playground
Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
+122
View File
@@ -1,5 +1,127 @@
# docs
## 0.0.43
### Patch Changes
- llamaindex@0.5.2
## 0.0.42
### Patch Changes
- 2774681: Add mixedbread's embeddings and reranking API
- Updated dependencies [2774681]
- Updated dependencies [a0f424e]
- llamaindex@0.5.1
## 0.0.41
### Patch Changes
- 36ddec4: fix: typo in custom page separator parameter for LlamaParse
- Updated dependencies [16ef5dd]
- Updated dependencies [16ef5dd]
- Updated dependencies [36ddec4]
- llamaindex@0.5.0
- @llamaindex/examples@0.0.7
## 0.0.40
### Patch Changes
- llamaindex@0.4.14
## 0.0.39
### Patch Changes
- Updated dependencies [e8f8bea]
- Updated dependencies [304484b]
- llamaindex@0.4.13
## 0.0.38
### Patch Changes
- Updated dependencies [f326ab8]
- llamaindex@0.4.12
## 0.0.37
### Patch Changes
- Updated dependencies [8bf5b4a]
- llamaindex@0.4.11
## 0.0.36
### Patch Changes
- Updated dependencies [7dce3d2]
- llamaindex@0.4.10
## 0.0.35
### Patch Changes
- Updated dependencies [3a96a48]
- llamaindex@0.4.9
## 0.0.34
### Patch Changes
- Updated dependencies [83ebdfb]
- llamaindex@0.4.8
## 0.0.33
### Patch Changes
- Updated dependencies [41fe871]
- Updated dependencies [321c39d]
- Updated dependencies [f7f1af0]
- llamaindex@0.4.7
## 0.0.32
### Patch Changes
- Updated dependencies [1feb23b]
- Updated dependencies [08c55ec]
- llamaindex@0.4.6
## 0.0.31
### Patch Changes
- Updated dependencies [6c3e5d0]
- llamaindex@0.4.5
## 0.0.30
### Patch Changes
- Updated dependencies [42eb73a]
- llamaindex@0.4.4
## 0.0.29
### Patch Changes
- Updated dependencies [2ef62a9]
- llamaindex@0.4.3
- @llamaindex/examples@0.0.6
## 0.0.28
### Patch Changes
- Updated dependencies [a87a4d1]
- Updated dependencies [0730140]
- llamaindex@0.4.2
## 0.0.27
### Patch Changes
+6
View File
@@ -0,0 +1,6 @@
# Gemini Agent
import CodeBlock from "@theme/CodeBlock";
import CodeSourceGemini from "!raw-loader!../../../../examples/gemini/agent.ts";
<CodeBlock language="ts">{CodeSourceGemini}</CodeBlock>
+2 -2
View File
@@ -32,7 +32,7 @@ LlamaIndex.TS help you prepare the knowledge base with a suite of data connector
![](../_static/concepts/indexing.jpg)
[**Data Loaders**](../modules/data_loader.md):
[**Data Loaders**](../modules/data_loaders/index.mdx):
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/documents_and_nodes/index.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.
@@ -62,7 +62,7 @@ These building blocks can be customized to reflect ranking preferences, as well
[**Retrievers**](../modules/retriever.md):
A retriever defines how to efficiently retrieve relevant context from a knowledge base (i.e. index) when given a query.
The specific retrieval logic differs for difference indices, the most popular being dense retrieval against a vector index.
The specific retrieval logic differs for different indices, the most popular being dense retrieval against a vector index.
[**Response Synthesizers**](../modules/response_synthesizer.md):
A response synthesizer generates a response from an LLM, using a user query and a given set of retrieved text chunks.
@@ -21,7 +21,7 @@ npm install -D typescript @types/node
Then, check out the [installation](../installation) steps to install LlamaIndex.TS and prepare an OpenAI key.
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
You can use [other LLMs](../../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Run queries
@@ -7,9 +7,9 @@ import CodeSource from "!raw-loader!../../../../../examples/jsonExtract";
# Structured data extraction tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](../installation) guide.
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
You can use [other LLMs](../../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Set up
+9 -1
View File
@@ -12,9 +12,17 @@ An “agent” is an automated reasoning and decision engine. It takes in a user
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
- OpenAI Agent
- Anthropic Agent
- Anthropic Agent both via Anthropic and Bedrock (in `@llamaIndex/community`)
- Gemini Agent
- ReACT Agent
## Examples
- [OpenAI Agent](../../examples/agent.mdx)
- [Gemini Agent](../../examples/agent_gemini.mdx)
## Api References
- [OpenAIAgent](../../api/classes/OpenAIAgent.md)
- [AnthropicAgent](../../api/classes/AnthropicAgent.md)
- [ReActAgent](../../api/classes/ReActAgent.md)
-68
View File
@@ -1,68 +0,0 @@
---
sidebar_position: 4
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/readers/src/simple-directory-reader";
import CodeSource2 from "!raw-loader!../../../../examples/readers/src/custom-simple-directory-reader";
import CodeSource3 from "!raw-loader!../../../../examples/readers/src/llamaparse";
import CodeSource4 from "!raw-loader!../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
# Loader
Before you can start indexing your documents, you need to load them into memory.
### SimpleDirectoryReader
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
It is a simple reader that reads all files from a directory and its subdirectories.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Currently, it supports reading `.txt`, `.pdf`, `.csv`, `.md`, `.docx`, `.htm`, `.html`, `.jpg`, `.jpeg`, `.png` and `.gif` files, but support for other file types is planned.
You can override the default reader for all file types, inlcuding unsupported ones, with the `overrideReader` option.
Additionally, you can override the default reader for specific file types or add support for additional file types with the `fileExtToReader` option.
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions. By default it is `TextFileReader`.
SimpleDirectoryReader supports up to 9 concurrent requests. Use the `numWorkers` option to set the number of concurrent requests. By default it runs in sequential mode, i.e. set to 1.
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
{CodeSource2}
</CodeBlock>
### LlamaParse
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key as `apiKey` parameter or in the environment variable `LLAMA_CLOUD_API_KEY`.
Then, you can use the `LlamaParseReader` class to local files and convert them into a parsed document that can be used by LlamaIndex.
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/LlamaParseReader.ts#L6) for a list of supported file types:
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
Additional options can be set with the `LlamaParseReader` constructor:
- `resultType` can be set to `markdown`, `text` or `.json`. Defaults to `text`
- `language` primarly helps with OCR recognition. Defaults to `en`. See [../readers/type.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/type.ts#L20) for a list of supported languages.
- `parsingInstructions` can help with complicated document structures. See this [LlamaIndex Blog Post](https://www.llamaindex.ai/blog/launching-the-first-genai-native-document-parsing-platform) for an example.
- `skipDiagonalText` set to true to ignore diagonal text.
- `invalidateCache` set to true to ignore the LlamaCloud cache. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice. Can be useful for testing when trying to re-parse the same document with, e.g. different `parsingInstructions`.
- `gpt4oMode` set to true to use GPT-4o to extract content.
- `gpt4oApiKey` set the GPT-4o API key. Optional. Lowers the cost of parsing by using your own API key. Your OpenAI account will be charged. Can also be set in the environment variable `LLAMA_CLOUD_GPT4O_API_KEY`.
- `numWorkers` as in the python version, is set in `SimpleDirectoryReader`. Default is 1.
## LlamaParse with SimpleDirectoryReader
Below a full example of `LlamaParse` integrated in `SimpleDirectoryReader` with additional options.
<CodeBlock language="ts">{CodeSource4}</CodeBlock>
## API Reference
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
- [LlamaParseReader](../api/classes/LlamaParseReader.md)
@@ -0,0 +1,2 @@
label: "Loaders"
position: 1
@@ -0,0 +1,37 @@
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/readers/src/simple-directory-reader";
import CodeSource2 from "!raw-loader!../../../../../examples/readers/src/custom-simple-directory-reader";
# Loader
Before you can start indexing your documents, you need to load them into memory.
## SimpleDirectoryReader
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
It is a simple reader that reads all files from a directory and its subdirectories.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Currently, it supports reading `.txt`, `.pdf`, `.csv`, `.md`, `.docx`, `.htm`, `.html`, `.jpg`, `.jpeg`, `.png` and `.gif` files, but support for other file types is planned.
You can modify the reader three different ways:
- `overrideReader` overrides the reader for all file types, including unsupported ones.
- `fileExtToReader` maps a reader to a specific file type. Can override reader for existing file types or add support for new file types.
- `defaultReader` sets a fallback reader for files with unsupported extensions. By default it is `TextFileReader`.
SimpleDirectoryReader supports up to 9 concurrent requests. Use the `numWorkers` option to set the number of concurrent requests. By default it runs in sequential mode, i.e. set to 1.
### Example
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
{CodeSource2}
</CodeBlock>
## API Reference
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
@@ -0,0 +1 @@
label: "LlamaParse"
@@ -0,0 +1,117 @@
---
sidebar_position: 2
---
# Image Retrieval
LlamaParse `json` mode supports extracting any images found in a page object by using the `getImages` function. They are downloaded to a local folder and can then be sent to a multimodal LLM for further processing.
## Usage
We use the `getImages` method to input our array of JSON objects, download the images to a specified folder and get a list of ImageNodes.
```ts
const reader = new LlamaParseReader();
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
const imageDicts = await reader.getImages(jsonObjs, "images");
```
### Multimodal Indexing
You can create an index across both text and image nodes by requesting alternative text for the image from a multimodal LLM.
```ts
import {
Document,
ImageNode,
LlamaParseReader,
OpenAI,
VectorStoreIndex,
} from "llamaindex";
import { createMessageContent } from "llamaindex/synthesizers/utils";
const reader = new LlamaParseReader();
async function main() {
// Load PDF using LlamaParse JSON mode and return an array of json objects
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
// Access the first "pages" (=a single parsed file) object in the array
const jsonList = jsonObjs[0]["pages"];
const textDocs = getTextDocs(jsonList);
const imageTextDocs = await getImageTextDocs(jsonObjs);
const documents = [...textDocs, ...imageTextDocs];
// Split text, create embeddings and query the index
const index = await VectorStoreIndex.fromDocuments(documents);
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query:
"What does the bar graph titled 'Monthly Active Platform Consumers' show?",
});
console.log(response.toString());
}
main().catch(console.error);
```
We use two helper functions to create documents from the text and image nodes provided.
#### Text Documents
To create documents from the text nodes of the json object, we just map the needed values to a new `Document` object. In this case we assign the text as text and the page number as metadata.
```ts
function getTextDocs(jsonList: { text: string; page: number }[]): Document[] {
return jsonList.map(
(page) => new Document({ text: page.text, metadata: { page: page.page } }),
);
}
```
#### Image Documents
To create documents from the images, we need to use a multimodal LLM to generate alt text.
For this we create `ImageNodes` and add them as part of our message.
We can use the `createMessageContent` function to simplify this.
```ts
async function getImageTextDocs(
jsonObjs: Record<string, any>[],
): Promise<Document[]> {
const llm = new OpenAI({
model: "gpt-4o",
temperature: 0.2,
maxTokens: 1000,
});
const imageDicts = await reader.getImages(jsonObjs, "images");
const imageDocs = [];
for (const imageDict of imageDicts) {
const imageDoc = new ImageNode({ image: imageDict.path });
const prompt = () => `Describe the image as alt text`;
const message = await createMessageContent(prompt, [imageDoc]);
const response = await llm.complete({
prompt: message,
});
const doc = new Document({
text: response.text,
metadata: { path: imageDict.path },
});
imageDocs.push(doc);
}
return imageDocs;
}
```
The returned `imageDocs` have the alt text assigned as text and the image path as metadata.
You can see the full example file [here](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/readers/src/llamaparse-json.ts).
## API Reference
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
@@ -0,0 +1,60 @@
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../../examples/readers/src/llamaparse";
import CodeSource2 from "!raw-loader!../../../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
# LlamaParse
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key as `apiKey` parameter or in the environment variable `LLAMA_CLOUD_API_KEY`.
Official documentation for LlamaParse can be found [here](https://docs.cloud.llamaindex.ai/).
## Usage
You can then use the `LlamaParseReader` class to load local files and convert them into a parsed document that can be used by LlamaIndex.
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/llamaindex/src/readers/LlamaParseReader.ts) for a list of supported file types:
<CodeBlock language="ts">{CodeSource}</CodeBlock>
### Params
All options can be set with the `LlamaParseReader` constructor.
They can be divided into two groups.
#### General params:
- `apiKey` is required. Can be set as an environment variable `LLAMA_CLOUD_API_KEY`
- `checkInterval` is the interval in seconds to check if the parsing is done. Default is `1`.
- `maxTimeout` is the maximum timeout to wait for parsing to finish. Default is `2000`
- `verbose` shows progress of the parsing. Default is `true`
- `ignoreErrors` set to false to get errors while parsing. Default is `true` and returns an empty array on error.
#### Advanced params:
- `resultType` can be set to `markdown`, `text` or `json`. Defaults to `text`. More information about `json` mode on the next pages.
- `language` primarily helps with OCR recognition. Defaults to `en`. Click [here](../../../api/type-aliases/Language.md) for a list of supported languages.
- `parsingInstructions?` Optional. Can help with complicated document structures. See this [LlamaIndex Blog Post](https://www.llamaindex.ai/blog/launching-the-first-genai-native-document-parsing-platform) for an example.
- `skipDiagonalText?` Optional. Set to true to ignore diagonal text. (Text that is not rotated 0, 90, 180 or 270 degrees)
- `invalidateCache?` Optional. Set to true to ignore the LlamaCloud cache. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice. Can be useful for testing when trying to re-parse the same document with, e.g. different `parsingInstructions`.
- `doNotCache?` Optional. Set to true to not cache the document.
- `fastMode?` Optional. Set to true to use the fast mode. This mode will skip OCR of images, and table/heading reconstruction. Note: Non-compatible with `gpt4oMode`.
- `doNotUnrollColumns?` Optional. Set to true to keep the text according to document layout. Reduce reconstruction accuracy, and LLMs/embeddings performances in most cases.
- `pageSeparator?` Optional. The page separator to use. Defaults is `\\n---\\n`.
- `gpt4oMode` set to true to use GPT-4o to extract content. Default is `false`.
- `gpt4oApiKey?` Optional. Set the GPT-4o API key. Lowers the cost of parsing by using your own API key. Your OpenAI account will be charged. Can also be set in the environment variable `LLAMA_CLOUD_GPT4O_API_KEY`.
- `boundingBox?` Optional. Specify an area of the document to parse. Expects the bounding box margins as a string in clockwise order, e.g. `boundingBox = "0.1,0,0,0"` to not parse the top 10% of the document.
- `targetPages?` Optional. Specify which pages to parse by specifying them as a comma-separated list. First page is `0`.
- `numWorkers` as in the python version, is set in `SimpleDirectoryReader`. Default is 1.
### LlamaParse with SimpleDirectoryReader
Below a full example of `LlamaParse` integrated in `SimpleDirectoryReader` with additional options.
<CodeBlock language="ts">{CodeSource2}</CodeBlock>
## API Reference
- [SimpleDirectoryReader](../../../api/classes/SimpleDirectoryReader.md)
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
@@ -0,0 +1,95 @@
---
sidebar_position: 1
---
# JSON Mode
In JSON mode, LlamaParse will return a data structure representing the parsed object.
## Usage
For Json mode, you need to use `loadJson`. The `resultType` is automatically set with this method.
More information about indexing the results on the next page.
```ts
const reader = new LlamaParseReader();
async function main() {
// Load the file and return an array of json objects
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
// Access the first "pages" (=a single parsed file) object in the array
const jsonList = jsonObjs[0]["pages"];
// Further process the jsonList object as needed.
}
```
### Output
The result format of the response, written to `jsonObjs` in the example, follows this structure:
```json
{
"pages": [
..page objects..
],
"job_metadata": {
"credits_used": int,
"credits_max": int,
"job_credits_usage": int,
"job_pages": int,
"job_is_cache_hit": boolean
},
"job_id": string ,
"file_path": string,
}
}
```
#### Page objects
Within page objects, the following keys may be present depending on your document.
- `page`: The page number of the document.
- `text`: The text extracted from the page.
- `md`: The markdown version of the extracted text.
- `images`: Any images extracted from the page.
- `items`: An array of heading, text and table objects in the order they appear on the page.
### JSON Mode with SimpleDirectoryReader
All Readers share a `loadData` method with `SimpleDirectoryReader` that promises to return a uniform Document with Metadata. This makes JSON mode incompatible with SimpleDirectoryReader.
However, a simple work around is to create a new reader class that extends `LlamaParseReader` and adds a new method or overrides `loadData`, wrapping around JSON mode, extracting the required values, and returning a Document object.
```ts
import { LlamaParseReader, Document } from "llamaindex";
class LlamaParseReaderWithJson extends LlamaParseReader {
// Override the loadData method
override async loadData(filePath: string): Promise<Document[]> {
// Call loadJson method that was inherited by LlamaParseReader
const jsonObjs = await super.loadJson(filePath);
let documents: Document[] = [];
jsonObjs.forEach((jsonObj) => {
// Making sure it's an array before iterating over it
if (Array.isArray(jsonObj.pages)) {
}
const docs = jsonObj.pages.map(
(page: { text: string; page: number }) =>
new Document({ text: page.text, metadata: { page: page.page } }),
);
documents = documents.concat(docs);
});
return documents;
}
}
```
Now we have documents with page number as metadata. This new reader can be used like any other and be integrated with SimpleDirectoryReader. Since it extends `LlamaParseReader`, you can use the same params.
You can assign any other values of the JSON response to the Document as needed.
## API Reference
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
- [SimpleDirectoryReader](../../../api/classes/SimpleDirectoryReader.md)
@@ -14,5 +14,5 @@ document = new Document({ text: "text", metadata: { key: "val" } });
## API Reference
- [Document](../api/classes/Document.md)
- [TextNode](../api/classes/TextNode.md)
- [Document](../../api/classes/Document.md)
- [TextNode](../../api/classes/TextNode.md)
@@ -43,3 +43,10 @@ async function main() {
main().then(() => console.log("done"));
```
## API Reference
- [SummaryExtractor](../../api/classes/SummaryExtractor.md)
- [QuestionsAnsweredExtractor](../../api/classes/QuestionsAnsweredExtractor.md)
- [TitleExtractor](../../api/classes/TitleExtractor.md)
- [KeywordExtractor](../../api/classes/KeywordExtractor.md)
@@ -77,3 +77,7 @@ main();
```
For questions or feedback, please contact us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
## API Reference
- [DeepInfraEmbedding](../../../api/classes/DeepInfraEmbedding.md)
@@ -31,3 +31,7 @@ Settings.embedModel = new GeminiEmbedding({
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
});
```
## API Reference
- [GeminiEmbedding](../../../api/classes/GeminiEmbedding.md)
@@ -32,3 +32,7 @@ Settings.embedModel = new HuggingFaceEmbedding({
quantized: false,
});
```
## API Reference
- [HuggingFaceEmbedding](../../../api/classes/HuggingFaceEmbedding.md)
@@ -19,3 +19,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [JinaAIEmbedding](../../../api/classes/JinaAIEmbedding.md)
@@ -22,3 +22,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [MistralAIEmbedding](../../../api/classes/MistralAIEmbedding.md)
@@ -0,0 +1,100 @@
# MixedbreadAI
Welcome to the mixedbread embeddings guide! This guide will help you use the mixedbread ai's API to generate embeddings for your text documents, ensuring you get the most relevant information, just like picking the freshest bread from the bakery.
To find out more about the latest features, updates, and available models, visit [mixedbread.ai](https://mixedbread-ai.com/).
## Table of Contents
1. [Setup](#setup)
2. [Usage with LlamaIndex](#integration-with-llamaindex)
3. [Embeddings with Custom Parameters](#embeddings-with-custom-parameters)
## Setup
First, you will need to install the `llamaindex` package.
```bash
pnpm install llamaindex
```
Next, sign up for an API key at [mixedbread.ai](https://mixedbread.ai/). Once you have your API key, you can import the necessary modules and create a new instance of the `MixedbreadAIEmbeddings` class.
```ts
import { MixedbreadAIEmbeddings, Document, Settings } from "llamaindex";
```
## Usage with LlamaIndex
This section will guide you through integrating mixedbread embeddings with LlamaIndex for more advanced usage.
### Step 1: Load and Index Documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index, like a variety of breads in a bakery.
```ts
Settings.embedModel = new MixedbreadAIEmbeddings({
apiKey: "<MIXEDBREAD_API_KEY>",
model: "mixedbread-ai/mxbai-embed-large-v1",
});
const document = new Document({
text: "The true source of happiness.",
id_: "bread",
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
### Step 2: Create a Query Engine
Combine the retriever and the embed model to create a query engine. This setup ensures that your queries are processed to provide the best results, like arranging the bread in the order of freshness and quality.
Models can require prompts to generate embeddings for queries, in the 'mixedbread-ai/mxbai-embed-large-v1' model's case, the prompt is `Represent this sentence for searching relevant passages:`.
```ts
const queryEngine = index.asQueryEngine();
const query =
"Represent this sentence for searching relevant passages: What is bread?";
// Log the response
const results = await queryEngine.query(query);
console.log(results); // Serving up the freshest, most relevant results.
```
## Embeddings with Custom Parameters
This section will guide you through generating embeddings with custom parameters and usage with f.e. matryoshka and binary embeddings.
### Step 1: Create an Instance of MixedbreadAIEmbeddings
Create a new instance of the `MixedbreadAIEmbeddings` class with custom parameters. For example, to use the `mixedbread-ai/mxbai-embed-large-v1` model with a batch size of 64, normalized embeddings, and binary encoding format:
```ts
const embeddings = new MixedbreadAIEmbeddings({
apiKey: "<MIXEDBREAD_API_KEY>",
model: "mixedbread-ai/mxbai-embed-large-v1",
batchSize: 64,
normalized: true,
dimensions: 512,
encodingFormat: MixedbreadAI.EncodingFormat.Binary,
});
```
### Step 2: Define Texts
Define the texts you want to generate embeddings for.
```ts
const texts = ["Bread is life", "Bread is love"];
```
### Step 3: Generate Embeddings
Use the `embedDocuments` method to generate embeddings for the texts.
```ts
const result = await embeddings.embedDocuments(texts);
console.log(result); // Perfectly customized embeddings, ready to serve.
```
@@ -27,3 +27,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [OllamaEmbedding](../../../api/classes/OllamaEmbedding.md)
@@ -19,3 +19,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [OpenAIEmbedding](../../../api/classes/OpenAIEmbedding.md)
@@ -21,3 +21,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [TogetherEmbedding](../../../api/classes/TogetherEmbedding.md)
@@ -56,3 +56,7 @@ console.log(
```bash
the response is not correct with a score of 2.5
```
## API Reference
- [CorrectnessEvaluator](../../../api/classes/CorrectnessEvaluator.md)
@@ -76,3 +76,7 @@ console.log(`the response is ${result.passing ? "faithful" : "not faithful"}`);
```bash
the response is faithful
```
## API Reference
- [FaithfulnessEvaluator](../../../api/classes/FaithfulnessEvaluator.md)
@@ -70,3 +70,7 @@ console.log(`the response is ${result.passing ? "relevant" : "not relevant"}`);
```bash
the response is relevant
```
## API Reference
- [RelevancyEvaluator](../../../api/classes/RelevancyEvaluator.md)
@@ -97,3 +97,7 @@ async function main() {
main().catch(console.error);
```
## API Reference
- [IngestionPipeline](../../api/classes/IngestionPipeline.md)
@@ -4,9 +4,9 @@ A transformation is something that takes a list of nodes as an input, and return
Currently, the following components are Transformation objects:
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
- [SimpleNodeParser](../../api/classes/SimpleNodeParser.md)
- [MetadataExtractor](../documents_and_nodes/metadata_extraction.md)
- Embeddings
- [Embeddings](../embeddings/index.md)
## Usage Pattern
@@ -63,3 +63,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Anthropic](../../../api/classes/Anthropic.md)
@@ -74,3 +74,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [OpenAI](../../../api/classes/OpenAI.md)
@@ -15,7 +15,7 @@ Settings.llm = new Bedrock({
});
```
Currently only supports Anthropic models:
Currently only supports Anthropic and Meta models:
```ts
ANTHROPIC_CLAUDE_INSTANT_1 = "anthropic.claude-instant-v1";
@@ -25,6 +25,10 @@ ANTHROPIC_CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0";
ANTHROPIC_CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0";
ANTHROPIC_CLAUDE_3_OPUS = "anthropic.claude-3-opus-20240229-v1:0"; // available on us-west-2
ANTHROPIC_CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-20240620-v1:0";
META_LLAMA2_13B_CHAT = "meta.llama2-13b-chat-v1";
META_LLAMA2_70B_CHAT = "meta.llama2-70b-chat-v1";
META_LLAMA3_8B_INSTRUCT = "meta.llama3-8b-instruct-v1:0";
META_LLAMA3_70B_INSTRUCT = "meta.llama3-70b-instruct-v1:0";
```
Sonnet, Haiku and Opus are multimodal, image_url only supports base64 data url format, e.g. `data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ==`
@@ -81,3 +81,7 @@ async function main() {
## Feedback
If you have any feedback, please reach out to us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
## API Reference
- [DeepInfra](../../../api/classes/DeepInfra)
@@ -59,3 +59,7 @@ async function main() {
main().catch(console.error);
```
## API Reference
- [FireworksLLM](../../../api/classes/FireworksLLM.md)
@@ -99,3 +99,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Gemini](../../../api/classes/Gemini.md)
@@ -50,3 +50,7 @@ const results = await queryEngine.query({
<CodeBlock language="ts" showLineNumbers>
{CodeSource}
</CodeBlock>
## API Reference
- [Groq](../../../api/classes/Groq.md)
@@ -89,3 +89,8 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [LlamaDeuce](../../../api/variables/LlamaDeuce.md)
- [DeuceChatStrategy](../../../api/variables/DeuceChatStrategy.md)
@@ -66,3 +66,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [MistralAI](../../../api/classes/MistralAI.md)
@@ -71,3 +71,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Ollama](../../../api/classes/Ollama.md)
@@ -67,3 +67,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [OpenAI](../../../api/classes/OpenAI.md)
@@ -68,3 +68,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Portkey](../../../api/classes/Portkey.md)
@@ -66,3 +66,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [TogetherLLM](../../../api/classes/TogetherLLM.md)
+1 -1
View File
@@ -32,4 +32,4 @@ For local LLMs, currently we recommend the use of [Ollama](./available_llms/olla
## API Reference
- [OpenAI](../api/classes/OpenAI.md)
- [OpenAI](../../api/classes/OpenAI.md)
+1
View File
@@ -95,3 +95,4 @@ The output metadata will be something like:
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
- [SentenceSplitter](../api/classes/SentenceSplitter.md)
- [MarkdownNodeParser](../api/classes/MarkdownNodeParser.md)
@@ -65,3 +65,7 @@ const queryEngine = index.asQueryEngine({
// log the response
const response = await queryEngine.query("Where did the author grown up?");
```
## API Reference
- [CohereRerank](../../api/classes/CohereRerank.md)
@@ -103,3 +103,7 @@ const processor = new SimilarityPostprocessor({
const filteredNodes = processor.postprocessNodes(nodes);
```
## API Reference
- [SimilarityPostprocessor](../../api/classes/SimilarityPostprocessor.md)
@@ -69,3 +69,7 @@ const queryEngine = index.asQueryEngine({
// log the response
const response = await queryEngine.query("Where did the author grown up?");
```
## API Reference
- [JinaAIReranker](../../api/classes/JinaAIReranker.md)
@@ -0,0 +1,164 @@
# MixedbreadAI
Welcome to the mixedbread ai reranker guide! This guide will help you use mixedbread ai's API to rerank search query results, ensuring you get the most relevant information, just like picking the freshest bread from the bakery.
To find out more about the latest features and updates, visit the [mixedbread.ai](https://mixedbread.ai/).
## Table of Contents
1. [Setup](#setup)
2. [Usage with LlamaIndex](#integration-with-llamaindex)
3. [Simple Reranking Guide](#simple-reranking-guide)
4. [Reranking with Objects](#reranking-with-objects)
## Setup
First, you will need to install the `llamaindex` package.
```bash
pnpm install llamaindex
```
Next, sign up for an API key at [mixedbread.ai](https://mixedbread.ai/). Once you have your API key, you can import the necessary modules and create a new instance of the `MixedbreadAIReranker` class.
```ts
import {
MixedbreadAIReranker,
Document,
OpenAI,
VectorStoreIndex,
Settings,
} from "llamaindex";
```
## Usage with LlamaIndex
This section will guide you through integrating mixedbread's reranker with LlamaIndex.
### Step 1: Load and Index Documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index, like a variety of breads in a bakery.
```ts
const document = new Document({
text: "This is a sample document.",
id_: "sampleDoc",
});
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const index = await VectorStoreIndex.fromDocuments([document]);
```
### Step 2: Increase Similarity TopK
The default value for `similarityTopK` is 2, which means only the most similar document will be returned. To get more results, like picking a variety of fresh breads, you can increase the value of `similarityTopK`.
```ts
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
```
### Step 3: Create a MixedbreadAIReranker Instance
Create a new instance of the `MixedbreadAIReranker` class.
```ts
const nodePostprocessor = new MixedbreadAIReranker({
apiKey: "<MIXEDBREAD_API_KEY>",
topN: 4,
});
```
### Step 4: Create a Query Engine
Combine the retriever and node postprocessor to create a query engine. This setup ensures that your queries are processed and reranked to provide the best results, like arranging the bread in the order of freshness and quality.
```ts
const queryEngine = index.asQueryEngine({
retriever,
nodePostprocessors: [nodePostprocessor],
});
// Log the response
const response = await queryEngine.query("Where did the author grow up?");
console.log(response);
```
With mixedbread's Reranker, you're all set to serve up the most relevant and well-ordered results, just like a skilled baker arranging their best breads for eager customers. Enjoy the perfect blend of technology and culinary delight!
## Simple Reranking Guide
This section will guide you through a simple reranking process using mixedbread ai.
### Step 1: Create an Instance of MixedbreadAIReranker
Create a new instance of the `MixedbreadAIReranker` class, passing in your API key and the number of results you want to return. It's like setting up your bakery to offer a specific number of freshly baked items.
```ts
const reranker = new MixedbreadAIReranker({
apiKey: "<MIXEDBREAD_API_KEY>",
topN: 4,
});
```
### Step 2: Define Nodes and Query
Define the nodes (documents) you want to rerank and the query.
```ts
const nodes = [
{ node: new BaseNode("To bake bread you need flour") },
{ node: new BaseNode("To bake bread you need yeast") },
];
const query = "What do you need to bake bread?";
```
### Step 3: Perform Reranking
Use the `postprocessNodes` method to rerank the nodes based on the query.
```ts
const result = await reranker.postprocessNodes(nodes, query);
console.log(result); // Like pulling freshly baked nodes out of the oven.
```
## Reranking with Objects
This section will guide you through reranking when working with objects.
### Step 1: Create an Instance of MixedbreadAIReranker
Create a new instance of the `MixedbreadAIReranker` class, just like before.
```ts
const reranker = new MixedbreadAIReranker({
apiKey: "<MIXEDBREAD_API_KEY>",
model: "mixedbread-ai/mxbai-rerank-large-v1",
topK: 5,
rankFields: ["title", "content"],
returnInput: true,
maxRetries: 5,
});
```
### Step 2: Define Documents and Query
Define the documents (objects) you want to rerank and the query.
```ts
const documents = [
{ title: "Bread Recipe", content: "To bake bread you need flour" },
{ title: "Bread Recipe", content: "To bake bread you need yeast" },
];
const query = "What do you need to bake bread?";
```
### Step 3: Perform Reranking
Use the `rerank` method to reorder the documents based on the query.
```ts
const result = await reranker.rerank(documents, query);
console.log(result); // Perfectly customized results, ready to serve.
```
+6
View File
@@ -70,3 +70,9 @@ const response = await queryEngine.query({
query: "What did the author do in college?",
});
```
## API Reference
- [TextQaPrompt](../../api/type-aliases/TextQaPrompt.md)
- [ResponseSynthesizer](../../api/classes/ResponseSynthesizer.md)
- [CompactAndRefine](../../api/classes/CompactAndRefine.md)
@@ -38,4 +38,4 @@ You can learn more about Tools by taking a look at the LlamaIndex Python documen
- [RetrieverQueryEngine](../../api/classes/RetrieverQueryEngine.md)
- [SubQuestionQueryEngine](../../api/classes/SubQuestionQueryEngine.md)
- [QueryEngineTool](../../api/interfaces/QueryEngineTool.md)
- [QueryEngineTool](../../api/classes/QueryEngineTool.md)
@@ -151,3 +151,8 @@ async function main() {
main();
```
## API Reference
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
- [ChromaVectorStore](../../api/classes/ChromaVectorStore.md)
@@ -165,3 +165,7 @@ async function main() {
main().then(() => console.log("Done"));
```
## API Reference
- [RouterQueryEngine](../../api/classes/RouterQueryEngine.md)
+1 -1
View File
@@ -23,4 +23,4 @@ const index = await VectorStoreIndex.fromDocuments([document], {
## API Reference
- [StorageContext](../api/interfaces//StorageContext.md)
- [StorageContext](../api/interfaces/StorageContext.md)
@@ -84,3 +84,7 @@ async function main() {
main().catch(console.error);
```
## API Reference
- [QdrantVectorStore](../../api/classes/QdrantVectorStore.md)
-24
View File
@@ -25,30 +25,6 @@ const config = {
onBrokenLinks: "warn",
onBrokenMarkdownLinks: "warn",
// Even if you don't use internalization, you can use this field to set useful
// metadata like html lang. For example, if your site is Chinese, you may want
// to replace "en" with "zh-Hans".
i18n: {
defaultLocale: "en",
locales: [
"en",
"zh-Hans",
"es",
"fr",
"de",
"ja",
"ko",
"pt",
"ar",
"it",
"tr",
"pl",
"nl",
"vi",
"th",
], // "fa", "ru", "ro", "sv", "hu", "cs", "el", "da", "fi", "he", "no", "hi", "in", "sl", "se", "sk", "uk", "bg", "hr", "lt", "lv", "et", "cat"
},
presets: [
[
"@docusaurus/preset-classic",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

@@ -1 +0,0 @@
../../../../docs/api
@@ -1,86 +0,0 @@
---
sidebar_position: 3
---
# المفاهيم على المستوى العالي
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يساعدك LlamaIndex.TS في بناء تطبيقات قائمة على LLM (مثل Q&A و chatbot) على بيانات مخصصة.
في هذا الدليل عن المفاهيم على المستوى العالي، ستتعلم:
- كيف يمكن لـ LLM الإجابة على الأسئلة باستخدام بياناتك الخاصة.
- المفاهيم الرئيسية والوحدات في LlamaIndex.TS لبناء خط أنابيب الاستعلام الخاص بك.
## الإجابة على الأسئلة عبر بياناتك
يستخدم LlamaIndex طريقة مكونة من مرحلتين عند استخدام LLM مع بياناتك:
1. **مرحلة الفهرسة**: إعداد قاعدة المعرفة، و
2. **مرحلة الاستعلام**: استرداد السياق ذي الصلة من المعرفة لمساعدة LLM في الاستجابة لسؤال
![](./_static/concepts/rag.jpg)
تُعرف هذه العملية أيضًا باسم "استرجاع معزز للتوليد" (RAG).
يوفر LlamaIndex.TS أدوات أساسية لجعل كلا المرحلتين سهلتين للغاية.
دعنا نستكشف كل مرحلة بالتفصيل.
### مرحلة الفهرسة
يساعدك LlamaIndex.TS في إعداد قاعدة المعرفة باستخدام مجموعة من موصلات البيانات والفهارس.
![](./_static/concepts/indexing.jpg)
[**محمّلات البيانات**](./modules/high_level/data_loader.md):
موصل البيانات (أي `Reader`) يقوم بتجميع البيانات من مصادر بيانات مختلفة وتنسيقات بيانات مختلفة في تمثيل بسيط للـ `Document` (نص وبيانات تعريفية بسيطة).
[**المستندات / العقد**](./modules/high_level/documents_and_nodes.md): المستند هو حاوية عامة حول أي مصدر بيانات - على سبيل المثال، ملف PDF، نتائج واجهة برمجة التطبيقات، أو بيانات استرداد من قاعدة بيانات. العقد هو الوحدة الذرية للبيانات في LlamaIndex ويمثل "قطعة" من المستند الأصلي. إنه تمثيل غني يتضمن بيانات تعريفية وعلاقات (مع عقد أخرى) لتمكين عمليات الاسترجاع الدقيقة والتعبيرية.
[**فهارس البيانات**](./modules/high_level/data_index.md):
بمجرد أن تقوم بتجميع بياناتك، يساعدك LlamaIndex في فهرسة البيانات في تنسيق سهل الاسترداد.
تحت الغطاء، يقوم LlamaIndex بتحليل المستندات الخام إلى تمثيلات وسيطة، وحساب تضمينات الناقلات، وتخزين بياناتك في الذاكرة أو على القرص.
"
### مرحلة الاستعلام
في مرحلة الاستعلام، يقوم خط الأنابيب للاستعلام بجلب السياق الأكثر صلة بناءً على استعلام المستخدم،
ويمرر ذلك إلى LLM (جنبًا إلى جنب مع الاستعلام) لتوليد استجابة.
يمنح ذلك LLM معرفة محدثة ليست موجودة في بيانات التدريب الأصلية لديه،
(مما يقلل أيضًا من الهلوسة).
التحدي الرئيسي في مرحلة الاستعلام هو الاسترجاع والتنسيق والاستدلال عبر قواعد المعرفة (المحتملة).
يوفر LlamaIndex وحدات قابلة للتركيب تساعدك في بناء ودمج خطوط أنابيب RAG لـ Q&A (محرك الاستعلام)، chatbot (محرك الدردشة)، أو كجزء من وكيل.
يمكن تخصيص هذه الكتل البنائية لتعكس تفضيلات التصنيف، وكذلك تركيبها للاستدلال عبر عدة قواعد معرفة بطريقة منظمة.
![](./_static/concepts/querying.jpg)
#### الكتل الأساسية
[**مسترجعات**](./modules/low_level/retriever.md):
يحدد المسترجع كيفية استرجاع السياق ذي الصلة بكفاءة من قاعدة المعرفة (أي الفهرس) عند إعطاء استعلام.
تختلف منطق الاسترجاع المحددة حسب الفهارس المختلفة، والأكثر شيوعًا هو الاسترجاع الكثيف ضد فهرس الناقل.
[**مركبات الاستجابة**](./modules/low_level/response_synthesizer.md):
تقوم مركبة الاستجابة بتوليد استجابة من LLM باستخدام استعلام المستخدم ومجموعة معينة من أجزاء النص المسترجعة.
"
#### خطوط الأنابيب
[**محركات الاستعلام**](./modules/high_level/query_engine.md):
محرك الاستعلام هو خط أنابيب شامل يتيح لك طرح الأسئلة على بياناتك.
يأخذ استعلامًا بلغة طبيعية ويعيد استجابة، جنبًا إلى جنب مع السياق المرجعي المسترجع والممرر إلى LLM.
[**محركات الدردشة**](./modules/high_level/chat_engine.md):
محرك الدردشة هو خط أنابيب شامل لإجراء محادثة مع بياناتك
(عدة تفاعلات بدلاً من سؤال وجواب واحد).
"
@@ -1,61 +0,0 @@
---
sidebar_position: 4
---
# أمثلة من البداية إلى النهاية
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
نقدم العديد من الأمثلة من البداية إلى النهاية باستخدام LlamaIndex.TS في المستودع
تحقق من الأمثلة أدناه أو جربها وأكملها في دقائق مع دروس تفاعلية على Github Codespace المقدمة من Dev-Docs [هنا](https://codespaces.new/team-dev-docs/lits-dev-docs-playground?devcontainer_path=.devcontainer%2Fjavascript_ltsquickstart%2Fdevcontainer.json):
## [محرك الدردشة](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/chatEngine.ts)
اقرأ ملفًا وتحدث عنه مع LLM.
## [فهرس الفيكتور](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndex.ts)
إنشاء فهرس فيكتور واستعلامه. سيستخدم فهرس الفيكتور التضمينات لاسترداد أعلى k عقد ذات صلة. بشكل افتراضي ، يكون k الأعلى هو 2.
"
## [مؤشر الملخص](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/summaryIndex.ts)
إنشاء مؤشر قائمة واستعلامه. يستخدم هذا المثال أيضًا `LLMRetriever` ، الذي سيستخدم LLM لتحديد أفضل العقد لاستخدامها عند إنشاء الإجابة.
"
## [حفظ / تحميل فهرس](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/storageContext.ts)
إنشاء وتحميل فهرس ناقل. يحدث التخزين المؤقت على القرص تلقائيًا في LlamaIndex.TS بمجرد إنشاء كائن سياق التخزين.
"
## [فهرس الناقل المخصص](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndexCustomize.ts)
إنشاء فهرس ناقل واستعلامه، مع تكوين `LLM` و `ServiceContext` و `similarity_top_k`.
"
## [OpenAI LLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/openai.ts)
أنشئ OpenAI LLM واستخدمه مباشرة للدردشة.
"
## [Llama2 DeuceLLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/llamadeuce.ts)
إنشاء Llama-2 LLM واستخدامه مباشرة للدردشة.
"
## [محرك استعلام الأسئلة الفرعية](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts)
يستخدم `محرك استعلام الأسئلة الفرعية` الذي يقسم الاستعلامات المعقدة إلى أسئلة فرعية متعددة، ثم يجمع الاستجابة عبر الإجابات على جميع الأسئلة الفرعية.
"
## [وحدات منخفضة المستوى](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/lowlevel.ts)
يستخدم هذا المثال العديد من المكونات منخفضة المستوى، مما يزيل الحاجة إلى محرك استعلام فعلي. يمكن استخدام هذه المكونات في أي مكان، في أي تطبيق، أو تخصيصها وتصنيفها الفرعي لتلبية احتياجاتك الخاصة.
@@ -1,17 +0,0 @@
---
sidebar_position: 5
---
# البيئات
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يدعم LlamaIndex حاليًا رسميًا NodeJS 18 و NodeJS 20.
## NextJS App Router
إذا كنت تستخدم معالج الطرق / الوظائف الخادمة في NextJS App Router ، فستحتاج إلى استخدام وضع NodeJS:
```js
export const runtime = "nodejs"; // الافتراضي
```
@@ -1,67 +0,0 @@
---
sidebar_position: 1
---
# التثبيت والإعداد
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
تأكد من أن لديك 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 الخاص بك إلى نظام التحكم في الإصدارات.
"
@@ -1,60 +0,0 @@
---
sidebar_position: 0
slug: /
---
# ما هو LlamaIndex.TS؟
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
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 على:
- Github: https://github.com/run-llama/LlamaIndexTS
- NPM: https://www.npmjs.com/package/llamaindex
"
## المجتمع
هل تحتاج إلى مساعدة؟ هل لديك اقتراح لميزة؟ انضم إلى مجتمع LlamaIndex:
- تويتر: https://twitter.com/llama_index
- ديسكورد: https://discord.gg/dGcwcsnxhU
@@ -1,22 +0,0 @@
---
sidebar_position: 4
---
# محرك الدردشة (ChatEngine)
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
محرك الدردشة هو طريقة سريعة وبسيطة للدردشة مع البيانات في الفهرس الخاص بك.
```typescript
const retriever = index.asRetriever();
const chatEngine = new ContextChatEngine({ retriever });
// بدء الدردشة
const response = await chatEngine.chat(query);
```
## مراجع الواجهة البرمجية
- [محرك الدردشة السياقي (ContextChatEngine)](../../api/classes/ContextChatEngine.md)
- [محرك الدردشة المكثف للأسئلة (CondenseQuestionChatEngine)](../../api/classes/ContextChatEngine.md)
@@ -1,27 +0,0 @@
---
sidebar_position: 2
---
# الفهرس
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
الفهرس هو الحاوية الأساسية والتنظيم لبياناتك. يدعم LlamaIndex.TS نوعين من الفهارس:
- `VectorStoreIndex` - سيقوم بإرسال أعلى `Node` الموجودة إلى LLM عند إنشاء استجابة. القيمة الافتراضية لأعلى `k` هي 2.
- `SummaryIndex` - سيقوم بإرسال كل `Node` في الفهرس إلى LLM لإنشاء استجابة.
```typescript
import { Document, VectorStoreIndex } from "llamaindex";
const document = new Document({ text: "اختبار" });
const index = await VectorStoreIndex.fromDocuments([document]);
```
## مرجع الواجهة البرمجية
- [SummaryIndex](../../api/classes/SummaryIndex.md)
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
"
@@ -1,19 +0,0 @@
---
sidebar_position: 1
---
# قارئ / محمل
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يدعم LlamaIndex.TS تحميل الملفات بسهولة من المجلدات باستخدام فئة `SimpleDirectoryReader`. حاليًا ، يتم دعم الملفات `.txt` ، `.pdf` ، `.csv` ، `.md` و `.docx` ، مع المزيد المخطط له في المستقبل!
```typescript
import { SimpleDirectoryReader } from "llamaindex";
documents = new SimpleDirectoryReader().loadData("./data");
```
## مرجع الواجهة البرمجية
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
@@ -1,22 +0,0 @@
---
sidebar_position: 0
---
# المستندات والعقد
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
`المستندات` و `العقد` هما العناصر الأساسية لأي فهرس. بينما يكون واجهة برمجة التطبيق (API) لهذه الكائنات مشابهة، يُمثل كائن `المستند` ملفات كاملة، بينما تكون `العقد` قطعًا أصغر من ذلك المستند الأصلي، والتي تكون مناسبة لـ LLM و Q&A.
```typescript
import { Document } from "llamaindex";
document = new Document({ text: "نص", metadata: { key: "val" } });
```
## مرجع الواجهة البرمجية
- [المستند (Document)](../../api/classes/Document.md)
- [نص العقد (TextNode)](../../api/classes/TextNode.md)
"
@@ -1,42 +0,0 @@
---
sidebar_position: 3
---
# محرك الاستعلامات (QueryEngine)
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يقوم محرك الاستعلامات بتجميع "Retriever" و "ResponseSynthesizer" في أنبوبة، والتي ستستخدم سلسلة الاستعلام لاسترداد العقد ومن ثم إرسالها إلى LLM لتوليد استجابة.
```typescript
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query("سلسلة الاستعلام");
```
## محرك الاستعلام للأسئلة الفرعية
الفكرة الأساسية لمحرك الاستعلام للأسئلة الفرعية هي تقسيم استعلام واحد إلى استعلامات متعددة، والحصول على إجابة لكل من تلك الاستعلامات، ثم دمج تلك الإجابات المختلفة في استجابة واحدة متسقة للمستخدم. يمكنك أن تفكر فيها كتقنية "فكر في ذلك خطوة بخطوة" ولكن بتكرار مصادر البيانات الخاصة بك!
### البدء
أسهل طريقة لبدء تجربة محرك الاستعلام للأسئلة الفرعية هي تشغيل ملف 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
"
## مرجع واجهة برمجة التطبيق (API)
- [محرك استعلام الاسترجاع (RetrieverQueryEngine)](../../api/classes/RetrieverQueryEngine.md)
- [محرك استعلام السؤال الفرعي (SubQuestionQueryEngine)](../../api/classes/SubQuestionQueryEngine.md)
- [أداة محرك الاستعلام (QueryEngineTool)](../../api/interfaces/QueryEngineTool.md)
@@ -1,33 +0,0 @@
# الوحدات الأساسية
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يوفر 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 هي تجريدات تتيح لك ذلك. مجتمعة، تشكل هذه التجريدات سياق التخزين. حاليًا، نسمح لك بالاحتفاظ بالتضمينات الخاصة بك في ملفات على نظام الملفات (أو نظام ملفات افتراضي في الذاكرة)، ولكننا نضيف أيضًا تكاملات مع قواعد بيانات المتجهات.
@@ -1,26 +0,0 @@
---
sidebar_position: 1
---
# تضمين
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يتولى النموذج المضمن في LlamaIndex إنشاء تمثيلات رقمية للنص. بشكل افتراضي ، ستستخدم LlamaIndex نموذج `text-embedding-ada-002` من OpenAI.
يمكن تعيين ذلك بشكل صريح في كائن `ServiceContext`.
```typescript
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
const openaiEmbeds = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
```
## مرجع الواجهة البرمجية
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
- [ServiceContext](../../api/interfaces/ServiceContext.md)
"
@@ -1,26 +0,0 @@
---
sidebar_position: 0
---
# LLM
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يتولى LLM قراءة النص وتوليد استجابات لغوية طبيعية للاستفسارات. بشكل افتراضي ، يستخدم LlamaIndex.TS `gpt-3.5-turbo`.
يمكن تعيين LLM بشكل صريح في كائن `ServiceContext`.
```typescript
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
```
## مرجع الواجهة البرمجية
- [OpenAI](../../api/classes/OpenAI.md)
- [ServiceContext](../../api/interfaces/ServiceContext.md)
"
@@ -1,37 +0,0 @@
---
sidebar_position: 3
---
# NodeParser (محلل العقدة)
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
`NodeParser` في LlamaIndex مسؤول عن تقسيم كائنات `Document` إلى كائنات `Node` أكثر إدارة. عند استدعاء `.fromDocuments()`, يتم استخدام `NodeParser` من `ServiceContext` للقيام بذلك تلقائيًا بالنسبة لك. بدلاً من ذلك ، يمكنك استخدامه لتقسيم المستندات مسبقًا.
```typescript
import { Document, SimpleNodeParser } from "llamaindex";
const nodeParser = new SimpleNodeParser();
const nodes = nodeParser.getNodesFromDocuments([
new Document({ text: "أنا عمري 10 سنوات. جون عمره 20 سنة." }),
]);
```
## TextSplitter (مقسم النص)
سيقوم مقسم النص الأساسي بتقسيم النص إلى جمل. يمكن أيضًا استخدامه كوحدة مستقلة لتقسيم النص الخام.
```typescript
import { SentenceSplitter } from "llamaindex";
const splitter = new SentenceSplitter({ chunkSize: 1 });
const textSplits = splitter.splitText("مرحبًا بالعالم");
```
## مرجع الواجهة البرمجية
- [SimpleNodeParser (محلل العقدة البسيط)](../../api/classes/SimpleNodeParser.md)
- [SentenceSplitter (مقسم الجمل)](../../api/classes/SentenceSplitter.md)
"
@@ -1,45 +0,0 @@
---
sidebar_position: 6
---
# مركب الاستجابة (ResponseSynthesizer)
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
مركب الاستجابة (ResponseSynthesizer) مسؤول عن إرسال الاستعلام والعقد وقوالب الاستفسار إلى LLM لتوليد استجابة. هناك بعض وسائط رئيسية لتوليد استجابة:
- `تحسين`: "إنشاء وتحسين" إجابة عن طريق المرور تتاليًا عبر كل قطعة نص مُسترجعة. يتم إجراء استدعاء LLM منفصل لكل عقدة. جيد للإجابات المفصلة.
- `مضغوط وتحسين` (الافتراضي): "ضغط" الاستفسار أثناء كل استدعاء LLM عن طريق حشو أكبر عدد ممكن من قطع النص التي يمكن أن تتناسب مع حجم الاستفسار الأقصى. إذا كان هناك الكثير من القطع لتعبئتها في استفسار واحد، "إنشاء وتحسين" إجابة عن طريق المرور بعدة استفسارات مضغوطة. نفس العملية كـ `تحسين`، ولكن يجب أن تؤدي إلى مزيد من استدعاءات LLM أقل.
- `ملخص الشجرة`: بناء شجرة بشكل متكرر بناءً على مجموعة من قطع النص والاستعلام، وإرجاع العقدة الجذرية كاستجابة. جيد لأغراض التلخيص.
- `منشئ الاستجابة البسيط`: تطبيق الاستعلام على كل قطعة نص وتجميع الاستجابات في مصفوفة. يعيد سلسلة متصلة من جميع الاستجابات. جيد عندما تحتاج إلى تشغيل نفس الاستعلام بشكل منفصل على كل قطعة نص.
```typescript
import { NodeWithScore, ResponseSynthesizer, TextNode } from "llamaindex";
const responseSynthesizer = new ResponseSynthesizer();
const nodesWithScore: NodeWithScore[] = [
{
node: new TextNode({ text: "أنا عمري 10 سنوات." }),
score: 1,
},
{
node: new TextNode({ text: "جون عمره 20 سنة." }),
score: 0.5,
},
];
const response = await responseSynthesizer.synthesize(
"ما هو عمري؟",
nodesWithScore,
);
console.log(response.response);
```
## مرجع الواجهة البرمجية
- [مركب الاستجابة (ResponseSynthesizer)](../../api/classes/ResponseSynthesizer.md)
- [تحسين (Refine)](../../api/classes/Refine.md)
- [مضغوط وتحسين (CompactAndRefine)](../../api/classes/CompactAndRefine.md)
- [ملخص الشجرة (TreeSummarize)](../../api/classes/TreeSummarize.md)
- [منشئ الاستجابة البسيط (SimpleResponseBuilder)](../../api/classes/SimpleResponseBuilder.md)
@@ -1,23 +0,0 @@
---
sidebar_position: 5
---
# الباحث (Retriever)
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
الباحث في LlamaIndex هو ما يُستخدم لاسترداد العقد (`Node`) من فهرس باستخدام سلسلة الاستعلام. سيقوم الباحث `VectorIndexRetriever` بجلب أعلى k عقد مشابهة. بينما سيقوم الباحث `SummaryIndexRetriever` بجلب جميع العقد بغض النظر عن الاستعلام.
```typescript
const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// جلب العقد!
const nodesWithScore = await retriever.retrieve({ query: "سلسلة الاستعلام" });
```
## مرجع الواجهة البرمجية (API Reference)
- [SummaryIndexRetriever](../../api/classes/SummaryIndexRetriever.md)
- [SummaryIndexLLMRetriever](../../api/classes/SummaryIndexLLMRetriever.md)
- [VectorIndexRetriever](../../api/classes/VectorIndexRetriever.md)
@@ -1,30 +0,0 @@
---
sidebar_position: 7
---
# التخزين
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
يعمل التخزين في LlamaIndex.TS تلقائيًا بمجرد تكوين كائن `StorageContext`. قم بتكوين `persistDir` وربطه بفهرس.
في الوقت الحالي ، يتم دعم حفظ وتحميل البيانات من القرص فقط ، مع وجود تكاملات مستقبلية مخططة!
```typescript
import { Document, VectorStoreIndex, storageContextFromDefaults } from "./src";
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
const document = new Document({ text: "نص اختبار" });
const index = await VectorStoreIndex.fromDocuments([document], {
storageContext,
});
```
## مرجع الواجهة البرمجية
- [StorageContext](../../api/interfaces/StorageContext.md)
"
@@ -1,58 +0,0 @@
---
sidebar_position: 2
---
# دليل البداية
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
بمجرد [تثبيت 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
"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

@@ -1 +0,0 @@
../../../../docs/api
@@ -1,86 +0,0 @@
---
sidebar_position: 3
---
# Високо ниво на концепции
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
LlamaIndex.TS ви помага да създавате приложения, базирани на LLM (например Q&A, чатбот) върху персонализирани данни.
В това ръководство за високо ниво на концепции ще научите:
- как LLM може да отговори на въпроси, използвайки вашите собствени данни.
- ключови концепции и модули в LlamaIndex.TS за създаване на ваша собствена заявка.
## Отговаряне на въпроси върху вашите данни
LlamaIndex използва двустепенен метод при използване на LLM с вашите данни:
1. **стъпка за индексиране**: подготовка на база от знания и
2. **стъпка за заявка**: извличане на съответния контекст от знанията, за да помогне на LLM да отговори на въпрос
![](./_static/concepts/rag.jpg)
Този процес е известен също като Retrieval Augmented Generation (RAG).
LlamaIndex.TS предоставя основния инструментариум, който прави и двете стъпки изключително лесни.
Нека изследваме всяка стъпка подробно.
### Стъпка на индексиране
LlamaIndex.TS ви помага да подготвите базата от знания с помощта на набор от конектори за данни и индекси.
![](./_static/concepts/indexing.jpg)
[**Data Loaders**](./modules/high_level/data_loader.md):
Конектор за данни (т.е. `Reader`) поема данни от различни източници на данни и формати на данни и ги превръща в просто представяне на `Document` (текст и прости метаданни).
[**Documents / Nodes**](./modules/high_level/documents_and_nodes.md): `Document` е общ контейнер за всякакъв вид данни - например PDF, изход от API или извлечени данни от база данни. `Node` е атомарната единица от данни в LlamaIndex и представлява "част" от източниковия `Document`. Това е богато представяне, което включва метаданни и връзки (към други възли), за да позволи точни и изразителни операции за извличане.
[**Data Indexes**](./modules/high_level/data_index.md):
След като сте поели данните си, LlamaIndex ви помага да индексирате данните във формат, който е лесен за извличане.
Под капака, LlamaIndex анализира суровите документи в промеждинни представяния, изчислява векторни вложения и съхранява данните в паметта или на диска.
"
### Стъпка за заявка
В стъпката за заявка, конвейерът за заявки извлича най-съответния контекст, даден на потребителска заявка,
и го предава на LLM (заедно със заявката), за да синтезира отговор.
Това дава на LLM актуални познания, които не са в неговите оригинални обучаващи данни,
(също така намалява халюцинацията).
Основното предизвикателство в стъпката за заявка е извличането, организирането и резонирането върху (потенциално много) бази от знания.
LlamaIndex предоставя модули, които могат да се комбинират и помагат за създаването и интегрирането на RAG конвейери за Q&A (заявки), чатбот (чат двигател) или като част от агент.
Тези строителни блокове могат да бъдат персонализирани, за да отразяват предпочитанията за ранжиране, както и да бъдат комбинирани, за да резонират върху множество бази от знания по структуриран начин.
![](./_static/concepts/querying.jpg)
#### Строителни блокове
[**Извличатели**](./modules/low_level/retriever.md):
Извличател дефинира как да се извлича ефективно съответния контекст от база от знания (т.е. индекс), когато се предостави заявка.
Конкретната логика за извличане се различава за различни индекси, като най-популярното е плътно извличане срещу векторен индекс.
[**Синтезатори на отговори**](./modules/low_level/response_synthesizer.md):
Синтезаторът на отговор генерира отговор от LLM, използвайки потребителска заявка и даден набор от извлечени текстови части.
"
#### Конвейери
[**Заявки**](./modules/high_level/query_engine.md):
Заявката е цялостен конвейер, който ви позволява да задавате въпроси относно вашите данни.
Тя приема заявка на естествен език и връща отговор, заедно с извлечения контекст, предаден на LLM.
[**Чат двигатели**](./modules/high_level/chat_engine.md):
Чат двигателът е цялостен конвейер за провеждане на разговор с вашите данни
(множество въпроси и отговори вместо единичен въпрос и отговор).
"
@@ -1,57 +0,0 @@
---
sidebar_position: 4
---
# Примери от начало до край
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите 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):
## [Чат двигател (Chat Engine)](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/chatEngine.ts)
Прочетете файл и обсъждайте го с LLM.
## [Векторен индекс](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndex.ts)
Създайте векторен индекс и го запитайте. Векторният индекс ще използва вграждания, за да извлече най-релевантните k върха. По подразбиране, k е 2.
"
## [Summary Index](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/summaryIndex.ts)
Създайте списъчен индекс и го заявете. Този пример също използва `LLMRetriever`, който използва LLM, за да избере най-добрите възли за използване при генериране на отговор.
"
## [Запазване / Зареждане на индекс](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/storageContext.ts)
Създайте и заредете векторен индекс. Запазването на диска в LlamaIndex.TS става автоматично, веднага след като е създаден обект за контекст на съхранение.
## [Персонализиран векторен индекс](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndexCustomize.ts)
Създайте векторен индекс и го заявете, като конфигурирате `LLM`, `ServiceContext` и `similarity_top_k`.
"
## [OpenAI LLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/openai.ts)
Създайте OpenAI LLM и го използвайте директно за чат.
## [Llama2 DeuceLLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/llamadeuce.ts)
Създайте Llama-2 LLM и го използвайте директно за чат.
## [SubQuestionQueryEngine](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts)
Използва `SubQuestionQueryEngine`, който разбива сложни заявки на множество въпроси и след това агрегира отговорите на всички под-въпроси.
"
## [Модули с ниско ниво](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/lowlevel.ts)
Този пример използва няколко компонента с ниско ниво, които премахват нуждата от реален двигател за заявки. Тези компоненти могат да се използват навсякъде, във всяко приложение или да бъдат персонализирани и подкласирани, за да отговарят на вашите нужди.
"
@@ -1,17 +0,0 @@
---
sidebar_position: 5
---
# Среди
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
LlamaIndex в момента официално поддържа NodeJS 18 и NodeJS 20.
## NextJS App Router
Ако използвате обработчици на маршрути/сървърни функции на NextJS App Router, ще трябва да използвате режима на NodeJS:
```js
export const runtime = "nodejs"; // по подразбиране
```
@@ -1,65 +0,0 @@
---
sidebar_position: 1
---
# Инсталация и настройка
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите 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 ключ в системата за контрол на версиите.
@@ -1,62 +0,0 @@
---
sidebar_position: 0
slug: /
---
# Какво е LlamaIndex.TS?
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите 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 на:
- Github: https://github.com/run-llama/LlamaIndexTS
- NPM: https://www.npmjs.com/package/llamaindex
"
## Общност
Нуждаете се от помощ? Имате предложение за функционалност? Присъединете се към общността на LlamaIndex:
- Twitter: https://twitter.com/llama_index
- Discord: https://discord.gg/dGcwcsnxhU
@@ -1,24 +0,0 @@
---
sidebar_position: 4
---
# Чат двигател (ChatEngine)
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
Чат двигателят е бърз и прост начин да чатите с данните във вашата индекс.
```typescript
const retriever = index.asRetriever();
const chatEngine = new ContextChatEngine({ retriever });
// започнете да чатите
const response = await chatEngine.chat(query);
```
## Api Референции
- [Чат двигател за контекст (ContextChatEngine)](../../api/classes/ContextChatEngine.md)
- [Чат двигател за кондензиране на въпроси (CondenseQuestionChatEngine)](../../api/classes/ContextChatEngine.md)
"
@@ -1,27 +0,0 @@
---
sidebar_position: 2
---
# Индекс
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
Индексът е основният контейнер и организация за вашите данни. LlamaIndex.TS поддържа два вида индекси:
- `VectorStoreIndex` - ще изпраща най-добрите `Node` до LLM при генериране на отговор. По подразбиране, най-добрите два.
- `SummaryIndex` - ще изпраща всеки `Node` в индекса до LLM, за да генерира отговор.
```typescript
import { Document, VectorStoreIndex } from "llamaindex";
const document = new Document({ text: "тест" });
const index = await VectorStoreIndex.fromDocuments([document]);
```
## API Референция
- [SummaryIndex](../../api/classes/SummaryIndex.md)
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
"
@@ -1,21 +0,0 @@
---
sidebar_position: 1
---
# Четец / Зареждач
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
LlamaIndex.TS поддържа лесно зареждане на файлове от папки с помощта на класа `SimpleDirectoryReader`. В момента се поддържат файлове с разширения `.txt`, `.pdf`, `.csv`, `.md` и `.docx`, с планове за добавяне на още в бъдеще!
```typescript
import { SimpleDirectoryReader } from "llamaindex";
documents = new SimpleDirectoryReader().loadData("./data");
```
## API Референция
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
"
@@ -1,22 +0,0 @@
---
sidebar_position: 0
---
# Документи и Възли
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
`Документи` и `Възли` са основните строителни блокове на всяко индексиране. Въпреки че API-то за тези обекти е подобно, обектите `Документ` представляват цели файлове, докато `Възли` са по-малки части от оригиналния документ, които са подходящи за LLM и Q&A.
```typescript
import { Document } from "llamaindex";
document = new Document({ text: "текст", metadata: { key: "val" } });
```
## API Референция
- [Документ](../../api/classes/Document.md)
- [ТекстовВъзел](../../api/classes/TextNode.md)
"
@@ -1,40 +0,0 @@
---
sidebar_position: 3
---
# QueryEngine (Заявка на двигател)
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
Заявка на двигател обвива `Retriever` и `ResponseSynthesizer` в тръбопровод, който използва низа от заявки, за да извлече възли и след това ги изпраща към LLM, за да генерира отговор.
```typescript
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query("query string");
```
## Заявка на подзапитване на двигател
Основната концепция на Заявка на подзапитване на двигател е, че тя разделя една заявка на множество заявки, получава отговор за всяка от тези заявки и след това комбинира тези различни отговори в един цялостен отговор за потребителя. Можете да си представите това като техника за "мислене стъпка по стъпка", но като итерира върху източниците на данни!
### Започване
Най-лесният начин да започнете да използвате Заявка на подзапитване на двигател е да стартирате файла 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)
"

Some files were not shown because too many files have changed in this diff Show More