mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-15 06:52:45 -04:00
Compare commits
35 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eac09e7816 | |||
| dd95927498 | |||
| 4f72feae91 | |||
| 3cd8f9f597 | |||
| d2e8d0c62a | |||
| fafbd8c9c7 | |||
| a40c91b054 | |||
| 98894055c6 | |||
| 4589a84643 | |||
| e6b7f52d3e | |||
| b169db617a | |||
| 89a49f4f4f | |||
| 58490715fe | |||
| 4c2283c4e5 | |||
| a059070dec | |||
| 20dfeb4cfa | |||
| aefc3266c1 | |||
| fdf48dd459 | |||
| 66525346a2 | |||
| c9b2ec4a2b | |||
| bf583a7266 | |||
| de194d1c73 | |||
| ecdc289df1 | |||
| 9e198ac40d | |||
| 0a06998690 | |||
| 484a7105a9 | |||
| 8d18ea167b | |||
| a2ca89bfe0 | |||
| edeea40898 | |||
| 2a7080b094 | |||
| b354f2386b | |||
| d766bd03d2 | |||
| 6a69148356 | |||
| e1e1b0b522 | |||
| d824876653 |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"create-llama": patch
|
||||
---
|
||||
|
||||
Add LlamaParse option when selecting a pdf file or a folder
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
Add quantized parameter to HuggingFaceEmbedding
|
||||
@@ -11,5 +11,13 @@ module.exports = {
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["examples/**/*.ts"],
|
||||
rules: {
|
||||
"turbo/no-undeclared-env-vars": "off",
|
||||
},
|
||||
},
|
||||
],
|
||||
ignorePatterns: ["dist/", "lib/"],
|
||||
};
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
name: E2E Tests
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
paths:
|
||||
- "packages/create-llama/**"
|
||||
- ".github/workflows/e2e.yml"
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: create-llama
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
python-version: ["3.11"]
|
||||
os: [macos-latest, windows-latest]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install --with-deps
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Build create-llama
|
||||
run: pnpm run build
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Pack
|
||||
run: pnpm pack --pack-destination ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Extract Pack
|
||||
run: tar -xvzf ./output/*.tgz -C ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Run Playwright tests
|
||||
run: pnpm exec playwright test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
working-directory: ./packages/create-llama
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: ./packages/create-llama/playwright-report/
|
||||
retention-days: 30
|
||||
@@ -0,0 +1,28 @@
|
||||
name: Publish
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- 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/core
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
+1
-2
@@ -84,8 +84,7 @@ Any changes you make should be reflected in the browser. If you need to regenera
|
||||
To publish a new version of the library, run
|
||||
|
||||
```shell
|
||||
pnpm new-llamaindex
|
||||
pnpm new-create-llama
|
||||
pnpm new-version
|
||||
pnpm release
|
||||
git push # push to the main branch
|
||||
git push --tags
|
||||
|
||||
@@ -121,6 +121,42 @@ const nextConfig = {
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
### NextJS with Milvus:
|
||||
|
||||
As proto files are not loaded per default in NextJS, you'll need to add the following to your next.config.js to have it load the proto files.
|
||||
|
||||
```js
|
||||
const path = require("path");
|
||||
const CopyWebpackPlugin = require("copy-webpack-plugin");
|
||||
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
webpack: (config, { isServer }) => {
|
||||
if (isServer) {
|
||||
// Copy the proto files to the server build directory
|
||||
config.plugins.push(
|
||||
new CopyWebpackPlugin({
|
||||
patterns: [
|
||||
{
|
||||
from: path.join(
|
||||
__dirname,
|
||||
"node_modules/@zilliz/milvus2-sdk-node/dist",
|
||||
),
|
||||
to: path.join(__dirname, ".next"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Important: return the modified config
|
||||
return config;
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
## Supported LLMs:
|
||||
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Transformations
|
||||
|
||||
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformatio class has both a `transform` definition responsible for transforming the nodes
|
||||
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformation class has both a `transform` definition responsible for transforming the nodes.
|
||||
|
||||
Currently, the following components are Transformation objects:
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ const response = await queryEngine.query("<user_query>");
|
||||
```ts
|
||||
import { SimilarityPostprocessor } from "llamaindex";
|
||||
|
||||
nodes = await index.asRetriever().retrieve("test query str");
|
||||
nodes = await index.asRetriever().retrieve({ query: "test query str" });
|
||||
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
|
||||
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Fetch nodes!
|
||||
const nodesWithScore = await retriever.retrieve("query string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// جلب العقد!
|
||||
const nodesWithScore = await retriever.retrieve("سلسلة الاستعلام");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "سلسلة الاستعلام" });
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية (API Reference)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Извличане на върхове!
|
||||
const nodesWithScore = await retriever.retrieve("query string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference (API справка)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
|
||||
recuperador.similarityTopK = 3;
|
||||
|
||||
// Obteniu els nodes!
|
||||
const nodesAmbPuntuació = await recuperador.retrieve("cadena de consulta");
|
||||
const nodesAmbPuntuació = await recuperador.retrieve({ query: "cadena de consulta" });
|
||||
```
|
||||
|
||||
## Referència de l'API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Získání uzlů!
|
||||
const nodesWithScore = await retriever.retrieve("dotazovací řetězec");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "dotazovací řetězec" });
|
||||
```
|
||||
|
||||
## API Reference (Odkazy na rozhraní)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hent noder!
|
||||
const nodesWithScore = await retriever.retrieve("forespørgselsstreng");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "forespørgselsstreng" });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Knoten abrufen!
|
||||
const nodesWithScore = await retriever.retrieve("Abfragezeichenfolge");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "Abfragezeichenfolge" });
|
||||
```
|
||||
|
||||
## API-Referenz
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Ανάκτηση κόμβων!
|
||||
const nodesWithScore = await retriever.retrieve("συμβολοσειρά ερωτήματος");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "συμβολοσειρά ερωτήματος" });
|
||||
```
|
||||
|
||||
## Αναφορά API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
|
||||
recuperador.similarityTopK = 3;
|
||||
|
||||
// ¡Obtener nodos!
|
||||
const nodosConPuntuación = await recuperador.retrieve("cadena de consulta");
|
||||
const nodosConPuntuación = await recuperador.retrieve({ query: "cadena de consulta" });
|
||||
```
|
||||
|
||||
## Referencia de la API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Too sõlmed!
|
||||
const nodesWithScore = await retriever.retrieve("päringu string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "päringu string" });
|
||||
```
|
||||
|
||||
## API viide
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// بازیابی گره ها!
|
||||
const nodesWithScore = await retriever.retrieve("رشته پرس و جو");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "رشته پرس و جو" });
|
||||
```
|
||||
|
||||
## مرجع API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hae solmut!
|
||||
const nodesWithScore = await retriever.retrieve("kyselymerkkijono");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "kyselymerkkijono" });
|
||||
```
|
||||
|
||||
## API-viite
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Récupérer les nœuds !
|
||||
const nodesWithScore = await retriever.retrieve("chaîne de requête");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "chaîne de requête" });
|
||||
```
|
||||
|
||||
## Référence de l'API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// אחזור צמתים!
|
||||
const nodesWithScore = await retriever.retrieve("מחרוזת שאילתה");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "מחרוזת שאילתה" });
|
||||
```
|
||||
|
||||
## מדריך לממשק API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// नोड्स प्राप्त करें!
|
||||
const nodesWithScore = await retriever.retrieve("क्वेरी स्ट्रिंग");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "क्वेरी स्ट्रिंग" });
|
||||
```
|
||||
|
||||
## एपीआई संदर्भ (API Reference)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const dohvatnik = vector_index.asRetriever();
|
||||
dohvatnik.similarityTopK = 3;
|
||||
|
||||
// Dohvati čvorove!
|
||||
const čvoroviSaRezultatom = await dohvatnik.retrieve("upitni niz");
|
||||
const čvoroviSaRezultatom = await dohvatnik.retrieve({ query: "upitni niz" });
|
||||
```
|
||||
|
||||
## API Referenca
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Node-ok lekérése!
|
||||
const nodesWithScore = await retriever.retrieve("lekérdezési karakterlánc");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "lekérdezési karakterlánc" });
|
||||
```
|
||||
|
||||
## API Referencia
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Mengambil node!
|
||||
const nodesWithScore = await retriever.retrieve("string query");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "string query" });
|
||||
```
|
||||
|
||||
## Referensi API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Recupera i nodi!
|
||||
const nodesWithScore = await retriever.retrieve("stringa di query");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "stringa di query" });
|
||||
```
|
||||
|
||||
## Riferimento API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// ノードを取得します!
|
||||
const nodesWithScore = await retriever.retrieve("クエリ文字列");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "クエリ文字列" });
|
||||
```
|
||||
|
||||
## API リファレンス
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// 노드를 가져옵니다!
|
||||
const nodesWithScore = await retriever.retrieve("쿼리 문자열");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "쿼리 문자열" });
|
||||
```
|
||||
|
||||
## API 참조
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const gavėjas = vector_index.asRetriever();
|
||||
gavėjas.similarityTopK = 3;
|
||||
|
||||
// Išgaunami mazgai!
|
||||
const mazgaiSuRezultatu = await gavėjas.retrieve("užklausos eilutė");
|
||||
const mazgaiSuRezultatu = await gavėjas.retrieve({ query: "užklausos eilutė" });
|
||||
```
|
||||
|
||||
## API nuorodos (API Reference)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Haal knooppunten op!
|
||||
const nodesWithScore = await retriever.retrieve("zoekopdracht");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "zoekopdracht" });
|
||||
```
|
||||
|
||||
## API Referentie
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hent noder!
|
||||
const nodesWithScore = await retriever.retrieve("spørringsstreng");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "spørringsstreng" });
|
||||
```
|
||||
|
||||
## API-referanse
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Pobierz węzły!
|
||||
const nodesWithScore = await retriever.retrieve("ciąg zapytania");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "ciąg zapytania" });
|
||||
```
|
||||
|
||||
## Dokumentacja interfejsu API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
|
||||
recuperador.similarityTopK = 3;
|
||||
|
||||
// Buscar nós!
|
||||
const nósComPontuação = await recuperador.retrieve("string de consulta");
|
||||
const nósComPontuação = await recuperador.retrieve({ query: "string de consulta" });
|
||||
```
|
||||
|
||||
## Referência da API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperator = vector_index.asRetriever();
|
||||
recuperator.similarityTopK = 3;
|
||||
|
||||
// Preia nodurile!
|
||||
const noduriCuScor = await recuperator.retrieve("șir de interogare");
|
||||
const noduriCuScor = await recuperator.retrieve({ query: "șir de interogare" });
|
||||
```
|
||||
|
||||
## Referință API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Получение узлов!
|
||||
const nodesWithScore = await retriever.retrieve("строка запроса");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "строка запроса" });
|
||||
```
|
||||
|
||||
## Справочник по API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Dohvati čvorove!
|
||||
const nodesWithScore = await retriever.retrieve("upitni niz");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "upitni niz" });
|
||||
```
|
||||
|
||||
## API Referenca
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const pridobitelj = vector_index.asRetriever();
|
||||
pridobitelj.similarityTopK = 3;
|
||||
|
||||
// Pridobivanje vozlišč!
|
||||
const vozliščaZRezultatom = await pridobitelj.retrieve("poizvedbeni niz");
|
||||
const vozliščaZRezultatom = await pridobitelj.retrieve({ query: "poizvedbeni niz" });
|
||||
```
|
||||
|
||||
## API Sklic
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Získajte uzly!
|
||||
const nodesWithScore = await retriever.retrieve("reťazec dotazu");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "reťazec dotazu" });
|
||||
```
|
||||
|
||||
## API Referencia
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hämta noder!
|
||||
const nodesWithScore = await retriever.retrieve("frågesträng");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "frågesträng" });
|
||||
```
|
||||
|
||||
## API-referens
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// เรียกคืนโหนด!
|
||||
const nodesWithScore = await retriever.retrieve("query string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference (การอ้างอิง API)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Düğümleri getir!
|
||||
const nodesWithScore = await retriever.retrieve("sorgu dizesi");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "sorgu dizesi" });
|
||||
```
|
||||
|
||||
## API Referansı
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Отримати вузли!
|
||||
const nodesWithScore = await retriever.retrieve("рядок запиту");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "рядок запиту" });
|
||||
```
|
||||
|
||||
## Довідник API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Lấy các node!
|
||||
const nodesWithScore = await retriever.retrieve("chuỗi truy vấn");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "chuỗi truy vấn" });
|
||||
```
|
||||
|
||||
## Tài liệu tham khảo API
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// 获取节点!
|
||||
const nodesWithScore = await retriever.retrieve("查询字符串");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "查询字符串" });
|
||||
```
|
||||
|
||||
## API 参考
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// 提取節點!
|
||||
const nodesWithScore = await retriever.retrieve("查詢字串");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "查詢字串" });
|
||||
```
|
||||
|
||||
## API 參考
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# examples
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d2e8d0c: add support for Milvus vector store
|
||||
- Updated dependencies [d2e8d0c]
|
||||
- Updated dependencies [aefc326]
|
||||
- Updated dependencies [484a710]
|
||||
- Updated dependencies [d766bd0]
|
||||
- Updated dependencies [dd95927]
|
||||
- Updated dependencies [bf583a7]
|
||||
- llamaindex@0.2.0
|
||||
@@ -0,0 +1,77 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const functionTool2 = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: false,
|
||||
});
|
||||
|
||||
const stream = await agent.chat({
|
||||
message: "Divide 16 by 2 then add 20",
|
||||
stream: true,
|
||||
});
|
||||
|
||||
for await (const chunk of stream.response) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("\nDone");
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Anthropic } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
model: "claude-3-haiku",
|
||||
});
|
||||
const result = await anthropic.chat({
|
||||
messages: [
|
||||
{ content: "You want to talk in rhymes.", role: "system" },
|
||||
{
|
||||
content:
|
||||
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(result);
|
||||
})();
|
||||
@@ -32,10 +32,10 @@ run `ts-node astradb/example`
|
||||
|
||||
This sample loads the same dataset of movie reviews as the Astra Portal sample dataset. (Feel free to load the data in your the Astra Data Explorer to compare)
|
||||
|
||||
run `ts-node astradb/load`
|
||||
run `npx ts-node astradb/load`
|
||||
|
||||
### Use RAG to Query the data
|
||||
|
||||
Check out your data in the Astra Data Explorer and change the sample query as you see fit.
|
||||
|
||||
run `ts-node astradb/query`
|
||||
run `npx ts-node astradb/query`
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Milvus Vector Store
|
||||
|
||||
Here are two sample scripts which work with loading and querying data from a Milvus Vector Store.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- An Milvus Vector Database
|
||||
- Hosted https://milvus.io/
|
||||
- Self Hosted https://milvus.io/docs/install_standalone-docker.md
|
||||
- An OpenAI API Key
|
||||
|
||||
## Setup
|
||||
|
||||
1. Set your env variables:
|
||||
|
||||
- `MILVUS_ADDRESS`: Address of your Milvus Vector Store (like localhost:19530)
|
||||
- `MILVUS_USERNAME`: empty or username for your Milvus Vector Store
|
||||
- `MILVUS_PASSWORD`: empty or password for your Milvus Vector Store
|
||||
- `OPENAI_API_KEY`: Your OpenAI key
|
||||
|
||||
2. `cd` Into the `examples` directory
|
||||
3. run `npm i`
|
||||
|
||||
## Load the data
|
||||
|
||||
This sample loads the same dataset of movie reviews as sample dataset. You can install https://github.com/zilliztech/attu to inspect the loaded data.
|
||||
|
||||
run `npx ts-node milvus/load`
|
||||
|
||||
## Use RAG to Query the data
|
||||
|
||||
Check out your data in Attu and change the sample query as you see fit.
|
||||
|
||||
run `npx ts-node milvus/query`
|
||||
@@ -0,0 +1,101 @@
|
||||
title,reviewid,creationdate,criticname,originalscore,reviewstate,reviewtext
|
||||
Beavers,1145982,2003-05-23,Ivan M. Lincoln,3.5/4,fresh,"Timed to be just long enough for most youngsters' brief attention spans -- and it's packed with plenty of interesting activity, both on land and under the water."
|
||||
Blood Mask,1636744,2007-06-02,The Foywonder,1/5,rotten,"It doesn't matter if a movie costs 300 million or only 300 dollars; good is good and bad is bad, and Bloodmask: The Possession of Nicole Lameroux is just plain bad."
|
||||
City Hunter: Shinjuku Private Eyes,2590987,2019-05-28,Reuben Baron,,fresh,"The choreography is so precise and lifelike at points one might wonder whether the movie was rotoscoped, but no live-action reference footage was used. The quality is due to the skill of the animators and Kodama's love for professional wrestling."
|
||||
City Hunter: Shinjuku Private Eyes,2558908,2019-02-14,Matt Schley,2.5/5,rotten,The film's out-of-touch attempts at humor may find them hunting for the reason the franchise was so popular in the first place.
|
||||
Dangerous Men,2504681,2018-08-29,Pat Padua,,fresh,Its clumsy determination is endearing and sometimes wildly entertaining
|
||||
Dangerous Men,2299284,2015-12-13,Eric Melin,4/5,fresh,"With every new minute, there's another head-scratching choice that's bound to elicit some amazing out-loud responses, so this feels like a true party flick."
|
||||
Dangerous Men,2295858,2015-11-22,Matt Donato,7/10,fresh,"Emotionless reaction shots, zero characterization, guns that have absolutely no special effects when blasted - Dangerous Men is rare winning dish from a one star restaurant."
|
||||
Dangerous Men,2295338,2015-11-19,Peter Keough,0.5/4,rotten,"Conceivably, it could serve as a primer for students on how not to make a movie, and perhaps as a deconstruction of filmic conventions for the more theoretical minded."
|
||||
Dangerous Men,2294641,2015-11-16,Jason Wilson,3/10,rotten,"If you're not a fan of garbage cinema, even for the fun of it, Dangerous Men is best to be avoided."
|
||||
Dangerous Men,2294129,2015-11-12,Soren Andersen,0/4,rotten,"""Dangerous Men,"" the picture's production notes inform, took 26 years to reach the big screen. After having seen it, I wonder: What was the rush?"
|
||||
Dangerous Men,2293902,2015-11-12,Maitland McDonagh,,rotten,Will entertain some viewers and infuriate others with its clunky mix of feminist fury and awkward action sequences.
|
||||
Dangerous Men,2293900,2015-11-12,Marjorie Baumgarten,1.5/5,rotten,"This is a bad movie, but one that awakens your senses every so often with flashes of originality and abundant self-belief."
|
||||
Dangerous Men,2293815,2015-11-12,Katie Rife,B+,fresh,"Ridiculous, artless, and wildly entertaining, Dangerous Men is more than the sum of its fascinatingly misguided parts, although it will take a special sort of moviegoer to truly appreciate (or endure, depending on your perspective) its charms."
|
||||
Dangerous Men,2293605,2015-11-11,Amy Nicholson,C,fresh,To sit through it feels like honoring the dreamers of the world who at least get shit done. Is it terrible? Of course. Is there belly-dancing? Duh.
|
||||
Small Town Wisconsin,102711819,2022-07-22,Peter Gray,,fresh,Small Town Wisconsin could hit some home truths for viewers, and though being faced with the truth isn’t always pleasant, it feels necessary in growing towards a happier fruition.
|
||||
Small Town Wisconsin,102711545,2022-07-22,Tim Grierson,,fresh,"This low-key drama has lovely interludes and some nicely understated performances, although director Niels Mueller doesn’t glean too many new insights from Jason Naczek’s familiar story..."
|
||||
Small Town Wisconsin,102700937,2022-06-16,Sumner Forbes,8.5/10,fresh,"Small Town Wisconsin is a success in almost every regard, and if you can see over the legions of cheeseheads in the rows ahead of you, it shouldn’t be missed."
|
||||
Small Town Wisconsin,102699897,2022-06-14,Tara McNamara,3/5,fresh,Just like Wayne, Small Town Wisconsin has flaws, but the poignancy of the story will stick with you for a long time.
|
||||
Small Town Wisconsin,102698744,2022-06-10,Rob Thomas,3/4,fresh,It’s a movie with its heart in the right place, and does both small town and big city Wisconsin proud.
|
||||
Small Town Wisconsin,102698639,2022-06-10,Todd Jorgenson,,rotten,Despite some intriguing character dynamics and performances that generate sympathy for this fractured family, the film stumbles when it veers into melodrama without the narrative dexterity to tackle its weightier ambitions.
|
||||
Small Town Wisconsin,102698482,2022-06-10,Jackie K. Cooper,7/10,fresh,This is the kind of movie that draws you so deeply into its story you are reluctant to let it end.
|
||||
Small Town Wisconsin,102698164,2022-06-09,Glenn Kenny,,fresh,"Mueller’s direction is patient and sensitive, the cast is accomplished and committed, and the picture’s comedic aspects sometimes earn a chuckle."
|
||||
Small Town Wisconsin,102697854,2022-06-08,Brian Orndorf,B+,fresh,Naczek isn't interested in making a soap opera with this examination of fallibility, going somewhere much more authentic when exploring character aches and pains.
|
||||
Small Town Wisconsin,102695788,2022-06-02,Eddie Harrison,4/5,fresh,…a warm-hearted story of everyday life that’s easy to recommend for those who like films about people rather than portals and vortexes…
|
||||
Small Town Wisconsin,102695250,2022-05-31,Laura Clifford,C,rotten,Debuting screenwriter Jason Naczek has concocted a manchild redemption story using metaphors as heavy as a hammer and a fairy godmother who makes everything alright with a seeming flip of the switch.
|
||||
Small Town Wisconsin,2733251,2020-10-12,Jared Mobarak,B,fresh,Small Town Wisconsin is always proving itself to be more than its familiar premise thanks to Naczek's ability to infuse a lot more drama into the mix than one custody battle.
|
||||
Tejano,2564925,2019-03-07,Joe Friar,3/4,fresh,The story of a South Texas ranch hand who gets mixed up with a Mexican cartel moves with pulse-pounding velocity and features top performances from a talented cast of actors with Texas roots.
|
||||
Tejano,2557738,2019-02-12,Cary Darling,4/5,fresh,"An entertaining blast of Texas noir that nods toward the work of the Coen brothers, Quentin Tarantino and fellow Austinite Greg Kwedar's 2016 low-budget thriller ""Transpecos"" as well as ""Breaking Bad."""
|
||||
Tejano,2547231,2019-01-10,Danielle White,3/5,fresh,The story itself slithers with twists and turns and unexpected betrayals. It's almost ridiculous how many characters die in this film.
|
||||
Tejano,2530119,2018-11-08,Chris Salce,9/10,fresh,"Tejano is one of those films that can be described as a hidden gem as it sneaks under the radar and will have you talking, telling your friends about it, and wanting to watch it again."
|
||||
Death of a Salesman,2770637,2021-02-23,Michael Dougan,,fresh,"Miller has taken a small, intimate tale and expanded it into a treatise on larger themes, primarily the abuse of the American Dream."
|
||||
Death of a Salesman,1950734,2011-01-02,Randy White,5/5,fresh,A classic American tragedy.
|
||||
Death of a Salesman,1422415,2005-08-04,Jules Brenner,4/5,fresh,
|
||||
Death of a Salesman,1409415,2005-07-05,Emanuel Levy,3/5,fresh,
|
||||
Death of a Salesman,839546,2003-02-06,Frederic and Mary Ann Brussat,,fresh,"Death of a Salesman, directed by Volker Schlondorff, draws out the multiple meanings of this Pulitzer Prize-winning play by Arthur Miller about change, family and fatherhood, work and love."
|
||||
Death of a Salesman,788410,2002-09-29,Dan Lybarger,4/5,fresh,"Schlndorff's artificial settings and some amazing performances help keep this from looking like a typical ""filmed play."""
|
||||
Death of a Salesman,751951,2002-08-08,Cory Cheney,4/5,fresh,
|
||||
Death of a Salesman,743794,2002-07-26,Bob Grimm,5/5,fresh,
|
||||
Death of a Salesman,743291,2002-07-26,Scott Weinberg,5/5,fresh,They MAKE you watch it in English class for a good reason!
|
||||
Sahara,1137710,2003-05-13,Dragan Antulov,5/10,fresh,
|
||||
The Debt,2628192,2019-09-20,Diego Batlle,,fresh,A Bresson-esque movie that is always enigmatic. [Full Review in Spanish]
|
||||
The Debt,2627988,2019-09-20,Gaspar Zimerman,,fresh,The story [Director Gustavo Fontán] tells is an excuse to give way to the exploration of feelings and sensations that avoid verbality. [Full review in Spanish]
|
||||
Peppermint Candy,2725008,2020-09-16,A.S. Hamrah,,fresh,"South Korean political history of the previous twenty years, Peppermint Candy is not tempered by its hysterical edge, which adds unpredictable violence to its vignettes of romantic, domestic, and business failure."
|
||||
Peppermint Candy,2541271,2018-12-16,Panos Kotzathanasis,,fresh,"Lee Chang-dong presents a melodrama that stands apart from the plethora of similar productions due to its intense political element, because it doesn't lose its seriousness at any point and because it doesn't become hyperbolic in his effort to draw tears"
|
||||
Peppermint Candy,1883708,2010-05-11,Anton Bitel,,fresh,"This is Korea's millennial elegy, filtering its search for times past through a confection no less bittersweet than Proust's madeleine."
|
||||
Peppermint Candy,1706014,2008-01-29,Beth Accomando,9/10,fresh,The film offers a heartbreaking drama told in reverse chronology and spanning twenty years in both the life of the main character and the political history of Korea.
|
||||
Peppermint Candy,1231988,2003-12-22,Greg Muskewitz,2/5,rotten,
|
||||
Peppermint Candy,1187104,2003-08-14,Joshua Tanzer,4/4,fresh,"It's a story about the original sin of a nation as well as one character. There has rarely been a better film made, ever"
|
||||
Prison Girls,2475348,2018-05-03,Roger Ebert,,rotten,Prison Girls didn't have a lot of prison sets because it was a big-budget exploitation movie. Maybe.
|
||||
Gimme the Power,2575688,2019-04-09,Afroxander,,fresh,"Rubio's film shows ambition where none is required, making Gimme the Power a lot like Molotov's music: politically engaged without having to take itself too seriously."
|
||||
Paa,2673089,2020-02-27,Nikhat Kazmi,3.5/5,fresh,"The film, which peters off into vague sub-plots about slum redevelopment and unwarranted media-bashing in the first half, suddenly picks up and scales new heights in the second half."
|
||||
Paa,2578129,2019-04-17,Shubhra Gupta,2/5,rotten,"Disappointingly, Paa is not as out-of-the-box as it could have been."
|
||||
Paa,2429810,2017-10-24,Anil Sinanan,3/5,rotten,Will Auro survive to know his Pa and reunite his parents? Forget about the disease: this is a vanity vehicle designed to showcase the Big B's versatility.
|
||||
Paa,1860476,2009-12-14,Frank Lovece,,rotten,This would-be tearjerker without the musical numbers of typical Bollywood fare is for die-hard Amitabh Bachchan fans only.
|
||||
Paa,1860473,2009-12-14,David Chute,,fresh,"The film owes much of its interest to the alertness and sincerity of the younger Bachchan and the luminous Vidya Balan as the anguished parents, and to the soft wash of the tasteful playback songs supplied by Ilaiyaraaja."
|
||||
Paa,1858964,2009-12-05,Avi Offer,5.85/10,rotten,"Well-acted, funny and occasionally witty with terrific make-up design. However, it's often convoluted, awkwardly paced and too uneven as a whole."
|
||||
Paa,1858853,2009-12-04,Frank Lovece,,fresh,"A would-be tearjerker without the singing-dancing musical numbers of typical Bollywood fare seen in the U.S., the lackluster Paa is for die-hard Amitabh Bachchan fans only%u2014of which there is no small number."
|
||||
Paa,1858816,2009-12-04,Rachel Saltz,3/5,fresh,Odd and sometimes oddly affecting.
|
||||
Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love),2835964,2021-10-30,Erich Hellmund-Waldow,,fresh,"The acting is not only artistic, it is also as realistic as can be possible in such a film."
|
||||
Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love),2357086,2016-10-17,C. Hooper Trask,,fresh,"Aimed straight for the gooseflesh, it strikes directly into the centre of the target."
|
||||
Toorbos,2760593,2021-01-29,Neil Young,,fresh,Built around a luminous and intriguing central performance by dancer-actor Elani Dekker.
|
||||
Toorbos,2752827,2020-12-21,Guy Lodge,,fresh,"A satisfying marriage of folky period romance and environmental parable from the misty, mossy depths of South Africa's Knysna forest region..."
|
||||
Connors' War,1555113,2006-11-09,David Nusair,1.5/4,rotten,"...although Criss does show some potential as a performer, his efforts to step into the shoes of a blind character are laughable."
|
||||
Connors' War,1539106,2006-09-19,Scott Weinberg,2/5,rotten,"Standard cable fodder all the way, with only a few solid action scenes and maybe one colorful performance in the whole thing."
|
||||
Born to Kill,2710947,2020-08-05,Mike Massie,10/10,fresh,"One of the most acerbic of all films noir, boasting essentially no redeemable characters (or a wealth of deliciously evil villains) while also being utterly enthralling."
|
||||
Born to Kill,2340106,2016-07-15,David Nusair,3/4,fresh,...a fairly typical film-noir premise that's employed to watchable yet entirely unmemorable effect by Robert Wise...
|
||||
Born to Kill,1507021,2006-05-16,Nick Schager,B,fresh,Competent if slightly too tame for a supposedly sleazy story.
|
||||
Born to Kill,1501617,2006-05-01,Fernando F. Croce,,fresh,"The usually meek Robert Wise trades his chameleonic tastefulness for full-on, jazzy misanthropy in this nasty melodrama."
|
||||
Born to Kill,1433953,2005-09-09,Jeffrey M. Anderson,3/4,fresh,"Hard to watch, but effective and alluring nonetheless."
|
||||
Born to Kill,1123980,2003-04-02,Dennis Schwartz,C,rotten,A revolting B film noir...
|
||||
The Soong Sisters,1402087,2005-06-15,Emanuel Levy,3/5,fresh,
|
||||
La Sapienza,102772380,2023-01-24,Vadim Rizov,,fresh,"Sapienza is a pretty lovely film. Symmetricities are everywhere, starting with that opening architectural showreel, which deliberately avoids perfect symmetricity..."
|
||||
La Sapienza,2767839,2021-02-14,Dustin Chang,,fresh,Their sincere expression of these thoughts rings true and melts away its artificiality in its presentation soon enough. This is the beauty of La Sapienza and Green films in general.
|
||||
La Sapienza,2598336,2019-06-18,C.J. Prince,,fresh,"It's a nice entry point into a peculiar cinematic universe, and those willing to open themselves to it will find a lot to enjoy."
|
||||
La Sapienza,2503963,2018-08-28,Charles Mudede,,fresh,"If architecture aspires to the condition of music, the acting in La Sapienza aspires to the condition of architecture. You will love the ending of this very original and elegant and arty work."
|
||||
La Sapienza,2314368,2016-03-12,Forrest Cardamenis,B,fresh,This startling architectural juxtaposition feels like a wake-up call.
|
||||
La Sapienza,2275677,2015-08-03,Nicole Armour,,fresh,"While Green's film is dense with historical fact and theory, it's not averse to plumbing life's mysteries. Suffused with warmth, it expresses a potent admiration for human striving and accomplishment."
|
||||
La Sapienza,2273804,2015-07-23,Norman Wilner,2/5,rotten,"The uncomplicated narrative resists stylization; Green's presentation turns everyone into mannequins, rendering their emotions theoretical. That may well be his point, but it didn't work for me."
|
||||
La Sapienza,2269287,2015-06-26,Sam Lubell,,fresh,"On the surface, writer-director Eugne Green's film ""La Sapienza"" is slow, strange and awkward - but stick with it and it may win you over."
|
||||
La Sapienza,2265997,2015-06-05,Rob Garratt,4/5,fresh,"Layered with reels of swirling shots of Rome's most beautiful buildings -- all crucially shot from the ground upwards, staring at the heavens-- La Sapienza is visually stunning."
|
||||
La Sapienza,2265990,2015-06-05,Boyd van Hoeij,,fresh,"The Sapience juxtaposes insights on how people are emotionally connected with ruminations on the buildings and spaces through which they move, in which they live and, in Alexandre's case, which they also create."
|
||||
La Sapienza,2265989,2015-06-05,Robert Horton,3/4,fresh,"If you can groove into this non-realistic mode, the film casts a spell."
|
||||
La Sapienza,2265790,2015-06-04,Tom Keogh,3.5/4,fresh,A beautiful space for people and light.
|
||||
La Sapienza,2255621,2015-04-09,Wesley Morris,,rotten,This kind of formalism needs to do more than walk through classical wonders. It should want to create cinema that can stand near or beside them. This movie defensively consecrates what's already there. You don't need a film to do that.
|
||||
La Sapienza,2255195,2015-04-08,Scott Foundas,,fresh,"An exquisite rumination on life, love and art that tickles the heart and mind in equal measure."
|
||||
La Sapienza,2252858,2015-03-23,Richard Brody,,fresh,"Green's richly textured, painterly images fuse with the story to evoke the essence of humane urbanity and the relationships that it fosters, whether educational, familial, or erotic."
|
||||
La Sapienza,2252553,2015-03-20,Ignatiy Vishnevetsky,B+,fresh,"Green doesn't so much use his characters as mouthpieces as emotionally invest them in art, turning opinions into feelings."
|
||||
La Sapienza,2252541,2015-03-20,Godfrey Cheshire,4/4,fresh,"""La Sapienza"" strikes this reviewer as easily the most astonishing and important movie to emerge from France in quite some time."
|
||||
La Sapienza,2252452,2015-03-19,A.O. Scott,,fresh,The movie is an unapologetically rarefied undertaking and at the same time a gracious and inviting film.
|
||||
La Sapienza,2252301,2015-03-19,David Noh,,rotten,"Pretentious, stuffy and slow. There's some beautiful scenery here but oh, what you must put up with to earn it!"
|
||||
La Sapienza,2252028,2015-03-18,Noel Murray,3/5,fresh,"While La Sapienza is unsatisfying as drama, it's frequently beautiful just as a tour through architecturally significant Italian buildings."
|
||||
La Sapienza,2251985,2015-03-17,David Ehrlich,3/5,fresh,La Sapienza alternately feels like a self-reflexive love story or a haunted history lesson -- its best scenes play like both.
|
||||
La Sapienza,2251926,2015-03-17,Zachary Wigon,,fresh,A picture that balances heart and mind with nuance.
|
||||
La Sapienza,2251650,2015-03-14,Harvey S. Karten,B+,fresh,"As in ""Who's Afraid of Virginia Woolf,"" both the younger couple and their older mentors are changed from a relationship."
|
||||
La Sapienza,2250991,2015-03-12,Ben Sachs,,fresh,"This recalls Manoel de Oliveira and Eric Rohmer in its poker-faced style, deliberately archaic storytelling, and magisterial epiphanies."
|
||||
La Sapienza,2225361,2014-09-28,Donald J. Levit,,fresh,"Although a love-fiction crossed with documentary lecture and superb Raphael O'Byrne cinematography, 'La Sapienza' is as close as celluloid can approach to architecture."
|
||||
La Sapienza,2222032,2014-09-10,Carson Lund,3/4,fresh,"Eugne Green's mannered direction doesn't work for every situation it's homogenously applied to, but at its most effective it inspires an enhanced sensitivity to the import of every gesture, visual or verbal."
|
||||
Uncle Tom,2713732,2020-08-14,Megan Basham,,fresh,Uncle Tom suffers from an overreliance on pundits. Its most compelling insights come from people who've never been quoted in a Twitter or Facebook battle.
|
||||
Uncle Tom,2706229,2020-07-19,Matthew Pejkovic,4/5,fresh,"An incredibly relevant and insightful documentary that delves into the past, present, and future of the black American conservative movement."
|
||||
Uncle Tom,2698525,2020-06-24,Dante James,7/10,fresh,"It's a little misleading in some areas, especially if you know the players involved in this doc, but there are a lot of interesting historical facts about the breakdown of the Black family and how the whole welfare system targeted the Black community."
|
||||
|
@@ -0,0 +1,65 @@
|
||||
import { DataType } from "@zilliz/milvus2-sdk-node";
|
||||
import {
|
||||
MilvusVectorStore,
|
||||
PapaCSVReader,
|
||||
storageContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "movie_reviews";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const reader = new PapaCSVReader(false);
|
||||
const docs = await reader.loadData("./data/movie_reviews.csv");
|
||||
|
||||
const vectorStore = new MilvusVectorStore({
|
||||
contentKey: "content",
|
||||
});
|
||||
|
||||
const milvus = vectorStore.client();
|
||||
|
||||
await milvus.createCollection({
|
||||
collection_name: collectionName,
|
||||
fields: [
|
||||
{
|
||||
name: "id",
|
||||
data_type: DataType.VarChar,
|
||||
is_primary_key: true,
|
||||
max_length: 200,
|
||||
},
|
||||
{
|
||||
name: "embedding",
|
||||
data_type: DataType.FloatVector,
|
||||
dim: 1536,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
data_type: DataType.VarChar,
|
||||
max_length: 9000,
|
||||
},
|
||||
{
|
||||
name: "metadata",
|
||||
data_type: DataType.JSON,
|
||||
},
|
||||
],
|
||||
});
|
||||
await milvus.createIndex({
|
||||
collection_name: collectionName,
|
||||
field_name: "embedding",
|
||||
index_type: "HNSW",
|
||||
params: { efConstruction: 10, M: 4 },
|
||||
metric_type: "L2",
|
||||
});
|
||||
await vectorStore.connect(collectionName);
|
||||
|
||||
const ctx = await storageContextFromDefaults({ vectorStore });
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: ctx,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
MilvusVectorStore,
|
||||
serviceContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "movie_reviews";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const milvus = new MilvusVectorStore({
|
||||
contentKey: "content",
|
||||
});
|
||||
await milvus.connect(collectionName);
|
||||
|
||||
const ctx = serviceContextFromDefaults();
|
||||
const index = await VectorStoreIndex.fromVectorStore(milvus, ctx);
|
||||
|
||||
const retriever = await index.asRetriever({ similarityTopK: 20 });
|
||||
|
||||
const queryEngine = await index.asQueryEngine({ retriever });
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query: "What is the best reviewed movie?",
|
||||
});
|
||||
|
||||
console.log(results.response);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -27,9 +27,9 @@ async function main() {
|
||||
// retrieve documents using the index
|
||||
const index = await createIndex();
|
||||
const retriever = index.asRetriever({ similarityTopK: 3 });
|
||||
const results = await retriever.retrieve(
|
||||
"what are Vincent van Gogh's famous paintings",
|
||||
);
|
||||
const results = await retriever.retrieve({
|
||||
query: "what are Vincent van Gogh's famous paintings",
|
||||
});
|
||||
for (const result of results) {
|
||||
const node = result.node;
|
||||
if (!node) {
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
{
|
||||
"name": "examples",
|
||||
"private": true,
|
||||
"version": "0.0.3",
|
||||
"version": "0.0.4",
|
||||
"dependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@datastax/astra-db-ts": "^0.1.4",
|
||||
"@notionhq/client": "^2.2.14",
|
||||
"@pinecone-database/pinecone": "^1.1.3",
|
||||
"@zilliz/milvus2-sdk-node": "^2.3.5",
|
||||
"chromadb": "^1.8.1",
|
||||
"commander": "^11.1.0",
|
||||
"dotenv": "^16.4.1",
|
||||
"llamaindex": "latest",
|
||||
"mongodb": "^6.2.0"
|
||||
"llamaindex": "workspace:*",
|
||||
"mongodb": "^6.2.0",
|
||||
"pathe": "^1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.10",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# llamaindex-loader-example
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d2e8d0c]
|
||||
- Updated dependencies [aefc326]
|
||||
- Updated dependencies [484a710]
|
||||
- Updated dependencies [d766bd0]
|
||||
- Updated dependencies [dd95927]
|
||||
- Updated dependencies [bf583a7]
|
||||
- llamaindex@0.2.0
|
||||
@@ -12,11 +12,12 @@
|
||||
"start:llamaparse": "node --loader ts-node/esm ./src/llamaparse.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"llamaindex": "latest"
|
||||
"llamaindex": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.14",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.3.3"
|
||||
}
|
||||
},
|
||||
"version": null
|
||||
}
|
||||
|
||||
+1
-3
@@ -12,9 +12,7 @@
|
||||
"test": "turbo run test",
|
||||
"type-check": "tsc -b --diagnostics",
|
||||
"release": "pnpm run build:release && changeset publish",
|
||||
"new-llamaindex": "pnpm run build:release && changeset version --ignore create-llama",
|
||||
"new-create-llama": "pnpm run build:release && changeset version --ignore llamaindex",
|
||||
"new-snapshots": "pnpm run build:release && changeset version --snapshot"
|
||||
"new-version": "pnpm run build:release && changeset version"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.1",
|
||||
|
||||
@@ -1,5 +1,32 @@
|
||||
# llamaindex
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- bf583a7: Use parameter object for retrieve function of Retriever (to align usage with query function of QueryEngine)
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d2e8d0c: add support for Milvus vector store
|
||||
- aefc326: feat: experimental package + json query engine
|
||||
- 484a710: - Add missing exports:
|
||||
- `IndexStructType`,
|
||||
- `IndexDict`,
|
||||
- `jsonToIndexStruct`,
|
||||
- `IndexList`,
|
||||
- `IndexStruct`
|
||||
- Fix `IndexDict.toJson()` method
|
||||
- d766bd0: Add streaming to agents
|
||||
- dd95927: add Claude Haiku support and update anthropic SDK
|
||||
|
||||
## 0.1.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 552a61a: Add quantized parameter to HuggingFaceEmbedding
|
||||
- d824876: Add support for Claude 3
|
||||
|
||||
## 0.1.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/core",
|
||||
"version": "0.1.20",
|
||||
"version": "0.1.21",
|
||||
"exports": "./src/index.ts",
|
||||
"imports": {
|
||||
"@llamaindex/env": "jsr:@llamaindex/env@0.0.5"
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "llamaindex",
|
||||
"version": "0.1.20",
|
||||
"version": "0.2.0",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.15.0",
|
||||
"@anthropic-ai/sdk": "^0.18.0",
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@datastax/astra-db-ts": "^0.1.4",
|
||||
"@grpc/grpc-js": "^1.10.2",
|
||||
"@llamaindex/cloud": "0.0.4",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@mistralai/mistralai": "^0.0.10",
|
||||
@@ -18,6 +19,7 @@
|
||||
"@types/papaparse": "^5.3.14",
|
||||
"@types/pg": "^8.11.0",
|
||||
"@xenova/transformers": "^2.15.0",
|
||||
"@zilliz/milvus2-sdk-node": "^2.3.5",
|
||||
"assemblyai": "^4.2.2",
|
||||
"chromadb": "~1.7.3",
|
||||
"cohere-ai": "^7.7.5",
|
||||
@@ -92,9 +94,9 @@
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"build": "rm -rf ./dist && pnpm run build:esm && pnpm run build:cjs && pnpm run build:type",
|
||||
"build:esm": "swc src -d dist --strip-leading-paths --config-file .swcrc",
|
||||
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file .cjs.swcrc",
|
||||
"build:type": "pnpm run -w type-check",
|
||||
"build:esm": "swc src -d dist --strip-leading-paths --config-file ../../.swcrc",
|
||||
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file ../../.cjs.swcrc",
|
||||
"build:type": "tsc -p tsconfig.json",
|
||||
"copy": "cp -r ../../README.md ../../LICENSE .",
|
||||
"postbuild": "pnpm run copy && node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
|
||||
"circular-check": "madge -c ./src/index.ts",
|
||||
|
||||
@@ -2,14 +2,16 @@ import type { Event } from "./callbacks/CallbackManager.js";
|
||||
import type { NodeWithScore } from "./Node.js";
|
||||
import type { ServiceContext } from "./ServiceContext.js";
|
||||
|
||||
export type RetrieveParams = {
|
||||
query: string;
|
||||
parentEvent?: Event;
|
||||
preFilters?: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrievers retrieve the nodes that most closely match our query in similarity.
|
||||
*/
|
||||
export interface BaseRetriever {
|
||||
retrieve(
|
||||
query: string,
|
||||
parentEvent?: Event,
|
||||
preFilters?: unknown,
|
||||
): Promise<NodeWithScore[]>;
|
||||
retrieve(params: RetrieveParams): Promise<NodeWithScore[]>;
|
||||
getServiceContext(): ServiceContext;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// Assuming that the necessary interfaces and classes (like BaseTool, OpenAI, ChatMessage, CallbackManager, etc.) are defined elsewhere
|
||||
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import { Response } from "../../Response.js";
|
||||
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
|
||||
import {
|
||||
AgentChatResponse,
|
||||
ChatResponseMode,
|
||||
StreamingAgentChatResponse,
|
||||
} from "../../engines/chat/types.js";
|
||||
import type {
|
||||
ChatMessage,
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ChatResponseChunk,
|
||||
} from "../../llm/index.js";
|
||||
import { OpenAI } from "../../llm/index.js";
|
||||
import { streamConverter, streamReducer } from "../../llm/utils.js";
|
||||
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
|
||||
import type { ObjectRetriever } from "../../objects/base.js";
|
||||
import type { ToolOutput } from "../../tools/types.js";
|
||||
@@ -192,13 +193,40 @@ export class OpenAIAgentWorker implements AgentWorker {
|
||||
private _processMessage(
|
||||
task: Task,
|
||||
chatResponse: ChatResponse,
|
||||
): AgentChatResponse | AsyncIterable<ChatResponseChunk> {
|
||||
): AgentChatResponse {
|
||||
const aiMessage = chatResponse.message;
|
||||
task.extraState.newMemory.put(aiMessage);
|
||||
|
||||
return new AgentChatResponse(aiMessage.content, task.extraState.sources);
|
||||
}
|
||||
|
||||
private async _getStreamAiResponse(
|
||||
task: Task,
|
||||
llmChatKwargs: any,
|
||||
): Promise<StreamingAgentChatResponse> {
|
||||
const stream = await this.llm.chat({
|
||||
stream: true,
|
||||
...llmChatKwargs,
|
||||
});
|
||||
|
||||
const iterator = streamConverter(
|
||||
streamReducer({
|
||||
stream,
|
||||
initialValue: "",
|
||||
reducer: (accumulator, part) => (accumulator += part.delta),
|
||||
finished: (accumulator) => {
|
||||
task.extraState.newMemory.put({
|
||||
content: accumulator,
|
||||
role: "assistant",
|
||||
});
|
||||
},
|
||||
}),
|
||||
(r: ChatResponseChunk) => new Response(r.delta),
|
||||
);
|
||||
|
||||
return new StreamingAgentChatResponse(iterator, task.extraState.sources);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent response.
|
||||
* @param task: task
|
||||
@@ -210,7 +238,7 @@ export class OpenAIAgentWorker implements AgentWorker {
|
||||
task: Task,
|
||||
mode: ChatResponseMode,
|
||||
llmChatKwargs: any,
|
||||
): Promise<AgentChatResponse> {
|
||||
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
|
||||
if (mode === ChatResponseMode.WAIT) {
|
||||
const chatResponse = (await this.llm.chat({
|
||||
stream: false,
|
||||
@@ -218,9 +246,11 @@ export class OpenAIAgentWorker implements AgentWorker {
|
||||
})) as unknown as ChatResponse;
|
||||
|
||||
return this._processMessage(task, chatResponse) as AgentChatResponse;
|
||||
} else {
|
||||
throw new Error("Not implemented");
|
||||
} else if (mode === ChatResponseMode.STREAM) {
|
||||
return this._getStreamAiResponse(task, llmChatKwargs);
|
||||
}
|
||||
|
||||
throw new Error("Invalid mode");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
|
||||
import {
|
||||
AgentChatResponse,
|
||||
ChatResponseMode,
|
||||
StreamingAgentChatResponse,
|
||||
} from "../../engines/chat/index.js";
|
||||
import type { ChatMessage, LLM } from "../../llm/index.js";
|
||||
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
|
||||
@@ -231,23 +232,26 @@ export class AgentRunner extends BaseAgentRunner {
|
||||
taskId: string,
|
||||
stepOutput: TaskStepOutput,
|
||||
kwargs?: any,
|
||||
): Promise<AgentChatResponse> {
|
||||
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
|
||||
if (!stepOutput) {
|
||||
stepOutput =
|
||||
this.getCompletedSteps(taskId)[
|
||||
this.getCompletedSteps(taskId).length - 1
|
||||
];
|
||||
}
|
||||
|
||||
if (!stepOutput.isLast) {
|
||||
throw new Error(
|
||||
"finalizeResponse can only be called on the last step output",
|
||||
);
|
||||
}
|
||||
|
||||
if (!(stepOutput.output instanceof AgentChatResponse)) {
|
||||
throw new Error(
|
||||
`When \`isLast\` is True, cur_step_output.output must be AGENT_CHAT_RESPONSE_TYPE: ${stepOutput.output}`,
|
||||
);
|
||||
if (!(stepOutput.output instanceof StreamingAgentChatResponse)) {
|
||||
if (!(stepOutput.output instanceof AgentChatResponse)) {
|
||||
throw new Error(
|
||||
`When \`isLast\` is True, cur_step_output.output must be AGENT_CHAT_RESPONSE_TYPE: ${stepOutput.output}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.agentWorker.finalizeTask(this.getTask(taskId), kwargs);
|
||||
@@ -262,20 +266,32 @@ export class AgentRunner extends BaseAgentRunner {
|
||||
protected async _chat({
|
||||
message,
|
||||
toolChoice,
|
||||
}: ChatEngineAgentParams & { mode: ChatResponseMode }) {
|
||||
stream,
|
||||
}: ChatEngineAgentParams): Promise<AgentChatResponse>;
|
||||
protected async _chat({
|
||||
message,
|
||||
toolChoice,
|
||||
stream,
|
||||
}: ChatEngineAgentParams & {
|
||||
stream: true;
|
||||
}): Promise<StreamingAgentChatResponse>;
|
||||
protected async _chat({
|
||||
message,
|
||||
toolChoice,
|
||||
stream,
|
||||
}: ChatEngineAgentParams): Promise<
|
||||
AgentChatResponse | StreamingAgentChatResponse
|
||||
> {
|
||||
const task = this.createTask(message as string);
|
||||
|
||||
let resultOutput;
|
||||
|
||||
const mode = stream ? ChatResponseMode.STREAM : ChatResponseMode.WAIT;
|
||||
|
||||
while (true) {
|
||||
const curStepOutput = await this._runStep(
|
||||
task.taskId,
|
||||
undefined,
|
||||
ChatResponseMode.WAIT,
|
||||
{
|
||||
toolChoice,
|
||||
},
|
||||
);
|
||||
const curStepOutput = await this._runStep(task.taskId, undefined, mode, {
|
||||
toolChoice,
|
||||
});
|
||||
|
||||
if (curStepOutput.isLast) {
|
||||
resultOutput = curStepOutput;
|
||||
@@ -299,7 +315,26 @@ export class AgentRunner extends BaseAgentRunner {
|
||||
message,
|
||||
chatHistory,
|
||||
toolChoice,
|
||||
}: ChatEngineAgentParams): Promise<AgentChatResponse> {
|
||||
stream,
|
||||
}: ChatEngineAgentParams & {
|
||||
stream?: false;
|
||||
}): Promise<AgentChatResponse>;
|
||||
public async chat({
|
||||
message,
|
||||
chatHistory,
|
||||
toolChoice,
|
||||
stream,
|
||||
}: ChatEngineAgentParams & {
|
||||
stream: true;
|
||||
}): Promise<StreamingAgentChatResponse>;
|
||||
public async chat({
|
||||
message,
|
||||
chatHistory,
|
||||
toolChoice,
|
||||
stream,
|
||||
}: ChatEngineAgentParams): Promise<
|
||||
AgentChatResponse | StreamingAgentChatResponse
|
||||
> {
|
||||
if (!toolChoice) {
|
||||
toolChoice = this.defaultToolChoice;
|
||||
}
|
||||
@@ -308,7 +343,7 @@ export class AgentRunner extends BaseAgentRunner {
|
||||
message,
|
||||
chatHistory,
|
||||
toolChoice,
|
||||
mode: ChatResponseMode.WAIT,
|
||||
stream,
|
||||
});
|
||||
|
||||
return chatResponse;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { AgentChatResponse } from "../../engines/chat/index.js";
|
||||
import type {
|
||||
AgentChatResponse,
|
||||
StreamingAgentChatResponse,
|
||||
} from "../../engines/chat/index.js";
|
||||
import type { Task, TaskStep, TaskStepOutput } from "../types.js";
|
||||
import { BaseAgent } from "../types.js";
|
||||
|
||||
@@ -57,7 +60,7 @@ export abstract class BaseAgentRunner extends BaseAgent {
|
||||
taskId: string,
|
||||
stepOutput: TaskStepOutput,
|
||||
kwargs?: any,
|
||||
): Promise<AgentChatResponse>;
|
||||
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
|
||||
|
||||
abstract undoStep(taskId: string): void;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type {
|
||||
AgentChatResponse,
|
||||
ChatEngineAgentParams,
|
||||
StreamingAgentChatResponse,
|
||||
} from "../engines/chat/index.js";
|
||||
|
||||
import type { QueryEngineParamsNonStreaming } from "../types.js";
|
||||
|
||||
export interface AgentWorker {
|
||||
@@ -12,11 +14,15 @@ export interface AgentWorker {
|
||||
}
|
||||
|
||||
interface BaseChatEngine {
|
||||
chat(params: ChatEngineAgentParams): Promise<AgentChatResponse>;
|
||||
chat(
|
||||
params: ChatEngineAgentParams,
|
||||
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
|
||||
}
|
||||
|
||||
interface BaseQueryEngine {
|
||||
query(params: QueryEngineParamsNonStreaming): Promise<AgentChatResponse>;
|
||||
query(
|
||||
params: QueryEngineParamsNonStreaming,
|
||||
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -31,7 +37,10 @@ export abstract class BaseAgent implements BaseChatEngine, BaseQueryEngine {
|
||||
return [];
|
||||
}
|
||||
|
||||
abstract chat(params: ChatEngineAgentParams): Promise<AgentChatResponse>;
|
||||
abstract chat(
|
||||
params: ChatEngineAgentParams,
|
||||
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
|
||||
|
||||
abstract reset(): void;
|
||||
|
||||
/**
|
||||
@@ -41,7 +50,7 @@ export abstract class BaseAgent implements BaseChatEngine, BaseQueryEngine {
|
||||
*/
|
||||
async query(
|
||||
params: QueryEngineParamsNonStreaming,
|
||||
): Promise<AgentChatResponse> {
|
||||
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
|
||||
// Handle non-streaming query
|
||||
const agentResponse = await this.chat({
|
||||
message: params.query,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { RetrieverQueryEngine } from "../engines/query/RetrieverQueryEngine.js";
|
||||
import type { BaseNodePostprocessor } from "../postprocessors/types.js";
|
||||
import type { BaseSynthesizer } from "../synthesizers/types.js";
|
||||
import type { BaseQueryEngine } from "../types.js";
|
||||
import type { RetrieveParams } from "./LlamaCloudRetriever.js";
|
||||
import type { CloudRetrieveParams } from "./LlamaCloudRetriever.js";
|
||||
import { LlamaCloudRetriever } from "./LlamaCloudRetriever.js";
|
||||
import type { CloudConstructorParams } from "./types.js";
|
||||
|
||||
@@ -14,7 +14,7 @@ export class LlamaCloudIndex {
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
asRetriever(params: RetrieveParams = {}): BaseRetriever {
|
||||
asRetriever(params: CloudRetrieveParams = {}): BaseRetriever {
|
||||
return new LlamaCloudRetriever({ ...this.params, ...params });
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export class LlamaCloudIndex {
|
||||
responseSynthesizer?: BaseSynthesizer;
|
||||
preFilters?: unknown;
|
||||
nodePostprocessors?: BaseNodePostprocessor[];
|
||||
} & RetrieveParams,
|
||||
} & CloudRetrieveParams,
|
||||
): BaseQueryEngine {
|
||||
const retriever = new LlamaCloudRetriever({
|
||||
...this.params,
|
||||
|
||||
@@ -2,15 +2,14 @@ import type { PlatformApi, PlatformApiClient } from "@llamaindex/cloud";
|
||||
import { globalsHelper } from "../GlobalsHelper.js";
|
||||
import type { NodeWithScore } from "../Node.js";
|
||||
import { ObjectType, jsonToNode } from "../Node.js";
|
||||
import type { BaseRetriever } from "../Retriever.js";
|
||||
import type { BaseRetriever, RetrieveParams } from "../Retriever.js";
|
||||
import type { ServiceContext } from "../ServiceContext.js";
|
||||
import { serviceContextFromDefaults } from "../ServiceContext.js";
|
||||
import type { Event } from "../callbacks/CallbackManager.js";
|
||||
import type { ClientParams, CloudConstructorParams } from "./types.js";
|
||||
import { DEFAULT_PROJECT_NAME } from "./types.js";
|
||||
import { getClient } from "./utils.js";
|
||||
|
||||
export type RetrieveParams = Omit<
|
||||
export type CloudRetrieveParams = Omit<
|
||||
PlatformApi.RetrievalParams,
|
||||
"query" | "searchFilters" | "pipelineId" | "className"
|
||||
> & { similarityTopK?: number };
|
||||
@@ -18,7 +17,7 @@ export type RetrieveParams = Omit<
|
||||
export class LlamaCloudRetriever implements BaseRetriever {
|
||||
client?: PlatformApiClient;
|
||||
clientParams: ClientParams;
|
||||
retrieveParams: RetrieveParams;
|
||||
retrieveParams: CloudRetrieveParams;
|
||||
projectName: string = DEFAULT_PROJECT_NAME;
|
||||
pipelineName: string;
|
||||
serviceContext: ServiceContext;
|
||||
@@ -35,7 +34,7 @@ export class LlamaCloudRetriever implements BaseRetriever {
|
||||
});
|
||||
}
|
||||
|
||||
constructor(params: CloudConstructorParams & RetrieveParams) {
|
||||
constructor(params: CloudConstructorParams & CloudRetrieveParams) {
|
||||
this.clientParams = { apiKey: params.apiKey, baseUrl: params.baseUrl };
|
||||
if (params.similarityTopK) {
|
||||
params.denseSimilarityTopK = params.similarityTopK;
|
||||
@@ -55,11 +54,11 @@ export class LlamaCloudRetriever implements BaseRetriever {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
async retrieve(
|
||||
query: string,
|
||||
parentEvent?: Event | undefined,
|
||||
preFilters?: unknown,
|
||||
): Promise<NodeWithScore[]> {
|
||||
async retrieve({
|
||||
query,
|
||||
parentEvent,
|
||||
preFilters,
|
||||
}: RetrieveParams): Promise<NodeWithScore[]> {
|
||||
const pipelines = await (
|
||||
await this.getClient()
|
||||
).pipeline.searchPipelines({
|
||||
|
||||
@@ -64,10 +64,10 @@ export class DefaultContextGenerator
|
||||
tags: ["final"],
|
||||
};
|
||||
}
|
||||
const sourceNodesWithScore = await this.retriever.retrieve(
|
||||
message,
|
||||
const sourceNodesWithScore = await this.retriever.retrieve({
|
||||
query: message,
|
||||
parentEvent,
|
||||
);
|
||||
});
|
||||
|
||||
const nodes = await this.applyNodePostprocessors(
|
||||
sourceNodesWithScore,
|
||||
|
||||
@@ -27,6 +27,7 @@ export interface ChatEngineParamsNonStreaming extends ChatEngineParamsBase {
|
||||
|
||||
export interface ChatEngineAgentParams extends ChatEngineParamsBase {
|
||||
toolChoice?: string | Record<string, any>;
|
||||
stream?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,3 +87,20 @@ export class AgentChatResponse {
|
||||
return this.response ?? "";
|
||||
}
|
||||
}
|
||||
|
||||
export class StreamingAgentChatResponse {
|
||||
response: AsyncIterable<Response>;
|
||||
|
||||
sources: ToolOutput[];
|
||||
sourceNodes?: BaseNode[];
|
||||
|
||||
constructor(
|
||||
response: AsyncIterable<Response>,
|
||||
sources?: ToolOutput[],
|
||||
sourceNodes?: BaseNode[],
|
||||
) {
|
||||
this.response = response;
|
||||
this.sources = sources ?? [];
|
||||
this.sourceNodes = sourceNodes ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,11 +63,11 @@ export class RetrieverQueryEngine
|
||||
}
|
||||
|
||||
private async retrieve(query: string, parentEvent: Event) {
|
||||
const nodes = await this.retriever.retrieve(
|
||||
const nodes = await this.retriever.retrieve({
|
||||
query,
|
||||
parentEvent,
|
||||
this.preFilters,
|
||||
);
|
||||
preFilters: this.preFilters,
|
||||
});
|
||||
|
||||
return await this.applyNodePostprocessors(nodes, query);
|
||||
}
|
||||
|
||||
@@ -30,3 +30,4 @@ export * from "./selectors/index.js";
|
||||
export * from "./storage/index.js";
|
||||
export * from "./synthesizers/index.js";
|
||||
export * from "./tools/index.js";
|
||||
export * from "./types.js";
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
export * from "./BaseIndex.js";
|
||||
export * from "./IndexStruct.js";
|
||||
export * from "./json-to-index-struct.js";
|
||||
export * from "./keyword/index.js";
|
||||
export * from "./summary/index.js";
|
||||
export * from "./vectorStore/index.js";
|
||||
|
||||
@@ -24,9 +24,15 @@ export class IndexDict extends IndexStruct {
|
||||
}
|
||||
|
||||
toJson(): Record<string, unknown> {
|
||||
const nodesDict: Record<string, unknown> = {};
|
||||
|
||||
for (const [key, node] of Object.entries(this.nodesDict)) {
|
||||
nodesDict[key] = node.toJSON();
|
||||
}
|
||||
|
||||
return {
|
||||
...super.toJson(),
|
||||
nodesDict: this.nodesDict,
|
||||
nodesDict,
|
||||
type: this.type,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
defaultKeywordExtractPrompt,
|
||||
defaultQueryKeywordExtractPrompt,
|
||||
} from "../../Prompt.js";
|
||||
import type { BaseRetriever } from "../../Retriever.js";
|
||||
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
|
||||
import type { ServiceContext } from "../../ServiceContext.js";
|
||||
import { serviceContextFromDefaults } from "../../ServiceContext.js";
|
||||
import { RetrieverQueryEngine } from "../../engines/query/index.js";
|
||||
@@ -79,7 +79,7 @@ abstract class BaseKeywordTableRetriever implements BaseRetriever {
|
||||
|
||||
abstract getKeywords(query: string): Promise<string[]>;
|
||||
|
||||
async retrieve(query: string): Promise<NodeWithScore[]> {
|
||||
async retrieve({ query }: RetrieveParams): Promise<NodeWithScore[]> {
|
||||
const keywords = await this.getKeywords(query);
|
||||
const chunkIndicesCount: { [key: string]: number } = {};
|
||||
const filteredKeywords = keywords.filter((keyword) =>
|
||||
|
||||
@@ -3,10 +3,9 @@ import { globalsHelper } from "../../GlobalsHelper.js";
|
||||
import type { BaseNode, Document, NodeWithScore } from "../../Node.js";
|
||||
import type { ChoiceSelectPrompt } from "../../Prompt.js";
|
||||
import { defaultChoiceSelectPrompt } from "../../Prompt.js";
|
||||
import type { BaseRetriever } from "../../Retriever.js";
|
||||
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
|
||||
import type { ServiceContext } from "../../ServiceContext.js";
|
||||
import { serviceContextFromDefaults } from "../../ServiceContext.js";
|
||||
import type { Event } from "../../callbacks/CallbackManager.js";
|
||||
import { RetrieverQueryEngine } from "../../engines/query/index.js";
|
||||
import type { BaseNodePostprocessor } from "../../postprocessors/index.js";
|
||||
import type {
|
||||
@@ -281,7 +280,10 @@ export class SummaryIndexRetriever implements BaseRetriever {
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
async retrieve(query: string, parentEvent?: Event): Promise<NodeWithScore[]> {
|
||||
async retrieve({
|
||||
query,
|
||||
parentEvent,
|
||||
}: RetrieveParams): Promise<NodeWithScore[]> {
|
||||
const nodeIds = this.index.indexStruct.nodes;
|
||||
const nodes = await this.index.docStore.getNodes(nodeIds);
|
||||
const result = nodes.map((node) => ({
|
||||
@@ -337,7 +339,10 @@ export class SummaryIndexLLMRetriever implements BaseRetriever {
|
||||
this.serviceContext = serviceContext || index.serviceContext;
|
||||
}
|
||||
|
||||
async retrieve(query: string, parentEvent?: Event): Promise<NodeWithScore[]> {
|
||||
async retrieve({
|
||||
query,
|
||||
parentEvent,
|
||||
}: RetrieveParams): Promise<NodeWithScore[]> {
|
||||
const nodeIds = this.index.indexStruct.nodes;
|
||||
const results: NodeWithScore[] = [];
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
ObjectType,
|
||||
splitNodesByType,
|
||||
} from "../../Node.js";
|
||||
import type { BaseRetriever } from "../../Retriever.js";
|
||||
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
|
||||
import type { ServiceContext } from "../../ServiceContext.js";
|
||||
import { serviceContextFromDefaults } from "../../ServiceContext.js";
|
||||
import type { Event } from "../../callbacks/CallbackManager.js";
|
||||
@@ -426,14 +426,17 @@ export class VectorIndexRetriever implements BaseRetriever {
|
||||
this.imageSimilarityTopK = imageSimilarityTopK ?? DEFAULT_SIMILARITY_TOP_K;
|
||||
}
|
||||
|
||||
async retrieve(
|
||||
query: string,
|
||||
parentEvent?: Event,
|
||||
preFilters?: MetadataFilters,
|
||||
): Promise<NodeWithScore[]> {
|
||||
let nodesWithScores = await this.textRetrieve(query, preFilters);
|
||||
async retrieve({
|
||||
query,
|
||||
parentEvent,
|
||||
preFilters,
|
||||
}: RetrieveParams): Promise<NodeWithScore[]> {
|
||||
let nodesWithScores = await this.textRetrieve(
|
||||
query,
|
||||
preFilters as MetadataFilters,
|
||||
);
|
||||
nodesWithScores = nodesWithScores.concat(
|
||||
await this.textToImageRetrieve(query, preFilters),
|
||||
await this.textToImageRetrieve(query, preFilters as MetadataFilters),
|
||||
);
|
||||
this.sendEvent(query, nodesWithScores, parentEvent);
|
||||
return nodesWithScores;
|
||||
|
||||
@@ -620,6 +620,7 @@ export const ALL_AVAILABLE_ANTHROPIC_LEGACY_MODELS = {
|
||||
export const ALL_AVAILABLE_V3_MODELS = {
|
||||
"claude-3-opus": { contextWindow: 200000 },
|
||||
"claude-3-sonnet": { contextWindow: 200000 },
|
||||
"claude-3-haiku": { contextWindow: 200000 },
|
||||
};
|
||||
|
||||
export const ALL_AVAILABLE_ANTHROPIC_MODELS = {
|
||||
@@ -630,6 +631,7 @@ export const ALL_AVAILABLE_ANTHROPIC_MODELS = {
|
||||
const AVAILABLE_ANTHROPIC_MODELS_WITHOUT_DATE: { [key: string]: string } = {
|
||||
"claude-3-opus": "claude-3-opus-20240229",
|
||||
"claude-3-sonnet": "claude-3-sonnet-20240229",
|
||||
"claude-3-haiku": "claude-3-haiku-20240307",
|
||||
} as { [key in keyof typeof ALL_AVAILABLE_ANTHROPIC_MODELS]: string };
|
||||
|
||||
/**
|
||||
|
||||
@@ -69,7 +69,7 @@ export class ObjectRetriever {
|
||||
|
||||
// Translating the retrieve method
|
||||
async retrieve(strOrQueryBundle: QueryType): Promise<any> {
|
||||
const nodes = await this.retriever.retrieve(strOrQueryBundle);
|
||||
const nodes = await this.retriever.retrieve({ query: strOrQueryBundle });
|
||||
const objs = nodes.map((n) => this._objectNodeMapping.fromNode(n.node));
|
||||
return objs;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ export { SimpleKVStore } from "./kvStore/SimpleKVStore.js";
|
||||
export * from "./kvStore/types.js";
|
||||
export { AstraDBVectorStore } from "./vectorStore/AstraDBVectorStore.js";
|
||||
export { ChromaVectorStore } from "./vectorStore/ChromaVectorStore.js";
|
||||
export { MilvusVectorStore } from "./vectorStore/MilvusVectorStore.js";
|
||||
export { MongoDBAtlasVectorSearch } from "./vectorStore/MongoDBAtlasVectorStore.js";
|
||||
export { PGVectorStore } from "./vectorStore/PGVectorStore.js";
|
||||
export { PineconeVectorStore } from "./vectorStore/PineconeVectorStore.js";
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/* eslint-disable turbo/no-undeclared-env-vars */
|
||||
import type { ChannelOptions } from "@grpc/grpc-js";
|
||||
import {
|
||||
MilvusClient,
|
||||
type ClientConfig,
|
||||
type DeleteReq,
|
||||
type RowData,
|
||||
} from "@zilliz/milvus2-sdk-node";
|
||||
import { BaseNode, Document, MetadataMode, type Metadata } from "../../Node.js";
|
||||
import type {
|
||||
VectorStore,
|
||||
VectorStoreQuery,
|
||||
VectorStoreQueryResult,
|
||||
} from "./types.js";
|
||||
|
||||
export class MilvusVectorStore implements VectorStore {
|
||||
public storesText: boolean = true;
|
||||
public isEmbeddingQuery?: boolean;
|
||||
|
||||
private milvusClient: MilvusClient;
|
||||
private collection: string = "";
|
||||
|
||||
private idKey: string;
|
||||
private contentKey: string | undefined; // if undefined the entirety of the node aside from the id and embedding will be stored as content
|
||||
private metadataKey: string;
|
||||
private embeddingKey: string;
|
||||
|
||||
constructor(
|
||||
init?: Partial<{ milvusClient: MilvusClient }> & {
|
||||
params?: {
|
||||
configOrAddress: ClientConfig | string;
|
||||
ssl?: boolean;
|
||||
username?: string;
|
||||
password?: string;
|
||||
channelOptions?: ChannelOptions;
|
||||
};
|
||||
idKey?: string;
|
||||
contentKey?: string;
|
||||
metadataKey?: string;
|
||||
embeddingKey?: string;
|
||||
},
|
||||
) {
|
||||
if (init?.milvusClient) {
|
||||
this.milvusClient = init.milvusClient;
|
||||
} else {
|
||||
const configOrAddress =
|
||||
init?.params?.configOrAddress ?? process.env.MILVUS_ADDRESS;
|
||||
const ssl = init?.params?.ssl ?? process.env.MILVUS_SSL === "true";
|
||||
const username = init?.params?.username ?? process.env.MILVUS_USERNAME;
|
||||
const password = init?.params?.password ?? process.env.MILVUS_PASSWORD;
|
||||
|
||||
if (!configOrAddress) {
|
||||
throw new Error("Must specify MILVUS_ADDRESS via env variable.");
|
||||
}
|
||||
this.milvusClient = new MilvusClient(
|
||||
configOrAddress,
|
||||
ssl,
|
||||
username,
|
||||
password,
|
||||
init?.params?.channelOptions,
|
||||
);
|
||||
}
|
||||
|
||||
this.idKey = init?.idKey ?? "id";
|
||||
this.contentKey = init?.contentKey;
|
||||
this.metadataKey = init?.metadataKey ?? "metadata";
|
||||
this.embeddingKey = init?.embeddingKey ?? "embedding";
|
||||
}
|
||||
|
||||
public client(): MilvusClient {
|
||||
return this.milvusClient;
|
||||
}
|
||||
|
||||
public async connect(collection: string): Promise<void> {
|
||||
await this.milvusClient.connectPromise;
|
||||
await this.milvusClient.loadCollectionSync({
|
||||
collection_name: collection,
|
||||
});
|
||||
|
||||
this.collection = collection;
|
||||
}
|
||||
|
||||
public async add(nodes: BaseNode<Metadata>[]): Promise<string[]> {
|
||||
if (!this.collection) {
|
||||
throw new Error("Must connect to collection before adding.");
|
||||
}
|
||||
|
||||
const result = await this.milvusClient.insert({
|
||||
collection_name: this.collection,
|
||||
data: nodes.map((node) => {
|
||||
const entry: RowData = {
|
||||
[this.idKey]: node.id_,
|
||||
[this.embeddingKey]: node.getEmbedding(),
|
||||
[this.metadataKey]: node.metadata ?? {},
|
||||
};
|
||||
|
||||
if (this.contentKey) {
|
||||
entry[this.contentKey] = String(node.getContent(MetadataMode.NONE));
|
||||
}
|
||||
|
||||
return entry;
|
||||
}),
|
||||
});
|
||||
|
||||
if (!result.IDs) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if ("int_id" in result.IDs) {
|
||||
return result.IDs.int_id.data.map((i) => String(i));
|
||||
}
|
||||
|
||||
return result.IDs.str_id.data.map((s) => String(s));
|
||||
}
|
||||
|
||||
public async delete(
|
||||
refDocId: string,
|
||||
deleteOptions?: Omit<DeleteReq, "ids">,
|
||||
): Promise<void> {
|
||||
await this.milvusClient.delete({
|
||||
ids: [refDocId],
|
||||
collection_name: this.collection,
|
||||
...deleteOptions,
|
||||
});
|
||||
}
|
||||
|
||||
public async query(
|
||||
query: VectorStoreQuery,
|
||||
_options?: any,
|
||||
): Promise<VectorStoreQueryResult> {
|
||||
if (!this.collection) {
|
||||
throw new Error("Must connect to collection before querying.");
|
||||
}
|
||||
|
||||
const found = await this.milvusClient.search({
|
||||
collection_name: this.collection,
|
||||
limit: query.similarityTopK,
|
||||
vector: query.queryEmbedding,
|
||||
});
|
||||
|
||||
return {
|
||||
nodes: found.results.map((result) => {
|
||||
return new Document({
|
||||
id_: result[this.idKey],
|
||||
metadata: result[this.metadataKey] ?? {},
|
||||
text: this.contentKey
|
||||
? result[this.contentKey]
|
||||
: JSON.stringify(result),
|
||||
embedding: result[this.embeddingKey],
|
||||
});
|
||||
}),
|
||||
similarities: found.results.map((result) => result.score),
|
||||
ids: found.results.map((result) => String(result.id)),
|
||||
};
|
||||
}
|
||||
|
||||
public async persist() {
|
||||
// no need to do anything
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# @llamaindex/core-test
|
||||
|
||||
## 0.0.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 484a710: - Add missing exports:
|
||||
- `IndexStructType`,
|
||||
- `IndexDict`,
|
||||
- `jsonToIndexStruct`,
|
||||
- `IndexList`,
|
||||
- `IndexStruct`
|
||||
- Fix `IndexDict.toJson()` method
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
IndexDict,
|
||||
IndexList,
|
||||
IndexStruct,
|
||||
IndexStructType,
|
||||
MetadataMode,
|
||||
TextNode,
|
||||
jsonToIndexStruct,
|
||||
} from "llamaindex";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("jsonToIndexStruct", () => {
|
||||
it("transforms json to IndexDict", () => {
|
||||
function isIndexDict(some: IndexStruct): some is IndexDict {
|
||||
return "type" in some && some.type === IndexStructType.SIMPLE_DICT;
|
||||
}
|
||||
|
||||
const node = new TextNode({ text: "text", id_: "nodeId" });
|
||||
const expected = new IndexDict();
|
||||
expected.addNode(node);
|
||||
|
||||
console.log("expected.toJson()", expected.toJson());
|
||||
const actual = jsonToIndexStruct(expected.toJson());
|
||||
|
||||
expect(isIndexDict(actual)).toBe(true);
|
||||
expect(
|
||||
(actual as IndexDict).nodesDict.nodeId.getContent(MetadataMode.NONE),
|
||||
).toEqual("text");
|
||||
});
|
||||
it("transforms json to IndexList", () => {
|
||||
function isIndexList(some: IndexStruct): some is IndexList {
|
||||
return "type" in some && some.type === IndexStructType.LIST;
|
||||
}
|
||||
|
||||
const node = new TextNode({ text: "text", id_: "nodeId" });
|
||||
const expected = new IndexList();
|
||||
expected.addNode(node);
|
||||
|
||||
const actual = jsonToIndexStruct(expected.toJson());
|
||||
|
||||
expect(isIndexList(actual)).toBe(true);
|
||||
expect((actual as IndexList).nodes[0]).toEqual("nodeId");
|
||||
});
|
||||
it("fails for unknown index type", () => {
|
||||
expect(() => {
|
||||
const json = {
|
||||
indexId: "dd120b16-8dce-4ce3-9bb6-15ca87fe4a1d",
|
||||
summary: undefined,
|
||||
nodesDict: {},
|
||||
type: "FOO",
|
||||
};
|
||||
return jsonToIndexStruct(json);
|
||||
}).toThrowError("Unknown index struct type: FOO");
|
||||
});
|
||||
it("fails for unknown node type", () => {
|
||||
expect(() => {
|
||||
const json = {
|
||||
indexId: "dd120b16-8dce-4ce3-9bb6-15ca87fe4a1d",
|
||||
summary: undefined,
|
||||
nodesDict: {
|
||||
nodeId: {
|
||||
...new TextNode({ text: "text", id_: "nodeId" }).toJSON(),
|
||||
type: "BAR",
|
||||
},
|
||||
},
|
||||
type: IndexStructType.SIMPLE_DICT,
|
||||
};
|
||||
return jsonToIndexStruct(json);
|
||||
}).toThrowError("Invalid node type: BAR");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/core-test",
|
||||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "vitest run"
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
# create-llama
|
||||
|
||||
## 0.0.26
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 09d532e: feat: generate llama pack project from llama index
|
||||
- cfdd6db: feat: add pinecone support to create llama
|
||||
- ef25d69: upgrade llama-index package to version v0.10.7 for create-llama app
|
||||
- 50dfd7b: update fastapi for CVE-2024-24762
|
||||
|
||||
## 0.0.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d06a85b: Add option to create an agent by selecting tools (Google, Wikipedia)
|
||||
- 7b7329b: Added latest turbo models for GPT-3.5 and GPT 4
|
||||
|
||||
## 0.0.24
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ba95ca3: Use condense plus context chat engine for FastAPI as default
|
||||
|
||||
## 0.0.23
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- c680af6: Fixed issues with locating templates path
|
||||
|
||||
## 0.0.22
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 6dd401e: Add an option to provide an URL and chat with the website data (FastAPI only)
|
||||
- e9b87ef: Select a folder as data source and support more file types (.pdf, .doc, .docx, .xls, .xlsx, .csv)
|
||||
|
||||
## 0.0.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 27d55fd: Add an option to provide an URL and chat with the website data
|
||||
|
||||
## 0.0.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3a29a80: Add node_modules to gitignore in Express backends
|
||||
- fe03aaa: feat: generate llama pack example
|
||||
|
||||
## 0.0.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 88d3b41: fix packaging
|
||||
|
||||
## 0.0.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fa17f7e: Add an option that allows the user to run the generated app
|
||||
- 9e5d8e1: Add an option to select a local PDF file as data source
|
||||
|
||||
## 0.0.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- a73942d: Fix: Bundle mongo dependency with NextJS
|
||||
- 9492cc6: Feat: Added option to automatically install dependencies (for Python and TS)
|
||||
- f74dea5: Feat: Show images in chat messages using GPT4 Vision (Express and NextJS only)
|
||||
|
||||
## 0.0.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 8e124e5: feat: support showing image on chat message
|
||||
|
||||
## 0.0.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 2e6b36e: fix: re-organize file structure
|
||||
- 2b356c8: fix: relative path incorrect
|
||||
|
||||
## 0.0.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Added PostgreSQL vector store (for Typescript and Python)
|
||||
- Improved async handling in FastAPI
|
||||
|
||||
## 0.0.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 9c5e22a: Added cross-env so frontends with Express/FastAPI backends are working under Windows
|
||||
- 5ab65eb: Bring Python templates with TS templates to feature parity
|
||||
- 9c5e22a: Added vector DB selector to create-llama (starting with MongoDB support)
|
||||
|
||||
## 0.0.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 2aeb341: - Added option to create a new project based on community templates
|
||||
- Added OpenAI model selector for NextJS projects
|
||||
- Added GPT4 Vision support (and file upload)
|
||||
|
||||
## 0.0.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Bugfixes (thanks @marcusschiesser)
|
||||
|
||||
## 0.0.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- acfe232: Deployment fixes (thanks @seldo)
|
||||
|
||||
## 0.0.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 8cdb07f: Fix Next deployment (thanks @seldo and @marcusschiesser)
|
||||
|
||||
## 0.0.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 9f9f293: Added more to README and made it easier to switch models (thanks @seldo)
|
||||
|
||||
## 0.0.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 4431ec7: Label bug fix (thanks @marcusschiesser)
|
||||
|
||||
## 0.0.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 25257f4: Fix issue where it doesn't find OpenAI Key when running npm run generate (#182) (thanks @RayFernando1337)
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 031e926: Update create-llama readme (thanks @logan-markewich)
|
||||
|
||||
## 0.0.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 91b42a3: change version (thanks @marcusschiesser)
|
||||
|
||||
## 0.0.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- e2a6805: Hello Create Llama (thanks @marcusschiesser)
|
||||
@@ -1,9 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2023 LlamaIndex, Vercel, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,126 +0,0 @@
|
||||
# Create LlamaIndex App
|
||||
|
||||
The easiest way to get started with [LlamaIndex](https://www.llamaindex.ai/) is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
|
||||
|
||||
Just run
|
||||
|
||||
```bash
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
to get started, or see below for more options. Once your app is generated, run
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app.
|
||||
|
||||
## What you'll get
|
||||
|
||||
- A Next.js-powered front-end. The app is set up as a chat interface that can answer questions about your data (see below)
|
||||
- You can style it with HTML and CSS, or you can optionally use components from [shadcn/ui](https://ui.shadcn.com/)
|
||||
- Your choice of 3 back-ends:
|
||||
- **Next.js**: if you select this option, you’ll have a full stack Next.js application that you can deploy to a host like [Vercel](https://vercel.com/) in just a few clicks. This uses [LlamaIndex.TS](https://www.npmjs.com/package/llamaindex), our TypeScript library.
|
||||
- **Express**: if you want a more traditional Node.js application you can generate an Express backend. This also uses LlamaIndex.TS.
|
||||
- **Python FastAPI**: if you select this option you’ll get a backend powered by the [llama-index python package](https://pypi.org/project/llama-index/), which you can deploy to a service like Render or fly.io.
|
||||
- The back-end has a single endpoint that allows you to send the state of your chat and receive additional responses
|
||||
- You can choose whether you want a streaming or non-streaming back-end (if you're not sure, we recommend streaming)
|
||||
- You can choose whether you want to use `ContextChatEngine` or `SimpleChatEngine`
|
||||
- `SimpleChatEngine` will just talk to the LLM directly without using your data
|
||||
- `ContextChatEngine` will use your data to answer questions (see below).
|
||||
- The app uses OpenAI by default, so you'll need an OpenAI API key, or you can customize it to use any of the dozens of LLMs we support.
|
||||
|
||||
## Using your data
|
||||
|
||||
If you've enabled `ContextChatEngine`, you can supply your own data and the app will index it and answer questions. Your generated app will have a folder called `data`:
|
||||
|
||||
- With the Next.js backend this is `./data`
|
||||
- With the Express or Python backend this is in `./backend/data`
|
||||
|
||||
The app will ingest any supported files you put in this directory. Your Next.js and Express apps use LlamaIndex.TS so they will be able to ingest any PDF, text, CSV, Markdown, Word and HTML files. The Python backend can read even more types, including video and audio files.
|
||||
|
||||
Before you can use your data, you need to index it. If you're using the Next.js or Express apps, run:
|
||||
|
||||
```bash
|
||||
npm run generate
|
||||
```
|
||||
|
||||
Then re-start your app. Remember you'll need to re-run `generate` if you add new files to your `data` folder. If you're using the Python backend, you can trigger indexing of your data by deleting the `./storage` folder and re-starting the app.
|
||||
|
||||
## Don't want a front-end?
|
||||
|
||||
It's optional! If you've selected the Python or Express back-ends, just delete the `frontend` folder and you'll get an API without any front-end code.
|
||||
|
||||
## Customizing the LLM
|
||||
|
||||
By default the app will use OpenAI's gpt-3.5-turbo model. If you want to use GPT-4, you can modify this by editing a file:
|
||||
|
||||
- In the Next.js backend, edit `./app/api/chat/route.ts` and replace `gpt-3.5-turbo` with `gpt-4`
|
||||
- In the Express backend, edit `./backend/src/controllers/chat.controller.ts` and likewise replace `gpt-3.5-turbo` with `gpt-4`
|
||||
- In the Python backend, edit `./backend/app/utils/index.py` and once again replace `gpt-3.5-turbo` with `gpt-4`
|
||||
|
||||
You can also replace OpenAI with one of our [dozens of other supported LLMs](https://docs.llamaindex.ai/en/stable/module_guides/models/llms/modules.html).
|
||||
|
||||
## Example
|
||||
|
||||
The simplest thing to do is run `create-llama` in interactive mode:
|
||||
|
||||
```bash
|
||||
npx create-llama@latest
|
||||
# or
|
||||
npm create llama@latest
|
||||
# or
|
||||
yarn create llama
|
||||
# or
|
||||
pnpm create llama@latest
|
||||
```
|
||||
|
||||
You will be asked for the name of your project, along with other configuration options, something like this:
|
||||
|
||||
```bash
|
||||
>> npm create llama@latest
|
||||
Need to install the following packages:
|
||||
create-llama@latest
|
||||
Ok to proceed? (y) y
|
||||
✔ What is your project named? … my-app
|
||||
✔ Which template would you like to use? › Chat with streaming
|
||||
✔ Which framework would you like to use? › NextJS
|
||||
✔ Which UI would you like to use? › Just HTML
|
||||
✔ Which chat engine would you like to use? › ContextChatEngine
|
||||
✔ Please provide your OpenAI API key (leave blank to skip): …
|
||||
✔ Would you like to use ESLint? … No / Yes
|
||||
Creating a new LlamaIndex app in /home/my-app.
|
||||
```
|
||||
|
||||
### Running non-interactively
|
||||
|
||||
You can also pass command line arguments to set up a new project
|
||||
non-interactively. See `create-llama --help`:
|
||||
|
||||
```bash
|
||||
create-llama <project-directory> [options]
|
||||
|
||||
Options:
|
||||
-V, --version output the version number
|
||||
|
||||
--use-npm
|
||||
|
||||
Explicitly tell the CLI to bootstrap the app using npm
|
||||
|
||||
--use-pnpm
|
||||
|
||||
Explicitly tell the CLI to bootstrap the app using pnpm
|
||||
|
||||
--use-yarn
|
||||
|
||||
Explicitly tell the CLI to bootstrap the app using Yarn
|
||||
|
||||
```
|
||||
|
||||
## LlamaIndex Documentation
|
||||
|
||||
- [TS/JS docs](https://ts.llamaindex.ai/)
|
||||
- [Python docs](https://docs.llamaindex.ai/en/stable/)
|
||||
|
||||
Inspired by and adapted from [create-next-app](https://github.com/vercel/next.js/tree/canary/packages/create-next-app)
|
||||
@@ -1,142 +0,0 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */
|
||||
import path from "path";
|
||||
import { green, yellow } from "picocolors";
|
||||
import { tryGitInit } from "./helpers/git";
|
||||
import { isFolderEmpty } from "./helpers/is-folder-empty";
|
||||
import { getOnline } from "./helpers/is-online";
|
||||
import { isWriteable } from "./helpers/is-writeable";
|
||||
import { makeDir } from "./helpers/make-dir";
|
||||
|
||||
import fs from "fs";
|
||||
import terminalLink from "terminal-link";
|
||||
import type { InstallTemplateArgs } from "./helpers";
|
||||
import { installTemplate } from "./helpers";
|
||||
import { templatesDir } from "./helpers/dir";
|
||||
import { toolsRequireConfig } from "./helpers/tools";
|
||||
|
||||
export type InstallAppArgs = Omit<
|
||||
InstallTemplateArgs,
|
||||
"appName" | "root" | "isOnline" | "customApiPath"
|
||||
> & {
|
||||
appPath: string;
|
||||
frontend: boolean;
|
||||
};
|
||||
|
||||
export async function createApp({
|
||||
template,
|
||||
framework,
|
||||
engine,
|
||||
ui,
|
||||
appPath,
|
||||
packageManager,
|
||||
eslint,
|
||||
frontend,
|
||||
openAiKey,
|
||||
llamaCloudKey,
|
||||
model,
|
||||
communityProjectPath,
|
||||
llamapack,
|
||||
vectorDb,
|
||||
externalPort,
|
||||
postInstallAction,
|
||||
dataSource,
|
||||
tools,
|
||||
}: InstallAppArgs): Promise<void> {
|
||||
const root = path.resolve(appPath);
|
||||
|
||||
if (!(await isWriteable(path.dirname(root)))) {
|
||||
console.error(
|
||||
"The application path is not writable, please check folder permissions and try again.",
|
||||
);
|
||||
console.error(
|
||||
"It is likely you do not have write permissions for this folder.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const appName = path.basename(root);
|
||||
|
||||
await makeDir(root);
|
||||
if (!isFolderEmpty(root, appName)) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const useYarn = packageManager === "yarn";
|
||||
const isOnline = !useYarn || (await getOnline());
|
||||
|
||||
console.log(`Creating a new LlamaIndex app in ${green(root)}.`);
|
||||
console.log();
|
||||
|
||||
const args = {
|
||||
appName,
|
||||
root,
|
||||
template,
|
||||
framework,
|
||||
engine,
|
||||
ui,
|
||||
packageManager,
|
||||
isOnline,
|
||||
eslint,
|
||||
openAiKey,
|
||||
llamaCloudKey,
|
||||
model,
|
||||
communityProjectPath,
|
||||
llamapack,
|
||||
vectorDb,
|
||||
externalPort,
|
||||
postInstallAction,
|
||||
dataSource,
|
||||
tools,
|
||||
};
|
||||
|
||||
if (frontend) {
|
||||
// install backend
|
||||
const backendRoot = path.join(root, "backend");
|
||||
await makeDir(backendRoot);
|
||||
await installTemplate({ ...args, root: backendRoot, backend: true });
|
||||
// install frontend
|
||||
const frontendRoot = path.join(root, "frontend");
|
||||
await makeDir(frontendRoot);
|
||||
await installTemplate({
|
||||
...args,
|
||||
root: frontendRoot,
|
||||
framework: "nextjs",
|
||||
customApiPath: `http://localhost:${externalPort ?? 8000}/api/chat`,
|
||||
backend: false,
|
||||
});
|
||||
// copy readme for fullstack
|
||||
await fs.promises.copyFile(
|
||||
path.join(templatesDir, "README-fullstack.md"),
|
||||
path.join(root, "README.md"),
|
||||
);
|
||||
} else {
|
||||
await installTemplate({ ...args, backend: true, forBackend: framework });
|
||||
}
|
||||
|
||||
process.chdir(root);
|
||||
if (tryGitInit(root)) {
|
||||
console.log("Initialized a git repository.");
|
||||
console.log();
|
||||
}
|
||||
|
||||
if (toolsRequireConfig(tools)) {
|
||||
console.log(
|
||||
yellow(
|
||||
`You have selected tools that require configuration. Please configure them in the ${terminalLink(
|
||||
"tools_config.json",
|
||||
`file://${root}/tools_config.json`,
|
||||
)} file.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
console.log("");
|
||||
console.log(`${green("Success!")} Created ${appName} at ${appPath}`);
|
||||
|
||||
console.log(
|
||||
`Now have a look at the ${terminalLink(
|
||||
"README.md",
|
||||
`file://${root}/README.md`,
|
||||
)} and learn how to get started.`,
|
||||
);
|
||||
console.log();
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
/* eslint-disable turbo/no-undeclared-env-vars */
|
||||
import { expect, test } from "@playwright/test";
|
||||
import { ChildProcess } from "child_process";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import type {
|
||||
TemplateEngine,
|
||||
TemplateFramework,
|
||||
TemplatePostInstallAction,
|
||||
TemplateType,
|
||||
TemplateUI,
|
||||
} from "../helpers";
|
||||
import { createTestDir, runCreateLlama, type AppType } from "./utils";
|
||||
|
||||
const templateTypes: TemplateType[] = ["streaming", "simple"];
|
||||
const templateFrameworks: TemplateFramework[] = [
|
||||
"nextjs",
|
||||
"express",
|
||||
"fastapi",
|
||||
];
|
||||
const templateEngines: TemplateEngine[] = ["simple", "context"];
|
||||
const templateUIs: TemplateUI[] = ["shadcn", "html"];
|
||||
const templatePostInstallActions: TemplatePostInstallAction[] = [
|
||||
"none",
|
||||
"runApp",
|
||||
];
|
||||
|
||||
for (const templateType of templateTypes) {
|
||||
for (const templateFramework of templateFrameworks) {
|
||||
for (const templateEngine of templateEngines) {
|
||||
for (const templateUI of templateUIs) {
|
||||
for (const templatePostInstallAction of templatePostInstallActions) {
|
||||
if (templateFramework === "nextjs" && templateType === "simple") {
|
||||
// nextjs doesn't support simple templates - skip tests
|
||||
continue;
|
||||
}
|
||||
const appType: AppType =
|
||||
templateFramework === "express" || templateFramework === "fastapi"
|
||||
? templateType === "simple"
|
||||
? "--no-frontend" // simple templates don't have frontends
|
||||
: "--frontend"
|
||||
: "";
|
||||
if (appType === "--no-frontend" && templateUI !== "html") {
|
||||
// if there's no frontend, don't iterate over UIs
|
||||
continue;
|
||||
}
|
||||
test.describe(`try create-llama ${templateType} ${templateFramework} ${templateEngine} ${templateUI} ${appType} ${templatePostInstallAction}`, async () => {
|
||||
let port: number;
|
||||
let externalPort: number;
|
||||
let cwd: string;
|
||||
let name: string;
|
||||
let appProcess: ChildProcess;
|
||||
// Only test without using vector db for now
|
||||
const vectorDb = "none";
|
||||
|
||||
test.beforeAll(async () => {
|
||||
port = Math.floor(Math.random() * 10000) + 10000;
|
||||
externalPort = port + 1;
|
||||
cwd = await createTestDir();
|
||||
const result = await runCreateLlama(
|
||||
cwd,
|
||||
templateType,
|
||||
templateFramework,
|
||||
templateEngine,
|
||||
templateUI,
|
||||
vectorDb,
|
||||
appType,
|
||||
port,
|
||||
externalPort,
|
||||
templatePostInstallAction,
|
||||
);
|
||||
name = result.projectName;
|
||||
appProcess = result.appProcess;
|
||||
});
|
||||
|
||||
test("App folder should exist", async () => {
|
||||
const dirExists = fs.existsSync(path.join(cwd, name));
|
||||
expect(dirExists).toBeTruthy();
|
||||
});
|
||||
test("Frontend should have a title", async ({ page }) => {
|
||||
test.skip(templatePostInstallAction !== "runApp");
|
||||
test.skip(appType === "--no-frontend");
|
||||
await page.goto(`http://localhost:${port}`);
|
||||
await expect(page.getByText("Built by LlamaIndex")).toBeVisible();
|
||||
});
|
||||
|
||||
test("Frontend should be able to submit a message and receive a response", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.skip(templatePostInstallAction !== "runApp");
|
||||
test.skip(appType === "--no-frontend");
|
||||
await page.goto(`http://localhost:${port}`);
|
||||
await page.fill("form input", "hello");
|
||||
await page.click("form button[type=submit]");
|
||||
const response = await page.waitForResponse(
|
||||
(res) => {
|
||||
return (
|
||||
res.url().includes("/api/chat") && res.status() === 200
|
||||
);
|
||||
},
|
||||
{
|
||||
timeout: 1000 * 60,
|
||||
},
|
||||
);
|
||||
const text = await response.text();
|
||||
console.log("AI response when submitting message: ", text);
|
||||
expect(response.ok()).toBeTruthy();
|
||||
});
|
||||
|
||||
test("Backend should response when calling API", async ({
|
||||
request,
|
||||
}) => {
|
||||
test.skip(templatePostInstallAction !== "runApp");
|
||||
test.skip(appType !== "--no-frontend");
|
||||
const backendPort = appType === "" ? port : externalPort;
|
||||
const response = await request.post(
|
||||
`http://localhost:${backendPort}/api/chat`,
|
||||
{
|
||||
data: {
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: "Hello",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
const text = await response.text();
|
||||
console.log("AI response when calling API: ", text);
|
||||
expect(response.ok()).toBeTruthy();
|
||||
});
|
||||
|
||||
// clean processes
|
||||
test.afterAll(async () => {
|
||||
appProcess?.kill();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2019",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"strict": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": false,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"incremental": true,
|
||||
"tsBuildInfoFile": "./lib/.tsbuildinfo"
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
import { ChildProcess, exec } from "child_process";
|
||||
import crypto from "node:crypto";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import * as path from "path";
|
||||
import waitPort from "wait-port";
|
||||
import {
|
||||
TemplateEngine,
|
||||
TemplateFramework,
|
||||
TemplatePostInstallAction,
|
||||
TemplateType,
|
||||
TemplateUI,
|
||||
TemplateVectorDB,
|
||||
} from "../helpers";
|
||||
|
||||
export type AppType = "--frontend" | "--no-frontend" | "";
|
||||
const MODEL = "gpt-3.5-turbo";
|
||||
export type CreateLlamaResult = {
|
||||
projectName: string;
|
||||
appProcess: ChildProcess;
|
||||
};
|
||||
|
||||
// eslint-disable-next-line max-params
|
||||
export async function checkAppHasStarted(
|
||||
frontend: boolean,
|
||||
framework: TemplateFramework,
|
||||
port: number,
|
||||
externalPort: number,
|
||||
timeout: number,
|
||||
) {
|
||||
if (frontend) {
|
||||
await Promise.all([
|
||||
waitPort({
|
||||
host: "localhost",
|
||||
port: port,
|
||||
timeout,
|
||||
}),
|
||||
waitPort({
|
||||
host: "localhost",
|
||||
port: externalPort,
|
||||
timeout,
|
||||
}),
|
||||
]).catch((err) => {
|
||||
console.error(err);
|
||||
throw err;
|
||||
});
|
||||
} else {
|
||||
let wPort: number;
|
||||
if (framework === "nextjs") {
|
||||
wPort = port;
|
||||
} else {
|
||||
wPort = externalPort;
|
||||
}
|
||||
await waitPort({
|
||||
host: "localhost",
|
||||
port: wPort,
|
||||
timeout,
|
||||
}).catch((err) => {
|
||||
console.error(err);
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-params
|
||||
export async function runCreateLlama(
|
||||
cwd: string,
|
||||
templateType: TemplateType,
|
||||
templateFramework: TemplateFramework,
|
||||
templateEngine: TemplateEngine,
|
||||
templateUI: TemplateUI,
|
||||
vectorDb: TemplateVectorDB,
|
||||
appType: AppType,
|
||||
port: number,
|
||||
externalPort: number,
|
||||
postInstallAction: TemplatePostInstallAction,
|
||||
): Promise<CreateLlamaResult> {
|
||||
const createLlama = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"output",
|
||||
"package",
|
||||
"dist",
|
||||
"index.js",
|
||||
);
|
||||
|
||||
const name = [
|
||||
templateType,
|
||||
templateFramework,
|
||||
templateEngine,
|
||||
templateUI,
|
||||
appType,
|
||||
].join("-");
|
||||
const command = [
|
||||
"node",
|
||||
createLlama,
|
||||
name,
|
||||
"--template",
|
||||
templateType,
|
||||
"--framework",
|
||||
templateFramework,
|
||||
"--engine",
|
||||
templateEngine,
|
||||
"--ui",
|
||||
templateUI,
|
||||
"--vector-db",
|
||||
vectorDb,
|
||||
"--model",
|
||||
MODEL,
|
||||
"--open-ai-key",
|
||||
process.env.OPENAI_API_KEY || "testKey",
|
||||
appType,
|
||||
"--eslint",
|
||||
"--use-npm",
|
||||
"--port",
|
||||
port,
|
||||
"--external-port",
|
||||
externalPort,
|
||||
"--post-install-action",
|
||||
postInstallAction,
|
||||
"--tools",
|
||||
"none",
|
||||
].join(" ");
|
||||
console.log(`running command '${command}' in ${cwd}`);
|
||||
const appProcess = exec(command, {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
},
|
||||
});
|
||||
appProcess.stderr?.on("data", (data) => {
|
||||
console.log(data.toString());
|
||||
});
|
||||
appProcess.on("exit", (code) => {
|
||||
if (code !== 0 && code !== null) {
|
||||
throw new Error(`create-llama command was failed!`);
|
||||
}
|
||||
});
|
||||
|
||||
// Wait for app to start
|
||||
if (postInstallAction === "runApp") {
|
||||
await checkAppHasStarted(
|
||||
appType === "--frontend",
|
||||
templateFramework,
|
||||
port,
|
||||
externalPort,
|
||||
1000 * 60 * 5,
|
||||
);
|
||||
} else {
|
||||
// wait create-llama to exit
|
||||
// we don't test install dependencies for now, so just set timeout for 10 seconds
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error("create-llama timeout error"));
|
||||
}, 1000 * 10);
|
||||
appProcess.on("exit", (code) => {
|
||||
if (code !== 0 && code !== null) {
|
||||
clearTimeout(timeout);
|
||||
reject(new Error("create-llama command was failed!"));
|
||||
} else {
|
||||
clearTimeout(timeout);
|
||||
resolve(undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
projectName: name,
|
||||
appProcess,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createTestDir() {
|
||||
const cwd = path.join(__dirname, ".cache", crypto.randomUUID());
|
||||
await mkdir(cwd, { recursive: true });
|
||||
return cwd;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
export const COMMUNITY_OWNER = "run-llama";
|
||||
export const COMMUNITY_REPO = "create_llama_projects";
|
||||
export const LLAMA_PACK_OWNER = "run-llama";
|
||||
export const LLAMA_PACK_REPO = "llama_index";
|
||||
export const LLAMA_PACK_FOLDER = "llama-index-packs";
|
||||
export const LLAMA_PACK_FOLDER_PATH = `${LLAMA_PACK_OWNER}/${LLAMA_PACK_REPO}/main/${LLAMA_PACK_FOLDER}`;
|
||||
@@ -1,50 +0,0 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */
|
||||
import { async as glob } from "fast-glob";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
interface CopyOption {
|
||||
cwd?: string;
|
||||
rename?: (basename: string) => string;
|
||||
parents?: boolean;
|
||||
}
|
||||
|
||||
const identity = (x: string) => x;
|
||||
|
||||
export const copy = async (
|
||||
src: string | string[],
|
||||
dest: string,
|
||||
{ cwd, rename = identity, parents = true }: CopyOption = {},
|
||||
) => {
|
||||
const source = typeof src === "string" ? [src] : src;
|
||||
|
||||
if (source.length === 0 || !dest) {
|
||||
throw new TypeError("`src` and `dest` are required");
|
||||
}
|
||||
|
||||
const sourceFiles = await glob(source, {
|
||||
cwd,
|
||||
dot: true,
|
||||
absolute: false,
|
||||
stats: false,
|
||||
});
|
||||
|
||||
const destRelativeToCwd = cwd ? path.resolve(cwd, dest) : dest;
|
||||
|
||||
return Promise.all(
|
||||
sourceFiles.map(async (p) => {
|
||||
const dirname = path.dirname(p);
|
||||
const basename = rename(path.basename(p));
|
||||
|
||||
const from = cwd ? path.resolve(cwd, p) : p;
|
||||
const to = parents
|
||||
? path.join(destRelativeToCwd, dirname, basename)
|
||||
: path.join(destRelativeToCwd, basename);
|
||||
|
||||
// Ensure the destination directory exists
|
||||
await fs.promises.mkdir(path.dirname(to), { recursive: true });
|
||||
|
||||
return fs.promises.copyFile(from, to);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
import path from "path";
|
||||
|
||||
export const templatesDir = path.join(__dirname, "..", "templates");
|
||||
@@ -1,15 +0,0 @@
|
||||
export type PackageManager = "npm" | "pnpm" | "yarn";
|
||||
|
||||
export function getPkgManager(): PackageManager {
|
||||
const userAgent = process.env.npm_config_user_agent || "";
|
||||
|
||||
if (userAgent.startsWith("yarn")) {
|
||||
return "yarn";
|
||||
}
|
||||
|
||||
if (userAgent.startsWith("pnpm")) {
|
||||
return "pnpm";
|
||||
}
|
||||
|
||||
return "npm";
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */
|
||||
import { execSync } from "child_process";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
function isInGitRepository(): boolean {
|
||||
try {
|
||||
execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore" });
|
||||
return true;
|
||||
} catch (_) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isInMercurialRepository(): boolean {
|
||||
try {
|
||||
execSync("hg --cwd . root", { stdio: "ignore" });
|
||||
return true;
|
||||
} catch (_) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isDefaultBranchSet(): boolean {
|
||||
try {
|
||||
execSync("git config init.defaultBranch", { stdio: "ignore" });
|
||||
return true;
|
||||
} catch (_) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function tryGitInit(root: string): boolean {
|
||||
let didInit = false;
|
||||
try {
|
||||
execSync("git --version", { stdio: "ignore" });
|
||||
if (isInGitRepository() || isInMercurialRepository()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
execSync("git init", { stdio: "ignore" });
|
||||
didInit = true;
|
||||
|
||||
if (!isDefaultBranchSet()) {
|
||||
execSync("git checkout -b main", { stdio: "ignore" });
|
||||
}
|
||||
|
||||
execSync("git add -A", { stdio: "ignore" });
|
||||
execSync('git commit -m "Initial commit from Create Llama"', {
|
||||
stdio: "ignore",
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (didInit) {
|
||||
try {
|
||||
fs.rmSync(path.join(root, ".git"), { recursive: true, force: true });
|
||||
} catch (_) {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user