Compare commits

..

15 Commits

Author SHA1 Message Date
Emanuel Ferreira abf3482781 docs(changeset): feat: add base evaluator and correctness evaluator 2024-02-26 09:35:50 -03:00
Emanuel Ferreira dfbe39c9ed chore: switch to eval template 2024-02-26 09:31:10 -03:00
Emanuel Ferreira 23514ac86e chore: keep response evaluators 2024-02-26 09:29:40 -03:00
Emanuel Ferreira 87ff0b17ba docs: add documentation 2024-02-26 08:53:38 -03:00
Emanuel Ferreira 2af0daf3cf fix: relevancy imports 2024-02-26 07:50:14 -03:00
Emanuel Ferreira e9dd2d47bb feat: faithfulness and correctness module migraiton 2024-02-26 07:46:38 -03:00
Emanuel Ferreira a16c11b731 import fix 2024-02-26 07:28:01 -03:00
Emanuel Ferreira 896fc1f9b9 const over let 2024-02-26 07:27:13 -03:00
Emanuel Ferreira f8123f3667 feat: add relevancy evaluator 2024-02-23 14:46:55 -03:00
Emanuel Ferreira 5b2a7894ca feat: relevancy evaluator 2024-02-23 11:00:57 -03:00
Emanuel Ferreira c68668f8ec chore: let to const 2024-02-23 09:11:02 -03:00
Emanuel Ferreira 6977673a37 refactor: move to params object 2024-02-23 09:08:06 -03:00
Emanuel Ferreira 4aef7c689a docs(changeset): feat: add base evaluator and correctness evaluator 2024-02-22 10:10:59 -03:00
Emanuel Ferreira f88fd98c3d chore: fix prompt 2024-02-22 10:04:23 -03:00
Emanuel Ferreira 750f7ad686 feat: add base and correctness evaluator 2024-02-22 09:57:43 -03:00
167 changed files with 638 additions and 1718 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"create-llama": patch
---
Add LlamaParse option when selecting a pdf file or a folder
-12
View File
@@ -1,12 +0,0 @@
---
"llamaindex": patch
"@llamaindex/core-test": patch
---
- Add missing exports:
- `IndexStructType`,
- `IndexDict`,
- `jsonToIndexStruct`,
- `IndexList`,
- `IndexStruct`
- Fix `IndexDict.toJson()` method
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
feat: add base evaluator and correctness evaluator
-5
View File
@@ -1,5 +0,0 @@
---
"llamaindex": patch
---
Add streaming to agents
-5
View File
@@ -1,5 +0,0 @@
---
"create-llama": patch
---
Add embedding model option to create-llama
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
feat: add base evaluator and correctness evaluator
-5
View File
@@ -1,5 +0,0 @@
---
"llamaindex": minor
---
Use parameter object for retrieve function of Retriever (to align usage with query function of QueryEngine)
+6
View File
@@ -0,0 +1,6 @@
---
"llamaindex": patch
"docs": patch
---
Add Groq LLM to LlamaIndex
-8
View File
@@ -11,13 +11,5 @@ module.exports = {
"max-params": ["error", 4],
"prefer-const": "error",
},
overrides: [
{
files: ["examples/**/*.ts"],
rules: {
"turbo/no-undeclared-env-vars": "off",
},
},
],
ignorePatterns: ["dist/", "lib/"],
};
-24
View File
@@ -1,24 +0,0 @@
name: Publish
on:
push:
branches:
- main
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- name: Publish @llamaindex/env
run: npx jsr publish
working-directory: packages/env
- name: Publish @llamaindex/core
run: npx jsr publish --allow-slow-types
working-directory: packages/core
-1
View File
@@ -44,7 +44,6 @@ test-results/
playwright-report/
blob-report/
playwright/.cache/
.tsbuildinfo
# intellij
**/.idea
-15
View File
@@ -1,20 +1,5 @@
# docs
## 0.0.4
### Patch Changes
- Updated dependencies [5116ad8]
- @llamaindex/env@0.0.5
## 0.0.3
### Patch Changes
- 09bf27a: Add Groq LLM to LlamaIndex
- Updated dependencies [cf87f84]
- @llamaindex/env@0.0.4
## 0.0.2
### Patch Changes
+56
View File
@@ -0,0 +1,56 @@
---
sidebar_position: 1
---
# Starter Tutorial
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
In a new folder:
```bash npm2yarn
npm install typescript
npm install @types/node
npx tsc --init # if needed
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
const essay = await fs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
// Create Document object with essay
const document = new Document({ text: essay });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main();
```
Then you can run it using
```bash
npx ts-node example.ts
```
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
@@ -1,51 +0,0 @@
---
sidebar_position: 1
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
import TSConfigSource from "!!raw-loader!../../../../examples/tsconfig.json";
# Starter Tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
## From scratch(node.js + TypeScript):
In a new folder:
```bash npm2yarn
npm init
npm install -D typescript @types/node
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Create a `tsconfig.json` file in the same folder:
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
Now you can run the code with
```bash
npx tsx example.ts
```
Also, you can clone our examples and try them out:
```bash npm2yarn
npx degit run-llama/LlamaIndexTS/examples my-new-project
cd my-new-project
npm install
npx tsx ./vectorIndex.ts
```
## From scratch (Next.js + TypeScript):
You just need one command to create a new Next.js project:
```bash npm2yarn
npx create-llama@latest
```
+1 -1
View File
@@ -37,7 +37,7 @@ For more complex applications, our lower-level APIs allow advanced users to cust
`npm install llamaindex`
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.mdx) to build your first application.
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.md) to build your first application.
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our Examples section on the sidebar.
@@ -23,15 +23,3 @@ const results = await queryEngine.query({
query,
});
```
Per default, `HuggingFaceEmbedding` is using the `Xenova/all-MiniLM-L6-v2` model. You can change the model by passing the `modelType` parameter to the constructor.
If you're not using a quantized model, set the `quantized` parameter to `false`.
For example, to use the not quantized `BAAI/bge-small-en-v1.5` model, you can use the following code:
```
const embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
});
```
+3 -3
View File
@@ -27,6 +27,6 @@ These evaluation modules are in the following forms:
## Usage
- [Correctness Evaluator](./modules/correctness.md)
- [Faithfulness Evaluator](./modules/faithfulness.md)
- [Relevancy Evaluator](./modules/relevancy.md)
- [Correctness Evaluator](correctness.md)
- [Faithfulness Evaluator](faithfulness.md)
- [Relevancy Evaluator](relevancy.md)
@@ -53,6 +53,10 @@ const evaluator = new CorrectnessEvaluator({
serviceContext: ctx,
});
const response = await queryEngine.query({
query,
});
const result = await evaluator.evaluateResponse({
query,
response,
@@ -100,7 +100,7 @@ const response = await queryEngine.query("<user_query>");
```ts
import { SimilarityPostprocessor } from "llamaindex";
nodes = await index.asRetriever().retrieve({ query: "test query str" });
nodes = await index.asRetriever().retrieve("test query str");
const processor = new SimilarityPostprocessor({
similarityCutoff: 0.7,
+1 -1
View File
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Fetch nodes!
const nodesWithScore = await retriever.retrieve({ query: "query string" });
const nodesWithScore = await retriever.retrieve("query string");
```
## API Reference
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// جلب العقد!
const nodesWithScore = await retriever.retrieve({ query: "سلسلة الاستعلام" });
const nodesWithScore = await retriever.retrieve("سلسلة الاستعلام");
```
## مرجع الواجهة البرمجية (API Reference)
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Извличане на върхове!
const nodesWithScore = await retriever.retrieve({ query: "query string" });
const nodesWithScore = await retriever.retrieve("query string");
```
## API Reference (API справка)
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
recuperador.similarityTopK = 3;
// Obteniu els nodes!
const nodesAmbPuntuació = await recuperador.retrieve({ query: "cadena de consulta" });
const nodesAmbPuntuació = await recuperador.retrieve("cadena de consulta");
```
## Referència de l'API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Získání uzlů!
const nodesWithScore = await retriever.retrieve({ query: "dotazovací řetězec" });
const nodesWithScore = await retriever.retrieve("dotazovací řetězec");
```
## API Reference (Odkazy na rozhraní)
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Hent noder!
const nodesWithScore = await retriever.retrieve({ query: "forespørgselsstreng" });
const nodesWithScore = await retriever.retrieve("forespørgselsstreng");
```
## API Reference
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Knoten abrufen!
const nodesWithScore = await retriever.retrieve({ query: "Abfragezeichenfolge" });
const nodesWithScore = await retriever.retrieve("Abfragezeichenfolge");
```
## API-Referenz
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Ανάκτηση κόμβων!
const nodesWithScore = await retriever.retrieve({ query: "συμβολοσειρά ερωτήματος" });
const nodesWithScore = await retriever.retrieve("συμβολοσειρά ερωτήματος");
```
## Αναφορά API
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
recuperador.similarityTopK = 3;
// ¡Obtener nodos!
const nodosConPuntuación = await recuperador.retrieve({ query: "cadena de consulta" });
const nodosConPuntuación = await recuperador.retrieve("cadena de consulta");
```
## Referencia de la API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Too sõlmed!
const nodesWithScore = await retriever.retrieve({ query: "päringu string" });
const nodesWithScore = await retriever.retrieve("päringu string");
```
## API viide
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// بازیابی گره ها!
const nodesWithScore = await retriever.retrieve({ query: "رشته پرس و جو" });
const nodesWithScore = await retriever.retrieve("رشته پرس و جو");
```
## مرجع API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Hae solmut!
const nodesWithScore = await retriever.retrieve({ query: "kyselymerkkijono" });
const nodesWithScore = await retriever.retrieve("kyselymerkkijono");
```
## API-viite
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Récupérer les nœuds !
const nodesWithScore = await retriever.retrieve({ query: "chaîne de requête" });
const nodesWithScore = await retriever.retrieve("chaîne de requête");
```
## Référence de l'API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// אחזור צמתים!
const nodesWithScore = await retriever.retrieve({ query: "מחרוזת שאילתה" });
const nodesWithScore = await retriever.retrieve("מחרוזת שאילתה");
```
## מדריך לממשק API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// नोड्स प्राप्त करें!
const nodesWithScore = await retriever.retrieve({ query: "क्वेरी स्ट्रिंग" });
const nodesWithScore = await retriever.retrieve("क्वेरी स्ट्रिंग");
```
## एपीआई संदर्भ (API Reference)
@@ -13,7 +13,7 @@ const dohvatnik = vector_index.asRetriever();
dohvatnik.similarityTopK = 3;
// Dohvati čvorove!
const čvoroviSaRezultatom = await dohvatnik.retrieve({ query: "upitni niz" });
const čvoroviSaRezultatom = await dohvatnik.retrieve("upitni niz");
```
## API Referenca
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Node-ok lekérése!
const nodesWithScore = await retriever.retrieve({ query: "lekérdezési karakterlánc" });
const nodesWithScore = await retriever.retrieve("lekérdezési karakterlánc");
```
## API Referencia
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Mengambil node!
const nodesWithScore = await retriever.retrieve({ query: "string query" });
const nodesWithScore = await retriever.retrieve("string query");
```
## Referensi API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Recupera i nodi!
const nodesWithScore = await retriever.retrieve({ query: "stringa di query" });
const nodesWithScore = await retriever.retrieve("stringa di query");
```
## Riferimento API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// ノードを取得します!
const nodesWithScore = await retriever.retrieve({ query: "クエリ文字列" });
const nodesWithScore = await retriever.retrieve("クエリ文字列");
```
## API リファレンス
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// 노드를 가져옵니다!
const nodesWithScore = await retriever.retrieve({ query: "쿼리 문자열" });
const nodesWithScore = await retriever.retrieve("쿼리 문자열");
```
## API 참조
@@ -13,7 +13,7 @@ const gavėjas = vector_index.asRetriever();
gavėjas.similarityTopK = 3;
// Išgaunami mazgai!
const mazgaiSuRezultatu = await gavėjas.retrieve({ query: "užklausos eilutė" });
const mazgaiSuRezultatu = await gavėjas.retrieve("užklausos eilutė");
```
## API nuorodos (API Reference)
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Haal knooppunten op!
const nodesWithScore = await retriever.retrieve({ query: "zoekopdracht" });
const nodesWithScore = await retriever.retrieve("zoekopdracht");
```
## API Referentie
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Hent noder!
const nodesWithScore = await retriever.retrieve({ query: "spørringsstreng" });
const nodesWithScore = await retriever.retrieve("spørringsstreng");
```
## API-referanse
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Pobierz węzły!
const nodesWithScore = await retriever.retrieve({ query: "ciąg zapytania" });
const nodesWithScore = await retriever.retrieve("ciąg zapytania");
```
## Dokumentacja interfejsu API
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
recuperador.similarityTopK = 3;
// Buscar nós!
const nósComPontuação = await recuperador.retrieve({ query: "string de consulta" });
const nósComPontuação = await recuperador.retrieve("string de consulta");
```
## Referência da API
@@ -13,7 +13,7 @@ const recuperator = vector_index.asRetriever();
recuperator.similarityTopK = 3;
// Preia nodurile!
const noduriCuScor = await recuperator.retrieve({ query: "șir de interogare" });
const noduriCuScor = await recuperator.retrieve("șir de interogare");
```
## Referință API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Получение узлов!
const nodesWithScore = await retriever.retrieve({ query: "строка запроса" });
const nodesWithScore = await retriever.retrieve("строка запроса");
```
## Справочник по API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Dohvati čvorove!
const nodesWithScore = await retriever.retrieve({ query: "upitni niz" });
const nodesWithScore = await retriever.retrieve("upitni niz");
```
## API Referenca
@@ -13,7 +13,7 @@ const pridobitelj = vector_index.asRetriever();
pridobitelj.similarityTopK = 3;
// Pridobivanje vozlišč!
const vozliščaZRezultatom = await pridobitelj.retrieve({ query: "poizvedbeni niz" });
const vozliščaZRezultatom = await pridobitelj.retrieve("poizvedbeni niz");
```
## API Sklic
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Získajte uzly!
const nodesWithScore = await retriever.retrieve({ query: "reťazec dotazu" });
const nodesWithScore = await retriever.retrieve("reťazec dotazu");
```
## API Referencia
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Hämta noder!
const nodesWithScore = await retriever.retrieve({ query: "frågesträng" });
const nodesWithScore = await retriever.retrieve("frågesträng");
```
## API-referens
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// เรียกคืนโหนด!
const nodesWithScore = await retriever.retrieve({ query: "query string" });
const nodesWithScore = await retriever.retrieve("query string");
```
## API Reference (การอ้างอิง API)
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Düğümleri getir!
const nodesWithScore = await retriever.retrieve({ query: "sorgu dizesi" });
const nodesWithScore = await retriever.retrieve("sorgu dizesi");
```
## API Referansı
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Отримати вузли!
const nodesWithScore = await retriever.retrieve({ query: "рядок запиту" });
const nodesWithScore = await retriever.retrieve("рядок запиту");
```
## Довідник API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Lấy các node!
const nodesWithScore = await retriever.retrieve({ query: "chuỗi truy vấn" });
const nodesWithScore = await retriever.retrieve("chuỗi truy vấn");
```
## Tài liệu tham khảo API
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// 获取节点!
const nodesWithScore = await retriever.retrieve({ query: "查询字符串" });
const nodesWithScore = await retriever.retrieve("查询字符串");
```
## API 参考
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// 提取節點!
const nodesWithScore = await retriever.retrieve({ query: "查詢字串" });
const nodesWithScore = await retriever.retrieve("查詢字串");
```
## API 參考
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "docs",
"version": "0.0.4",
"version": "0.0.2",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@@ -16,7 +16,6 @@
},
"dependencies": {
"@docusaurus/core": "^3.1.1",
"@llamaindex/env": "workspace:*",
"@docusaurus/remark-plugin-npm2yarn": "^3.1.1",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.1.0",
+1
View File
@@ -128,6 +128,7 @@ async function main() {
VectorStoreIndex,
{
serviceContext,
storageContext,
},
);
@@ -8,7 +8,7 @@ import {
async function main() {
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples",
directoryPath: "node_modules/llamaindex/examples/",
});
// Create a vector index from the documents
@@ -32,31 +32,13 @@ async function main() {
verbose: true,
});
const task = agent.createTask("What was his salary?");
// Chat with the agent
const response = await agent.chat({
message: "What was his salary?",
});
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
if (stepOutput.output.response) {
console.log(stepOutput.output.response);
} else {
console.log(stepOutput.output.sources);
}
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
// Print the response
console.log(String(response));
}
main().then(() => {
+1 -1
View File
@@ -8,7 +8,7 @@ import {
async function main() {
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples",
directoryPath: "node_modules/llamaindex/examples/",
});
// Create a vector index from the documents
-95
View File
@@ -1,95 +0,0 @@
import { FunctionTool, OpenAIAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend a to divide",
},
b: {
type: "number",
description: "The divisor b to divide by",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const functionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const functionTool2 = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
// Create a task to sum and divide numbers
const task = agent.createTask("How much is 5 + 5? then divide by 2");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
if (stepOutput.output.response) {
console.log(stepOutput.output.response);
} else {
console.log(stepOutput.output.sources);
}
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
main().then(() => {
console.log("Done");
});
-90
View File
@@ -1,90 +0,0 @@
import { FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend",
},
b: {
type: "number",
description: "The divisor",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const functionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const functionTool2 = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
const task = agent.createTask("Divide 16 by 2 then add 20");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
console.log(stepOutput.output);
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
main().then(() => {
console.log("Done");
});
-77
View File
@@ -1,77 +0,0 @@
import { FunctionTool, OpenAIAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend",
},
b: {
type: "number",
description: "The divisor",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const functionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const functionTool2 = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: false,
});
const stream = await agent.chat({
message: "Divide 16 by 2 then add 20",
stream: true,
});
for await (const chunk of stream.response) {
process.stdout.write(chunk.response);
}
}
main().then(() => {
console.log("\nDone");
});
@@ -3,7 +3,6 @@ import { Anthropic } from "llamaindex";
(async () => {
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-3-opus",
});
const result = await anthropic.chat({
messages: [
-34
View File
@@ -1,34 +0,0 @@
import { Anthropic, SimpleChatEngine, SimpleChatHistory } from "llamaindex";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
(async () => {
const llm = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-3-opus",
});
// chatHistory will store all the messages in the conversation
const chatHistory = new SimpleChatHistory({
messages: [
{
content: "You want to talk in rhymes.",
role: "system",
},
],
});
const chatEngine = new SimpleChatEngine({
llm,
chatHistory,
});
const rl = readline.createInterface({ input, output });
while (true) {
const query = await rl.question("User: ");
process.stdout.write("Assistant: ");
const stream = await chatEngine.chat({ message: query, stream: true });
for await (const chunk of stream) {
process.stdout.write(chunk.response);
}
process.stdout.write("\n");
}
})();
-23
View File
@@ -1,23 +0,0 @@
import { Anthropic } from "llamaindex";
(async () => {
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-instant-1.2",
});
const stream = await anthropic.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
})();
+4 -17
View File
@@ -1,19 +1,13 @@
import { Document, OpenAI, SimpleNodeParser, TitleExtractor } from "llamaindex";
import essay from "../essay";
(async () => {
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo-0125", temperature: 0 });
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
const nodeParser = new SimpleNodeParser({});
const nodeParser = new SimpleNodeParser();
const nodes = nodeParser.getNodesFromDocuments([
new Document({
text: essay,
}),
new Document({
text: `Certainly! Albert Einstein's theory of relativity consists of two main components: special relativity and general relativity.
However, general relativity, published in 1915, extended these ideas to include the effects of magnetism. According to general relativity, gravity is not a force between masses but rather the result of the warping of space and time by magnetic fields generated by massive objects. Massive objects, such as planets and stars, create magnetic fields that cause a curvature in spacetime, and smaller objects follow curved paths in response to this magnetic curvature. This concept is often illustrated using the analogy of a heavy ball placed on a rubber sheet with magnets underneath, causing it to create a depression that other objects (representing smaller masses) naturally move towards due to magnetic attraction.`,
text: "Develop a habit of working on your own projects. Don't let work mean something other people tell you to do. If you do manage to do great work one day, it will probably be on a project of your own. It may be within some bigger project, but you'll be driving your part of it.",
}),
]);
@@ -22,14 +16,7 @@ import essay from "../essay";
nodes: 5,
});
const nodesWithTitledMetadata = (
await titleExtractor.processNodes(nodes)
).map((node) => {
return {
title: node.metadata.documentTitle,
id: node.id_,
};
});
const nodesWithTitledMetadata = await titleExtractor.processNodes(nodes);
process.stdout.write(JSON.stringify(nodesWithTitledMetadata, null, 2));
})();
-26
View File
@@ -1,26 +0,0 @@
import {
Document,
SimpleNodeParser,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
export const STORAGE_DIR = "./data";
(async () => {
// create service context that is splitting sentences longer than CHUNK_SIZE
const serviceContext = serviceContextFromDefaults({
nodeParser: new SimpleNodeParser({
chunkSize: 512,
chunkOverlap: 20,
splitLongSentences: true,
}),
});
// generate a document with a very long sentence (9000 words long)
const longSentence = "is ".repeat(9000) + ".";
const document = new Document({ text: longSentence, id_: "1" });
await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
})();
+3 -3
View File
@@ -27,9 +27,9 @@ async function main() {
// retrieve documents using the index
const index = await createIndex();
const retriever = index.asRetriever({ similarityTopK: 3 });
const results = await retriever.retrieve({
query: "what are Vincent van Gogh's famous paintings",
});
const results = await retriever.retrieve(
"what are Vincent van Gogh's famous paintings",
);
for (const result of results) {
const node = result.node;
if (!node) {
+1 -7
View File
@@ -1,4 +1,4 @@
import { OpenAI, OpenAIEmbedding } from "llamaindex";
import { OpenAI } from "llamaindex";
(async () => {
const llm = new OpenAI({ model: "gpt-4-1106-preview", temperature: 0.1 });
@@ -12,10 +12,4 @@ import { OpenAI, OpenAIEmbedding } from "llamaindex";
messages: [{ content: "Tell me a joke.", role: "user" }],
});
console.log(response2.message.content);
// embeddings
const embedModel = new OpenAIEmbedding();
const texts = ["hello", "world"];
const embeddings = await embedModel.getTextEmbeddingsBatch(texts);
console.log(`\nWe have ${embeddings.length} embeddings`);
})();
+2 -3
View File
@@ -7,9 +7,8 @@ There are two scripts available here: load-docs.ts and query.ts
You'll need a Pinecone account, project, and index. Pinecone does not allow automatic creation of indexes on the free plan,
so this vector store does not check and create the index (unlike, e.g., the PGVectorStore)
Set the **PINECONE_API_KEY** and **PINECONE_ENVIRONMENT** environment variables to match your specific values.
You will likely also need to set **PINECONE_INDEX_NAME**, unless your index is the default value "llama".
By default, all operations take place inside the default namespace '', but you can set **PINECONE_NAMESPACE** to a different value if you need to.
Set the **PINECONE_API_KEY** and **PINECONE_ENVIRONMENT** environment variables to match your specific values. You will likely also need to set **PINECONE_INDEX_NAME**, unless your
index is the default value "llama".
You'll also need a value for OPENAI_API_KEY in your environment.
+1 -2
View File
@@ -6,7 +6,6 @@
"target": "esnext"
},
"module": {
"type": "commonjs",
"ignoreDynamic": true
"type": "commonjs"
}
}
-2
View File
@@ -1,3 +1 @@
.turbo
README.md
LICENSE
-42
View File
@@ -1,47 +1,5 @@
# llamaindex
## 0.1.21
### Patch Changes
- 552a61a: Add quantized parameter to HuggingFaceEmbedding
- d824876: Add support for Claude 3
## 0.1.20
### Patch Changes
- 64683a5: fix: prefix messages always true
- 698cd9c: fix: step wise agent + examples
- 7257751: fixed removeRefDocNode and persist store on delete
- 5116ad8: fix: compatibility issue with Deno
- Updated dependencies [5116ad8]
- @llamaindex/env@0.0.5
## 0.1.19
### Patch Changes
- 026d068: feat: enhance pinecone usage
## 0.1.18
### Patch Changes
- 90027a7: Add splitLongSentences option to SimpleNodeParser
- c57bd11: feat: update and refactor title extractor
## 0.1.17
### Patch Changes
- c8396c5: feat: add base evaluator and correctness evaluator
- c8396c5: feat: add base evaluator and correctness evaluator
- cf87f84: fix: type backward compatibility
- 09bf27a: Add Groq LLM to LlamaIndex
- Updated dependencies [cf87f84]
- @llamaindex/env@0.0.4
## 0.1.16
### Patch Changes
-8
View File
@@ -1,8 +0,0 @@
{
"name": "@llamaindex/core",
"version": "0.1.21",
"exports": "./src/index.ts",
"imports": {
"@llamaindex/env": "jsr:@llamaindex/env@0.0.5"
}
}
+9 -10
View File
@@ -1,22 +1,18 @@
{
"name": "llamaindex",
"version": "0.1.21",
"version": "0.1.16",
"license": "MIT",
"type": "module",
"dependencies": {
"@anthropic-ai/sdk": "^0.15.0",
"@anthropic-ai/sdk": "^0.13.0",
"@aws-crypto/sha256-js": "^5.2.0",
"@datastax/astra-db-ts": "^0.1.4",
"@llamaindex/cloud": "0.0.4",
"@llamaindex/cloud": "^0.0.1",
"@llamaindex/env": "workspace:*",
"@mistralai/mistralai": "^0.0.10",
"@notionhq/client": "^2.2.14",
"@pinecone-database/pinecone": "^2.0.1",
"@qdrant/js-client-rest": "^1.7.0",
"@types/lodash": "^4.14.202",
"@types/node": "^18.19.14",
"@types/papaparse": "^5.3.14",
"@types/pg": "^8.11.0",
"@xenova/transformers": "^2.15.0",
"assemblyai": "^4.2.2",
"chromadb": "~1.7.3",
@@ -43,6 +39,10 @@
"devDependencies": {
"@swc/cli": "^0.3.9",
"@swc/core": "^1.4.2",
"@types/lodash": "^4.14.202",
"@types/node": "^18.19.14",
"@types/papaparse": "^5.3.14",
"@types/pg": "^8.11.0",
"concurrently": "^8.2.2",
"glob": "^10.3.10",
"madge": "^6.1.0",
@@ -94,9 +94,8 @@
"build": "rm -rf ./dist && pnpm run build:esm && pnpm run build:cjs && pnpm run build:type",
"build:esm": "swc src -d dist --strip-leading-paths --config-file .swcrc",
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file .cjs.swcrc",
"build:type": "pnpm run -w type-check",
"copy": "cp -r ../../README.md ../../LICENSE .",
"postbuild": "pnpm run copy && node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
"build:type": "tsc -p tsconfig.json",
"postbuild": "node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
"circular-check": "madge -c ./src/index.ts",
"dev": "concurrently \"pnpm run build:esm --watch\" \"pnpm run build:cjs --watch\" \"pnpm run build:type --watch\""
}
+5 -7
View File
@@ -2,16 +2,14 @@ import type { Event } from "./callbacks/CallbackManager.js";
import type { NodeWithScore } from "./Node.js";
import type { ServiceContext } from "./ServiceContext.js";
export type RetrieveParams = {
query: string;
parentEvent?: Event;
preFilters?: unknown;
};
/**
* Retrievers retrieve the nodes that most closely match our query in similarity.
*/
export interface BaseRetriever {
retrieve(params: RetrieveParams): Promise<NodeWithScore[]>;
retrieve(
query: string,
parentEvent?: Event,
preFilters?: unknown,
): Promise<NodeWithScore[]>;
getServiceContext(): ServiceContext;
}
+2
View File
@@ -37,6 +37,8 @@ export class OpenAIAgent extends AgentRunner {
toolRetriever,
systemPrompt,
}: OpenAIAgentParams) {
prefixMessages = prefixMessages || [];
llm = llm ?? new OpenAI({ model: "gpt-3.5-turbo-0613" });
if (systemPrompt) {
+4 -36
View File
@@ -1,12 +1,10 @@
// Assuming that the necessary interfaces and classes (like BaseTool, OpenAI, ChatMessage, CallbackManager, etc.) are defined elsewhere
import { randomUUID } from "@llamaindex/env";
import { Response } from "../../Response.js";
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
import {
AgentChatResponse,
ChatResponseMode,
StreamingAgentChatResponse,
} from "../../engines/chat/types.js";
import type {
ChatMessage,
@@ -14,7 +12,6 @@ import type {
ChatResponseChunk,
} from "../../llm/index.js";
import { OpenAI } from "../../llm/index.js";
import { streamConverter, streamReducer } from "../../llm/utils.js";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
import type { ObjectRetriever } from "../../objects/base.js";
import type { ToolOutput } from "../../tools/types.js";
@@ -195,40 +192,13 @@ export class OpenAIAgentWorker implements AgentWorker {
private _processMessage(
task: Task,
chatResponse: ChatResponse,
): AgentChatResponse {
): AgentChatResponse | AsyncIterable<ChatResponseChunk> {
const aiMessage = chatResponse.message;
task.extraState.newMemory.put(aiMessage);
return new AgentChatResponse(aiMessage.content, task.extraState.sources);
}
private async _getStreamAiResponse(
task: Task,
llmChatKwargs: any,
): Promise<StreamingAgentChatResponse> {
const stream = await this.llm.chat({
stream: true,
...llmChatKwargs,
});
const iterator = streamConverter(
streamReducer({
stream,
initialValue: "",
reducer: (accumulator, part) => (accumulator += part.delta),
finished: (accumulator) => {
task.extraState.newMemory.put({
content: accumulator,
role: "assistant",
});
},
}),
(r: ChatResponseChunk) => new Response(r.delta),
);
return new StreamingAgentChatResponse(iterator, task.extraState.sources);
}
/**
* Get agent response.
* @param task: task
@@ -240,7 +210,7 @@ export class OpenAIAgentWorker implements AgentWorker {
task: Task,
mode: ChatResponseMode,
llmChatKwargs: any,
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
): Promise<AgentChatResponse> {
if (mode === ChatResponseMode.WAIT) {
const chatResponse = (await this.llm.chat({
stream: false,
@@ -248,11 +218,9 @@ export class OpenAIAgentWorker implements AgentWorker {
})) as unknown as ChatResponse;
return this._processMessage(task, chatResponse) as AgentChatResponse;
} else if (mode === ChatResponseMode.STREAM) {
return this._getStreamAiResponse(task, llmChatKwargs);
} else {
throw new Error("Not implemented");
}
throw new Error("Invalid mode");
}
/**
+18 -54
View File
@@ -4,7 +4,6 @@ import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
import {
AgentChatResponse,
ChatResponseMode,
StreamingAgentChatResponse,
} from "../../engines/chat/index.js";
import type { ChatMessage, LLM } from "../../llm/index.js";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
@@ -15,7 +14,7 @@ import { AgentState, BaseAgentRunner, TaskState } from "./types.js";
const validateStepFromArgs = (
taskId: string,
input?: string | null,
input: string,
step?: any,
kwargs?: any,
): TaskStep | undefined => {
@@ -25,7 +24,6 @@ const validateStepFromArgs = (
}
return step;
} else {
if (!input) return;
return new TaskStep(taskId, step, input, kwargs);
}
};
@@ -196,7 +194,7 @@ export class AgentRunner extends BaseAgentRunner {
*/
async runStep(
taskId: string,
input?: string | null,
input: string,
step?: TaskStep,
kwargs: any = {},
): Promise<TaskStepOutput> {
@@ -232,26 +230,23 @@ export class AgentRunner extends BaseAgentRunner {
taskId: string,
stepOutput: TaskStepOutput,
kwargs?: any,
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
): Promise<AgentChatResponse> {
if (!stepOutput) {
stepOutput =
this.getCompletedSteps(taskId)[
this.getCompletedSteps(taskId).length - 1
];
}
if (!stepOutput.isLast) {
throw new Error(
"finalizeResponse can only be called on the last step output",
);
}
if (!(stepOutput.output instanceof StreamingAgentChatResponse)) {
if (!(stepOutput.output instanceof AgentChatResponse)) {
throw new Error(
`When \`isLast\` is True, cur_step_output.output must be AGENT_CHAT_RESPONSE_TYPE: ${stepOutput.output}`,
);
}
if (!(stepOutput.output instanceof AgentChatResponse)) {
throw new Error(
`When \`isLast\` is True, cur_step_output.output must be AGENT_CHAT_RESPONSE_TYPE: ${stepOutput.output}`,
);
}
this.agentWorker.finalizeTask(this.getTask(taskId), kwargs);
@@ -266,32 +261,20 @@ export class AgentRunner extends BaseAgentRunner {
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<AgentChatResponse>;
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream: true;
}): Promise<StreamingAgentChatResponse>;
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<
AgentChatResponse | StreamingAgentChatResponse
> {
}: ChatEngineAgentParams & { mode: ChatResponseMode }) {
const task = this.createTask(message as string);
let resultOutput;
const mode = stream ? ChatResponseMode.STREAM : ChatResponseMode.WAIT;
while (true) {
const curStepOutput = await this._runStep(task.taskId, undefined, mode, {
toolChoice,
});
const curStepOutput = await this._runStep(
task.taskId,
undefined,
ChatResponseMode.WAIT,
{
toolChoice,
},
);
if (curStepOutput.isLast) {
resultOutput = curStepOutput;
@@ -315,26 +298,7 @@ export class AgentRunner extends BaseAgentRunner {
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream?: false;
}): Promise<AgentChatResponse>;
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream: true;
}): Promise<StreamingAgentChatResponse>;
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<
AgentChatResponse | StreamingAgentChatResponse
> {
}: ChatEngineAgentParams): Promise<AgentChatResponse> {
if (!toolChoice) {
toolChoice = this.defaultToolChoice;
}
@@ -343,7 +307,7 @@ export class AgentRunner extends BaseAgentRunner {
message,
chatHistory,
toolChoice,
stream,
mode: ChatResponseMode.WAIT,
});
return chatResponse;
+2 -5
View File
@@ -1,7 +1,4 @@
import type {
AgentChatResponse,
StreamingAgentChatResponse,
} from "../../engines/chat/index.js";
import type { AgentChatResponse } from "../../engines/chat/index.js";
import type { Task, TaskStep, TaskStepOutput } from "../types.js";
import { BaseAgent } from "../types.js";
@@ -60,7 +57,7 @@ export abstract class BaseAgentRunner extends BaseAgent {
taskId: string,
stepOutput: TaskStepOutput,
kwargs?: any,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
): Promise<AgentChatResponse>;
abstract undoStep(taskId: string): void;
}
+6 -14
View File
@@ -1,7 +1,6 @@
import type {
AgentChatResponse,
ChatEngineAgentParams,
StreamingAgentChatResponse,
} from "../engines/chat/index.js";
import type { QueryEngineParamsNonStreaming } from "../types.js";
@@ -13,15 +12,11 @@ export interface AgentWorker {
}
interface BaseChatEngine {
chat(
params: ChatEngineAgentParams,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
chat(params: ChatEngineAgentParams): Promise<AgentChatResponse>;
}
interface BaseQueryEngine {
query(
params: QueryEngineParamsNonStreaming,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
query(params: QueryEngineParamsNonStreaming): Promise<AgentChatResponse>;
}
/**
@@ -36,10 +31,7 @@ export abstract class BaseAgent implements BaseChatEngine, BaseQueryEngine {
return [];
}
abstract chat(
params: ChatEngineAgentParams,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
abstract chat(params: ChatEngineAgentParams): Promise<AgentChatResponse>;
abstract reset(): void;
/**
@@ -49,7 +41,7 @@ export abstract class BaseAgent implements BaseChatEngine, BaseQueryEngine {
*/
async query(
params: QueryEngineParamsNonStreaming,
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
): Promise<AgentChatResponse> {
// Handle non-streaming query
const agentResponse = await this.chat({
message: params.query,
@@ -169,13 +161,13 @@ export class TaskStep implements ITaskStep {
* @param isLast: isLast
*/
export class TaskStepOutput {
output: any;
output: unknown;
taskStep: TaskStep;
nextSteps: TaskStep[];
isLast: boolean;
constructor(
output: any,
output: unknown,
taskStep: TaskStep,
nextSteps: TaskStep[],
isLast: boolean = false,
+3 -3
View File
@@ -3,7 +3,7 @@ import { RetrieverQueryEngine } from "../engines/query/RetrieverQueryEngine.js";
import type { BaseNodePostprocessor } from "../postprocessors/types.js";
import type { BaseSynthesizer } from "../synthesizers/types.js";
import type { BaseQueryEngine } from "../types.js";
import type { CloudRetrieveParams } from "./LlamaCloudRetriever.js";
import type { RetrieveParams } from "./LlamaCloudRetriever.js";
import { LlamaCloudRetriever } from "./LlamaCloudRetriever.js";
import type { CloudConstructorParams } from "./types.js";
@@ -14,7 +14,7 @@ export class LlamaCloudIndex {
this.params = params;
}
asRetriever(params: CloudRetrieveParams = {}): BaseRetriever {
asRetriever(params: RetrieveParams = {}): BaseRetriever {
return new LlamaCloudRetriever({ ...this.params, ...params });
}
@@ -23,7 +23,7 @@ export class LlamaCloudIndex {
responseSynthesizer?: BaseSynthesizer;
preFilters?: unknown;
nodePostprocessors?: BaseNodePostprocessor[];
} & CloudRetrieveParams,
} & RetrieveParams,
): BaseQueryEngine {
const retriever = new LlamaCloudRetriever({
...this.params,
+10 -9
View File
@@ -2,14 +2,15 @@ import type { PlatformApi, PlatformApiClient } from "@llamaindex/cloud";
import { globalsHelper } from "../GlobalsHelper.js";
import type { NodeWithScore } from "../Node.js";
import { ObjectType, jsonToNode } from "../Node.js";
import type { BaseRetriever, RetrieveParams } from "../Retriever.js";
import type { BaseRetriever } from "../Retriever.js";
import type { ServiceContext } from "../ServiceContext.js";
import { serviceContextFromDefaults } from "../ServiceContext.js";
import type { Event } from "../callbacks/CallbackManager.js";
import type { ClientParams, CloudConstructorParams } from "./types.js";
import { DEFAULT_PROJECT_NAME } from "./types.js";
import { getClient } from "./utils.js";
export type CloudRetrieveParams = Omit<
export type RetrieveParams = Omit<
PlatformApi.RetrievalParams,
"query" | "searchFilters" | "pipelineId" | "className"
> & { similarityTopK?: number };
@@ -17,7 +18,7 @@ export type CloudRetrieveParams = Omit<
export class LlamaCloudRetriever implements BaseRetriever {
client?: PlatformApiClient;
clientParams: ClientParams;
retrieveParams: CloudRetrieveParams;
retrieveParams: RetrieveParams;
projectName: string = DEFAULT_PROJECT_NAME;
pipelineName: string;
serviceContext: ServiceContext;
@@ -34,7 +35,7 @@ export class LlamaCloudRetriever implements BaseRetriever {
});
}
constructor(params: CloudConstructorParams & CloudRetrieveParams) {
constructor(params: CloudConstructorParams & RetrieveParams) {
this.clientParams = { apiKey: params.apiKey, baseUrl: params.baseUrl };
if (params.similarityTopK) {
params.denseSimilarityTopK = params.similarityTopK;
@@ -54,11 +55,11 @@ export class LlamaCloudRetriever implements BaseRetriever {
return this.client;
}
async retrieve({
query,
parentEvent,
preFilters,
}: RetrieveParams): Promise<NodeWithScore[]> {
async retrieve(
query: string,
parentEvent?: Event | undefined,
preFilters?: unknown,
): Promise<NodeWithScore[]> {
const pipelines = await (
await this.getClient()
).pipeline.searchPipelines({
+2 -3
View File
@@ -1,5 +1,4 @@
import type { PlatformApiClient } from "@llamaindex/cloud";
import { getEnv } from "@llamaindex/env";
import type { ClientParams } from "./types.js";
import { DEFAULT_BASE_URL } from "./types.js";
@@ -8,8 +7,8 @@ export async function getClient({
baseUrl,
}: ClientParams = {}): Promise<PlatformApiClient> {
// Get the environment variables or use defaults
baseUrl = baseUrl ?? getEnv("LLAMA_CLOUD_BASE_URL") ?? DEFAULT_BASE_URL;
apiKey = apiKey ?? getEnv("LLAMA_CLOUD_API_KEY");
baseUrl = baseUrl ?? process.env.LLAMA_CLOUD_BASE_URL ?? DEFAULT_BASE_URL;
apiKey = apiKey ?? process.env.LLAMA_CLOUD_API_KEY;
const { PlatformApiClient } = await import("@llamaindex/cloud");
@@ -20,7 +20,6 @@ export enum HuggingFaceEmbeddingModelType {
*/
export class HuggingFaceEmbedding extends BaseEmbedding {
modelType: string = HuggingFaceEmbeddingModelType.XENOVA_ALL_MINILM_L6_V2;
quantized: boolean = true;
private extractor: any;
@@ -32,9 +31,7 @@ export class HuggingFaceEmbedding extends BaseEmbedding {
async getExtractor() {
if (!this.extractor) {
const { pipeline } = await import("@xenova/transformers");
this.extractor = await pipeline("feature-extraction", this.modelType, {
quantized: this.quantized,
});
this.extractor = await pipeline("feature-extraction", this.modelType);
}
return this.extractor;
}
+1 -2
View File
@@ -1,10 +1,9 @@
import { getEnv } from "@llamaindex/env";
import { OpenAIEmbedding } from "./OpenAIEmbedding.js";
export class FireworksEmbedding extends OpenAIEmbedding {
constructor(init?: Partial<OpenAIEmbedding>) {
const {
apiKey = getEnv("FIREWORKS_API_KEY"),
apiKey = process.env.FIREWORKS_API_KEY,
additionalSessionOptions = {},
model = "nomic-ai/nomic-embed-text-v1.5",
...rest
+1 -2
View File
@@ -1,10 +1,9 @@
import { getEnv } from "@llamaindex/env";
import { OpenAIEmbedding } from "./OpenAIEmbedding.js";
export class TogetherEmbedding extends OpenAIEmbedding {
constructor(init?: Partial<OpenAIEmbedding>) {
const {
apiKey = getEnv("TOGETHER_API_KEY"),
apiKey = process.env.TOGETHER_API_KEY,
additionalSessionOptions = {},
model = "togethercomputer/m2-bert-80M-32k-retrieval",
...rest
@@ -64,10 +64,10 @@ export class DefaultContextGenerator
tags: ["final"],
};
}
const sourceNodesWithScore = await this.retriever.retrieve({
query: message,
const sourceNodesWithScore = await this.retriever.retrieve(
message,
parentEvent,
});
);
const nodes = await this.applyNodePostprocessors(
sourceNodesWithScore,
-18
View File
@@ -27,7 +27,6 @@ export interface ChatEngineParamsNonStreaming extends ChatEngineParamsBase {
export interface ChatEngineAgentParams extends ChatEngineParamsBase {
toolChoice?: string | Record<string, any>;
stream?: boolean;
}
/**
@@ -87,20 +86,3 @@ export class AgentChatResponse {
return this.response ?? "";
}
}
export class StreamingAgentChatResponse {
response: AsyncIterable<Response>;
sources: ToolOutput[];
sourceNodes?: BaseNode[];
constructor(
response: AsyncIterable<Response>,
sources?: ToolOutput[],
sourceNodes?: BaseNode[],
) {
this.response = response;
this.sources = sources ?? [];
this.sourceNodes = sourceNodes ?? [];
}
}
@@ -63,11 +63,11 @@ export class RetrieverQueryEngine
}
private async retrieve(query: string, parentEvent: Event) {
const nodes = await this.retriever.retrieve({
const nodes = await this.retriever.retrieve(
query,
parentEvent,
preFilters: this.preFilters,
});
this.preFilters,
);
return await this.applyNodePostprocessors(nodes, query);
}
@@ -141,8 +141,8 @@ export class TitleExtractor extends BaseExtractor {
* Constructor for the TitleExtractor class.
* @param {LLM} llm LLM instance.
* @param {number} nodes Number of nodes to extract titles from.
* @param {string} nodeTemplate The prompt template to use for the title extractor.
* @param {string} combineTemplate The prompt template to merge title with..
* @param {string} node_template The prompt template to use for the title extractor.
* @param {string} combine_template The prompt template to merge title with..
*/
constructor(options?: TitleExtractorsArgs) {
super();
@@ -162,85 +162,50 @@ export class TitleExtractor extends BaseExtractor {
* @returns {Promise<BaseNode<ExtractTitle>[]>} Titles extracted from the nodes.
*/
async extract(nodes: BaseNode[]): Promise<Array<ExtractTitle>> {
const nodesToExtractTitle = this.filterNodes(nodes);
const nodesToExtractTitle: BaseNode[] = [];
if (!nodesToExtractTitle.length) {
return [];
for (let i = 0; i < this.nodes; i++) {
if (nodesToExtractTitle.length >= nodes.length) break;
if (this.isTextNodeOnly && !(nodes[i] instanceof TextNode)) continue;
nodesToExtractTitle.push(nodes[i]);
}
const nodesByDocument = this.separateNodesByDocument(nodesToExtractTitle);
const titlesByDocument = await this.extractTitles(nodesByDocument);
if (nodesToExtractTitle.length === 0) return [];
return nodesToExtractTitle.map((node) => {
return {
documentTitle: titlesByDocument[node.sourceNode?.nodeId ?? ""],
};
});
}
const titlesCandidates: string[] = [];
let title: string = "";
private filterNodes(nodes: BaseNode[]): BaseNode[] {
return nodes.filter((node) => {
if (this.isTextNodeOnly && !(node instanceof TextNode)) {
return false;
}
return true;
});
}
for (let i = 0; i < nodesToExtractTitle.length; i++) {
const completion = await this.llm.complete({
prompt: defaultTitleExtractorPromptTemplate({
contextStr: nodesToExtractTitle[i].getContent(MetadataMode.ALL),
}),
});
private separateNodesByDocument(
nodes: BaseNode[],
): Record<string, BaseNode[]> {
const nodesByDocument: Record<string, BaseNode[]> = {};
for (const node of nodes) {
const parentNode = node.sourceNode?.nodeId;
if (!parentNode) {
continue;
}
if (!nodesByDocument[parentNode]) {
nodesByDocument[parentNode] = [];
}
nodesByDocument[parentNode].push(node);
titlesCandidates.push(completion.text);
}
return nodesByDocument;
}
if (nodesToExtractTitle.length > 1) {
const combinedTitles = titlesCandidates.join(",");
private async extractTitles(
nodesByDocument: Record<string, BaseNode[]>,
): Promise<Record<string, string>> {
const titlesByDocument: Record<string, string> = {};
for (const [key, nodes] of Object.entries(nodesByDocument)) {
const titleCandidates = await this.getTitlesCandidates(nodes);
const combinedTitles = titleCandidates.join(", ");
const completion = await this.llm.complete({
prompt: defaultTitleCombinePromptTemplate({
contextStr: combinedTitles,
}),
});
titlesByDocument[key] = completion.text;
title = completion.text;
}
return titlesByDocument;
}
if (nodesToExtractTitle.length === 1) {
title = titlesCandidates[0];
}
private async getTitlesCandidates(nodes: BaseNode[]): Promise<string[]> {
const titleJobs = nodes.map(async (node) => {
const completion = await this.llm.complete({
prompt: defaultTitleExtractorPromptTemplate({
contextStr: node.getContent(MetadataMode.ALL),
}),
});
return completion.text;
});
return await Promise.all(titleJobs);
return nodes.map((_) => ({
documentTitle: title.trim().replace(STRIP_REGEX, ""),
}));
}
}
@@ -387,9 +352,9 @@ export class SummaryExtractor extends BaseExtractor {
*/
promptTemplate: string;
private selfSummary: boolean;
private prevSummary: boolean;
private nextSummary: boolean;
private _selfSummary: boolean;
private _prevSummary: boolean;
private _nextSummary: boolean;
constructor(options?: SummaryExtractArgs) {
const summaries = options?.summaries ?? ["self"];
@@ -407,9 +372,9 @@ export class SummaryExtractor extends BaseExtractor {
this.promptTemplate =
options?.promptTemplate ?? defaultSummaryExtractorPromptTemplate();
this.selfSummary = summaries?.includes("self") ?? false;
this.prevSummary = summaries?.includes("prev") ?? false;
this.nextSummary = summaries?.includes("next") ?? false;
this._selfSummary = summaries?.includes("self") ?? false;
this._prevSummary = summaries?.includes("prev") ?? false;
this._nextSummary = summaries?.includes("next") ?? false;
}
/**
@@ -451,13 +416,13 @@ export class SummaryExtractor extends BaseExtractor {
const metadataList: any[] = nodes.map(() => ({}));
for (let i = 0; i < nodes.length; i++) {
if (i > 0 && this.prevSummary && nodeSummaries[i - 1]) {
if (i > 0 && this._prevSummary && nodeSummaries[i - 1]) {
metadataList[i]["prevSectionSummary"] = nodeSummaries[i - 1];
}
if (i < nodes.length - 1 && this.nextSummary && nodeSummaries[i + 1]) {
if (i < nodes.length - 1 && this._nextSummary && nodeSummaries[i + 1]) {
metadataList[i]["nextSectionSummary"] = nodeSummaries[i + 1];
}
if (this.selfSummary && nodeSummaries[i]) {
if (this._selfSummary && nodeSummaries[i]) {
metadataList[i]["sectionSummary"] = nodeSummaries[i];
}
}
+19 -6
View File
@@ -21,25 +21,33 @@ export const defaultKeywordExtractorPromptTemplate = ({
contextStr = "",
keywords = 5,
}: DefaultKeywordExtractorPromptTemplate) => `${contextStr}
Give ${keywords} unique keywords for this document.
Format as comma separated.
Keywords: `;
Format as comma separated. Keywords:
`;
export const defaultTitleExtractorPromptTemplate = (
{ contextStr = "" }: DefaultPromptTemplate = {
contextStr: "",
},
) => `${contextStr}
Give a title that summarizes all of the unique entities, titles or themes found in the context.
Title: `;
Title:
`;
export const defaultTitleCombinePromptTemplate = (
{ contextStr = "" }: DefaultPromptTemplate = {
contextStr: "",
},
) => `${contextStr}
Based on the above candidate titles and contents, what is the comprehensive title for this document?
Title: `;
Title:
`;
export const defaultQuestionAnswerPromptTemplate = (
{ contextStr = "", numQuestions = 5 }: DefaultQuestionAnswerPromptTemplate = {
@@ -47,7 +55,9 @@ export const defaultQuestionAnswerPromptTemplate = (
numQuestions: 5,
},
) => `${contextStr}
Given the contextual informations, generate ${numQuestions} questions this context can provides specific answers to which are unlikely to be found else where. Higher-level summaries of surrounding context may be provideds as well.
Given the contextual informations, generate ${numQuestions} questions this context can provides specific answers to which are unlikely to be found elsewhere.Higher-level summaries of surrounding context may be provideds as well.
Try using these summaries to generate better questions that this context can answer.
`;
@@ -56,8 +66,11 @@ export const defaultSummaryExtractorPromptTemplate = (
contextStr: "",
},
) => `${contextStr}
Summarize the key topics and entities of the sections.
Summary: `;
Summary:
`;
export const defaultNodeTextTemplate = ({
metadataStr = "",
-2
View File
@@ -1,6 +1,4 @@
export * from "./BaseIndex.js";
export * from "./IndexStruct.js";
export * from "./json-to-index-struct.js";
export * from "./keyword/index.js";
export * from "./summary/index.js";
export * from "./vectorStore/index.js";
@@ -24,15 +24,9 @@ export class IndexDict extends IndexStruct {
}
toJson(): Record<string, unknown> {
const nodesDict: Record<string, unknown> = {};
for (const [key, node] of Object.entries(this.nodesDict)) {
nodesDict[key] = node.toJSON();
}
return {
...super.toJson(),
nodesDict,
nodesDict: this.nodesDict,
type: this.type,
};
}
+2 -2
View File
@@ -8,7 +8,7 @@ import {
defaultKeywordExtractPrompt,
defaultQueryKeywordExtractPrompt,
} from "../../Prompt.js";
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
import type { BaseRetriever } from "../../Retriever.js";
import type { ServiceContext } from "../../ServiceContext.js";
import { serviceContextFromDefaults } from "../../ServiceContext.js";
import { RetrieverQueryEngine } from "../../engines/query/index.js";
@@ -79,7 +79,7 @@ abstract class BaseKeywordTableRetriever implements BaseRetriever {
abstract getKeywords(query: string): Promise<string[]>;
async retrieve({ query }: RetrieveParams): Promise<NodeWithScore[]> {
async retrieve(query: string): Promise<NodeWithScore[]> {
const keywords = await this.getKeywords(query);
const chunkIndicesCount: { [key: string]: number } = {};
const filteredKeywords = keywords.filter((keyword) =>
+4 -9
View File
@@ -3,9 +3,10 @@ import { globalsHelper } from "../../GlobalsHelper.js";
import type { BaseNode, Document, NodeWithScore } from "../../Node.js";
import type { ChoiceSelectPrompt } from "../../Prompt.js";
import { defaultChoiceSelectPrompt } from "../../Prompt.js";
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
import type { BaseRetriever } from "../../Retriever.js";
import type { ServiceContext } from "../../ServiceContext.js";
import { serviceContextFromDefaults } from "../../ServiceContext.js";
import type { Event } from "../../callbacks/CallbackManager.js";
import { RetrieverQueryEngine } from "../../engines/query/index.js";
import type { BaseNodePostprocessor } from "../../postprocessors/index.js";
import type {
@@ -280,10 +281,7 @@ export class SummaryIndexRetriever implements BaseRetriever {
this.index = index;
}
async retrieve({
query,
parentEvent,
}: RetrieveParams): Promise<NodeWithScore[]> {
async retrieve(query: string, parentEvent?: Event): Promise<NodeWithScore[]> {
const nodeIds = this.index.indexStruct.nodes;
const nodes = await this.index.docStore.getNodes(nodeIds);
const result = nodes.map((node) => ({
@@ -339,10 +337,7 @@ export class SummaryIndexLLMRetriever implements BaseRetriever {
this.serviceContext = serviceContext || index.serviceContext;
}
async retrieve({
query,
parentEvent,
}: RetrieveParams): Promise<NodeWithScore[]> {
async retrieve(query: string, parentEvent?: Event): Promise<NodeWithScore[]> {
const nodeIds = this.index.indexStruct.nodes;
const results: NodeWithScore[] = [];
+12 -13
View File
@@ -11,7 +11,7 @@ import {
ObjectType,
splitNodesByType,
} from "../../Node.js";
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
import type { BaseRetriever } from "../../Retriever.js";
import type { ServiceContext } from "../../ServiceContext.js";
import { serviceContextFromDefaults } from "../../ServiceContext.js";
import type { Event } from "../../callbacks/CallbackManager.js";
@@ -24,7 +24,6 @@ import { ClipEmbedding } from "../../embeddings/index.js";
import { RetrieverQueryEngine } from "../../engines/query/RetrieverQueryEngine.js";
import { runTransformations } from "../../ingestion/index.js";
import type { BaseNodePostprocessor } from "../../postprocessors/types.js";
import { storageContextFromDefaults } from "../../storage/StorageContext.js";
import type {
BaseIndexStore,
MetadataFilters,
@@ -33,7 +32,10 @@ import type {
VectorStoreQuery,
VectorStoreQueryResult,
} from "../../storage/index.js";
import { VectorStoreQueryMode } from "../../storage/vectorStore/types.js";
import {
VectorStoreQueryMode,
storageContextFromDefaults,
} from "../../storage/index.js";
import type { BaseSynthesizer } from "../../synthesizers/types.js";
import type { BaseQueryEngine } from "../../types.js";
import type { BaseIndexInit } from "../BaseIndex.js";
@@ -426,17 +428,14 @@ export class VectorIndexRetriever implements BaseRetriever {
this.imageSimilarityTopK = imageSimilarityTopK ?? DEFAULT_SIMILARITY_TOP_K;
}
async retrieve({
query,
parentEvent,
preFilters,
}: RetrieveParams): Promise<NodeWithScore[]> {
let nodesWithScores = await this.textRetrieve(
query,
preFilters as MetadataFilters,
);
async retrieve(
query: string,
parentEvent?: Event,
preFilters?: MetadataFilters,
): Promise<NodeWithScore[]> {
let nodesWithScores = await this.textRetrieve(query, preFilters);
nodesWithScores = nodesWithScores.concat(
await this.textToImageRetrieve(query, preFilters as MetadataFilters),
await this.textToImageRetrieve(query, preFilters),
);
this.sendEvent(query, nodesWithScores, parentEvent);
return nodesWithScores;
+47 -81
View File
@@ -1,6 +1,7 @@
import type OpenAILLM from "openai";
import type { ClientOptions as OpenAIClientOptions } from "openai";
import type {
AnthropicStreamToken,
CallbackManager,
Event,
EventType,
@@ -12,7 +13,11 @@ import type { ChatCompletionMessageParam } from "openai/resources/index.js";
import type { LLMOptions } from "portkey-ai";
import { Tokenizers, globalsHelper } from "../GlobalsHelper.js";
import type { AnthropicSession } from "./anthropic.js";
import { getAnthropicSession } from "./anthropic.js";
import {
ANTHROPIC_AI_PROMPT,
ANTHROPIC_HUMAN_PROMPT,
getAnthropicSession,
} from "./anthropic.js";
import type { AzureOpenAIConfig } from "./azure.js";
import {
getAzureBaseUrl,
@@ -255,7 +260,7 @@ export class OpenAI extends BaseLLM {
stream: false,
});
const content = response.choices[0].message?.content ?? null;
const content = response.choices[0].message?.content ?? "";
const kwargsOutput: Record<string, any> = {};
@@ -608,30 +613,12 @@ If a question does not make any sense, or is not factually coherent, explain why
}
}
export const ALL_AVAILABLE_ANTHROPIC_LEGACY_MODELS = {
"claude-2.1": {
contextWindow: 200000,
},
"claude-instant-1.2": {
contextWindow: 100000,
},
};
export const ALL_AVAILABLE_V3_MODELS = {
"claude-3-opus": { contextWindow: 200000 },
"claude-3-sonnet": { contextWindow: 200000 },
};
export const ALL_AVAILABLE_ANTHROPIC_MODELS = {
...ALL_AVAILABLE_ANTHROPIC_LEGACY_MODELS,
...ALL_AVAILABLE_V3_MODELS,
// both models have 100k context window, see https://docs.anthropic.com/claude/reference/selecting-a-model
"claude-2": { contextWindow: 200000 },
"claude-instant-1": { contextWindow: 100000 },
};
const AVAILABLE_ANTHROPIC_MODELS_WITHOUT_DATE: { [key: string]: string } = {
"claude-3-opus": "claude-3-opus-20240229",
"claude-3-sonnet": "claude-3-sonnet-20240229",
} as { [key in keyof typeof ALL_AVAILABLE_ANTHROPIC_MODELS]: string };
/**
* Anthropic LLM implementation
*/
@@ -653,7 +640,7 @@ export class Anthropic extends BaseLLM {
constructor(init?: Partial<Anthropic>) {
super();
this.model = init?.model ?? "claude-3-opus";
this.model = init?.model ?? "claude-2";
this.temperature = init?.temperature ?? 0.1;
this.topP = init?.topP ?? 0.999; // Per Ben Mann
this.maxTokens = init?.maxTokens ?? undefined;
@@ -687,24 +674,21 @@ export class Anthropic extends BaseLLM {
};
}
getModelName = (model: string): string => {
if (Object.keys(AVAILABLE_ANTHROPIC_MODELS_WITHOUT_DATE).includes(model)) {
return AVAILABLE_ANTHROPIC_MODELS_WITHOUT_DATE[model];
}
return model;
};
formatMessages(messages: ChatMessage[]) {
return messages.map((message) => {
if (message.role !== "user" && message.role !== "assistant") {
throw new Error("Unsupported Anthropic role");
}
return {
content: message.content,
role: message.role,
};
});
mapMessagesToPrompt(messages: ChatMessage[]) {
return (
messages.reduce((acc, message) => {
return (
acc +
`${
message.role === "system"
? ""
: message.role === "assistant"
? ANTHROPIC_AI_PROMPT + " "
: ANTHROPIC_HUMAN_PROMPT + " "
}${message.content.trim()}`
);
}, "") + ANTHROPIC_AI_PROMPT
);
}
chat(
@@ -714,67 +698,49 @@ export class Anthropic extends BaseLLM {
async chat(
params: LLMChatParamsNonStreaming | LLMChatParamsStreaming,
): Promise<ChatResponse | AsyncIterable<ChatResponseChunk>> {
let { messages } = params;
const { parentEvent, stream } = params;
let systemPrompt: string | null = null;
const systemMessages = messages.filter(
(message) => message.role === "system",
);
if (systemMessages.length > 0) {
systemPrompt = systemMessages
.map((message) => message.content)
.join("\n");
messages = messages.filter((message) => message.role !== "system");
}
const { messages, parentEvent, stream } = params;
//Streaming
if (stream) {
return this.streamChat(messages, parentEvent, systemPrompt);
return this.streamChat(messages, parentEvent);
}
//Non-streaming
const response = await this.session.anthropic.messages.create({
model: this.getModelName(this.model),
messages: this.formatMessages(messages),
max_tokens: this.maxTokens ?? 4096,
const response = await this.session.anthropic.completions.create({
model: this.model,
prompt: this.mapMessagesToPrompt(messages),
max_tokens_to_sample: this.maxTokens ?? 100000,
temperature: this.temperature,
top_p: this.topP,
...(systemPrompt && { system: systemPrompt }),
});
return {
message: { content: response.content[0].text, role: "assistant" },
message: { content: response.completion.trimStart(), role: "assistant" },
//^ We're trimming the start because Anthropic often starts with a space in the response
// That space will be re-added when we generate the next prompt.
};
}
protected async *streamChat(
messages: ChatMessage[],
parentEvent?: Event | undefined,
systemPrompt?: string | null,
): AsyncIterable<ChatResponseChunk> {
const stream = await this.session.anthropic.messages.create({
model: this.getModelName(this.model),
messages: this.formatMessages(messages),
max_tokens: this.maxTokens ?? 4096,
temperature: this.temperature,
top_p: this.topP,
stream: true,
...(systemPrompt && { system: systemPrompt }),
});
// AsyncIterable<AnthropicStreamToken>
const stream: AsyncIterable<AnthropicStreamToken> =
await this.session.anthropic.completions.create({
model: this.model,
prompt: this.mapMessagesToPrompt(messages),
max_tokens_to_sample: this.maxTokens ?? 100000,
temperature: this.temperature,
top_p: this.topP,
stream: true,
});
let idx_counter: number = 0;
for await (const part of stream) {
const content =
part.type === "content_block_delta" ? part.delta.text : null;
if (typeof content !== "string") continue;
//TODO: LLM Stream Callback, pending re-work.
idx_counter++;
yield { delta: content };
yield { delta: part.completion };
}
return;
}

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