Compare commits

...

70 Commits

Author SHA1 Message Date
github-actions[bot] e248dc56bc Release 0.1.38 (#242)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-16 10:58:56 +07:00
Marcus Schiesser bd5e39a390 fix: files in sub folders of 'data' are not displayed (#241) 2024-08-16 10:57:44 +07:00
github-actions[bot] de2c7523dd Release 0.1.37 (#239)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-15 14:52:27 +07:00
Huu Le 9fd832c8b0 feat: In-text citing (#175)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-08-15 13:52:51 +07:00
github-actions[bot] b2c76dc7b6 Release 0.1.36 (#238)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-15 11:02:00 +07:00
Thuc Pham 2b7a5d8797 fix: optional params in file upload API (#237)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-08-15 11:00:53 +07:00
Marcus Schiesser d93ec803f5 feat: add ruff (#235)
* fix: formatting

* fix: ruff --fix

* feat: add ruff to github action

* fix: remove E402 check for some files
2024-08-15 09:38:13 +07:00
github-actions[bot] a6023b695b Release 0.1.35 (#234)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-14 17:22:49 +07:00
Marcus Schiesser 81ef7f0f93 feat: use llamacloud pipeline for private files and generate script in Python (#226)
---------
Co-authored-by: Thuc Pham <51660321+thucpn@users.noreply.github.com>
2024-08-14 17:03:16 +07:00
github-actions[bot] 8faf9170cf Release 0.1.34 (#233)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-14 14:59:19 +07:00
Huu Le c49a5e1620 chore: update wrong env name, add error handling for next question (#232) 2024-08-14 14:39:14 +07:00
github-actions[bot] 8b2de431f2 Release 0.1.33 (#229)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-13 11:06:17 +07:00
Huu Le d746c75e49 feat: Add Weaviate vector store for Typescript templates (#228) 2024-08-13 10:56:02 +07:00
Laurie Voss c87978ab96 Point the repo to the current one (#227) 2024-08-13 10:51:04 +07:00
github-actions[bot] 26359a0ac9 Release 0.1.32 (#224)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-12 17:19:22 +07:00
Huu Le 4039d3d1ea refactor: include chat configuration router in FastAPI app (#225) 2024-08-12 17:17:22 +07:00
Huu Le 3ec5163304 feat: add Weaviate vector database support for Python (#223)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-08-12 16:25:26 +07:00
Thuc Pham 878cfc2ca1 refactor: make llamacloud selector resuable (#221) 2024-08-09 12:02:43 +07:00
github-actions[bot] 9b5835b71c Release 0.1.31 (#222)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-09 11:55:58 +07:00
Thuc Pham 04a9c71759 feat: cluster nodes in document (#217)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-08-09 11:54:50 +07:00
github-actions[bot] 0bfdbc1dfe Release 0.1.30 (#214)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-08 15:59:57 +07:00
Thuc Pham fbcaebcbcf fix: use modern module resolution for express (#219) 2024-08-08 09:51:13 +02:00
Thuc Pham b6dd7a9acb fix: always send chat data when submit message (#213) 2024-08-07 15:22:33 +02:00
Marcus Schiesser 09e3022ad6 feat: add LlamaTrace support (#216) 2024-08-07 15:21:44 +02:00
Marcus Schiesser 9f739b9834 refactor: cleaned e2e runner (#215) 2024-08-07 17:41:22 +07:00
Marcus Schiesser c06ec4f14c fix: imports for MongoDB 2024-08-07 11:01:00 +02:00
Marcus Schiesser e7d30b1c69 refactor: test frameworks and datasources via matrix (#211) 2024-08-05 23:50:00 +07:00
github-actions[bot] e974c8ef11 Release 0.1.29 (#210)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-05 22:24:37 +07:00
Thuc Pham 8890e27a14 feat: implement index selector for LlamaCloud (#200)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-08-05 22:18:20 +07:00
Marcus Schiesser 072e69b465 fix: deactive llamacloud tests 2024-08-05 13:49:09 +02:00
Huu Le 83a648df0a chore: add use window.ENV.BASE_URL as backendOrigin (#205)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-08-02 15:50:04 +07:00
github-actions[bot] dcf52abdba Release 0.1.28 (#206)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-02 15:38:27 +07:00
Marcus Schiesser 9a09e8c7e2 fix: Vercel deployment (by including WASM files) (#201) 2024-08-02 15:36:54 +07:00
github-actions[bot] a4a55239e9 Release 0.1.27 (#204)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-01 17:09:07 +02:00
Thuc Pham c5c7eee04d refactor: make components resuable for chat llm (#202)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-08-01 16:31:38 +02:00
github-actions[bot] 8b89ac547f Release 0.1.26 (#199)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-31 08:56:00 +02:00
Marcus Schiesser f43399cc18 fix: Add metadatafilters to context chat engine (Typescript) (#196) 2024-07-31 08:55:06 +02:00
github-actions[bot] df51361ca1 Release 0.1.25 (#195)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-30 15:09:21 +07:00
Huu Le c67daeb2be fix: missing set private to false for default generate.py (#194) 2024-07-30 15:06:04 +07:00
github-actions[bot] af6ac9a444 Release 0.1.24 (#188)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-29 21:01:51 +07:00
Marcus Schiesser 22245ca9fd chore: remove azure openai key question 2024-07-29 15:51:58 +02:00
Marcus Schiesser 81b67794ef fix: throw errors if azure deployments are no 2024-07-29 15:51:58 +02:00
Bartłomiej Szczygło 5c13646e55 Fix starter questions not working in python backend (#189)
* Fix starter questions not working in python backend

* add changeset

---------

Co-authored-by: Arputikos <arputikos11@op.pl>
Co-authored-by: leehuwuj <leehuwuj@gmail.com>
2024-07-29 15:55:00 +07:00
Thuc Pham 43474a51ff feat: config llamacloud organization ID (#192)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-07-29 15:20:18 +07:00
Huu Le cf11b233c6 feat: support using azure code interpreter in create-llama (#158)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
Co-authored-by: Wassim Chegham <github@wassim.dev>
Co-authored-by: Thuc Pham <51660321+thucpn@users.noreply.github.com>
2024-07-26 17:34:36 +07:00
Thuc Pham fd9fb42ace feat: add azure model provider (#184) 2024-07-26 17:32:14 +07:00
Thuc Pham 92798f73dd fix: dont ask useLlamaParse if --no-llama-parse in command (#187) 2024-07-26 14:58:34 +07:00
Marcus Schiesser e71d8bd6e2 fix: lint 2024-07-25 15:25:53 +02:00
github-actions[bot] e25e112873 Release 0.1.23 (#186)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-25 20:23:04 +07:00
Marcus Schiesser 048187cce3 Update README.md 2024-07-25 20:21:19 +07:00
Marcus Schiesser 6bd76fbfb1 feat: Add template for structured extraction (#185) 2024-07-25 19:56:26 +07:00
github-actions[bot] a553d5051e Release 0.1.22 (#180)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-25 15:57:55 +07:00
Thuc Pham b0becaa8dc feat: add e2e testing for llamacloud datasource (#181)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-07-25 15:56:23 +07:00
Marcus Schiesser 6a42542642 chore: sync tsconfig with create-next-app (#182) 2024-07-25 15:11:05 +07:00
Thuc Pham f936a470f3 fix: ignore ts check grammar for regex (#183) 2024-07-25 14:40:34 +07:00
Thuc Pham df9cca5a52 feat: upgrade pdf viewer (#179)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-07-24 16:03:58 +07:00
Marcus Schiesser dc9ee895a7 Add video to README.md 2024-07-23 16:38:24 +02:00
github-actions[bot] 98ff3c2e77 Release 0.1.21 (#169)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-23 19:01:32 +07:00
Huu Le 0900413689 Add next questions suggestion to the user (#170)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-07-23 17:04:53 +07:00
Marcus Schiesser 8dc6a2bf5a fix: simplify webpack config using 0.57 (#174) 2024-07-23 16:16:38 +07:00
Huu Le 23b735717d chore: Use gpt-4o-mini as default (#173) 2024-07-22 21:42:40 +07:00
Thuc Pham bd4714ca8d feat: add filter for query in ts templates (#172)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-07-22 21:42:20 +07:00
Thuc Pham 455ab6862e feat: display files from llamacloud (#153)
---------
Co-authored-by: leehuwuj <leehuwuj@gmail.com>
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-07-18 22:46:06 +07:00
Huu Le 58e6c150c0 feat: Use LlamaParse to parse the private files (#167) 2024-07-17 19:15:43 +07:00
Thuc Pham e57e9813dd fix: use stable tsup version (#168) 2024-07-17 17:07:40 +07:00
github-actions[bot] 7302880c5f Release 0.1.20 (#166)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-15 22:17:09 +07:00
Marcus Schiesser 624c721ac4 chore: update to llamaindex 0.10.55 (#165) 2024-07-15 21:51:15 +07:00
github-actions[bot] d2c66cf550 Release 0.1.19 (#163)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-07-12 15:36:26 +07:00
Huu Le df96159e88 feat: Use Qdrant FastEmbed as local embedding provider (#162) 2024-07-12 15:01:41 +07:00
Thuc Pham 32fb32ab18 feat: support uploading pdf, docx, txt (#140)
---------
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
Co-authored-by: leehuwuj <leehuwuj@gmail.com>
2024-07-12 14:56:11 +07:00
152 changed files with 4243 additions and 1398 deletions
+5
View File
@@ -18,6 +18,8 @@ jobs:
node-version: [18, 20]
python-version: ["3.11"]
os: [macos-latest, windows-latest, ubuntu-22.04]
frameworks: ["nextjs", "express", "fastapi"]
datasources: ["--no-files", "--example-file"]
defaults:
run:
shell: bash
@@ -62,6 +64,9 @@ jobs:
run: pnpm run e2e
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
LLAMA_CLOUD_API_KEY: ${{ secrets.LLAMA_CLOUD_API_KEY }}
FRAMEWORK: ${{ matrix.frameworks }}
DATASOURCE: ${{ matrix.datasources }}
working-directory: .
- uses: actions/upload-artifact@v3
@@ -30,3 +30,13 @@ jobs:
- name: Run Prettier
run: pnpm run format
- name: Run Python format check
uses: chartboost/ruff-action@v1
with:
args: "format --check"
- name: Run Python lint
uses: chartboost/ruff-action@v1
with:
args: "check"
+3
View File
@@ -46,5 +46,8 @@ e2e/cache
# intellij
**/.idea
# Python
.mypy_cache/
# build artifacts
create-llama-*.tgz
+132
View File
@@ -1,5 +1,137 @@
# create-llama
## 0.1.38
### Patch Changes
- bd5e39a: Fix error that files in sub folders of 'data' are not displayed
## 0.1.37
### Patch Changes
- 9fd832c: Add in-text citation references
## 0.1.36
### Patch Changes
- 2b7a5d8: Fix: private file upload not working in Python without LlamaCloud
## 0.1.35
### Patch Changes
- 81ef7f0: Use LlamaCloud pipeline for data ingestion (private file uploads and generate script)
## 0.1.34
### Patch Changes
- c49a5e1: Add error handling for generating the next question
- c49a5e1: Fix wrong api key variable in Azure OpenAI provider
## 0.1.33
### Patch Changes
- d746c75: Add Weaviate vector store (Typescript)
## 0.1.32
### Patch Changes
- 3ec5163: Add Weaviate vector database support (Python)
## 0.1.31
### Patch Changes
- 04a9c71: Cluster nodes by document
## 0.1.30
### Patch Changes
- 09e3022: Add support for LlamaTrace (Python)
- c06ec4f: Fix imports for MongoDB
- b6dd7a9: Always send chat data when submit message
## 0.1.29
### Patch Changes
- 8890e27: Let user change indexes in LlamaCloud projects
## 0.1.28
### Patch Changes
- 9a09e8c: Fix Vercel deployment
## 0.1.27
### Patch Changes
- c5c7eee: Make components reusable for chat-llamaindex
## 0.1.26
### Patch Changes
- f43399c: Add metadatafilters to context chat engine (Typescript)
## 0.1.25
### Patch Changes
- c67daeb: fix: missing set private to false for default generate.py
## 0.1.24
### Patch Changes
- 43474a5: Configure LlamaCloud organization ID for Python
- cf11b23: Add Azure code interpreter for Python and TS
- fd9fb42: Add Azure OpenAI as model provider
- 5c13646: Fix starter questions not working in python backend
## 0.1.23
### Patch Changes
- 6bd76fb: Add template for structured extraction
## 0.1.22
### Patch Changes
- b0becaa: Add e2e testing for llamacloud datasource
- df9cca5: Upgrade pdf viewer
## 0.1.21
### Patch Changes
- bd4714c: Filter private documents for Typescript (Using MetadataFilters) and update to LlamaIndexTS 0.5.7
- 58e6c15: Add using LlamaParse for private file uploader
- 455ab68: Display files in sources using LlamaCloud indexes.
- 23b7357: Use gpt-4o-mini as default model
- 0900413: Add suggestions for next questions.
## 0.1.20
### Patch Changes
- 624c721: Update to LlamaIndex 0.10.55
## 0.1.19
### Patch Changes
- df96159: Use Qdrant FastEmbed as local embedding provider
- 32fb32a: Support upload document files: pdf, docx, txt
## 0.1.18
### Patch Changes
+17 -6
View File
@@ -1,14 +1,20 @@
# Create LlamaIndex App
# Create Llama
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.
## Get started
Just run
```bash
npx create-llama@latest
```
to get started, or see below for more options. Once your app is generated, run
to get started, or watch this video for a demo session:
https://github.com/user-attachments/assets/dd3edc36-4453-4416-91c2-d24326c6c167
Once your app is generated, run
```bash
npm run dev
@@ -18,16 +24,20 @@ to start the development server. You can then visit [http://localhost:3000](http
## What you'll get
- A Next.js-powered front-end using components from [shadcn/ui](https://ui.shadcn.com/). The app is set up as a chat interface that can answer questions about your data (see below)
- A Next.js-powered front-end using components from [shadcn/ui](https://ui.shadcn.com/). The app is set up as a chat interface that can answer questions about your data or interact with your agent
- Your choice of 3 back-ends:
- **Next.js**: if you select this option, youll 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, youll 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.
- **Python FastAPI**: if you select this option, youll 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 two endpoints (one streaming, the other one non-streaming) that allow you to send the state of your chat and receive additional responses
- You add arbitrary data sources to your chat, like local files, websites, or data retrieved from a database.
- Turn your chat into an AI agent by adding tools (functions called by the LLM).
- 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.
Here's how it looks like:
https://github.com/user-attachments/assets/d57af1a1-d99b-4e9c-98d9-4cbd1327eff8
## Using your data
You can supply your own data; the app will index it and answer questions. Your generated app will have a folder called `data` (If you're using Express or Python and generate a frontend, it will be `./backend/data`).
@@ -54,7 +64,7 @@ Optionally generate a frontend if you've selected the Python or Express back-end
## Customizing the AI models
The app will default to OpenAI's `gpt-4-turbo` LLM and `text-embedding-3-large` embedding model.
The app will default to OpenAI's `gpt-4o-mini` LLM and `text-embedding-3-large` embedding model.
If you want to use different OpenAI models, add the `--ask-models` CLI parameter.
@@ -84,7 +94,7 @@ 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
✔ Which template would you like to use? Agentic RAG (single agent)
✔ Which framework would you like to use? NextJS
✔ Would you like to set up observability? No
✔ Please provide your OpenAI API key (leave blank to skip): …
@@ -92,6 +102,7 @@ Ok to proceed? (y) y
✔ Would you like to add another data source? No
✔ Would you like to use LlamaParse (improved parser for RAG - requires API key)? … no / yes
✔ Would you like to use a vector database? No, just store the data in the file system
✔ Would you like to build an agent using tools? If so, select the tools here, otherwise just press enter Weather
? How would you like to proceed? - Use arrow-keys. Return to submit.
Just generate code (~1 sec)
Start in VSCode (~1 sec)
+23 -9
View File
@@ -9,7 +9,7 @@ import { makeDir } from "./helpers/make-dir";
import fs from "fs";
import terminalLink from "terminal-link";
import type { InstallTemplateArgs } from "./helpers";
import type { InstallTemplateArgs, TemplateObservability } from "./helpers";
import { installTemplate } from "./helpers";
import { writeDevcontainer } from "./helpers/devcontainer";
import { templatesDir } from "./helpers/dir";
@@ -142,14 +142,7 @@ export async function createApp({
)} and learn how to get started.`,
);
if (args.observability === "opentelemetry") {
console.log(
`\n${yellow("Observability")}: Visit the ${terminalLink(
"documentation",
"https://traceloop.com/docs/openllmetry/integrations",
)} to set up the environment variables and start seeing execution traces.`,
);
}
outputObservability(args.observability);
if (
dataSources.some((dataSource) => dataSource.type === "file") &&
@@ -167,3 +160,24 @@ export async function createApp({
console.log();
}
function outputObservability(observability?: TemplateObservability) {
switch (observability) {
case "traceloop":
console.log(
`\n${yellow("Observability")}: Visit the ${terminalLink(
"documentation",
"https://traceloop.com/docs/openllmetry/integrations",
)} to set up the environment variables and start seeing execution traces.`,
);
break;
case "llamatrace":
console.log(
`\n${yellow("Observability")}: LlamaTrace has been configured for your project. Visit the ${terminalLink(
"LlamaTrace dashboard",
"https://llamatrace.com/login",
)} to view your traces and monitor your application.`,
);
break;
}
}
+101 -110
View File
@@ -11,119 +11,110 @@ import type {
} from "../helpers";
import { createTestDir, runCreateLlama, type AppType } from "./utils";
const templateTypes: TemplateType[] = ["streaming"];
const templateFrameworks: TemplateFramework[] = [
"nextjs",
"express",
"fastapi",
];
const dataSources: string[] = ["--no-files", "--example-file"];
const templateUIs: TemplateUI[] = ["shadcn", "html"];
const templatePostInstallActions: TemplatePostInstallAction[] = [
"none",
"runApp",
];
const templateType: TemplateType = "streaming";
const templateFramework: TemplateFramework = process.env.FRAMEWORK
? (process.env.FRAMEWORK as TemplateFramework)
: "fastapi";
const dataSource: string = process.env.DATASOURCE
? process.env.DATASOURCE
: "--example-file";
const templateUI: TemplateUI = "shadcn";
const templatePostInstallAction: TemplatePostInstallAction = "runApp";
for (const templateType of templateTypes) {
for (const templateFramework of templateFrameworks) {
for (const dataSource of dataSources) {
for (const templateUI of templateUIs) {
for (const templatePostInstallAction of templatePostInstallActions) {
const appType: AppType =
templateFramework === "nextjs" ? "" : "--frontend";
test.describe(`try create-llama ${templateType} ${templateFramework} ${dataSource} ${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";
const llamaCloudProjectName = "create-llama";
const llamaCloudIndexName = "e2e-test";
test.beforeAll(async () => {
port = Math.floor(Math.random() * 10000) + 10000;
externalPort = port + 1;
cwd = await createTestDir();
const result = await runCreateLlama(
cwd,
templateType,
templateFramework,
dataSource,
templateUI,
vectorDb,
appType,
port,
externalPort,
templatePostInstallAction,
);
name = result.projectName;
appProcess = result.appProcess;
});
const appType: AppType = templateFramework === "nextjs" ? "" : "--frontend";
const userMessage =
dataSource !== "--no-files" ? "Physical standard for letters" : "Hello";
test.describe(`try create-llama ${templateType} ${templateFramework} ${dataSource} ${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("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");
await page.goto(`http://localhost:${port}`);
await expect(page.getByText("Built by LlamaIndex")).toBeVisible();
});
test.beforeAll(async () => {
port = Math.floor(Math.random() * 10000) + 10000;
externalPort = port + 1;
cwd = await createTestDir();
const result = await runCreateLlama(
cwd,
templateType,
templateFramework,
dataSource,
templateUI,
vectorDb,
appType,
port,
externalPort,
templatePostInstallAction,
llamaCloudProjectName,
llamaCloudIndexName,
);
name = result.projectName;
appProcess = result.appProcess;
});
test("Frontend should be able to submit a message and receive a response", async ({
page,
}) => {
test.skip(templatePostInstallAction !== "runApp");
await page.goto(`http://localhost:${port}`);
await page.fill("form input", "hello");
const [response] = await Promise.all([
page.waitForResponse(
(res) => {
return (
res.url().includes("/api/chat") && res.status() === 200
);
},
{
timeout: 1000 * 60,
},
),
page.click("form button[type=submit]"),
]);
const text = await response.text();
console.log("AI response when submitting message: ", text);
expect(response.ok()).toBeTruthy();
});
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");
await page.goto(`http://localhost:${port}`);
await expect(page.getByText("Built by LlamaIndex")).toBeVisible();
});
test("Backend frameworks should response when calling non-streaming chat API", async ({
request,
}) => {
test.skip(templatePostInstallAction !== "runApp");
test.skip(templateFramework === "nextjs");
const response = await request.post(
`http://localhost:${externalPort}/api/chat/request`,
{
data: {
messages: [
{
role: "user",
content: "Hello",
},
],
},
},
);
const text = await response.text();
console.log("AI response when calling API: ", text);
expect(response.ok()).toBeTruthy();
});
test("Frontend should be able to submit a message and receive a response", async ({
page,
}) => {
test.skip(templatePostInstallAction !== "runApp");
await page.goto(`http://localhost:${port}`);
await page.fill("form input", userMessage);
const [response] = await Promise.all([
page.waitForResponse(
(res) => {
return res.url().includes("/api/chat") && res.status() === 200;
},
{
timeout: 1000 * 60,
},
),
page.click("form button[type=submit]"),
]);
const text = await response.text();
console.log("AI response when submitting message: ", text);
expect(response.ok()).toBeTruthy();
});
// clean processes
test.afterAll(async () => {
appProcess?.kill();
});
});
}
}
}
}
}
test("Backend frameworks should response when calling non-streaming chat API", async ({
request,
}) => {
test.skip(templatePostInstallAction !== "runApp");
test.skip(templateFramework === "nextjs");
const response = await request.post(
`http://localhost:${externalPort}/api/chat/request`,
{
data: {
messages: [
{
role: "user",
content: userMessage,
},
],
},
},
);
const text = await response.text();
console.log("AI response when calling API: ", text);
expect(response.ok()).toBeTruthy();
});
// clean processes
test.afterAll(async () => {
appProcess?.kill();
});
});
+62 -61
View File
@@ -18,48 +18,6 @@ export type CreateLlamaResult = {
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,
@@ -72,9 +30,13 @@ export async function runCreateLlama(
port: number,
externalPort: number,
postInstallAction: TemplatePostInstallAction,
llamaCloudProjectName: string,
llamaCloudIndexName: string,
): Promise<CreateLlamaResult> {
if (!process.env.OPENAI_API_KEY) {
throw new Error("Setting OPENAI_API_KEY is mandatory to run tests");
if (!process.env.OPENAI_API_KEY || !process.env.LLAMA_CLOUD_API_KEY) {
throw new Error(
"Setting the OPENAI_API_KEY and LLAMA_CLOUD_API_KEY is mandatory to run tests",
);
}
const name = [
templateType,
@@ -110,12 +72,16 @@ export async function runCreateLlama(
"--no-llama-parse",
"--observability",
"none",
"--llama-cloud-key",
process.env.LLAMA_CLOUD_API_KEY,
].join(" ");
console.log(`running command '${command}' in ${cwd}`);
const appProcess = exec(command, {
cwd,
env: {
...process.env,
LLAMA_CLOUD_PROJECT_NAME: llamaCloudProjectName,
LLAMA_CLOUD_INDEX_NAME: llamaCloudIndexName,
},
});
appProcess.stderr?.on("data", (data) => {
@@ -134,25 +100,10 @@ export async function runCreateLlama(
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);
}
});
});
// wait 10 seconds for create-llama to exit
await waitForProcess(appProcess, 1000 * 10);
}
return {
@@ -166,3 +117,53 @@ export async function createTestDir() {
await mkdir(cwd, { recursive: true });
return cwd;
}
// eslint-disable-next-line max-params
async function checkAppHasStarted(
frontend: boolean,
framework: TemplateFramework,
port: number,
externalPort: number,
) {
const portsToWait = frontend
? [port, externalPort]
: [framework === "nextjs" ? port : externalPort];
await waitPorts(portsToWait);
}
async function waitPorts(ports: number[]): Promise<void> {
const waitForPort = async (port: number): Promise<void> => {
await waitPort({
host: "localhost",
port: port,
// wait max. 5 mins for start up of app
timeout: 1000 * 60 * 5,
});
};
try {
await Promise.all(ports.map(waitForPort));
} catch (err) {
console.error(err);
throw err;
}
}
async function waitForProcess(
process: ChildProcess,
timeoutMs: number,
): Promise<void> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error("Process timeout error"));
}, timeoutMs);
process.on("exit", (code) => {
clearTimeout(timeout);
if (code !== 0 && code !== null) {
reject(new Error("Process exited with non-zero code"));
} else {
resolve();
}
});
});
}
+147 -22
View File
@@ -2,9 +2,11 @@ import fs from "fs/promises";
import path from "path";
import { TOOL_SYSTEM_PROMPT_ENV_VAR, Tool } from "./tools";
import {
InstallTemplateArgs,
ModelConfig,
TemplateDataSource,
TemplateFramework,
TemplateObservability,
TemplateType,
TemplateVectorDB,
} from "./types";
@@ -155,6 +157,22 @@ const getVectorDBEnvs = (
"The base URL for the LlamaCloud API. Only change this for non-production environments",
value: "https://api.cloud.llamaindex.ai",
},
{
name: "LLAMA_CLOUD_ORGANIZATION_ID",
description:
"The organization ID for the LlamaCloud project (uses default organization if not specified - Python only)",
},
...(framework === "nextjs"
? // activate index selector per default (not needed for non-NextJS backends as it's handled by createFrontendEnvFile)
[
{
name: "NEXT_PUBLIC_USE_LLAMACLOUD",
description:
"Let's the user change indexes in LlamaCloud projects",
value: "true",
},
]
: []),
];
case "chroma":
const envs = [
@@ -181,6 +199,23 @@ Otherwise, use CHROMA_HOST and CHROMA_PORT config above`,
});
}
return envs;
case "weaviate":
return [
{
name: "WEAVIATE_CLUSTER_URL",
description:
"The URL of the Weaviate cloud cluster, see: https://weaviate.io/developers/wcs/connect",
},
{
name: "WEAVIATE_API_KEY",
description: "The API key for the Weaviate cloud cluster",
},
{
name: "WEAVIATE_INDEX_NAME",
description:
"(Optional) The collection name to use, default is LlamaIndex if not specified",
},
];
default:
return [];
}
@@ -274,6 +309,33 @@ const getModelEnvs = (modelConfig: ModelConfig): EnvVar[] => {
},
]
: []),
...(modelConfig.provider === "azure-openai"
? [
{
name: "AZURE_OPENAI_API_KEY",
description: "The Azure OpenAI key to use.",
value: modelConfig.apiKey,
},
{
name: "AZURE_OPENAI_ENDPOINT",
description: "The Azure OpenAI endpoint to use.",
},
{
name: "AZURE_OPENAI_API_VERSION",
description: "The Azure OpenAI API version to use.",
},
{
name: "AZURE_OPENAI_LLM_DEPLOYMENT",
description:
"The Azure OpenAI deployment to use for LLM deployment.",
},
{
name: "AZURE_OPENAI_EMBEDDING_DEPLOYMENT",
description:
"The Azure OpenAI deployment to use for embedding deployment.",
},
]
: []),
...(modelConfig.provider === "t-systems"
? [
{
@@ -362,7 +424,11 @@ const getToolEnvs = (tools?: Tool[]): EnvVar[] => {
return toolEnvs;
};
const getSystemPromptEnv = (tools?: Tool[]): EnvVar => {
const getSystemPromptEnv = (
tools?: Tool[],
dataSources?: TemplateDataSource[],
framework?: TemplateFramework,
): EnvVar[] => {
const defaultSystemPrompt =
"You are a helpful assistant who helps users with their questions.";
@@ -381,11 +447,49 @@ const getSystemPromptEnv = (tools?: Tool[]): EnvVar => {
? `\"${toolSystemPrompt}\"`
: defaultSystemPrompt;
return {
name: "SYSTEM_PROMPT",
description: "The system prompt for the AI model.",
value: systemPrompt,
};
const systemPromptEnv = [
{
name: "SYSTEM_PROMPT",
description: "The system prompt for the AI model.",
value: systemPrompt,
},
];
// Citation only works with FastAPI along with the chat engine and data source provided for now.
if (
framework === "fastapi" &&
tools?.length == 0 &&
(dataSources?.length ?? 0 > 0)
) {
const citationPrompt = `'You have provided information from a knowledge base that has been passed to you in nodes of information.
Each node has useful metadata such as node ID, file name, page, etc.
Please add the citation to the data node for each sentence or paragraph that you reference in the provided information.
The citation format is: . [citation:<node_id>]()
Where the <node_id> is the unique identifier of the data node.
Example:
We have two nodes:
node_id: xyz
file_name: llama.pdf
node_id: abc
file_name: animal.pdf
User question: Tell me a fun fact about Llama.
Your answer:
A baby llama is called "Cria" [citation:xyz]().
It often live in desert [citation:abc]().
It\\'s cute animal.
'`;
systemPromptEnv.push({
name: "SYSTEM_CITATION_PROMPT",
description:
"An additional system prompt to add citation when responding to user questions.",
value: citationPrompt,
});
}
return systemPromptEnv;
};
const getTemplateEnvs = (template?: TemplateType): EnvVar[] => {
@@ -418,18 +522,35 @@ const getTemplateEnvs = (template?: TemplateType): EnvVar[] => {
}
};
const getObservabilityEnvs = (
observability?: TemplateObservability,
): EnvVar[] => {
if (observability === "llamatrace") {
return [
{
name: "PHOENIX_API_KEY",
description:
"API key for LlamaTrace observability. Retrieve from https://llamatrace.com/login",
},
];
}
return [];
};
export const createBackendEnvFile = async (
root: string,
opts: {
llamaCloudKey?: string;
vectorDb?: TemplateVectorDB;
modelConfig: ModelConfig;
framework: TemplateFramework;
dataSources?: TemplateDataSource[];
template?: TemplateType;
port?: number;
tools?: Tool[];
},
opts: Pick<
InstallTemplateArgs,
| "llamaCloudKey"
| "vectorDb"
| "modelConfig"
| "framework"
| "dataSources"
| "template"
| "externalPort"
| "tools"
| "observability"
>,
) => {
// Init env values
const envFileName = ".env";
@@ -439,17 +560,15 @@ export const createBackendEnvFile = async (
description: `The Llama Cloud API key.`,
value: opts.llamaCloudKey,
},
// Add model environment variables
// Add environment variables of each component
...getModelEnvs(opts.modelConfig),
// Add engine environment variables
...getEngineEnvs(),
// Add vector database environment variables
...getVectorDBEnvs(opts.vectorDb, opts.framework),
...getFrameworkEnvs(opts.framework, opts.port),
...getFrameworkEnvs(opts.framework, opts.externalPort),
...getToolEnvs(opts.tools),
// Add template environment variables
...getTemplateEnvs(opts.template),
getSystemPromptEnv(opts.tools),
...getObservabilityEnvs(opts.observability),
...getSystemPromptEnv(opts.tools, opts.dataSources, opts.framework),
];
// Render and write env file
const content = renderEnvVar(envVars);
@@ -461,6 +580,7 @@ export const createFrontendEnvFile = async (
root: string,
opts: {
customApiPath?: string;
vectorDb?: TemplateVectorDB;
},
) => {
const defaultFrontendEnvs = [
@@ -471,6 +591,11 @@ export const createFrontendEnvFile = async (
? opts.customApiPath
: "http://localhost:8000/api/chat",
},
{
name: "NEXT_PUBLIC_USE_LLAMACLOUD",
description: "Let's the user change indexes in LlamaCloud projects",
value: opts.vectorDb === "llamacloud" ? "true" : "false",
},
];
const content = renderEnvVar(defaultFrontendEnvs);
await fs.writeFile(path.join(root, ".env"), content);
+57 -36
View File
@@ -8,6 +8,7 @@ import { writeLoadersConfig } from "./datasources";
import { createBackendEnvFile, createFrontendEnvFile } from "./env-variables";
import { PackageManager } from "./get-pkg-manager";
import { installLlamapackProject } from "./llama-pack";
import { makeDir } from "./make-dir";
import { isHavingPoetryLockFile, tryPoetryRun } from "./poetry";
import { installPythonTemplate } from "./python";
import { downloadAndExtractRepo } from "./repo";
@@ -22,6 +23,31 @@ import {
} from "./types";
import { installTSTemplate } from "./typescript";
const checkForGenerateScript = (
modelConfig: ModelConfig,
vectorDb?: TemplateVectorDB,
llamaCloudKey?: string,
useLlamaParse?: boolean,
) => {
const missingSettings = [];
if (!modelConfig.isConfigured()) {
missingSettings.push("your model provider API key");
}
const llamaCloudApiKey = llamaCloudKey ?? process.env["LLAMA_CLOUD_API_KEY"];
const isRequiredLlamaCloudKey = useLlamaParse || vectorDb === "llamacloud";
if (isRequiredLlamaCloudKey && !llamaCloudApiKey) {
missingSettings.push("your LLAMA_CLOUD_API_KEY");
}
if (vectorDb !== "none" && vectorDb !== "llamacloud") {
missingSettings.push("your Vector DB environment variables");
}
return missingSettings;
};
// eslint-disable-next-line max-params
async function generateContextData(
framework: TemplateFramework,
@@ -37,12 +63,15 @@ async function generateContextData(
? "poetry run generate"
: `${packageManager} run generate`,
)}`;
const modelConfigured = modelConfig.isConfigured();
const llamaCloudKeyConfigured = useLlamaParse
? llamaCloudKey || process.env["LLAMA_CLOUD_API_KEY"]
: true;
const hasVectorDb = vectorDb && vectorDb !== "none";
if (modelConfigured && llamaCloudKeyConfigured && !hasVectorDb) {
const missingSettings = checkForGenerateScript(
modelConfig,
vectorDb,
llamaCloudKey,
useLlamaParse,
);
if (!missingSettings.length) {
// If all the required environment variables are set, run the generate script
if (framework === "fastapi") {
if (isHavingPoetryLockFile()) {
@@ -62,15 +91,8 @@ async function generateContextData(
}
}
// generate the message of what to do to run the generate script manually
const settings = [];
if (!modelConfigured) settings.push("your model provider API key");
if (!llamaCloudKeyConfigured) settings.push("your Llama Cloud key");
if (hasVectorDb) settings.push("your Vector DB environment variables");
const settingsMessage =
settings.length > 0 ? `After setting ${settings.join(" and ")}, ` : "";
const generateMessage = `run ${runGenerate} to generate the context data.`;
console.log(`\n${settingsMessage}${generateMessage}\n\n`);
const settingsMessage = `After setting ${missingSettings.join(" and ")}, run ${runGenerate} to generate the context data.`;
console.log(`\n${settingsMessage}\n\n`);
}
}
@@ -120,12 +142,15 @@ export const installTemplate = async (
if (props.framework === "fastapi") {
await installPythonTemplate(props);
// write loaders configuration (currently Python only)
await writeLoadersConfig(
props.root,
props.dataSources,
props.useLlamaParse,
);
if (props.vectorDb !== "llamacloud") {
// write loaders configuration (currently Python only)
// not needed for LlamaCloud as it has its own loaders
await writeLoadersConfig(
props.root,
props.dataSources,
props.useLlamaParse,
);
}
} else {
await installTSTemplate(props);
}
@@ -141,17 +166,12 @@ export const installTemplate = async (
// This is a backend, so we need to copy the test data and create the env file.
// Copy the environment file to the target directory.
if (props.template === "streaming" || props.template === "multiagent") {
await createBackendEnvFile(props.root, {
modelConfig: props.modelConfig,
llamaCloudKey: props.llamaCloudKey,
vectorDb: props.vectorDb,
framework: props.framework,
dataSources: props.dataSources,
port: props.externalPort,
tools: props.tools,
template: props.template,
});
if (
props.template === "streaming" ||
props.template === "multiagent" ||
props.template === "extractor"
) {
await createBackendEnvFile(props.root, props);
}
if (props.dataSources.length > 0) {
@@ -175,14 +195,15 @@ export const installTemplate = async (
}
}
// Create tool-output directory
if (props.tools && props.tools.length > 0) {
await fsExtra.mkdir(path.join(props.root, "tool-output"));
}
// Create outputs directory
await makeDir(path.join(props.root, "output/tools"));
await makeDir(path.join(props.root, "output/uploaded"));
await makeDir(path.join(props.root, "output/llamacloud"));
} else {
// this is a frontend for a full-stack app, create .env file with model information
await createFrontendEnvFile(props.root, {
customApiPath: props.customApiPath,
vectorDb: props.vectorDb,
});
}
};
+118
View File
@@ -0,0 +1,118 @@
import ciInfo from "ci-info";
import prompts from "prompts";
import { ModelConfigParams, ModelConfigQuestionsParams } from ".";
import { questionHandlers } from "../../questions";
const ALL_AZURE_OPENAI_CHAT_MODELS: Record<string, { openAIModel: string }> = {
"gpt-35-turbo": { openAIModel: "gpt-3.5-turbo" },
"gpt-35-turbo-16k": {
openAIModel: "gpt-3.5-turbo-16k",
},
"gpt-4o": { openAIModel: "gpt-4o" },
"gpt-4o-mini": { openAIModel: "gpt-4o-mini" },
"gpt-4": { openAIModel: "gpt-4" },
"gpt-4-32k": { openAIModel: "gpt-4-32k" },
"gpt-4-turbo": {
openAIModel: "gpt-4-turbo",
},
"gpt-4-turbo-2024-04-09": {
openAIModel: "gpt-4-turbo",
},
"gpt-4-vision-preview": {
openAIModel: "gpt-4-vision-preview",
},
"gpt-4-1106-preview": {
openAIModel: "gpt-4-1106-preview",
},
"gpt-4o-2024-05-13": {
openAIModel: "gpt-4o-2024-05-13",
},
"gpt-4o-mini-2024-07-18": {
openAIModel: "gpt-4o-mini-2024-07-18",
},
};
const ALL_AZURE_OPENAI_EMBEDDING_MODELS: Record<
string,
{
dimensions: number;
openAIModel: string;
}
> = {
"text-embedding-3-small": {
dimensions: 1536,
openAIModel: "text-embedding-3-small",
},
"text-embedding-3-large": {
dimensions: 3072,
openAIModel: "text-embedding-3-large",
},
};
const DEFAULT_MODEL = "gpt-4o";
const DEFAULT_EMBEDDING_MODEL = "text-embedding-3-large";
export async function askAzureQuestions({
openAiKey,
askModels,
}: ModelConfigQuestionsParams): Promise<ModelConfigParams> {
const config: ModelConfigParams = {
apiKey: openAiKey || process.env.AZURE_OPENAI_KEY,
model: DEFAULT_MODEL,
embeddingModel: DEFAULT_EMBEDDING_MODEL,
dimensions: getDimensions(DEFAULT_EMBEDDING_MODEL),
isConfigured(): boolean {
// the Azure model provider can't be fully configured as endpoint and deployment names have to be configured with env variables
return false;
},
};
// use default model values in CI or if user should not be asked
const useDefaults = ciInfo.isCI || !askModels;
if (!useDefaults) {
const { model } = await prompts(
{
type: "select",
name: "model",
message: "Which LLM model would you like to use?",
choices: getAvailableModelChoices(),
initial: 0,
},
questionHandlers,
);
config.model = model;
const { embeddingModel } = await prompts(
{
type: "select",
name: "embeddingModel",
message: "Which embedding model would you like to use?",
choices: getAvailableEmbeddingModelChoices(),
initial: 0,
},
questionHandlers,
);
config.embeddingModel = embeddingModel;
config.dimensions = getDimensions(embeddingModel);
}
return config;
}
function getAvailableModelChoices() {
return Object.keys(ALL_AZURE_OPENAI_CHAT_MODELS).map((key) => ({
title: key,
value: key,
}));
}
function getAvailableEmbeddingModelChoices() {
return Object.keys(ALL_AZURE_OPENAI_EMBEDDING_MODELS).map((key) => ({
title: key,
value: key,
}));
}
function getDimensions(modelName: string) {
return ALL_AZURE_OPENAI_EMBEDDING_MODELS[modelName].dimensions;
}
+5
View File
@@ -3,6 +3,7 @@ import prompts from "prompts";
import { questionHandlers } from "../../questions";
import { ModelConfig, ModelProvider, TemplateFramework } from "../types";
import { askAnthropicQuestions } from "./anthropic";
import { askAzureQuestions } from "./azure";
import { askGeminiQuestions } from "./gemini";
import { askGroqQuestions } from "./groq";
import { askLLMHubQuestions } from "./llmhub";
@@ -34,6 +35,7 @@ export async function askModelConfig({
{ title: "Anthropic", value: "anthropic" },
{ title: "Gemini", value: "gemini" },
{ title: "Mistral", value: "mistral" },
{ title: "AzureOpenAI", value: "azure-openai" },
];
if (framework === "fastapi") {
@@ -69,6 +71,9 @@ export async function askModelConfig({
case "mistral":
modelConfig = await askMistralQuestions({ askModels });
break;
case "azure-openai":
modelConfig = await askAzureQuestions({ askModels });
break;
case "t-systems":
modelConfig = await askLLMHubQuestions({ askModels });
break;
+1 -1
View File
@@ -8,7 +8,7 @@ import { questionHandlers } from "../../questions";
const OPENAI_API_URL = "https://api.openai.com/v1";
const DEFAULT_MODEL = "gpt-3.5-turbo";
const DEFAULT_MODEL = "gpt-4o-mini";
const DEFAULT_EMBEDDING_MODEL = "text-embedding-3-large";
export async function askOpenAIQuestions({
+56 -17
View File
@@ -55,11 +55,11 @@ const getAdditionalDependencies = (
case "milvus": {
dependencies.push({
name: "llama-index-vector-stores-milvus",
version: "^0.1.6",
version: "^0.1.20",
});
dependencies.push({
name: "pymilvus",
version: "2.3.7",
version: "2.4.4",
});
break;
}
@@ -84,6 +84,13 @@ const getAdditionalDependencies = (
});
break;
}
case "weaviate": {
dependencies.push({
name: "llama-index-vector-stores-weaviate",
version: "^1.0.2",
});
break;
}
}
// Add data source dependencies
@@ -121,7 +128,7 @@ const getAdditionalDependencies = (
case "llamacloud":
dependencies.push({
name: "llama-index-indices-managed-llama-cloud",
version: "^0.2.1",
version: "^0.2.7",
});
break;
}
@@ -153,14 +160,24 @@ const getAdditionalDependencies = (
version: "0.2.6",
});
break;
case "groq":
dependencies.push({
name: "llama-index-llms-groq",
version: "0.1.4",
});
dependencies.push({
name: "llama-index-embeddings-fastembed",
version: "^0.1.4",
});
break;
case "anthropic":
dependencies.push({
name: "llama-index-llms-anthropic",
version: "0.1.10",
});
dependencies.push({
name: "llama-index-embeddings-huggingface",
version: "0.2.0",
name: "llama-index-embeddings-fastembed",
version: "^0.1.4",
});
break;
case "gemini":
@@ -183,6 +200,16 @@ const getAdditionalDependencies = (
version: "0.1.4",
});
break;
case "azure-openai":
dependencies.push({
name: "llama-index-llms-azure-openai",
version: "0.1.10",
});
dependencies.push({
name: "llama-index-embeddings-azure-openai",
version: "0.1.11",
});
break;
case "t-systems":
dependencies.push({
name: "llama-index-agent-openai",
@@ -323,12 +350,15 @@ export const installPythonTemplate = async ({
cwd: path.join(compPath, "vectordbs", "python", vectorDb ?? "none"),
});
// Copy all loaders to enginePath
const loaderPath = path.join(enginePath, "loaders");
await copy("**", loaderPath, {
parents: true,
cwd: path.join(compPath, "loaders", "python"),
});
if (vectorDb !== "llamacloud") {
// Copy all loaders to enginePath
// Not needed for LlamaCloud as it has its own loaders
const loaderPath = path.join(enginePath, "loaders");
await copy("**", loaderPath, {
parents: true,
cwd: path.join(compPath, "loaders", "python"),
});
}
// Copy settings.py to app
await copy("**", path.join(root, "app"), {
@@ -360,18 +390,27 @@ export const installPythonTemplate = async ({
tools,
);
if (observability === "opentelemetry") {
addOnDependencies.push({
name: "traceloop-sdk",
version: "^0.15.11",
});
if (observability && observability !== "none") {
if (observability === "traceloop") {
addOnDependencies.push({
name: "traceloop-sdk",
version: "^0.15.11",
});
}
if (observability === "llamatrace") {
addOnDependencies.push({
name: "llama-index-callbacks-arize-phoenix",
version: "^0.1.6",
});
}
const templateObservabilityPath = path.join(
templatesDir,
"components",
"observability",
"python",
"opentelemetry",
observability,
);
await copy("**", path.join(root, "app"), {
cwd: templateObservabilityPath,
+29
View File
@@ -188,6 +188,35 @@ For better results, you can specify the region parameter to get results from a s
},
],
},
{
display: "Azure Code Interpreter",
name: "azure_code_interpreter.AzureCodeInterpreterToolSpec",
supportedFrameworks: ["fastapi", "nextjs", "express"],
type: ToolType.LLAMAHUB,
dependencies: [
{
name: "llama-index-tools-azure-code-interpreter",
version: "0.2.0",
},
],
envVars: [
{
name: "AZURE_POOL_MANAGEMENT_ENDPOINT",
description:
"Please follow this guideline to create and get the pool management endpoint: https://learn.microsoft.com/azure/container-apps/sessions?tabs=azure-cli",
},
{
name: TOOL_SYSTEM_PROMPT_ENV_VAR,
description: "System prompt for Azure code interpreter tool.",
value: `-You are a Python interpreter that can run any python code in a secure environment.
- The python code runs in a Jupyter notebook. Every time you call the 'interpreter' tool, the python code is executed in a separate cell.
- You are given tasks to complete and you run python code to solve them.
- It's okay to make multiple calls to interpreter tool. If you get an error or the result is not what you expected, you can call the tool again. Don't give up too soon!
- Plot visualizations using matplotlib or any other visualization library directly in the notebook.
- You can install any pip package (if it exists) by running a cell with pip install.`,
},
],
},
];
export const getTool = (toolName: string): Tool | undefined => {
+5 -2
View File
@@ -8,6 +8,7 @@ export type ModelProvider =
| "anthropic"
| "gemini"
| "mistral"
| "azure-openai"
| "t-systems";
export type ModelConfig = {
provider: ModelProvider;
@@ -18,6 +19,7 @@ export type ModelConfig = {
isConfigured(): boolean;
};
export type TemplateType =
| "extractor"
| "streaming"
| "community"
| "llamapack"
@@ -33,7 +35,8 @@ export type TemplateVectorDB =
| "astra"
| "qdrant"
| "chroma"
| "llamacloud";
| "llamacloud"
| "weaviate";
export type TemplatePostInstallAction =
| "none"
| "VSCode"
@@ -44,7 +47,7 @@ export type TemplateDataSource = {
config: TemplateDataSourceConfig;
};
export type TemplateDataSourceType = "file" | "web" | "db" | "llamacloud";
export type TemplateObservability = "none" | "opentelemetry";
export type TemplateObservability = "none" | "traceloop" | "llamatrace";
// Config for both file and folder
export type FileSourceConfig = {
path: string;
+8 -2
View File
@@ -70,7 +70,7 @@ export const installTSTemplate = async ({
);
const webpackConfigOtelFile = path.join(root, "webpack.config.o11y.mjs");
if (observability === "opentelemetry") {
if (observability === "traceloop") {
const webpackConfigDefaultFile = path.join(root, "webpack.config.mjs");
await fs.rm(webpackConfigDefaultFile);
await fs.rename(webpackConfigOtelFile, webpackConfigDefaultFile);
@@ -104,6 +104,12 @@ export const installTSTemplate = async ({
: path.join("src", "controllers");
const enginePath = path.join(root, relativeEngineDestPath, "engine");
// copy llamaindex code for TS templates
await copy("**", path.join(root, relativeEngineDestPath, "llamaindex"), {
parents: true,
cwd: path.join(compPath, "llamaindex", "typescript"),
});
// copy vector db component
if (vectorDb === "llamacloud") {
console.log(
@@ -242,7 +248,7 @@ async function updatePackageJson({
};
}
if (observability === "opentelemetry") {
if (observability === "traceloop") {
packageJson.dependencies = {
...packageJson.dependencies,
"@traceloop/node-server-sdk": "^0.5.19",
+10 -2
View File
@@ -9,7 +9,7 @@ import prompts from "prompts";
import terminalLink from "terminal-link";
import checkForUpdate from "update-check";
import { createApp } from "./create-app";
import { getDataSources } from "./helpers/datasources";
import { EXAMPLE_FILE, getDataSources } from "./helpers/datasources";
import { getPkgManager } from "./helpers/get-pkg-manager";
import { isFolderEmpty } from "./helpers/is-folder-empty";
import { initializeGlobalAgent } from "./helpers/proxy";
@@ -194,8 +194,16 @@ if (process.argv.includes("--no-llama-parse")) {
program.askModels = process.argv.includes("--ask-models");
if (process.argv.includes("--no-files")) {
program.dataSources = [];
} else {
} else if (process.argv.includes("--example-file")) {
program.dataSources = getDataSources(program.files, program.exampleFile);
} else if (process.argv.includes("--llamacloud")) {
program.dataSources = [
{
type: "llamacloud",
config: {},
},
EXAMPLE_FILE,
];
}
const packageManager = !!program.useNpm
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "create-llama",
"version": "0.1.18",
"version": "0.1.38",
"description": "Create LlamaIndex-powered apps with one command",
"keywords": [
"rag",
@@ -9,7 +9,7 @@
],
"repository": {
"type": "git",
"url": "https://github.com/run-llama/LlamaIndexTS",
"url": "https://github.com/run-llama/create-llama",
"directory": "packages/create-llama"
},
"license": "MIT",
+47 -36
View File
@@ -103,6 +103,7 @@ const getVectorDbChoices = (framework: TemplateFramework) => {
{ title: "Astra", value: "astra" },
{ title: "Qdrant", value: "qdrant" },
{ title: "ChromaDB", value: "chroma" },
{ title: "Weaviate", value: "weaviate" },
];
const vectordbLang = framework === "fastapi" ? "python" : "typescript";
@@ -141,7 +142,7 @@ export const getDataSourceChoices = (
if (selectedDataSource === undefined || selectedDataSource.length === 0) {
if (template !== "multiagent") {
choices.push({
title: "No data, just a simple chat or agent",
title: "No datasource",
value: "none",
});
}
@@ -342,6 +343,7 @@ export const askQuestions = async (
title: "Multi-agent app (using llama-agents)",
value: "multiagent",
},
{ title: "Structured Extractor", value: "extractor" },
{
title: `Community template from ${styledRepo}`,
value: "community",
@@ -405,7 +407,7 @@ export const askQuestions = async (
return; // early return - no further questions needed for llamapack projects
}
if (program.template === "multiagent") {
if (program.template === "multiagent" || program.template === "extractor") {
// TODO: multi-agents currently only supports FastAPI
program.framework = preferences.framework = "fastapi";
}
@@ -485,7 +487,10 @@ export const askQuestions = async (
message: "Would you like to set up observability?",
choices: [
{ title: "No", value: "none" },
{ title: "OpenTelemetry", value: "opentelemetry" },
...(program.framework === "fastapi"
? [{ title: "LlamaTrace", value: "llamatrace" }]
: []),
{ title: "Traceloop", value: "traceloop" },
],
initial: 0,
},
@@ -647,45 +652,51 @@ export const askQuestions = async (
// default to use LlamaParse if using LlamaCloud
program.useLlamaParse = preferences.useLlamaParse = true;
} else {
if (program.dataSources.some((ds) => ds.type === "file")) {
if (ciInfo.isCI) {
program.useLlamaParse = getPrefOrDefault("useLlamaParse");
} else {
const { useLlamaParse } = await prompts(
{
type: "toggle",
name: "useLlamaParse",
message:
"Would you like to use LlamaParse (improved parser for RAG - requires API key)?",
initial: false,
active: "yes",
inactive: "no",
},
questionHandlers,
);
program.useLlamaParse = useLlamaParse;
preferences.useLlamaParse = useLlamaParse;
if (program.useLlamaParse === undefined) {
// if already set useLlamaParse, don't ask again
if (program.dataSources.some((ds) => ds.type === "file")) {
if (ciInfo.isCI) {
program.useLlamaParse = getPrefOrDefault("useLlamaParse");
} else {
const { useLlamaParse } = await prompts(
{
type: "toggle",
name: "useLlamaParse",
message:
"Would you like to use LlamaParse (improved parser for RAG - requires API key)?",
initial: false,
active: "yes",
inactive: "no",
},
questionHandlers,
);
program.useLlamaParse = useLlamaParse;
preferences.useLlamaParse = useLlamaParse;
}
}
}
}
// Ask for LlamaCloud API key when using a LlamaCloud index or LlamaParse
if (isUsingLlamaCloud || program.useLlamaParse) {
if (ciInfo.isCI) {
program.llamaCloudKey = getPrefOrDefault("llamaCloudKey");
} else {
// Ask for LlamaCloud API key
const { llamaCloudKey } = await prompts(
{
type: "text",
name: "llamaCloudKey",
message:
"Please provide your LlamaCloud API key (leave blank to skip):",
},
questionHandlers,
);
program.llamaCloudKey = preferences.llamaCloudKey =
llamaCloudKey || process.env.LLAMA_CLOUD_API_KEY;
if (!program.llamaCloudKey) {
// if already set, don't ask again
if (ciInfo.isCI) {
program.llamaCloudKey = getPrefOrDefault("llamaCloudKey");
} else {
// Ask for LlamaCloud API key
const { llamaCloudKey } = await prompts(
{
type: "text",
name: "llamaCloudKey",
message:
"Please provide your LlamaCloud API key (leave blank to skip):",
},
questionHandlers,
);
program.llamaCloudKey = preferences.llamaCloudKey =
llamaCloudKey || process.env.LLAMA_CLOUD_API_KEY;
}
}
}
@@ -6,7 +6,7 @@ from app.engine.tools import ToolFactory
from app.engine.index import get_index
def get_chat_engine():
def get_chat_engine(filters=None, params=None):
system_prompt = os.getenv("SYSTEM_PROMPT")
top_k = os.getenv("TOP_K", "3")
tools = []
@@ -14,7 +14,9 @@ def get_chat_engine():
# Add query tool if index exists
index = get_index()
if index is not None:
query_engine = index.as_query_engine(similarity_top_k=int(top_k))
query_engine = index.as_query_engine(
similarity_top_k=int(top_k), filters=filters
)
query_engine_tool = QueryEngineTool.from_defaults(query_engine=query_engine)
tools.append(query_engine_tool)
@@ -1,8 +1,6 @@
import os
import yaml
import json
import importlib
from cachetools import cached, LRUCache
from llama_index.core.tools.tool_spec.base import BaseToolSpec
from llama_index.core.tools.function_tool import FunctionTool
@@ -13,7 +11,6 @@ class ToolType:
class ToolFactory:
TOOL_SOURCE_PACKAGE_MAP = {
ToolType.LLAMAHUB: "llama_index.tools",
ToolType.LOCAL: "app.engine.tools",
@@ -26,7 +26,7 @@ class ImageGeneratorToolOutput(BaseModel):
class ImageGeneratorTool:
_IMG_OUTPUT_FORMAT = "webp"
_IMG_OUTPUT_DIR = "tool-output"
_IMG_OUTPUT_DIR = "output/tool"
_IMG_GEN_API = "https://api.stability.ai/v2beta/stable-image/generate/core"
def __init__(self, api_key: str = None):
@@ -3,7 +3,7 @@ import logging
import base64
import uuid
from pydantic import BaseModel
from typing import List, Tuple, Dict, Optional
from typing import List, Dict, Optional
from llama_index.core.tools import FunctionTool
from e2b_code_interpreter import CodeInterpreter
from e2b_code_interpreter.models import Logs
@@ -26,8 +26,7 @@ class E2BToolOutput(BaseModel):
class E2BCodeInterpreter:
output_dir = "tool-output"
output_dir = "output/tool"
def __init__(self, api_key: str = None):
if api_key is None:
@@ -1,13 +1,22 @@
import os
from app.engine.index import get_index
from app.engine.node_postprocessors import NodeCitationProcessor
from fastapi import HTTPException
from llama_index.core.chat_engine import CondensePlusContextChatEngine
def get_chat_engine():
def get_chat_engine(filters=None, params=None):
system_prompt = os.getenv("SYSTEM_PROMPT")
top_k = os.getenv("TOP_K", 3)
citation_prompt = os.getenv("SYSTEM_CITATION_PROMPT", None)
top_k = int(os.getenv("TOP_K", 3))
index = get_index()
node_postprocessors = []
if citation_prompt:
node_postprocessors = [NodeCitationProcessor()]
system_prompt = f"{system_prompt}\n{citation_prompt}"
index = get_index(params)
if index is None:
raise HTTPException(
status_code=500,
@@ -16,8 +25,13 @@ def get_chat_engine():
),
)
return index.as_chat_engine(
similarity_top_k=int(top_k),
system_prompt=system_prompt,
chat_mode="condense_plus_context",
retriever = index.as_retriever(
similarity_top_k=top_k,
filters=filters,
)
return CondensePlusContextChatEngine.from_defaults(
system_prompt=system_prompt,
retriever=retriever,
node_postprocessors=node_postprocessors,
)
@@ -0,0 +1,21 @@
from typing import List, Optional
from llama_index.core import QueryBundle
from llama_index.core.postprocessor.types import BaseNodePostprocessor
from llama_index.core.schema import NodeWithScore
class NodeCitationProcessor(BaseNodePostprocessor):
"""
Append node_id into metadata for citation purpose.
Config SYSTEM_CITATION_PROMPT in your runtime environment variable to enable this feature.
"""
def _postprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
) -> List[NodeWithScore]:
for node_score in nodes:
node_score.node.metadata["node_id"] = node_score.node.node_id
return nodes
@@ -2,18 +2,21 @@ import { BaseToolWithCall, OpenAIAgent, QueryEngineTool } from "llamaindex";
import fs from "node:fs/promises";
import path from "node:path";
import { getDataSource } from "./index";
import { generateFilters } from "./queryFilter";
import { createTools } from "./tools";
export async function createChatEngine() {
export async function createChatEngine(documentIds?: string[], params?: any) {
const tools: BaseToolWithCall[] = [];
// Add a query engine tool if we have a data source
// Delete this code if you don't have a data source
const index = await getDataSource();
const index = await getDataSource(params);
if (index) {
tools.push(
new QueryEngineTool({
queryEngine: index.asQueryEngine(),
queryEngine: index.asQueryEngine({
preFilters: generateFilters(documentIds || []),
}),
metadata: {
name: "data_query_engine",
description: `A query engine for documents from your data source.`,
@@ -37,7 +37,7 @@ const DEFAULT_META_DATA: ToolMetadata<JSONSchemaType<ImgGeneratorParameter>> = {
export class ImgGeneratorTool implements BaseTool<ImgGeneratorParameter> {
readonly IMG_OUTPUT_FORMAT = "webp";
readonly IMG_OUTPUT_DIR = "tool-output";
readonly IMG_OUTPUT_DIR = "output/tool";
readonly IMG_GEN_API =
"https://api.stability.ai/v2beta/stable-image/generate/core";
@@ -56,7 +56,7 @@ const DEFAULT_META_DATA: ToolMetadata<JSONSchemaType<InterpreterParameter>> = {
};
export class InterpreterTool implements BaseTool<InterpreterParameter> {
private readonly outputDir = "tool-output";
private readonly outputDir = "output/tool";
private apiKey?: string;
private fileServerURLPrefix?: string;
metadata: ToolMetadata<JSONSchemaType<InterpreterParameter>>;
@@ -1,8 +1,9 @@
import { ContextChatEngine, Settings } from "llamaindex";
import { getDataSource } from "./index";
import { generateFilters } from "./queryFilter";
export async function createChatEngine() {
const index = await getDataSource();
export async function createChatEngine(documentIds?: string[], params?: any) {
const index = await getDataSource(params);
if (!index) {
throw new Error(
`StorageContext is empty - call 'npm run generate' to generate the storage first`,
@@ -10,12 +11,12 @@ export async function createChatEngine() {
}
const retriever = index.asRetriever({
similarityTopK: process.env.TOP_K ? parseInt(process.env.TOP_K) : 3,
filters: generateFilters(documentIds || []),
});
return new ContextChatEngine({
chatModel: Settings.llm,
retriever,
// disable as a custom system prompt disables the generated context
// systemPrompt: process.env.SYSTEM_PROMPT,
systemPrompt: process.env.SYSTEM_PROMPT,
});
}
@@ -0,0 +1,44 @@
import fs from "fs";
import crypto from "node:crypto";
import { getExtractors } from "../../engine/loader";
const MIME_TYPE_TO_EXT: Record<string, string> = {
"application/pdf": "pdf",
"text/plain": "txt",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document":
"docx",
};
const UPLOADED_FOLDER = "output/uploaded";
export async function loadDocuments(fileBuffer: Buffer, mimeType: string) {
const extractors = getExtractors();
const reader = extractors[MIME_TYPE_TO_EXT[mimeType]];
if (!reader) {
throw new Error(`Unsupported document type: ${mimeType}`);
}
console.log(`Processing uploaded document of type: ${mimeType}`);
return await reader.loadDataAsContent(fileBuffer);
}
export async function saveDocument(fileBuffer: Buffer, mimeType: string) {
const fileExt = MIME_TYPE_TO_EXT[mimeType];
if (!fileExt) throw new Error(`Unsupported document type: ${mimeType}`);
const filename = `${crypto.randomUUID()}.${fileExt}`;
const filepath = `${UPLOADED_FOLDER}/${filename}`;
const fileurl = `${process.env.FILESERVER_URL_PREFIX}/${filepath}`;
if (!fs.existsSync(UPLOADED_FOLDER)) {
fs.mkdirSync(UPLOADED_FOLDER, { recursive: true });
}
await fs.promises.writeFile(filepath, fileBuffer);
console.log(`Saved document file to ${filepath}.\nURL: ${fileurl}`);
return {
filename,
filepath,
fileurl,
};
}
@@ -0,0 +1,38 @@
import {
Document,
IngestionPipeline,
Settings,
SimpleNodeParser,
VectorStoreIndex,
} from "llamaindex";
import { LlamaCloudIndex } from "llamaindex/cloud/LlamaCloudIndex";
export async function runPipeline(
currentIndex: VectorStoreIndex | LlamaCloudIndex,
documents: Document[],
) {
if (currentIndex instanceof LlamaCloudIndex) {
// LlamaCloudIndex processes the documents automatically
// so we don't need ingestion pipeline, just insert the documents directly
for (const document of documents) {
await currentIndex.insert(document);
}
} else {
// Use ingestion pipeline to process the documents into nodes and add them to the vector store
const pipeline = new IngestionPipeline({
transformations: [
new SimpleNodeParser({
chunkSize: Settings.chunkSize,
chunkOverlap: Settings.chunkOverlap,
}),
Settings.embedModel,
],
});
const nodes = await pipeline.run({ documents });
await currentIndex.insertNodes(nodes);
currentIndex.storageContext.docStore.persist();
console.log("Added nodes to the vector store.");
}
return documents.map((document) => document.id_);
}
@@ -0,0 +1,26 @@
import { VectorStoreIndex } from "llamaindex";
import { LlamaCloudIndex } from "llamaindex/cloud/LlamaCloudIndex";
import { loadDocuments, saveDocument } from "./helper";
import { runPipeline } from "./pipeline";
export async function uploadDocument(
index: VectorStoreIndex | LlamaCloudIndex,
raw: string,
): Promise<string[]> {
const [header, content] = raw.split(",");
const mimeType = header.replace("data:", "").replace(";base64", "");
const fileBuffer = Buffer.from(content, "base64");
const documents = await loadDocuments(fileBuffer, mimeType);
const { filename } = await saveDocument(fileBuffer, mimeType);
// Update documents with metadata
for (const document of documents) {
document.metadata = {
...document.metadata,
file_name: filename,
private: "true", // to separate private uploads from public documents
};
}
return await runPipeline(index, documents);
}
@@ -0,0 +1,124 @@
import { JSONValue } from "ai";
import { MessageContent, MessageContentDetail } from "llamaindex";
export type DocumentFileType = "csv" | "pdf" | "txt" | "docx";
export type DocumentFileContent = {
type: "ref" | "text";
value: string[] | string;
};
export type DocumentFile = {
id: string;
filename: string;
filesize: number;
filetype: DocumentFileType;
content: DocumentFileContent;
};
type Annotation = {
type: string;
data: object;
};
export function retrieveDocumentIds(annotations?: JSONValue[]): string[] {
if (!annotations) return [];
const ids: string[] = [];
for (const annotation of annotations) {
const { type, data } = getValidAnnotation(annotation);
if (
type === "document_file" &&
"files" in data &&
Array.isArray(data.files)
) {
const files = data.files as DocumentFile[];
for (const file of files) {
if (Array.isArray(file.content.value)) {
// it's an array, so it's an array of doc IDs
for (const id of file.content.value) {
ids.push(id);
}
}
}
}
}
return ids;
}
export function convertMessageContent(
content: string,
annotations?: JSONValue[],
): MessageContent {
if (!annotations) return content;
return [
{
type: "text",
text: content,
},
...convertAnnotations(annotations),
];
}
function convertAnnotations(annotations: JSONValue[]): MessageContentDetail[] {
const content: MessageContentDetail[] = [];
annotations.forEach((annotation: JSONValue) => {
const { type, data } = getValidAnnotation(annotation);
// convert image
if (type === "image" && "url" in data && typeof data.url === "string") {
content.push({
type: "image_url",
image_url: {
url: data.url,
},
});
}
// convert the content of files to a text message
if (
type === "document_file" &&
"files" in data &&
Array.isArray(data.files)
) {
// get all CSV files and convert their whole content to one text message
// currently CSV files are the only files where we send the whole content - we don't use an index
const csvFiles: DocumentFile[] = data.files.filter(
(file: DocumentFile) => file.filetype === "csv",
);
if (csvFiles && csvFiles.length > 0) {
const csvContents = csvFiles.map((file: DocumentFile) => {
const fileContent = Array.isArray(file.content.value)
? file.content.value.join("\n")
: file.content.value;
return "```csv\n" + fileContent + "\n```";
});
const text =
"Use the following CSV content:\n" + csvContents.join("\n\n");
content.push({
type: "text",
text,
});
}
}
});
return content;
}
function getValidAnnotation(annotation: JSONValue): Annotation {
if (
!(
annotation &&
typeof annotation === "object" &&
"type" in annotation &&
typeof annotation.type === "string" &&
"data" in annotation &&
annotation.data &&
typeof annotation.data === "object"
)
) {
throw new Error("Client sent invalid annotation. Missing data and type");
}
return { type: annotation.type, data: annotation.data };
}
@@ -2,43 +2,37 @@ import { StreamData } from "ai";
import {
CallbackManager,
Metadata,
MetadataMode,
NodeWithScore,
ToolCall,
ToolOutput,
} from "llamaindex";
function getNodeUrl(metadata: Metadata) {
const url = metadata["URL"];
if (url) return url;
const fileName = metadata["file_name"];
if (!process.env.FILESERVER_URL_PREFIX) {
console.warn(
"FILESERVER_URL_PREFIX is not set. File URLs will not be generated.",
);
return undefined;
}
if (fileName) {
return `${process.env.FILESERVER_URL_PREFIX}/data/${fileName}`;
}
return undefined;
}
import path from "node:path";
import { DATA_DIR } from "../../engine/loader";
import { LLamaCloudFileService } from "./service";
export function appendSourceData(
data: StreamData,
sourceNodes?: NodeWithScore<Metadata>[],
) {
if (!sourceNodes?.length) return;
data.appendMessageAnnotation({
type: "sources",
data: {
nodes: sourceNodes.map((node) => ({
...node.node.toMutableJSON(),
id: node.node.id_,
score: node.score ?? null,
url: getNodeUrl(node.node.metadata),
})),
},
});
try {
const nodes = sourceNodes.map((node) => ({
metadata: node.node.metadata,
id: node.node.id_,
score: node.score ?? null,
url: getNodeUrl(node.node.metadata),
text: node.node.getContent(MetadataMode.NONE),
}));
data.appendMessageAnnotation({
type: "sources",
data: {
nodes,
},
});
} catch (error) {
console.error("Error appending source data:", error);
}
}
export function appendEventData(data: StreamData, title?: string) {
@@ -85,17 +79,18 @@ export function createCallbackManager(stream: StreamData) {
const callbackManager = new CallbackManager();
callbackManager.on("retrieve-end", (data) => {
const { nodes, query } = data.detail.payload;
const { nodes, query } = data.detail;
appendSourceData(stream, nodes);
appendEventData(stream, `Retrieving context for query: '${query}'`);
appendEventData(
stream,
`Retrieved ${nodes.length} sources to use as context for the query`,
);
LLamaCloudFileService.downloadFiles(nodes); // don't await to avoid blocking chat streaming
});
callbackManager.on("llm-tool-call", (event) => {
const { name, input } = event.detail.payload.toolCall;
const { name, input } = event.detail.toolCall;
const inputString = Object.entries(input)
.map(([key, value]) => `${key}: ${value}`)
.join(", ");
@@ -106,16 +101,40 @@ export function createCallbackManager(stream: StreamData) {
});
callbackManager.on("llm-tool-result", (event) => {
const { toolCall, toolResult } = event.detail.payload;
const { toolCall, toolResult } = event.detail;
appendToolData(stream, toolCall, toolResult);
});
return callbackManager;
}
export type CsvFile = {
content: string;
filename: string;
filesize: number;
id: string;
};
function getNodeUrl(metadata: Metadata) {
if (!process.env.FILESERVER_URL_PREFIX) {
console.warn(
"FILESERVER_URL_PREFIX is not set. File URLs will not be generated.",
);
}
const fileName = metadata["file_name"];
if (fileName && process.env.FILESERVER_URL_PREFIX) {
// file_name exists and file server is configured
const pipelineId = metadata["pipeline_id"];
if (pipelineId && metadata["private"] == null) {
// file is from LlamaCloud and was not ingested locally
const name = LLamaCloudFileService.toDownloadedName(pipelineId, fileName);
return `${process.env.FILESERVER_URL_PREFIX}/output/llamacloud/${name}`;
}
const isPrivate = metadata["private"] === "true";
if (isPrivate) {
return `${process.env.FILESERVER_URL_PREFIX}/output/uploaded/${fileName}`;
}
const filePath = metadata["file_path"];
const dataDir = path.resolve(DATA_DIR);
if (filePath && dataDir) {
const relativePath = path.relative(dataDir, filePath);
return `${process.env.FILESERVER_URL_PREFIX}/data/${relativePath}`;
}
}
// fallback to URL in metadata (e.g. for websites)
return metadata["URL"];
}
@@ -0,0 +1,187 @@
import { Metadata, NodeWithScore } from "llamaindex";
import fs from "node:fs";
import https from "node:https";
import path from "node:path";
const LLAMA_CLOUD_OUTPUT_DIR = "output/llamacloud";
const LLAMA_CLOUD_BASE_URL = "https://cloud.llamaindex.ai/api/v1";
const FILE_DELIMITER = "$"; // delimiter between pipelineId and filename
type LlamaCloudFile = {
name: string;
file_id: string;
project_id: string;
};
type LLamaCloudProject = {
id: string;
organization_id: string;
name: string;
is_default: boolean;
};
type LLamaCloudPipeline = {
id: string;
name: string;
project_id: string;
};
export class LLamaCloudFileService {
private static readonly headers = {
Accept: "application/json",
Authorization: `Bearer ${process.env.LLAMA_CLOUD_API_KEY}`,
};
public static async getAllProjectsWithPipelines() {
try {
const projects = await LLamaCloudFileService.getAllProjects();
const pipelines = await LLamaCloudFileService.getAllPipelines();
return projects.map((project) => ({
...project,
pipelines: pipelines.filter((p) => p.project_id === project.id),
}));
} catch (error) {
console.error("Error listing projects and pipelines:", error);
return [];
}
}
public static async downloadFiles(nodes: NodeWithScore<Metadata>[]) {
const files = LLamaCloudFileService.nodesToDownloadFiles(nodes);
if (!files.length) return;
console.log("Downloading files from LlamaCloud...");
for (const file of files) {
await LLamaCloudFileService.downloadFile(file.pipelineId, file.fileName);
}
}
public static toDownloadedName(pipelineId: string, fileName: string) {
return `${pipelineId}${FILE_DELIMITER}${fileName}`;
}
/**
* This function will return an array of unique files to download from LlamaCloud
* We only download files that are uploaded directly in LlamaCloud datasources (don't have `private` in metadata)
* Files are uploaded directly in LlamaCloud datasources don't have `private` in metadata (public docs)
* Files are uploaded from local via `generate` command will have `private=false` (public docs)
* Files are uploaded from local via `/chat/upload` endpoint will have `private=true` (private docs)
*
* @param nodes
* @returns list of unique files to download
*/
private static nodesToDownloadFiles(nodes: NodeWithScore<Metadata>[]) {
const downloadFiles: Array<{
pipelineId: string;
fileName: string;
}> = [];
for (const node of nodes) {
const isLocalFile = node.node.metadata["private"] != null;
const pipelineId = node.node.metadata["pipeline_id"];
const fileName = node.node.metadata["file_name"];
if (isLocalFile || !pipelineId || !fileName) continue;
const isDuplicate = downloadFiles.some(
(f) => f.pipelineId === pipelineId && f.fileName === fileName,
);
if (!isDuplicate) {
downloadFiles.push({ pipelineId, fileName });
}
}
return downloadFiles;
}
private static async downloadFile(pipelineId: string, fileName: string) {
try {
const downloadedName = LLamaCloudFileService.toDownloadedName(
pipelineId,
fileName,
);
const downloadedPath = path.join(LLAMA_CLOUD_OUTPUT_DIR, downloadedName);
// Check if file already exists
if (fs.existsSync(downloadedPath)) return;
const urlToDownload = await LLamaCloudFileService.getFileUrlByName(
pipelineId,
fileName,
);
if (!urlToDownload) throw new Error("File not found in LlamaCloud");
const file = fs.createWriteStream(downloadedPath);
https
.get(urlToDownload, (response) => {
response.pipe(file);
file.on("finish", () => {
file.close(() => {
console.log("File downloaded successfully");
});
});
})
.on("error", (err) => {
fs.unlink(downloadedPath, () => {
console.error("Error downloading file:", err);
throw err;
});
});
} catch (error) {
throw new Error(`Error downloading file from LlamaCloud: ${error}`);
}
}
private static async getFileUrlByName(
pipelineId: string,
name: string,
): Promise<string | null> {
const files = await LLamaCloudFileService.getAllFiles(pipelineId);
const file = files.find((file) => file.name === name);
if (!file) return null;
return await LLamaCloudFileService.getFileUrlById(
file.project_id,
file.file_id,
);
}
private static async getFileUrlById(
projectId: string,
fileId: string,
): Promise<string> {
const url = `${LLAMA_CLOUD_BASE_URL}/files/${fileId}/content?project_id=${projectId}`;
const response = await fetch(url, {
method: "GET",
headers: LLamaCloudFileService.headers,
});
const data = (await response.json()) as { url: string };
return data.url;
}
private static async getAllFiles(
pipelineId: string,
): Promise<LlamaCloudFile[]> {
const url = `${LLAMA_CLOUD_BASE_URL}/pipelines/${pipelineId}/files`;
const response = await fetch(url, {
method: "GET",
headers: LLamaCloudFileService.headers,
});
const data = await response.json();
return data;
}
private static async getAllProjects(): Promise<LLamaCloudProject[]> {
const url = `${LLAMA_CLOUD_BASE_URL}/projects`;
const response = await fetch(url, {
method: "GET",
headers: LLamaCloudFileService.headers,
});
const data = (await response.json()) as LLamaCloudProject[];
return data;
}
private static async getAllPipelines(): Promise<LLamaCloudPipeline[]> {
const url = `${LLAMA_CLOUD_BASE_URL}/pipelines`;
const response = await fetch(url, {
method: "GET",
headers: LLamaCloudFileService.headers,
});
const data = (await response.json()) as LLamaCloudPipeline[];
return data;
}
}
@@ -0,0 +1,57 @@
import {
StreamData,
createCallbacksTransformer,
createStreamDataTransformer,
trimStartOfStreamHelper,
type AIStreamCallbacksAndOptions,
} from "ai";
import { ChatMessage, EngineResponse } from "llamaindex";
import { generateNextQuestions } from "./suggestion";
export function LlamaIndexStream(
response: AsyncIterable<EngineResponse>,
data: StreamData,
chatHistory: ChatMessage[],
opts?: {
callbacks?: AIStreamCallbacksAndOptions;
},
): ReadableStream<Uint8Array> {
return createParser(response, data, chatHistory)
.pipeThrough(createCallbacksTransformer(opts?.callbacks))
.pipeThrough(createStreamDataTransformer());
}
function createParser(
res: AsyncIterable<EngineResponse>,
data: StreamData,
chatHistory: ChatMessage[],
) {
const it = res[Symbol.asyncIterator]();
const trimStartOfStream = trimStartOfStreamHelper();
let llmTextResponse = "";
return new ReadableStream<string>({
async pull(controller): Promise<void> {
const { value, done } = await it.next();
if (done) {
controller.close();
// LLM stream is done, generate the next questions with a new LLM call
chatHistory.push({ role: "assistant", content: llmTextResponse });
const questions: string[] = await generateNextQuestions(chatHistory);
if (questions.length > 0) {
data.appendMessageAnnotation({
type: "suggested_questions",
data: questions,
});
}
data.close();
return;
}
const text = trimStartOfStream(value.delta ?? "");
if (text) {
llmTextResponse += text;
controller.enqueue(text);
}
},
});
}
@@ -0,0 +1,55 @@
import { ChatMessage, Settings } from "llamaindex";
const NEXT_QUESTION_PROMPT_TEMPLATE = `You're a helpful assistant! Your task is to suggest the next question that user might ask.
Here is the conversation history
---------------------
$conversation
---------------------
Given the conversation history, please give me $number_of_questions questions that you might ask next!
Your answer should be wrapped in three sticks which follows the following format:
\`\`\`
<question 1>
<question 2>\`\`\`
`;
const N_QUESTIONS_TO_GENERATE = 3;
export async function generateNextQuestions(
conversation: ChatMessage[],
numberOfQuestions: number = N_QUESTIONS_TO_GENERATE,
) {
const llm = Settings.llm;
// Format conversation
const conversationText = conversation
.map((message) => `${message.role}: ${message.content}`)
.join("\n");
const message = NEXT_QUESTION_PROMPT_TEMPLATE.replace(
"$conversation",
conversationText,
).replace("$number_of_questions", numberOfQuestions.toString());
try {
const response = await llm.complete({ prompt: message });
const questions = extractQuestions(response.text);
return questions;
} catch (error) {
console.error("Error when generating the next questions: ", error);
return [];
}
}
// TODO: instead of parsing the LLM's result we can use structured predict, once LITS supports it
function extractQuestions(text: string): string[] {
// Extract the text inside the triple backticks
// @ts-ignore
const contentMatch = text.match(/```(.*?)```/s);
const content = contentMatch ? contentMatch[1] : "";
// Split the content by newlines to get each question
const questions = content
.split("\n")
.map((question) => question.trim())
.filter((question) => question !== "");
return questions;
}
@@ -1,11 +1,9 @@
import os
import yaml
import importlib
import logging
from typing import Dict
import yaml
from app.engine.loaders.db import DBLoaderConfig, get_db_documents
from app.engine.loaders.file import FileLoaderConfig, get_file_documents
from app.engine.loaders.web import WebLoaderConfig, get_web_documents
from app.engine.loaders.db import DBLoaderConfig, get_db_documents
logger = logging.getLogger(__name__)
+1 -3
View File
@@ -1,8 +1,6 @@
import os
import logging
from typing import List
from pydantic import BaseModel, validator
from llama_index.core.indices.vector_store import VectorStoreIndex
from pydantic import BaseModel
logger = logging.getLogger(__name__)
+6 -10
View File
@@ -2,21 +2,16 @@ import os
import logging
from typing import Dict
from llama_parse import LlamaParse
from pydantic import BaseModel, validator
from pydantic import BaseModel
from app.config import DATA_DIR
logger = logging.getLogger(__name__)
class FileLoaderConfig(BaseModel):
data_dir: str = "data"
use_llama_parse: bool = False
@validator("data_dir")
def data_dir_must_exist(cls, v):
if not os.path.isdir(v):
raise ValueError(f"Directory '{v}' does not exist")
return v
def llama_parse_parser():
if os.getenv("LLAMA_CLOUD_API_KEY") is None:
@@ -54,7 +49,7 @@ def get_file_documents(config: FileLoaderConfig):
file_extractor = llama_parse_extractor()
reader = SimpleDirectoryReader(
config.data_dir,
DATA_DIR,
recursive=True,
filename_as_id=True,
raise_on_error=True,
@@ -62,7 +57,8 @@ def get_file_documents(config: FileLoaderConfig):
)
return reader.load_data()
except Exception as e:
import sys, traceback
import sys
import traceback
# Catch the error if the data dir is empty
# and return as empty document list
@@ -1,5 +1,3 @@
import os
import json
from pydantic import BaseModel, Field
@@ -1,9 +1,24 @@
import { SimpleDirectoryReader } from "llamaindex";
import {
FILE_EXT_TO_READER,
SimpleDirectoryReader,
} from "llamaindex/readers/SimpleDirectoryReader";
export const DATA_DIR = "./data";
export function getExtractors() {
return FILE_EXT_TO_READER;
}
export async function getDocuments() {
return await new SimpleDirectoryReader().loadData({
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: DATA_DIR,
});
// Set private=false to mark the document as public (required for filtering)
for (const document of documents) {
document.metadata = {
...document.metadata,
private: "false",
};
}
return documents;
}
@@ -1,19 +1,38 @@
import { LlamaParseReader } from "llamaindex/readers/LlamaParseReader";
import {
FILE_EXT_TO_READER,
LlamaParseReader,
SimpleDirectoryReader,
} from "llamaindex";
} from "llamaindex/readers/SimpleDirectoryReader";
export const DATA_DIR = "./data";
export function getExtractors() {
const llamaParseParser = new LlamaParseReader({ resultType: "markdown" });
const extractors = FILE_EXT_TO_READER;
// Change all the supported extractors to LlamaParse
// except for .txt, it doesn't need to be parsed
for (const key in extractors) {
if (key === "txt") {
continue;
}
extractors[key] = llamaParseParser;
}
return extractors;
}
export async function getDocuments() {
const reader = new SimpleDirectoryReader();
// Load PDFs using LlamaParseReader
return await reader.loadData({
const extractors = getExtractors();
const documents = await reader.loadData({
directoryPath: DATA_DIR,
fileExtToReader: {
...FILE_EXT_TO_READER,
pdf: new LlamaParseReader({ resultType: "markdown" }),
},
fileExtToReader: extractors,
});
// Set private=false to mark the document as public (required for filtering)
for (const document of documents) {
document.metadata = {
...document.metadata,
private: "false",
};
}
return documents;
}
@@ -0,0 +1,12 @@
import llama_index.core
import os
def init_observability():
PHOENIX_API_KEY = os.getenv("PHOENIX_API_KEY")
if not PHOENIX_API_KEY:
raise ValueError("PHOENIX_API_KEY environment variable is not set")
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"api_key={PHOENIX_API_KEY}"
llama_index.core.set_global_handler(
"arize_phoenix", endpoint="https://llamatrace.com/v1/traces"
)
@@ -6,7 +6,7 @@ authors = ["Marcus Schiesser <mail@marcusschiesser.de>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.11,<3.12"
python = "^3.11,<4.0"
llama-index = "^0.10.6"
llama-index-readers-file = "^0.1.3"
python-dotenv = "^1.0.0"
@@ -6,11 +6,13 @@ import os
DEFAULT_MODEL = "gpt-3.5-turbo"
DEFAULT_EMBEDDING_MODEL = "text-embedding-3-large"
class TSIEmbedding(OpenAIEmbedding):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._query_engine = self._text_engine = self.model_name
def llm_config_from_env() -> Dict:
from llama_index.core.constants import DEFAULT_TEMPERATURE
@@ -32,7 +34,7 @@ def llm_config_from_env() -> Dict:
def embedding_config_from_env() -> Dict:
from llama_index.core.constants import DEFAULT_EMBEDDING_DIM
model = os.getenv("EMBEDDING_MODEL", DEFAULT_EMBEDDING_MODEL)
dimension = os.getenv("EMBEDDING_DIM", DEFAULT_EMBEDDING_DIM)
api_key = os.getenv("T_SYSTEMS_LLMHUB_API_KEY")
@@ -46,6 +48,7 @@ def embedding_config_from_env() -> Dict:
}
return config
def init_llmhub():
from llama_index.llms.openai_like import OpenAILike
@@ -58,4 +61,4 @@ def init_llmhub():
is_chat_model=True,
is_function_calling_model=False,
context_window=4096,
)
)
@@ -75,31 +75,55 @@ def init_azure_openai():
from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding
from llama_index.llms.azure_openai import AzureOpenAI
llm_deployment = os.getenv("AZURE_OPENAI_LLM_DEPLOYMENT")
embedding_deployment = os.getenv("AZURE_OPENAI_EMBEDDING_DEPLOYMENT")
llm_deployment = os.environ["AZURE_OPENAI_LLM_DEPLOYMENT"]
embedding_deployment = os.environ["AZURE_OPENAI_EMBEDDING_DEPLOYMENT"]
max_tokens = os.getenv("LLM_MAX_TOKENS")
api_key = os.getenv("AZURE_OPENAI_API_KEY")
llm_config = {
"api_key": api_key,
"deployment_name": llm_deployment,
"model": os.getenv("MODEL"),
"temperature": float(os.getenv("LLM_TEMPERATURE", DEFAULT_TEMPERATURE)),
"max_tokens": int(max_tokens) if max_tokens is not None else None,
}
Settings.llm = AzureOpenAI(**llm_config)
temperature = os.getenv("LLM_TEMPERATURE", DEFAULT_TEMPERATURE)
dimensions = os.getenv("EMBEDDING_DIM")
embedding_config = {
"api_key": api_key,
"deployment_name": embedding_deployment,
"model": os.getenv("EMBEDDING_MODEL"),
"dimensions": int(dimensions) if dimensions is not None else None,
azure_config = {
"api_key": os.environ["AZURE_OPENAI_API_KEY"],
"azure_endpoint": os.environ["AZURE_OPENAI_ENDPOINT"],
"api_version": os.getenv("AZURE_OPENAI_API_VERSION")
or os.getenv("OPENAI_API_VERSION"),
}
Settings.embed_model = AzureOpenAIEmbedding(**embedding_config)
Settings.llm = AzureOpenAI(
model=os.getenv("MODEL"),
max_tokens=int(max_tokens) if max_tokens is not None else None,
temperature=float(temperature),
deployment_name=llm_deployment,
**azure_config,
)
Settings.embed_model = AzureOpenAIEmbedding(
model=os.getenv("EMBEDDING_MODEL"),
dimensions=int(dimensions) if dimensions is not None else None,
deployment_name=embedding_deployment,
**azure_config,
)
def init_fastembed():
"""
Use Qdrant Fastembed as the local embedding provider.
"""
from llama_index.embeddings.fastembed import FastEmbedEmbedding
embed_model_map: Dict[str, str] = {
# Small and multilingual
"all-MiniLM-L6-v2": "sentence-transformers/all-MiniLM-L6-v2",
# Large and multilingual
"paraphrase-multilingual-mpnet-base-v2": "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", # noqa: E501
}
# This will download the model automatically if it is not already downloaded
Settings.embed_model = FastEmbedEmbedding(
model_name=embed_model_map[os.getenv("EMBEDDING_MODEL")]
)
def init_groq():
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.groq import Groq
model_map: Dict[str, str] = {
@@ -108,19 +132,12 @@ def init_groq():
"mixtral-8x7b": "mixtral-8x7b-32768",
}
embed_model_map: Dict[str, str] = {
"all-MiniLM-L6-v2": "sentence-transformers/all-MiniLM-L6-v2",
"all-mpnet-base-v2": "sentence-transformers/all-mpnet-base-v2",
}
Settings.llm = Groq(model=model_map[os.getenv("MODEL")])
Settings.embed_model = HuggingFaceEmbedding(
model_name=embed_model_map[os.getenv("EMBEDDING_MODEL")]
)
# Groq does not provide embeddings, so we use FastEmbed instead
init_fastembed()
def init_anthropic():
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.anthropic import Anthropic
model_map: Dict[str, str] = {
@@ -131,15 +148,9 @@ def init_anthropic():
"claude-instant-1.2": "claude-instant-1.2",
}
embed_model_map: Dict[str, str] = {
"all-MiniLM-L6-v2": "sentence-transformers/all-MiniLM-L6-v2",
"all-mpnet-base-v2": "sentence-transformers/all-mpnet-base-v2",
}
Settings.llm = Anthropic(model=model_map[os.getenv("MODEL")])
Settings.embed_model = HuggingFaceEmbedding(
model_name=embed_model_map[os.getenv("EMBEDDING_MODEL")]
)
# Anthropic does not provide embeddings, so we use FastEmbed instead
init_fastembed()
def init_gemini():
@@ -1,30 +1,24 @@
"use client";
import { useEffect, useMemo, useState } from "react";
export interface ChatConfig {
chatAPI?: string;
starterQuestions?: string[];
backend?: string;
}
export function useClientConfig() {
const API_ROUTE = "/api/chat/config";
function getBackendOrigin(): string {
const chatAPI = process.env.NEXT_PUBLIC_CHAT_API;
const [config, setConfig] = useState<ChatConfig>({
chatAPI,
});
const configAPI = useMemo(() => {
const backendOrigin = chatAPI ? new URL(chatAPI).origin : "";
return `${backendOrigin}${API_ROUTE}`;
}, [chatAPI]);
useEffect(() => {
fetch(configAPI)
.then((response) => response.json())
.then((data) => setConfig({ ...data, chatAPI }))
.catch((error) => console.error("Error fetching config", error));
}, [chatAPI, configAPI]);
return config;
if (chatAPI) {
return new URL(chatAPI).origin;
} else {
if (typeof window !== "undefined") {
// Use BASE_URL from window.ENV
return (window as any).ENV?.BASE_URL || "";
}
return "";
}
}
export function useClientConfig(): ChatConfig {
return {
backend: getBackendOrigin(),
};
}
@@ -1,42 +1,47 @@
# flake8: noqa: E402
from dotenv import load_dotenv
from app.engine.index import get_index
load_dotenv()
import os
import logging
from app.settings import init_settings
from app.engine.loaders import get_documents
from llama_index.indices.managed.llama_cloud import LlamaCloudIndex
from llama_index.core.readers import SimpleDirectoryReader
from app.engine.service import LLamaCloudFileService
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def generate_datasource():
init_settings()
logger.info("Generate index for the provided data")
name = os.getenv("LLAMA_CLOUD_INDEX_NAME")
project_name = os.getenv("LLAMA_CLOUD_PROJECT_NAME")
api_key = os.getenv("LLAMA_CLOUD_API_KEY")
base_url = os.getenv("LLAMA_CLOUD_BASE_URL")
index = get_index()
project_id = index._get_project_id()
pipeline_id = index._get_pipeline_id()
if name is None or project_name is None or api_key is None:
raise ValueError(
"Please set LLAMA_CLOUD_INDEX_NAME, LLAMA_CLOUD_PROJECT_NAME and LLAMA_CLOUD_API_KEY"
" to your environment variables or config them in .env file"
)
documents = get_documents()
LlamaCloudIndex.from_documents(
documents=documents,
name=name,
project_name=project_name,
api_key=api_key,
base_url=base_url,
# use SimpleDirectoryReader to retrieve the files to process
reader = SimpleDirectoryReader(
"data",
recursive=True,
)
files_to_process = reader.input_files
# add each file to the LlamaCloud pipeline
for input_file in files_to_process:
with open(input_file, "rb") as f:
logger.info(
f"Adding file {input_file} to pipeline {index.name} in project {index.project_name}"
)
LLamaCloudFileService.add_file_to_pipeline(
project_id,
pipeline_id,
f,
custom_metadata={
# Set private=false to mark the document as public (required for filtering)
"private": "false",
},
)
logger.info("Finished generating the index")
@@ -1,16 +1,28 @@
import logging
import os
from llama_index.indices.managed.llama_cloud import LlamaCloudIndex
from llama_index.core.ingestion.api_utils import (
get_client as llama_cloud_get_client,
)
logger = logging.getLogger("uvicorn")
def get_index():
name = os.getenv("LLAMA_CLOUD_INDEX_NAME")
project_name = os.getenv("LLAMA_CLOUD_PROJECT_NAME")
def get_client():
return llama_cloud_get_client(
os.getenv("LLAMA_CLOUD_API_KEY"),
os.getenv("LLAMA_CLOUD_BASE_URL"),
)
def get_index(params=None):
configParams = params or {}
pipelineConfig = configParams.get("llamaCloudPipeline", {})
name = pipelineConfig.get("pipeline", os.getenv("LLAMA_CLOUD_INDEX_NAME"))
project_name = pipelineConfig.get("project", os.getenv("LLAMA_CLOUD_PROJECT_NAME"))
api_key = os.getenv("LLAMA_CLOUD_API_KEY")
base_url = os.getenv("LLAMA_CLOUD_BASE_URL")
organization_id = os.getenv("LLAMA_CLOUD_ORGANIZATION_ID")
if name is None or project_name is None or api_key is None:
raise ValueError(
@@ -23,6 +35,7 @@ def get_index():
project_name=project_name,
api_key=api_key,
base_url=base_url,
organization_id=organization_id,
)
return index
@@ -0,0 +1,35 @@
from llama_index.core.vector_stores.types import MetadataFilter, MetadataFilters
def generate_filters(doc_ids):
"""
Generate public/private document filters based on the doc_ids and the vector store.
"""
# Using "nin" filter to include the documents don't have the "private" key because they're uploaded in LlamaCloud UI
public_doc_filter = MetadataFilter(
key="private",
value=["true"],
operator="nin", # type: ignore
)
selected_doc_filter = MetadataFilter(
key="file_id", # Note: LLamaCloud uses "file_id" to reference private document ids as "doc_id" is a restricted field in LlamaCloud
value=doc_ids,
operator="in", # type: ignore
)
if len(doc_ids) > 0:
# If doc_ids are provided, we will select both public and selected documents
filters = MetadataFilters(
filters=[
public_doc_filter,
selected_doc_filter,
],
condition="or", # type: ignore
)
else:
filters = MetadataFilters(
filters=[
public_doc_filter,
]
)
return filters
@@ -0,0 +1,173 @@
from io import BytesIO
import logging
import os
import time
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import typing
from fastapi import BackgroundTasks
from llama_cloud import ManagedIngestionStatus, PipelineFileCreateCustomMetadataValue
from pydantic import BaseModel
import requests
from app.api.routers.models import SourceNodes
from app.engine.index import get_client
from llama_index.core.schema import NodeWithScore
logger = logging.getLogger("uvicorn")
class LlamaCloudFile(BaseModel):
file_name: str
pipeline_id: str
def __eq__(self, other):
if not isinstance(other, LlamaCloudFile):
return NotImplemented
return (
self.file_name == other.file_name and self.pipeline_id == other.pipeline_id
)
def __hash__(self):
return hash((self.file_name, self.pipeline_id))
class LLamaCloudFileService:
LOCAL_STORE_PATH = "output/llamacloud"
DOWNLOAD_FILE_NAME_TPL = "{pipeline_id}${filename}"
@classmethod
def get_all_projects_with_pipelines(cls) -> List[Dict[str, Any]]:
try:
client = get_client()
projects = client.projects.list_projects()
pipelines = client.pipelines.search_pipelines()
return [
{
**(project.dict()),
"pipelines": [
{"id": p.id, "name": p.name}
for p in pipelines
if p.project_id == project.id
],
}
for project in projects
]
except Exception as error:
logger.error(f"Error listing projects and pipelines: {error}")
return []
@classmethod
def add_file_to_pipeline(
cls,
project_id: str,
pipeline_id: str,
upload_file: Union[typing.IO, Tuple[str, BytesIO]],
custom_metadata: Optional[Dict[str, PipelineFileCreateCustomMetadataValue]],
) -> str:
client = get_client()
file = client.files.upload_file(project_id=project_id, upload_file=upload_file)
files = [
{
"file_id": file.id,
"custom_metadata": {"file_id": file.id, **(custom_metadata or {})},
}
]
files = client.pipelines.add_files_to_pipeline(pipeline_id, request=files)
# Wait 2s for the file to be processed
max_attempts = 20
attempt = 0
while attempt < max_attempts:
result = client.pipelines.get_pipeline_file_status(pipeline_id, file.id)
if result.status == ManagedIngestionStatus.ERROR:
raise Exception(f"File processing failed: {str(result)}")
if result.status == ManagedIngestionStatus.SUCCESS:
# File is ingested - return the file id
return file.id
attempt += 1
time.sleep(0.1) # Sleep for 100ms
raise Exception(
f"File processing did not complete after {max_attempts} attempts."
)
@classmethod
def download_pipeline_file(
cls,
file: LlamaCloudFile,
force_download: bool = False,
):
client = get_client()
file_name = file.file_name
pipeline_id = file.pipeline_id
# Check is the file already exists
downloaded_file_path = cls._get_file_path(file_name, pipeline_id)
if os.path.exists(downloaded_file_path) and not force_download:
logger.debug(f"File {file_name} already exists in local storage")
return
try:
logger.info(f"Downloading file {file_name} for pipeline {pipeline_id}")
files = client.pipelines.list_pipeline_files(pipeline_id)
if not files or not isinstance(files, list):
raise Exception("No files found in LlamaCloud")
for file_entry in files:
if file_entry.name == file_name:
file_id = file_entry.file_id
project_id = file_entry.project_id
file_detail = client.files.read_file_content(
file_id, project_id=project_id
)
cls._download_file(file_detail.url, downloaded_file_path)
break
except Exception as error:
logger.info(f"Error fetching file from LlamaCloud: {error}")
@classmethod
def download_files_from_nodes(
cls, nodes: List[NodeWithScore], background_tasks: BackgroundTasks
):
files = cls._get_files_to_download(nodes)
for file in files:
logger.info(f"Adding download of {file.file_name} to background tasks")
background_tasks.add_task(
LLamaCloudFileService.download_pipeline_file, file
)
@classmethod
def _get_files_to_download(cls, nodes: List[NodeWithScore]) -> Set[LlamaCloudFile]:
source_nodes = SourceNodes.from_source_nodes(nodes)
llama_cloud_files = [
LlamaCloudFile(
file_name=node.metadata.get("file_name"),
pipeline_id=node.metadata.get("pipeline_id"),
)
for node in source_nodes
if (
node.metadata.get("pipeline_id") is not None
and node.metadata.get("file_name") is not None
)
]
# Remove duplicates and return
return set(llama_cloud_files)
@classmethod
def _get_file_name(cls, name: str, pipeline_id: str) -> str:
return cls.DOWNLOAD_FILE_NAME_TPL.format(pipeline_id=pipeline_id, filename=name)
@classmethod
def _get_file_path(cls, name: str, pipeline_id: str) -> str:
return os.path.join(cls.LOCAL_STORE_PATH, cls._get_file_name(name, pipeline_id))
@classmethod
def _download_file(cls, url: str, local_file_path: str):
logger.info(f"Saving file to {local_file_path}")
# Create directory if it doesn't exist
os.makedirs(cls.LOCAL_STORE_PATH, exist_ok=True)
# Download the file
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_file_path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
logger.info("File downloaded successfully")
@@ -1,15 +1,16 @@
# flake8: noqa: E402
from dotenv import load_dotenv
load_dotenv()
import os
import logging
import os
from app.engine.loaders import get_documents
from app.settings import init_settings
from llama_index.core.indices import (
VectorStoreIndex,
)
from app.engine.loaders import get_documents
from app.settings import init_settings
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
@@ -21,6 +22,9 @@ def generate_datasource():
storage_dir = os.environ.get("STORAGE_DIR", "storage")
# load the documents and create the index
documents = get_documents()
# Set private=false to mark the document as public (required for filtering)
for doc in documents:
doc.metadata["private"] = "false"
index = VectorStoreIndex.from_documents(
documents,
)
@@ -17,7 +17,7 @@ def get_storage_context(persist_dir: str) -> StorageContext:
return StorageContext.from_defaults(persist_dir=persist_dir)
def get_index():
def get_index(params=None):
storage_dir = os.getenv("STORAGE_DIR", "storage")
# check if storage already exists
if not os.path.exists(storage_dir):
@@ -0,0 +1,36 @@
from llama_index.core.vector_stores.types import MetadataFilter, MetadataFilters
def generate_filters(doc_ids):
"""
Generate public/private document filters based on the doc_ids and the vector store.
"""
public_doc_filter = MetadataFilter(
key="private",
value="true",
operator="!=", # type: ignore
)
# Weaviate doesn't support "in" filter right now, so use "any" instead - it has the same behavior.
# TODO: Use "in" operator, once Weaviate supports it
selected_doc_filter = MetadataFilter(
key="doc_id",
value=doc_ids,
operator="any", # type: ignore
)
if len(doc_ids) > 0:
# If doc_ids are provided, we will select both public and selected documents
filters = MetadataFilters(
filters=[
public_doc_filter,
selected_doc_filter,
],
condition="or", # type: ignore
)
else:
filters = MetadataFilters(
filters=[
public_doc_filter,
]
)
return filters
@@ -0,0 +1,35 @@
import os
import weaviate
from llama_index.vector_stores.weaviate import WeaviateVectorStore
DEFAULT_INDEX_NAME = "LlamaIndex"
def _create_weaviate_client():
cluster_url = os.getenv("WEAVIATE_CLUSTER_URL")
api_key = os.getenv("WEAVIATE_API_KEY")
if not cluster_url or not api_key:
raise ValueError(
"Environment variables: WEAVIATE_CLUSTER_URL and WEAVIATE_API_KEY are required."
)
auth_credentials = weaviate.auth.AuthApiKey(api_key)
client = weaviate.connect_to_weaviate_cloud(cluster_url, auth_credentials)
return client
# Global variable to store the Weaviate client
client = None
def get_vector_store():
global client
if client is None:
client = _create_weaviate_client()
index_name = os.getenv("WEAVIATE_INDEX_NAME", DEFAULT_INDEX_NAME)
vector_store = WeaviateVectorStore(
weaviate_client=client,
index_name=index_name,
)
return vector_store
@@ -3,7 +3,7 @@ import { VectorStoreIndex } from "llamaindex";
import { AstraDBVectorStore } from "llamaindex/storage/vectorStore/AstraDBVectorStore";
import { checkRequiredEnvVars } from "./shared";
export async function getDataSource() {
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const store = new AstraDBVectorStore();
await store.connect(process.env.ASTRA_DB_COLLECTION!);
@@ -3,7 +3,7 @@ import { VectorStoreIndex } from "llamaindex";
import { ChromaVectorStore } from "llamaindex/storage/vectorStore/ChromaVectorStore";
import { checkRequiredEnvVars } from "./shared";
export async function getDataSource() {
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const chromaUri = `http://${process.env.CHROMA_HOST}:${process.env.CHROMA_PORT}`;
@@ -1,5 +1,6 @@
import * as dotenv from "dotenv";
import { LlamaCloudIndex } from "llamaindex";
import { getDataSource } from "./index";
import { getDocuments } from "./loader";
import { initSettings } from "./settings";
import { checkRequiredEnvVars } from "./shared";
@@ -8,6 +9,8 @@ dotenv.config();
async function loadAndIndex() {
const documents = await getDocuments();
await getDataSource();
await LlamaCloudIndex.fromDocuments({
documents,
name: process.env.LLAMA_CLOUD_INDEX_NAME!,
@@ -1,12 +1,26 @@
import { LlamaCloudIndex } from "llamaindex/cloud/LlamaCloudIndex";
import { checkRequiredEnvVars } from "./shared";
export async function getDataSource() {
checkRequiredEnvVars();
type LlamaCloudDataSourceParams = {
llamaCloudPipeline?: {
project: string;
pipeline: string;
};
};
export async function getDataSource(params?: LlamaCloudDataSourceParams) {
const { project, pipeline } = params?.llamaCloudPipeline ?? {};
const projectName = project ?? process.env.LLAMA_CLOUD_PROJECT_NAME;
const pipelineName = pipeline ?? process.env.LLAMA_CLOUD_INDEX_NAME;
const apiKey = process.env.LLAMA_CLOUD_API_KEY;
if (!projectName || !pipelineName || !apiKey) {
throw new Error(
"Set project, pipeline, and api key in the params or as environment variables.",
);
}
const index = new LlamaCloudIndex({
name: process.env.LLAMA_CLOUD_INDEX_NAME!,
projectName: process.env.LLAMA_CLOUD_PROJECT_NAME!,
apiKey: process.env.LLAMA_CLOUD_API_KEY,
name: pipelineName,
projectName,
apiKey,
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
});
return index;
@@ -0,0 +1,25 @@
import { MetadataFilter, MetadataFilters } from "llamaindex";
export function generateFilters(documentIds: string[]): MetadataFilters {
// public documents don't have the "private" field or it's set to "false"
const publicDocumentsFilter: MetadataFilter = {
key: "private",
value: ["true"],
operator: "nin",
};
// if no documentIds are provided, only retrieve information from public documents
if (!documentIds.length) return { filters: [publicDocumentsFilter] };
const privateDocumentsFilter: MetadataFilter = {
key: "doc_id",
value: documentIds,
operator: "in",
};
// if documentIds are provided, retrieve information from public and private documents
return {
filters: [publicDocumentsFilter, privateDocumentsFilter],
condition: "or",
};
}
@@ -2,7 +2,7 @@ import { VectorStoreIndex } from "llamaindex";
import { MilvusVectorStore } from "llamaindex/storage/vectorStore/MilvusVectorStore";
import { checkRequiredEnvVars, getMilvusClient } from "./shared";
export async function getDataSource() {
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const milvusClient = getMilvusClient();
const store = new MilvusVectorStore({ milvusClient });
@@ -4,7 +4,6 @@ const REQUIRED_ENV_VARS = [
"MILVUS_ADDRESS",
"MILVUS_USERNAME",
"MILVUS_PASSWORD",
"MILVUS_COLLECTION",
];
export function getMilvusClient() {
@@ -19,8 +18,13 @@ export function getMilvusClient() {
});
}
export function checkRequiredEnvVars() {
const missingEnvVars = REQUIRED_ENV_VARS.filter((envVar) => {
export function checkRequiredEnvVars(opts?: { checkCollectionEnv?: boolean }) {
const shouldCheckCollectionEnv = opts?.checkCollectionEnv ?? true; // default to true
const requiredEnvVars = [...REQUIRED_ENV_VARS]; // create a copy of the array
if (shouldCheckCollectionEnv) {
requiredEnvVars.push("MILVUS_COLLECTION");
}
const missingEnvVars = requiredEnvVars.filter((envVar) => {
return !process.env[envVar];
});
@@ -1,7 +1,10 @@
/* eslint-disable turbo/no-undeclared-env-vars */
import * as dotenv from "dotenv";
import { VectorStoreIndex, storageContextFromDefaults } from "llamaindex";
import { MongoDBAtlasVectorSearch } from "llamaindex/storage/vectorStore/MongoDBAtlasVectorSearch";
import {
MongoDBAtlasVectorSearch,
VectorStoreIndex,
storageContextFromDefaults,
} from "llamaindex";
import { MongoClient } from "mongodb";
import { getDocuments } from "./loader";
import { initSettings } from "./settings";
@@ -1,10 +1,9 @@
/* eslint-disable turbo/no-undeclared-env-vars */
import { VectorStoreIndex } from "llamaindex";
import { MongoDBAtlasVectorSearch } from "llamaindex/storage/vectorStore/MongoDBAtlasVectorSearch";
import { MongoDBAtlasVectorSearch, VectorStoreIndex } from "llamaindex";
import { MongoClient } from "mongodb";
import { checkRequiredEnvVars } from "./shared";
export async function getDataSource() {
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const client = new MongoClient(process.env.MONGO_URI!);
const store = new MongoDBAtlasVectorSearch({
@@ -25,6 +25,7 @@ async function generateDatasource() {
persistDir: STORAGE_CACHE_DIR,
});
const documents = await getDocuments();
await VectorStoreIndex.fromDocuments(documents, {
storageContext,
});
@@ -2,7 +2,7 @@ import { SimpleDocumentStore, VectorStoreIndex } from "llamaindex";
import { storageContextFromDefaults } from "llamaindex/storage/StorageContext";
import { STORAGE_CACHE_DIR } from "./shared";
export async function getDataSource() {
export async function getDataSource(params?: any) {
const storageContext = await storageContextFromDefaults({
persistDir: `${STORAGE_CACHE_DIR}`,
});
@@ -7,7 +7,7 @@ import {
checkRequiredEnvVars,
} from "./shared";
export async function getDataSource() {
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const pgvs = new PGVectorStore({
connectionString: process.env.PG_CONNECTION_STRING,
@@ -3,7 +3,7 @@ import { VectorStoreIndex } from "llamaindex";
import { PineconeVectorStore } from "llamaindex/storage/vectorStore/PineconeVectorStore";
import { checkRequiredEnvVars } from "./shared";
export async function getDataSource() {
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const store = new PineconeVectorStore();
return await VectorStoreIndex.fromVectorStore(store);
@@ -5,7 +5,7 @@ import { checkRequiredEnvVars, getQdrantClient } from "./shared";
dotenv.config();
export async function getDataSource() {
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const collectionName = process.env.QDRANT_COLLECTION;
const store = new QdrantVectorStore({
@@ -0,0 +1,33 @@
/* eslint-disable turbo/no-undeclared-env-vars */
import * as dotenv from "dotenv";
import {
VectorStoreIndex,
WeaviateVectorStore,
storageContextFromDefaults,
} from "llamaindex";
import { getDocuments } from "./loader";
import { initSettings } from "./settings";
import { DEFAULT_INDEX_NAME, checkRequiredEnvVars } from "./shared";
dotenv.config();
async function loadAndIndex() {
const indexName = process.env.WEAVIATE_INDEX_NAME || DEFAULT_INDEX_NAME;
// load objects from storage and convert them into LlamaIndex Document objects
const documents = await getDocuments();
const vectorStore = new WeaviateVectorStore({ indexName });
const storageContext = await storageContextFromDefaults({ vectorStore });
await VectorStoreIndex.fromDocuments(documents, {
storageContext: storageContext,
});
console.log(`Successfully upload embeddings to Weaviate index ${indexName}.`);
}
(async () => {
checkRequiredEnvVars();
initSettings();
await loadAndIndex();
console.log("Finished generating storage.");
})();
@@ -0,0 +1,14 @@
import * as dotenv from "dotenv";
import { VectorStoreIndex } from "llamaindex";
import { WeaviateVectorStore } from "llamaindex/storage/vectorStore/WeaviateVectorStore";
import { checkRequiredEnvVars, DEFAULT_INDEX_NAME } from "./shared";
dotenv.config();
export async function getDataSource(params?: any) {
checkRequiredEnvVars();
const indexName = process.env.WEAVIATE_INDEX_NAME || DEFAULT_INDEX_NAME;
const store = new WeaviateVectorStore({ indexName });
return await VectorStoreIndex.fromVectorStore(store);
}
@@ -0,0 +1,26 @@
import { MetadataFilter, MetadataFilters } from "llamaindex";
export function generateFilters(documentIds: string[]): MetadataFilters {
// filter all documents have the private metadata key set to true
const publicDocumentsFilter: MetadataFilter = {
key: "private",
value: "true",
operator: "!=",
};
// if no documentIds are provided, only retrieve information from public documents
if (!documentIds.length) return { filters: [publicDocumentsFilter] };
// Weaviate uses 'any' instead of 'in' for the operator
const privateDocumentsFilter: MetadataFilter = {
key: "doc_id",
value: documentIds,
operator: "any",
};
// if documentIds are provided, retrieve information from public and private documents
return {
filters: [publicDocumentsFilter, privateDocumentsFilter],
condition: "or",
};
}
@@ -0,0 +1,20 @@
const REQUIRED_ENV_VARS = ["WEAVIATE_CLUSTER_URL", "WEAVIATE_API_KEY"];
export const DEFAULT_INDEX_NAME = "LlamaIndex";
export function checkRequiredEnvVars() {
const missingEnvVars = REQUIRED_ENV_VARS.filter((envVar) => {
return !process.env[envVar];
});
if (missingEnvVars.length > 0) {
console.log(
`The following environment variables are required but missing: ${missingEnvVars.join(
", ",
)}`,
);
throw new Error(
`Missing environment variables: ${missingEnvVars.join(", ")}`,
);
}
}
@@ -0,0 +1,68 @@
This is a [LlamaIndex](https://www.llamaindex.ai/) project using [FastAPI](https://fastapi.tiangolo.com/) bootstrapped with [`create-llama`](https://github.com/run-llama/LlamaIndexTS/tree/main/packages/create-llama) featuring [structured extraction](https://docs.llamaindex.ai/en/stable/examples/structured_outputs/structured_outputs/?h=structured+output).
## Getting Started
First, setup the environment with poetry:
> **_Note:_** This step is not needed if you are using the dev-container.
```shell
poetry install
poetry shell
```
Then check the parameters that have been pre-configured in the `.env` file in this directory. (E.g. you might need to configure an `OPENAI_API_KEY` if you're using OpenAI as model provider).
Second, generate the embeddings of the documents in the `./data` directory (if this folder exists - otherwise, skip this step):
```shell
poetry run generate
```
Third, run the API in one command:
```shell
poetry run python main.py
```
The example provides the `/api/extractor/query` API endpoint.
This query endpoint returns structured data in the format of the [Output](./app/api/routers/output.py) class. Modify this class to change the output format.
You can test the endpoint with the following curl request:
```shell
curl --location 'localhost:8000/api/extractor/query' \
--header 'Content-Type: application/json' \
--data '{ "query": "What is the maximum weight for a parcel?" }'
```
Which will return a response that the RAG pipeline is confident about the answer.
Try
```shell
curl --location 'localhost:8000/api/extractor/query' \
--header 'Content-Type: application/json' \
--data '{ "query": "What is the weather today?" }'
```
To retrieve a response with low confidence since the question is not related to the provided document in the `./data` directory.
You can start editing the API endpoint by modifying [`extractor.py`](./app/api/routers/extractor.py). The endpoints auto-update as you save the file.
Open [http://localhost:8000/docs](http://localhost:8000/docs) with your browser to see the Swagger UI of the API.
The API allows CORS for all origins to simplify development. You can change this behavior by setting the `ENVIRONMENT` environment variable to `prod`:
```
ENVIRONMENT=prod python main.py
```
## Learn More
To learn more about LlamaIndex, take a look at the following resources:
- [LlamaIndex Documentation](https://docs.llamaindex.ai) - learn about LlamaIndex.
You can check out [the LlamaIndex GitHub repository](https://github.com/run-llama/llama_index) - your feedback and contributions are welcome!
@@ -0,0 +1,58 @@
import logging
import os
from fastapi import APIRouter, HTTPException
from llama_index.core.settings import Settings
from pydantic import BaseModel
from app.api.routers.output import Output
from app.engine.index import get_index
extractor_router = r = APIRouter()
logger = logging.getLogger("uvicorn")
class RequestData(BaseModel):
query: str
class Config:
json_schema_extra = {
"examples": [
{"query": "What's the maximum weight for a parcel?"},
],
}
@r.post("/query")
async def query_request(
data: RequestData,
):
# Create a query engine using that returns responses in the format of the Output class
query_engine = get_query_engine(Output)
response = await query_engine.aquery(data.query)
output_data = response.response.dict()
return Output(**output_data)
def get_query_engine(output_cls: BaseModel):
top_k = os.getenv("TOP_K", 3)
index = get_index()
if index is None:
raise HTTPException(
status_code=500,
detail=str(
"StorageContext is empty - call 'poetry run generate' to generate the storage first"
),
)
sllm = Settings.llm.as_structured_llm(output_cls)
return index.as_query_engine(
similarity_top_k=int(top_k),
llm=sllm,
response_mode="tree_summarize",
)
@@ -0,0 +1,32 @@
import logging
from llama_index.core.schema import BaseModel, Field
from typing import List
logger = logging.getLogger("uvicorn")
class Output(BaseModel):
response: str = Field(..., description="The answer to the question.")
page_numbers: List[int] = Field(
...,
description="The page numbers of the sources used to answer this question. Do not include a page number if the context is irrelevant.",
)
confidence: float = Field(
...,
ge=0,
le=1,
description="Confidence value between 0-1 of the correctness of the result.",
)
confidence_explanation: str = Field(
..., description="Explanation for the confidence score"
)
class Config:
json_schema_extra = {
"example": {
"response": "This is an example answer.",
"page_numbers": [1, 2, 3],
"confidence": 0.85,
"confidence_explanation": "This is an explanation for the confidence score.",
}
}
+46
View File
@@ -0,0 +1,46 @@
# flake8: noqa: E402
from dotenv import load_dotenv
load_dotenv()
import logging
import os
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from app.api.routers.extractor import extractor_router
from app.settings import init_settings
app = FastAPI()
init_settings()
environment = os.getenv("ENVIRONMENT", "dev") # Default to 'development' if not set
logger = logging.getLogger("uvicorn")
if environment == "dev":
logger.warning("Running in development mode - allowing CORS for all origins")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Redirect to documentation page when accessing base URL
@app.get("/")
async def redirect_to_docs():
return RedirectResponse(url="/docs")
app.include_router(extractor_router, prefix="/api/extractor")
if __name__ == "__main__":
app_host = os.getenv("APP_HOST", "0.0.0.0")
app_port = int(os.getenv("APP_PORT", "8000"))
reload = True if environment == "dev" else False
uvicorn.run(app="main:app", host=app_host, port=app_port, reload=reload)
@@ -0,0 +1,21 @@
[tool.poetry]
name = "app"
version = "0.1.0"
description = ""
authors = ["Marcus Schiesser <mail@marcusschiesser.de>"]
readme = "README.md"
[tool.poetry.scripts]
generate = "app.engine.generate:generate_datasource"
[tool.poetry.dependencies]
python = "^3.11,<4.0"
fastapi = "^0.109.1"
uvicorn = { extras = ["standard"], version = "^0.23.2" }
python-dotenv = "^1.0.0"
llama-index = "^0.10.58"
cachetools = "^5.3.3"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
@@ -5,4 +5,4 @@ def load_from_env(var: str, throw_error: bool = True) -> str:
res = os.getenv(var)
if res is None and throw_error:
raise ValueError(f"Missing environment variable: {var}")
return res
return res
@@ -1,3 +1,4 @@
# flake8: noqa: E402
from dotenv import load_dotenv
from app.settings import init_settings
+1 -1
View File
@@ -2,4 +2,4 @@
.env
node_modules/
tool-output/
output/
+2 -2
View File
@@ -14,7 +14,7 @@ const prodCorsOrigin = process.env["PROD_CORS_ORIGIN"];
initObservability();
app.use(express.json());
app.use(express.json({ limit: "50mb" }));
if (isDevelopment) {
console.warn("Running in development mode - allowing CORS for all origins");
@@ -32,7 +32,7 @@ if (isDevelopment) {
}
app.use("/api/files/data", express.static("data"));
app.use("/api/files/tool-output", express.static("tool-output"));
app.use("/api/files/output", express.static("output"));
app.use(express.text());
app.get("/", (req: Request, res: Response) => {
@@ -20,7 +20,7 @@
"dotenv": "^16.3.1",
"duck-duck-scrape": "^2.2.5",
"express": "^4.18.2",
"llamaindex": "0.4.6",
"llamaindex": "0.5.17",
"pdf2json": "3.0.5",
"ajv": "^8.12.0",
"@e2b/code-interpreter": "^0.0.5",
@@ -39,7 +39,7 @@
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^3.2.4",
"tsx": "^4.7.2",
"tsup": "^8.0.1",
"tsup": "8.1.0",
"typescript": "^5.3.2"
}
}
@@ -1,4 +1,5 @@
import { Request, Response } from "express";
import { LLamaCloudFileService } from "./llamaindex/streaming/service";
export const chatConfig = async (_req: Request, res: Response) => {
let starterQuestions = undefined;
@@ -12,3 +13,14 @@ export const chatConfig = async (_req: Request, res: Response) => {
starterQuestions,
});
};
export const chatLlamaCloudConfig = async (_req: Request, res: Response) => {
const config = {
projects: await LLamaCloudFileService.getAllProjectsWithPipelines(),
pipeline: {
pipeline: process.env.LLAMA_CLOUD_INDEX_NAME,
project: process.env.LLAMA_CLOUD_PROJECT_NAME,
},
};
return res.status(200).json(config);
};
@@ -0,0 +1,14 @@
import { Request, Response } from "express";
import { getDataSource } from "./engine";
import { uploadDocument } from "./llamaindex/documents/upload";
export const chatUpload = async (req: Request, res: Response) => {
const { base64, params }: { base64: string; params?: any } = req.body;
if (!base64) {
return res.status(400).json({
error: "base64 is required in the request body",
});
}
const index = await getDataSource(params);
return res.status(200).json(await uploadDocument(index, base64));
};
@@ -1,16 +1,23 @@
import { Message, StreamData, streamToResponse } from "ai";
import { JSONValue, Message, StreamData, streamToResponse } from "ai";
import { Request, Response } from "express";
import { ChatMessage, Settings } from "llamaindex";
import { createChatEngine } from "./engine/chat";
import { LlamaIndexStream, convertMessageContent } from "./llamaindex-stream";
import { createCallbackManager, createStreamTimeout } from "./stream-helper";
import {
convertMessageContent,
retrieveDocumentIds,
} from "./llamaindex/streaming/annotations";
import {
createCallbackManager,
createStreamTimeout,
} from "./llamaindex/streaming/events";
import { LlamaIndexStream } from "./llamaindex/streaming/stream";
export const chat = async (req: Request, res: Response) => {
// Init Vercel AI StreamData and timeout
const vercelStreamData = new StreamData();
const streamTimeout = createStreamTimeout(vercelStreamData);
try {
const { messages }: { messages: Message[] } = req.body;
const { messages, data }: { messages: Message[]; data?: any } = req.body;
const userMessage = messages.pop();
if (!messages || !userMessage || userMessage.role !== "user") {
return res.status(400).json({
@@ -19,8 +26,6 @@ export const chat = async (req: Request, res: Response) => {
});
}
const chatEngine = await createChatEngine();
let annotations = userMessage.annotations;
if (!annotations) {
// the user didn't send any new annotations with the last message
@@ -34,6 +39,15 @@ export const chat = async (req: Request, res: Response) => {
)?.annotations;
}
// retrieve document Ids from the annotations of all messages (if any) and create chat engine with index
const allAnnotations: JSONValue[] = [...messages, userMessage].flatMap(
(message) => {
return message.annotations ?? [];
},
);
const ids = retrieveDocumentIds(allAnnotations);
const chatEngine = await createChatEngine(ids, data);
// Convert message content from Vercel/AI format to LlamaIndex/OpenAI format
const userMessageContent = convertMessageContent(
userMessage.content,
@@ -53,7 +67,11 @@ export const chat = async (req: Request, res: Response) => {
});
// Return a stream, which can be consumed by the Vercel/AI client
const stream = LlamaIndexStream(response, vercelStreamData);
const stream = LlamaIndexStream(
response,
vercelStreamData,
messages as ChatMessage[],
);
return streamToResponse(stream, res, {}, vercelStreamData);
} catch (error) {
@@ -1,6 +1,6 @@
import { Settings, SimpleChatEngine } from "llamaindex";
export async function createChatEngine() {
export async function createChatEngine(documentIds?: string[]) {
return new SimpleChatEngine({
llm: Settings.llm,
});
@@ -0,0 +1,25 @@
import { MetadataFilter, MetadataFilters } from "llamaindex";
export function generateFilters(documentIds: string[]): MetadataFilters {
// filter all documents have the private metadata key set to true
const publicDocumentsFilter: MetadataFilter = {
key: "private",
value: "true",
operator: "!=",
};
// if no documentIds are provided, only retrieve information from public documents
if (!documentIds.length) return { filters: [publicDocumentsFilter] };
const privateDocumentsFilter: MetadataFilter = {
key: "doc_id",
value: documentIds,
operator: "in",
};
// if documentIds are provided, retrieve information from public and private documents
return {
filters: [publicDocumentsFilter, privateDocumentsFilter],
condition: "or",
};
}
@@ -45,6 +45,9 @@ export const initSettings = async () => {
case "mistral":
initMistralAI();
break;
case "azure-openai":
initAzureOpenAI();
break;
default:
initOpenAI();
break;
@@ -55,7 +58,7 @@ export const initSettings = async () => {
function initOpenAI() {
Settings.llm = new OpenAI({
model: process.env.MODEL ?? "gpt-3.5-turbo",
model: process.env.MODEL ?? "gpt-4o-mini",
maxTokens: process.env.LLM_MAX_TOKENS
? Number(process.env.LLM_MAX_TOKENS)
: undefined,
@@ -68,6 +71,53 @@ function initOpenAI() {
});
}
function initAzureOpenAI() {
// Map Azure OpenAI model names to OpenAI model names (only for TS)
const AZURE_OPENAI_MODEL_MAP: Record<string, string> = {
"gpt-35-turbo": "gpt-3.5-turbo",
"gpt-35-turbo-16k": "gpt-3.5-turbo-16k",
"gpt-4o": "gpt-4o",
"gpt-4": "gpt-4",
"gpt-4-32k": "gpt-4-32k",
"gpt-4-turbo": "gpt-4-turbo",
"gpt-4-turbo-2024-04-09": "gpt-4-turbo",
"gpt-4-vision-preview": "gpt-4-vision-preview",
"gpt-4-1106-preview": "gpt-4-1106-preview",
"gpt-4o-2024-05-13": "gpt-4o-2024-05-13",
};
const azureConfig = {
apiKey: process.env.AZURE_OPENAI_KEY,
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
apiVersion:
process.env.AZURE_OPENAI_API_VERSION || process.env.OPENAI_API_VERSION,
};
Settings.llm = new OpenAI({
model:
AZURE_OPENAI_MODEL_MAP[process.env.MODEL ?? "gpt-35-turbo"] ??
"gpt-3.5-turbo",
maxTokens: process.env.LLM_MAX_TOKENS
? Number(process.env.LLM_MAX_TOKENS)
: undefined,
azure: {
...azureConfig,
deployment: process.env.AZURE_OPENAI_LLM_DEPLOYMENT,
},
});
Settings.embedModel = new OpenAIEmbedding({
model: process.env.EMBEDDING_MODEL,
dimensions: process.env.EMBEDDING_DIM
? parseInt(process.env.EMBEDDING_DIM)
: undefined,
azure: {
...azureConfig,
deployment: process.env.AZURE_OPENAI_EMBEDDING_DEPLOYMENT,
},
});
}
function initOllama() {
const config = {
host: process.env.OLLAMA_BASE_URL ?? "http://127.0.0.1:11434",
@@ -1,111 +0,0 @@
import {
JSONValue,
StreamData,
createCallbacksTransformer,
createStreamDataTransformer,
trimStartOfStreamHelper,
type AIStreamCallbacksAndOptions,
} from "ai";
import {
EngineResponse,
MessageContent,
MessageContentDetail,
} from "llamaindex";
import { CsvFile } from "./stream-helper";
export const convertMessageContent = (
content: string,
annotations?: JSONValue[],
): MessageContent => {
if (!annotations) return content;
return [
{
type: "text",
text: content,
},
...convertAnnotations(annotations),
];
};
const convertAnnotations = (
annotations: JSONValue[],
): MessageContentDetail[] => {
const content: MessageContentDetail[] = [];
annotations.forEach((annotation: JSONValue) => {
// first skip invalid annotation
if (
!(
annotation &&
typeof annotation === "object" &&
"type" in annotation &&
"data" in annotation &&
annotation.data &&
typeof annotation.data === "object"
)
) {
console.log(
"Client sent invalid annotation. Missing data and type",
annotation,
);
return;
}
const { type, data } = annotation;
// convert image
if (type === "image" && "url" in data && typeof data.url === "string") {
content.push({
type: "image_url",
image_url: {
url: data.url,
},
});
}
// convert CSV files to text
if (type === "csv" && "csvFiles" in data && Array.isArray(data.csvFiles)) {
const rawContents = data.csvFiles.map((csv) => {
return "```csv\n" + (csv as CsvFile).content + "\n```";
});
const csvContent =
"Use data from following CSV raw contents:\n" +
rawContents.join("\n\n");
content.push({
type: "text",
text: csvContent,
});
}
});
return content;
};
function createParser(res: AsyncIterable<EngineResponse>, data: StreamData) {
const it = res[Symbol.asyncIterator]();
const trimStartOfStream = trimStartOfStreamHelper();
return new ReadableStream<string>({
async pull(controller): Promise<void> {
const { value, done } = await it.next();
if (done) {
controller.close();
data.close();
return;
}
const text = trimStartOfStream(value.delta ?? "");
if (text) {
controller.enqueue(text);
}
},
});
}
export function LlamaIndexStream(
response: AsyncIterable<EngineResponse>,
data: StreamData,
opts?: {
callbacks?: AIStreamCallbacksAndOptions;
},
): ReadableStream<Uint8Array> {
return createParser(response, data)
.pipeThrough(createCallbacksTransformer(opts?.callbacks))
.pipeThrough(createStreamDataTransformer());
}
@@ -1,6 +1,10 @@
import express, { Router } from "express";
import { chatConfig } from "../controllers/chat-config.controller";
import {
chatConfig,
chatLlamaCloudConfig,
} from "../controllers/chat-config.controller";
import { chatRequest } from "../controllers/chat-request.controller";
import { chatUpload } from "../controllers/chat-upload.controller";
import { chat } from "../controllers/chat.controller";
import { initSettings } from "../controllers/engine/settings";
@@ -10,5 +14,7 @@ initSettings();
llmRouter.route("/").post(chat);
llmRouter.route("/request").post(chatRequest);
llmRouter.route("/config").get(chatConfig);
llmRouter.route("/config/llamacloud").get(chatLlamaCloudConfig);
llmRouter.route("/upload").post(chatUpload);
export default llmRouter;
@@ -5,7 +5,7 @@
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"moduleResolution": "node",
"moduleResolution": "bundler",
"paths": {
"@/*": ["./*"]
}
@@ -1,20 +1,20 @@
import os
import logging
from typing import List
from aiostream import stream
from fastapi import APIRouter, Depends, HTTPException, Request, status
from llama_index.core.chat_engine.types import BaseChatEngine
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request, status
from llama_index.core.chat_engine.types import BaseChatEngine, NodeWithScore
from llama_index.core.llms import MessageRole
from app.engine import get_chat_engine
from app.api.routers.vercel_response import VercelStreamResponse
from app.api.routers.events import EventCallbackHandler
from app.api.routers.models import (
ChatData,
ChatConfig,
SourceNodes,
Result,
Message,
Result,
SourceNodes,
)
from app.api.routers.vercel_response import VercelStreamResponse
from app.engine import get_chat_engine
from app.engine.query_filter import generate_filters
chat_router = r = APIRouter()
@@ -26,61 +26,27 @@ logger = logging.getLogger("uvicorn")
async def chat(
request: Request,
data: ChatData,
chat_engine: BaseChatEngine = Depends(get_chat_engine),
background_tasks: BackgroundTasks,
):
try:
last_message_content = data.get_last_message_content()
messages = data.get_history_messages()
doc_ids = data.get_chat_document_ids()
filters = generate_filters(doc_ids)
params = data.data or {}
logger.info(
f"Creating chat engine with filters: {str(filters)}",
)
chat_engine = get_chat_engine(filters=filters, params=params)
event_handler = EventCallbackHandler()
chat_engine.callback_manager.handlers.append(event_handler) # type: ignore
async def content_generator():
# Yield the text response
async def _chat_response_generator():
response = await chat_engine.astream_chat(
last_message_content, messages
)
async for token in response.async_response_gen():
yield VercelStreamResponse.convert_text(token)
# the text_generator is the leading stream, once it's finished, also finish the event stream
event_handler.is_done = True
response = await chat_engine.astream_chat(last_message_content, messages)
process_response_nodes(response.source_nodes, background_tasks)
# Yield the source nodes
yield VercelStreamResponse.convert_data(
{
"type": "sources",
"data": {
"nodes": [
SourceNodes.from_source_node(node).dict()
for node in response.source_nodes
]
},
}
)
# Yield the events from the event handler
async def _event_generator():
async for event in event_handler.async_event_gen():
event_response = event.to_response()
if event_response is not None:
yield VercelStreamResponse.convert_data(event_response)
combine = stream.merge(_chat_response_generator(), _event_generator())
is_stream_started = False
async with combine.stream() as streamer:
async for output in streamer:
if not is_stream_started:
is_stream_started = True
# Stream a blank message to start the stream
yield VercelStreamResponse.convert_text("")
yield output
if await request.is_disconnected():
break
return VercelStreamResponse(content=content_generator())
return VercelStreamResponse(request, event_handler, response, data)
except Exception as e:
logger.exception("Error in chat engine", exc_info=True)
raise HTTPException(
@@ -105,10 +71,15 @@ async def chat_request(
)
@r.get("/config")
async def chat_config() -> ChatConfig:
starter_questions = None
conversation_starters = os.getenv("CONVERSATION_STARTERS")
if conversation_starters and conversation_starters.strip():
starter_questions = conversation_starters.strip().split("\n")
return ChatConfig(starterQuestions=starter_questions)
def process_response_nodes(
nodes: List[NodeWithScore],
background_tasks: BackgroundTasks,
):
try:
# Start background tasks to download documents from LlamaCloud if needed
from app.engine.service import LLamaCloudFileService
LLamaCloudFileService.download_files_from_nodes(nodes, background_tasks)
except ImportError:
logger.debug("LlamaCloud is not configured. Skipping post processing of nodes")
pass

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