Compare commits

...

121 Commits

Author SHA1 Message Date
github-actions[bot] 216ba1f22b Release 0.2.11 (#765)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-04-25 17:53:17 -07:00
Marcus Schiesser 74686f5776 ci: add version to release PR (#766) 2024-04-25 10:55:02 +07:00
Marcus Schiesser 1ebf9e67a4 ci: add release action (#764) 2024-04-25 10:09:55 +07:00
Alex Yang aeefc77da0 test: load large amount of data won't cause error (#762) 2024-04-24 15:04:29 -05:00
ezirmusitua 13d8d7cbbe fix: use Array.prototype.flat (#760)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-24 14:36:12 -05:00
Alex Yang 9c34e44b85 ci: coverage node.js 22 (#761) 2024-04-24 14:19:12 -05:00
Thuc Pham cb2dc802d9 docs: update next config for external packages (#759) 2024-04-24 17:27:20 +08:00
Ziniu Yu 5a6cc0e32e feat: support jina ai embedding and reranker (#734) 2024-04-24 15:45:36 +07:00
Marcus Schiesser a63256eb84 feat: add default file metadata (#758) 2024-04-24 13:54:29 +07:00
Alex Yang 0a160b97a0 fix(docs): api generation (#756) 2024-04-23 14:24:17 -05:00
Thuc Pham 95602c7959 feat: overide generate hash function for image document (#751)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-04-23 11:56:37 +07:00
Alex Yang 20bc466ca1 chore: bump notion reader (#753) 2024-04-22 15:14:06 -05:00
Thuc Pham efb1c56ba5 fix: return buffer when loading image data (#749) 2024-04-22 15:28:19 +07:00
Alex Yang 286499388d fix: agent class should implement ChatEngine interface (#746) 2024-04-22 02:13:29 -05:00
Alex Yang 460c6574cc fix: rename ReACTAgent to ReActAgent (#748) 2024-04-22 00:57:43 -05:00
Marcus Schiesser 8b0e0e3cc8 docs: use dedicated embedding model for ollama (#745) 2024-04-22 10:40:39 +07:00
Alex Yang 87142b29fa chore: update changeset 2024-04-21 20:32:57 -05:00
Alex Yang 501b844f0f refactor: use official ollama sdk (#744) 2024-04-21 20:31:16 -05:00
Alex Yang 03157dc295 feat: use json format for tool result (#742) 2024-04-21 19:27:10 -05:00
Alex Yang ef80b684f7 chore: fix llamaindex node_modules link (#743) 2024-04-21 18:21:15 -05:00
Alex Yang 472e70feee refactor: full typed & iterator of agent worker/runner (part 3) (#728)
Fixes: https://github.com/run-llama/LlamaIndexTS/issues/692, https://github.com/run-llama/LlamaIndexTS/issues/557

Refs: https://github.com/run-llama/llama_index/blob/5a6ffe32faa75db0b4737d1e7a85e6fe4afe94af/docs/module_guides/deploying/agents/agent_runner.md
2024-04-19 17:52:36 -05:00
Alex Yang cfb90f7666 docs: update (#738) 2024-04-19 15:17:48 -05:00
Mike Fortman 2e3a287a27 refactor: astra options (#737) 2024-04-19 11:57:34 -05:00
Marcus Schiesser 635fbb8618 release 0.2.10 2024-04-19 16:14:44 +08:00
Marcus Schiesser d2d34acb31 Add streaming for replicate (Llama 3) (#735) 2024-04-19 15:09:20 +07:00
Yi Ding cf70edbede llama 3 support (#731)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-18 17:08:40 -07:00
Mike Fortman 79b7d246bd chore: update deps Astra (#733) 2024-04-18 17:55:31 -05:00
Marcus Schiesser bcc3d0b4d1 release v0.2.9 2024-04-17 13:53:31 +08:00
Marcus Schiesser 238ca86534 fix: google fonts not reachable during build 2024-04-17 13:47:11 +08:00
Marcus Schiesser 1f3efe8947 fix: ensure to use build for examples (#729) 2024-04-17 10:40:02 +07:00
yemiscale3 89324b4067 docs: Add Langtrace to observability tools (#726)
Co-authored-by: Yi Ding <yi.s.ding@gmail.com>
2024-04-16 20:13:59 -07:00
Alex Yang 8cc848aee6 docs: fix example code (#727) 2024-04-16 16:00:26 -05:00
Alex Yang cd54a7a66b docs: remove verbose (#725) 2024-04-16 15:54:40 -05:00
Marcus Schiesser dca02f7277 refactor: VectorStoreIndex: use TransformerComponent to calc embeddings (#721) 2024-04-16 10:01:26 +07:00
Marcus Schiesser b757fa9aa3 fix: type-check of modified example 2024-04-16 10:35:26 +08:00
Marcus Schiesser bc594a0674 doc: update vector index example to show source nodes 2024-04-16 10:27:34 +08:00
Alex Yang 208282d62f feat: init anthropic agent (part 2) (#719) 2024-04-15 16:22:47 -05:00
Wessel 060880abfe fix: toolretriever for Agent OpenAI broken (#718) 2024-04-15 13:45:19 -05:00
Marcus Schiesser 728b35e774 chore: remove LLM.ts (#720) 2024-04-14 23:35:15 -05:00
Alex Yang bdaa043404 feat: init claude function call (part 1) (#717) 2024-04-14 15:55:34 -05:00
Alex Yang a55cf8d870 fix: type import 2024-04-14 01:30:54 -05:00
Alex Yang cf4244fd3a chore: put eslint into top level (#716) 2024-04-13 20:39:27 -05:00
Marcus Schiesser 76c3fd64ad feat: add scores to source nodes (#714) 2024-04-12 09:28:46 -07:00
Marcus Schiesser 701e0ac2be release 0.2.8 2024-04-12 12:43:45 +08:00
Alex Yang a285f8ba3a feat: improve ToolsFactory type (#713) 2024-04-11 21:26:14 -05:00
Alex Yang 663821cdf6 test: add openai agent stream chat (#712) 2024-04-11 19:21:02 -05:00
Alex Yang c4b95494ac fix: memory type (#711) 2024-04-11 18:11:33 -05:00
Marcus Schiesser 980fb4e5a3 release llamaindex@0.2.7 2024-04-11 14:57:01 +08:00
Alex Yang 96f8f40291 fix: agent stream (#710) 2024-04-10 23:22:11 -05:00
Alex Yang 1c698df6e0 fix: package.json version 2024-04-10 19:49:16 -05:00
Alex Yang 298cb433be feat: improve base tool type (#709) 2024-04-10 19:40:47 -05:00
Yi Ding 63af7dd99d Fix protobuf (#708) 2024-04-10 17:20:32 -07:00
Alex Yang af5df1d083 feat: add llm-stream event (#707) 2024-04-10 09:26:26 -05:00
Marcus Schiesser a3b44093c2 fix: agent streaming with new OpenAI models (#706)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-10 08:38:54 -05:00
Alex Yang c80bf3311f fix: response.raw should be null (#705) 2024-04-10 02:54:36 -05:00
Alex Yang 7940d249b0 test: coverage on mock mode (#704) 2024-04-10 02:40:37 -05:00
Marcus Schiesser 4a07c81f71 release llamaindex@0.2.5 2024-04-10 15:01:10 +08:00
Marcus Schiesser 7d56cdf045 fix: Allow OpenAIAgent to be called without tools (#703) 2024-04-10 13:43:38 +07:00
Marcus Schiesser 0affe621d5 ci: update pnpm lockfile after updating package.json from edge 2024-04-10 11:46:01 +08:00
Alex Yang 93932b1a9c refactor: chat message type (#701) 2024-04-09 21:56:47 -05:00
Yi Ding a87f13b9d2 release 2024-04-09 16:23:29 -07:00
Yi Ding 8d2b21ee75 update mistral (#700) 2024-04-09 16:19:51 -07:00
Yi Ding 87741c9be8 update example packages 2024-04-09 13:22:03 -07:00
Yi Ding 171cb89170 security update (docs) 2024-04-09 13:17:44 -07:00
Yi Ding 5dad867bbe update packages 2024-04-09 13:04:43 -07:00
Yi Ding 13f26fd84d pnpm version 2024-04-09 12:45:12 -07:00
Yi Ding 3bc77f7d7f gpt-4-turbo GA (#698) 2024-04-09 12:42:16 -07:00
Alex Yang aac1ee3af3 e2e: init llamaindex e2e test (#697) 2024-04-06 23:57:21 -05:00
Alex Yang e85893ac0f fix: message content type (#696) 2024-04-06 18:59:12 -05:00
Alex Yang 315947ee6f refactor: move anthropic class (#695) 2024-04-06 17:13:53 -05:00
Alex Yang 23a0d44b11 fix: jsr disallow global type 2024-04-06 17:09:39 -05:00
Alex Yang 3b501de057 chore: jsr release 2024-04-06 17:04:20 -05:00
Alex Yang 6cc645aa2a refactor: improve agent type (#694) 2024-04-05 15:21:49 -05:00
Marcus Schiesser 0b37207adc Release llamaindex@0.2.3 2024-04-05 15:15:39 +08:00
Marcus Schiesser f0704ec705 Add streaming for OpenAI agents (#693) 2024-04-05 12:53:26 +07:00
Thuc Pham 4fcbdf710e Add tool calls for openai streaming (#682)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-05 08:33:23 +07:00
Marcus Schiesser 866149193a fix: use LLM's context window to specify agent's token limit (#689) 2024-04-03 17:04:35 -05:00
Thuc Pham 6ffb161618 feat: add ts eslint plugin (#688) 2024-04-03 14:21:13 +07:00
Marcus Schiesser 8e4b49824b doc: document docstore strategies (#690) 2024-04-03 13:26:38 +07:00
Alex Yang 5263576de1 ci: test matrix on nodejs 18/20/21 (#687) 2024-04-02 17:23:11 -05:00
WarlaxZ 6d4e2ea0e9 fix: dynamic import cjs module pg (#685)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-02 16:07:13 -05:00
Emanuel Ferreira 3cbfa98e6b feat: LlamaCloudIndex from documents (#677) 2024-04-02 14:03:45 -03:00
Alex Yang d256cbe0e0 refactor: use event.reason, remove parentEvent (#681) 2024-04-01 17:03:39 -07:00
Alex Yang a6dfa30dcf RELEASING: Releasing 3 package(s) 2024-04-01 14:34:40 -05:00
Alex Yang d0365dc434 fix: docs dependencies (#680) 2024-04-01 14:19:37 -05:00
Alex Yang aa41432bbb refactor: remove llm.tokens api (#679) 2024-04-01 14:12:17 -05:00
Emanuel Ferreira 98a2b4a547 feat: add global settings (#668)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-01 13:43:35 -05:00
Benny 806ce9a360 fix: README links and examples (#678) 2024-04-01 13:16:10 -05:00
Marcus Schiesser 8b28092cc8 feat: Add doc store strategies to VectorStoreIndex.fromDocuments (#646) 2024-04-01 10:12:08 -07:00
Marcus Schiesser 5c5f4c1c84 Revert "feat: support calculate llama 2 tokens (#676)"
This reverts commit 041acd11fe.
2024-04-01 13:52:07 +08:00
Marcus Schiesser 949d330295 fix: typecheck 2024-04-01 12:26:22 +08:00
Marcus Schiesser 9a5ee4f37a Revert "fix: support import subdirectory (#655)"
This reverts commit 98d4cbdf95.
2024-04-01 11:52:41 +08:00
Alex Yang 7a23cc6c84 feat: improve callback manager (#675) 2024-03-31 15:34:48 -05:00
Alex Yang 041acd11fe feat: support calculate llama 2 tokens (#676) 2024-03-29 20:12:26 -05:00
Emanuel Ferreira 24b4033db9 feat: add result type json (#673) 2024-03-28 16:24:33 -03:00
Emanuel Ferreira 1115f83b8f fix: pipeline not found (#672) 2024-03-28 15:31:18 -03:00
Thuc Pham 60a1603636 fix: make edge run build after core (#670) 2024-03-28 18:26:35 +08:00
Peter Goldstein ea467fa031 Update to latest supported version list as of 2024-04-02. (#669) 2024-03-28 10:53:33 +07:00
Marcus Schiesser b0e6f73b1d docs: update readme for Edge runtime 2024-03-26 15:18:19 +08:00
Marcus Schiesser 6d9e015b5e feat: use claude3 with react agent (#661)
Co-authored-by: Emanuel Ferreira <contatoferreirads@gmail.com>
2024-03-22 09:25:31 -03:00
Thuc Pham fececd89ab feat: add tool factory (#663) 2024-03-22 14:40:41 +07:00
Marcus Schiesser 48e287892f test: use unique tmp dir for storage tests and wait to clean VectorStoreIndex files 2024-03-21 13:04:25 +07:00
Marcus Schiesser f118400820 docs: Add changeset instructions for PRs 2024-03-20 11:45:33 +07:00
Marcus Schiesser 3f8407c7af docs: changeset for pipeline.register added 2024-03-20 10:20:30 +07:00
Marcus Schiesser 83317739c7 feat: add pipeline.register (#589) 2024-03-19 13:32:32 -07:00
Thuc Pham 0b665bd1ca feat: add wikipedia tool (#648)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-03-19 11:31:08 +07:00
Alex Yang 98d4cbdf95 fix: support import subdirectory (#655) 2024-03-18 21:00:46 -05:00
Marcus Schiesser 6cb75b54a0 docs: update release process 2024-03-18 16:22:59 +07:00
Marcus Schiesser 53edfe93cf release llamaindex@0.2.1 2024-03-18 16:17:58 +07:00
Marcus Schiesser b856deae43 fix: fix syncing edge with core version 2024-03-18 15:53:31 +07:00
Marcus Schiesser 259c842259 Support NextJS edge runtime (#618) 2024-03-18 15:13:27 +07:00
shodevacc ffb195ea7a Fix: Metadata filters doesn't seem to work for Qdrant (#623) 2024-03-18 11:53:51 +07:00
Alex Yang b4677534d1 ci: install node_modules (#653) 2024-03-18 12:49:28 +08:00
Peli de Halleux f967b82467 [docs] missing await in sample (#650) 2024-03-15 16:23:27 -03:00
Marcus Schiesser c81946930e test: fix openai mock 2024-03-15 15:20:57 +07:00
Marcus Schiesser 1008b775a4 test: cleaned up tests and added test to ignore duplicates 2024-03-15 12:05:58 +07:00
Huu Le (Lee) 41210dfc51 feat: Add auto create collection and node metadata for Milvus vector store (#645) 2024-03-15 10:46:25 +07:00
Emanuel Ferreira 67b7272249 feat: expected minor version (#644) 2024-03-14 09:34:21 -03:00
Marcus Schiesser 964e045903 feat: add support for snapshots 2024-03-14 10:23:58 +07:00
Marcus Schiesser 137cf67f40 fix: Use Pinecone namespaces for all operations (#633) 2024-03-14 10:15:52 +07:00
Emanuel Ferreira 309a526e3c RELEASING: Releasing 5 package(s) (#643) 2024-03-13 22:17:27 -03:00
353 changed files with 26030 additions and 16314 deletions
-6
View File
@@ -1,6 +0,0 @@
---
"llamaindex": patch
"examples": patch
---
add support for Milvus vector store
-5
View File
@@ -1,5 +0,0 @@
---
"llamaindex": patch
---
feat: experimental package + json query engine
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": true,
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
-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
@@ -1,5 +0,0 @@
---
"llamaindex": patch
---
Add streaming to agents
-5
View File
@@ -1,5 +0,0 @@
---
"llamaindex": patch
---
add Claude Haiku support and update anthropic SDK
-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 -2
View File
@@ -1,9 +1,13 @@
{
"jsc": {
"parser": {
"syntax": "typescript"
"syntax": "typescript",
"decorators": true
},
"target": "esnext"
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
},
"module": {
"type": "commonjs",
+76
View File
@@ -0,0 +1,76 @@
module.exports = {
root: true,
extends: [
"turbo",
"prettier",
"plugin:@typescript-eslint/recommended-type-checked-only",
],
parserOptions: {
project: true,
__tsconfigRootDir: __dirname,
},
settings: {
react: {
version: "999.999.999",
},
},
rules: {
"max-params": ["error", 4],
"prefer-const": "error",
"@typescript-eslint/no-floating-promises": [
"error",
{
ignoreIIFE: true,
},
],
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/ban-types": "off",
"no-array-constructor": "off",
"@typescript-eslint/no-array-constructor": "off",
"@typescript-eslint/no-base-to-string": "off",
"@typescript-eslint/no-duplicate-enum-values": "off",
"@typescript-eslint/no-duplicate-type-constituents": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-extra-non-null-assertion": "off",
"@typescript-eslint/no-for-in-array": "off",
"no-implied-eval": "off",
"@typescript-eslint/no-implied-eval": "off",
"no-loss-of-precision": "off",
"@typescript-eslint/no-loss-of-precision": "off",
"@typescript-eslint/no-misused-new": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-non-null-asserted-optional-chain": "off",
"@typescript-eslint/no-redundant-type-constituents": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-unnecessary-type-assertion": "off",
"@typescript-eslint/no-unnecessary-type-constraint": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-declaration-merging": "off",
"@typescript-eslint/no-unsafe-enum-comparison": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/prefer-as-const": "off",
"require-await": "off",
"@typescript-eslint/require-await": "off",
"@typescript-eslint/restrict-plus-operands": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/triple-slash-reference": "off",
"@typescript-eslint/unbound-method": "off",
},
overrides: [
{
files: ["examples/**/*.ts"],
rules: {
"turbo/no-undeclared-env-vars": "off",
},
},
],
ignorePatterns: ["dist/", "lib/", "deps/"],
};
-23
View File
@@ -1,23 +0,0 @@
module.exports = {
root: true,
// This tells ESLint to load the config from the package `eslint-config-custom`
extends: ["custom"],
settings: {
next: {
rootDir: ["apps/*/"],
},
},
rules: {
"max-params": ["error", 4],
"prefer-const": "error",
},
overrides: [
{
files: ["examples/**/*.ts"],
rules: {
"turbo/no-undeclared-env-vars": "off",
},
},
],
ignorePatterns: ["dist/", "lib/"],
};
+1 -3
View File
@@ -13,9 +13,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: latest
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
+8
View File
@@ -14,6 +14,14 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Publish @llamaindex/env
run: npx jsr publish
+57
View File
@@ -0,0 +1,57 @@
name: Release
on:
push:
branches:
- main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Add auth token to .npmrc file
run: |
cat << EOF >> ".npmrc"
//registry.npmjs.org/:_authToken=$NPM_TOKEN
EOF
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Get changeset status
id: get-changeset-status
run: |
pnpm changeset status --output .changeset/status.json
new_version=$(jq -r '.releases[] | select(.name == "llamaindex") | .newVersion' < .changeset/status.json)
rm -v .changeset/status.json
echo "new-version=${new_version}" >> "$GITHUB_OUTPUT"
- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
with:
commit: Release ${{ steps.get-changeset-status.outputs.new-version }}
title: Release ${{ steps.get-changeset-status.outputs.new-version }}
# update version PR with the latest changesets
version: pnpm new-version
# build package and call changeset publish
publish: pnpm release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+63 -5
View File
@@ -1,18 +1,55 @@
name: Run Tests
on: [push, pull_request]
on:
push:
branches:
- main
pull_request:
branches:
- main
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
e2e:
strategy:
fail-fast: false
matrix:
node-version: [18.x, 20.x, 22.x]
name: E2E on Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Run E2E Tests
run: pnpm run e2e
test:
strategy:
fail-fast: false
matrix:
node-version: [18.x, 20.x, 22.x]
name: Test on Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
node-version: ${{ matrix.node-version }}
cache: "pnpm"
- name: Install dependencies
run: pnpm install
@@ -23,7 +60,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -33,6 +70,9 @@ jobs:
run: pnpm install
- name: Build
run: pnpm run build --filter llamaindex
- name: Use Build For Examples
run: pnpm link ../packages/core/
working-directory: ./examples
- name: Run Type Check
run: pnpm run type-check
- name: Run Circular Dependency Check
@@ -44,12 +84,30 @@ jobs:
name: typecheck-build-dist
path: ./packages/core/dist
if-no-files-found: error
core-edge-runtime:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm run build --filter @llamaindex/edge
- name: Build Edge Runtime
run: pnpm run build
working-directory: ./packages/edge/e2e/test-edge-runtime
typecheck-examples:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
+3
View File
@@ -1,2 +1,5 @@
auto-install-peers = true
enable-pre-post-scripts = true
prefer-workspace-packages = true
save-workspace-protocol = true
link-workspace-packages = true
+6 -2
View File
@@ -1,8 +1,12 @@
{
"jsc": {
"parser": {
"syntax": "typescript"
"syntax": "typescript",
"decorators": true
},
"target": "esnext"
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
}
}
+2 -1
View File
@@ -10,8 +10,9 @@
"name": "Debug Example",
"skipFiles": ["<node_internals>/**"],
"runtimeExecutable": "pnpm",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}/examples",
"runtimeArgs": ["ts-node", "${fileBasename}"]
"runtimeArgs": ["npx", "tsx", "${file}"]
}
]
}
+16 -7
View File
@@ -79,13 +79,22 @@ That should start a webserver which will serve the docs on https://localhost:300
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
## Publishing
## Changeset
To publish a new version of the library, run
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run:
```shell
pnpm new-version
pnpm release
git push # push to the main branch
git push --tags
```
pnpm changeset
```
Please send a descriptive changeset for each PR.
## Publishing (maintainers only)
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
PR called "Release {version}".
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
the current changesets in the [.changeset](.changeset/) folder.
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
-81
View File
@@ -1,81 +0,0 @@
# Turborepo starter
This is an official starter Turborepo.
## Using this example
Run the following command:
```sh
npx create-turbo@latest
```
## What's inside?
This Turborepo includes the following packages/apps:
### Apps and Packages
- `docs`: a [Next.js](https://nextjs.org/) app
- `web`: another [Next.js](https://nextjs.org/) app
- `ui`: a stub React component library shared by both `web` and `docs` applications
- `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
- `tsconfig`: `tsconfig.json`s used throughout the monorepo
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
### Utilities
This Turborepo has some additional tools already setup for you:
- [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting
- [Prettier](https://prettier.io) for code formatting
### Build
To build all apps and packages, run the following command:
```
cd my-turborepo
pnpm build
```
### Develop
To develop all apps and packages, run the following command:
```
cd my-turborepo
pnpm dev
```
### Remote Caching
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
```
cd my-turborepo
npx turbo login
```
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
```
npx turbo link
```
## Useful Links
Learn more about the power of Turborepo:
- [Tasks](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
- [Caching](https://turbo.build/repo/docs/core-concepts/caching)
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)
- [Configuration Options](https://turbo.build/repo/docs/reference/configuration)
- [CLI Usage](https://turbo.build/repo/docs/reference/command-line-reference)
+75 -47
View File
@@ -83,37 +83,52 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
- [Node](/packages/core/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
- [Embedding](/packages/core/src/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
- [Embedding](/packages/core/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/core/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/core/src/embeddings)).
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
- [QueryEngine](/packages/core/src/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
- [QueryEngine](/packages/core/src/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/core/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/core/src/engines/query).
- [ChatEngine](/packages/core/src/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
- [ChatEngine](/packages/core/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/core/src/engines/chat).
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
## Note: NextJS:
## Using NextJS
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the following config to your next.config.js to have it use imports/exports in the same way Node does.
If you're using the NextJS App Router, you can choose between the Node.js and the [Edge runtime](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#edge-runtime).
```js
export const runtime = "nodejs"; // default
With NextJS 13 and 14, using the Node.js runtime is the default. You can explicitly set the Edge runtime in your [router handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) by adding this line:
```typescript
export const runtime = "edge";
```
The following sections explain further differences in using the Node.js or Edge runtime.
### Using the Node.js runtime
Add the following config to your `next.config.js` to ignore specific packages in the server-side bundling:
```js
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverComponentsExternalPackages: ["pdf2json"],
serverComponentsExternalPackages: [
"pdf2json",
"@zilliz/milvus2-sdk-node",
"sharp",
"onnxruntime-node",
],
},
webpack: (config) => {
config.resolve.alias = {
...config.resolve.alias,
sharp$: false,
"onnxruntime-node$": false,
};
config.externals.push({
pdf2json: "commonjs pdf2json",
"@zilliz/milvus2-sdk-node": "commonjs @zilliz/milvus2-sdk-node",
sharp: "commonjs sharp",
"onnxruntime-node": "commonjs onnxruntime-node",
});
return config;
},
};
@@ -121,48 +136,61 @@ const nextConfig = {
module.exports = nextConfig;
```
### NextJS with Milvus:
### Using the Edge runtime
As proto files are not loaded per default in NextJS, you'll need to add the following to your next.config.js to have it load the proto files.
We publish a dedicated package (`@llamaindex/edge` instead of `llamaindex`) for using the Edge runtime. To use it, first install the package:
```js
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (config, { isServer }) => {
if (isServer) {
// Copy the proto files to the server build directory
config.plugins.push(
new CopyWebpackPlugin({
patterns: [
{
from: path.join(
__dirname,
"node_modules/@zilliz/milvus2-sdk-node/dist",
),
to: path.join(__dirname, ".next"),
},
],
}),
);
}
// Important: return the modified config
return config;
},
};
module.exports = nextConfig;
```shell
pnpm install @llamaindex/edge
```
> _Note_: Ensure that your `package.json` doesn't include the `llamaindex` package if you're using `@llamaindex/edge`.
Then make sure to use the correct import statement in your code:
```typescript
// replace 'llamaindex' with '@llamaindex/edge'
import {} from "@llamaindex/edge";
```
A further difference is that the `@llamaindex/edge` package doesn't export classes from the `readers` or `storage` folders. The reason is that most of these classes are not compatible with the Edge runtime.
If you need any of those classes, you have to import them instead directly. Here's an example for importing the `PineconeVectorStore` class:
```typescript
import { PineconeVectorStore } from "@llamaindex/edge/storage/vectorStore/PineconeVectorStore";
```
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
```typescript
import { SimpleDirectoryReader } from "@llamaindex/edge/readers/SimpleDirectoryReader";
import { LlamaParseReader } from "@llamaindex/edge/readers/LlamaParseReader";
export const DATA_DIR = "./data";
export async function getDocuments() {
const reader = new SimpleDirectoryReader();
// Load PDFs using LlamaParseReader
return await reader.loadData({
directoryPath: DATA_DIR,
fileExtToReader: {
pdf: new LlamaParseReader({ resultType: "markdown" }),
},
});
}
```
> _Note_: Reader classes have to be added explictly to the `fileExtToReader` map in the Edge version of the `SimpleDirectoryReader`.
You'll find a complete example of using the Edge runtime with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
## Supported LLMs:
- OpenAI GPT-3.5-turbo and GPT-4
- Anthropic Claude Instant and Claude 2
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
- Groq LLMs
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
- Llama2/3 Chat LLMs (70B, 13B, and 7B parameters)
- MistralAI Chat LLMs
- Fireworks Chat LLMs
+9
View File
@@ -1,5 +1,14 @@
# docs
## 0.0.5
### Patch Changes
- Updated dependencies [87142b2]
- Updated dependencies [5a6cc0e]
- Updated dependencies [87142b2]
- llamaindex@0.2.11
## 0.0.4
### Patch Changes
+3 -78
View File
@@ -4,82 +4,7 @@ A built-in agent that can take decisions and reasoning based on the tools provid
## OpenAI Agent
```ts
import { FunctionTool, OpenAIAgent } from "llamaindex";
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/agent/openai";
// 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"],
};
// Define the parameters of the divide function as a JSON schema
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend to divide",
},
b: {
type: "number",
description: "The divisor to divide by",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const divideFunctionTool = 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: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+7 -1
View File
@@ -11,4 +11,10 @@ An “agent” is an automated reasoning and decision engine. It takes in a user
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
- [OpenAI Agent](./openai.mdx)
- OpenAI Agent
- Anthropic Agent
- ReACT Agent
## Examples
- [OpenAI Agent](../../examples/agent.mdx)
@@ -1,314 +0,0 @@
# Multi-Document Agent
In this guide, you learn towards setting up an agent that can effectively answer different types of questions over a larger set of documents.
These questions include the following
- QA over a specific doc
- QA comparing different docs
- Summaries over a specific doc
- Comparing summaries between different docs
We do this with the following architecture:
- setup a “document agent” over each Document: each doc agent can do QA/summarization within its doc
- setup a top-level agent over this set of document agents. Do tool retrieval and then do CoT over the set of tools to answer a question.
## Setup and Download Data
We first start by installing the necessary libraries and downloading the data.
```bash
pnpm i llamaindex
```
```ts
import {
Document,
ObjectIndex,
OpenAI,
OpenAIAgent,
QueryEngineTool,
SimpleNodeParser,
SimpleToolNodeMapping,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
```
And then for the data we will run through a list of countries and download the wikipedia page for each country.
```ts
import fs from "fs";
import path from "path";
const dataPath = path.join(__dirname, "tmp_data");
const extractWikipediaTitle = async (title: string) => {
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
if (fileExists) {
console.log(`File already exists for the title: ${title}`);
return;
}
const queryParams = new URLSearchParams({
action: "query",
format: "json",
titles: title,
prop: "extracts",
explaintext: "true",
});
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
const response = await fetch(url);
const data: any = await response.json();
const pages = data.query.pages;
const page = pages[Object.keys(pages)[0]];
const wikiText = page.extract;
await new Promise((resolve) => {
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
if (err) {
console.error(err);
resolve(title);
return;
}
console.log(`${title} stored in file!`);
resolve(title);
});
});
};
```
```ts
export const extractWikipedia = async (titles: string[]) => {
if (!fs.existsSync(dataPath)) {
fs.mkdirSync(dataPath);
}
for await (const title of titles) {
await extractWikipediaTitle(title);
}
console.log("Extration finished!");
```
These files will be saved in the `tmp_data` folder.
Now we can call the function to download the data for each country.
```ts
await extractWikipedia([
"Brazil",
"United States",
"Canada",
"Mexico",
"Argentina",
"Chile",
"Colombia",
"Peru",
"Venezuela",
"Ecuador",
"Bolivia",
"Paraguay",
"Uruguay",
"Guyana",
"Suriname",
"French Guiana",
"Falkland Islands",
]);
```
## Load the data
Now that we have the data, we can load it into the LlamaIndex and store as a document.
```ts
import { Document } from "llamaindex";
const countryDocs: Record<string, Document> = {};
for (const title of wikiTitles) {
const path = `./agent/helpers/tmp_data/${title}.txt`;
const text = await fs.readFile(path, "utf-8");
const document = new Document({ text: text, id_: path });
countryDocs[title] = document;
}
```
## Setup LLM and StorageContext
We will be using gpt-4 for this example and we will use the `StorageContext` to store the documents in-memory.
```ts
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({ llm });
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
```
## Building Multi-Document Agents
In this section we show you how to construct the multi-document agent. We first build a document agent for each document, and then define the top-level parent agent with an object index.
```ts
const documentAgents: Record<string, any> = {};
const queryEngines: Record<string, any> = {};
```
Now we iterate over each country and create a document agent for each one.
### Build Agent for each Document
In this section we define “document agents” for each document.
We define both a vector index (for semantic search) and summary index (for summarization) for each document. The two query engines are then converted into tools that are passed to an OpenAI function calling agent.
This document agent can dynamically choose to perform semantic search or summarization within a given document.
We create a separate document agent for each coutnry.
```ts
for (const title of wikiTitles) {
// parse the document into nodes
const nodes = new SimpleNodeParser({
chunkSize: 200,
chunkOverlap: 20,
}).getNodesFromDocuments([countryDocs[title]]);
// create the vector index for specific search
const vectorIndex = await VectorStoreIndex.init({
serviceContext: serviceContext,
storageContext: storageContext,
nodes,
});
// create the summary index for broader search
const summaryIndex = await SummaryIndex.init({
serviceContext: serviceContext,
nodes,
});
const vectorQueryEngine = summaryIndex.asQueryEngine();
const summaryQueryEngine = summaryIndex.asQueryEngine();
// create the query engines for each task
const queryEngineTools = [
new QueryEngineTool({
queryEngine: vectorQueryEngine,
metadata: {
name: "vector_tool",
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
},
}),
new QueryEngineTool({
queryEngine: summaryQueryEngine,
metadata: {
name: "summary_tool",
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
},
}),
];
// create the document agent
const agent = new OpenAIAgent({
tools: queryEngineTools,
llm,
verbose: true,
});
documentAgents[title] = agent;
queryEngines[title] = vectorIndex.asQueryEngine();
}
```
## Build Top-Level Agent
Now we define the top-level agent that can answer questions over the set of document agents.
This agent takes in all document agents as tools. This specific agent RetrieverOpenAIAgent performs tool retrieval before tool use (unlike a default agent that tries to put all tools in the prompt).
Here we use a top-k retriever, but we encourage you to customize the tool retriever method!
Firstly, we create a tool for each document agent
```ts
const allTools: QueryEngineTool[] = [];
```
```ts
for (const title of wikiTitles) {
const wikiSummary = `
This content contains Wikipedia articles about ${title}.
Use this tool if you want to answer any questions about ${title}
`;
const docTool = new QueryEngineTool({
queryEngine: documentAgents[title],
metadata: {
name: `tool_${title}`,
description: wikiSummary,
},
});
allTools.push(docTool);
}
```
Our top level agent will use this document agents as tools and use toolRetriever to retrieve the best tool to answer a question.
```ts
// map the tools to nodes
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
// create the object index
const objectIndex = await ObjectIndex.fromObjects(
allTools,
toolMapping,
VectorStoreIndex,
{
serviceContext,
storageContext,
},
);
// create the top agent
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm,
verbose: true,
prefixMessages: [
{
content:
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
role: "system",
},
],
});
```
## Use the Agent
Now we can use the agent to answer questions.
```ts
const response = await topAgent.chat({
message: "Tell me the differences between Brazil and Canada economics?",
});
// print output
console.log(response);
```
You can find the full code for this example [here](https://github.com/run-llama/LlamaIndexTS/tree/main/examples/agent/multi-document-agent.ts)
-187
View File
@@ -1,187 +0,0 @@
---
sidebar_position: 0
---
# OpenAI Agent
OpenAI API that supports function calling, its never been easier to build your own agent!
In this notebook tutorial, we showcase how to write your own OpenAI agent
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
Then we can define a function to sum two numbers and another function to divide two numbers.
```ts
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;
}
```
## Create a function tool
Now we can create a function tool from the sum function and another function tool from the divide function.
For the parameters of the sum function, we can define a JSON schema.
### JSON Schema
```ts
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"],
};
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
```
## Create an OpenAIAgent
Now we can create an OpenAIAgent with the function tools.
```ts
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
console.log(String(response));
```
## Full code
```ts
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"],
};
// Define the parameters of the divide function as a JSON schema
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The argument a to divide",
},
b: {
type: "number",
description: "The argument b to divide",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const divideFunctionTool = 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: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
@@ -1,132 +0,0 @@
---
sidebar_position: 1
---
# OpenAI Agent + QueryEngineTool
QueryEngineTool is a tool that allows you to query a vector index. In this example, we will create a vector index from a set of documents and then create a QueryEngineTool from the vector index. We will then create an OpenAIAgent with the QueryEngineTool and chat with the agent.
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
Then you can import the necessary classes and functions.
```ts
import {
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
```
## Create a vector index
Now we can create a vector index from a set of documents.
```ts
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples/",
});
// Create a vector index from the documents
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
```
## Create a QueryEngineTool
Now we can create a QueryEngineTool from the vector index.
```ts
// Create a query engine from the vector index
const abramovQueryEngine = vectorIndex.asQueryEngine();
// Create a QueryEngineTool with the query engine
const queryEngineTool = new QueryEngineTool({
queryEngine: abramovQueryEngine,
metadata: {
name: "abramov_query_engine",
description: "A query engine for the Abramov documents",
},
});
```
## Create an OpenAIAgent
```ts
// Create an OpenAIAgent with the query engine tool tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "What was his salary?",
});
console.log(String(response));
```
## Full code
```ts
import {
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
async function main() {
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples/",
});
// Create a vector index from the documents
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
// Create a query engine from the vector index
const abramovQueryEngine = vectorIndex.asQueryEngine();
// Create a QueryEngineTool with the query engine
const queryEngineTool = new QueryEngineTool({
queryEngine: abramovQueryEngine,
metadata: {
name: "abramov_query_engine",
description: "A query engine for the Abramov documents",
},
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "What was his salary?",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
@@ -1,203 +0,0 @@
# ReAct Agent
The ReAct agent is an AI agent that can reason over the next action, construct an action command, execute the action, and repeat these steps in an iterative loop until the task is complete.
In this notebook tutorial, we showcase how to write your ReAct agent using the `llamaindex` package.
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
And then you can import the `OpenAIAgent` and `FunctionTool` from the `llamaindex` package.
```ts
import { FunctionTool, OpenAIAgent } from "llamaindex";
```
Then we can define a function to sum two numbers and another function to divide two numbers.
```ts
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;
}
```
## Create a function tool
Now we can create a function tool from the sum function and another function tool from the divide function.
For the parameters of the sum function, we can define a JSON schema.
### JSON Schema
```ts
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"],
};
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
```
## Create an ReAct
Now we can create an OpenAIAgent with the function tools.
```ts
const agent = new ReActAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
console.log(String(response));
```
The output will be:
```bash
Thought: I need to use a tool to help me answer the question.
Action: sumNumbers
Action Input: {"a":5,"b":5}
Observation: 10
Thought: I can answer without using any more tools.
Answer: The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
```
## Full code
```ts
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"],
};
// Define the parameters of the divide function as a JSON schema
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The argument a to divide",
},
b: {
type: "number",
description: "The argument b to divide",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const divideFunctionTool = 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: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "I want to sum 5 and 5 and then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
@@ -3,17 +3,14 @@
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
```ts
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
import { HuggingFaceEmbedding, Settings } from "llamaindex";
const huggingFaceEmbeds = new HuggingFaceEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
// Update Embed Model
Settings.embedModel = new HuggingFaceEmbedding();
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
@@ -29,8 +26,8 @@ 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({
```ts
Settings.embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
});
@@ -0,0 +1,21 @@
# Jina AI
To use Jina AI embeddings, you need to import `JinaAIEmbedding` from `llamaindex`.
```ts
import { JinaAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new JinaAIEmbedding();
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -3,21 +3,16 @@
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
```ts
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
import { MistralAIEmbedding, Settings } from "llamaindex";
const mistralEmbedModel = new MistralAIEmbedding({
// Update Embed Model
Settings.embedModel = new MistralAIEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: mistralEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
@@ -1,21 +1,23 @@
# Ollama
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
To use Ollama embeddings, you need to import `OllamaEmbedding` from `llamaindex`.
Note that you need to pull the embedding model first before using it.
In the example below, we're using the [`nomic-embed-text`](https://ollama.com/library/nomic-embed-text) model, so you have to call:
```shell
ollama pull nomic-embed-text
```
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
import { OllamaEmbedding, Settings } from "llamaindex";
const ollamaEmbedModel = new Ollama();
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaEmbedModel,
});
Settings.embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
@@ -3,19 +3,13 @@
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
```ts
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
import { OpenAIEmbedding, Settings } from "llamaindex";
const openaiEmbedModel = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({
embedModel: openaiEmbedModel,
});
Settings.embedModel = new OpenAIEmbedding();
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
@@ -3,21 +3,15 @@
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
```ts
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
import { TogetherEmbedding, Settings } from "llamaindex";
const togetherEmbedModel = new TogetherEmbedding({
Settings.embedModel = new TogetherEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: togetherEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
+5 -6
View File
@@ -2,14 +2,14 @@
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
This can be explicitly set in the `ServiceContext` object.
This can be explicitly updated through `Settings`
```typescript
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
import { OpenAIEmbedding, Settings } from "llamaindex";
const openaiEmbeds = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
Settings.embedModel = new OpenAIEmbedding({
model: "text-embedding-ada-002",
});
```
## Local Embedding
@@ -19,4 +19,3 @@ For local embeddings, you can use the [HuggingFace](./available_embeddings/huggi
## API Reference
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
- [ServiceContext](../../api/interfaces//ServiceContext.md)
@@ -21,23 +21,15 @@ export OPENAI_API_KEY=your-api-key
Import the required modules:
```ts
import {
CorrectnessEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
const llm = new OpenAI({
Settings.llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
```ts
@@ -49,9 +41,7 @@ const response = ` Certainly! Albert Einstein's theory of relativity consists of
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.
`;
const evaluator = new CorrectnessEvaluator({
serviceContext: ctx,
});
const evaluator = new CorrectnessEvaluator();
const result = await evaluator.evaluateResponse({
query,
@@ -28,20 +28,16 @@ import {
FaithfulnessEvaluator,
OpenAI,
VectorStoreIndex,
serviceContextFromDefaults,
Settings,
} from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
const llm = new OpenAI({
Settings.llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
@@ -63,9 +59,7 @@ Now, let's evaluate the response:
```ts
const query = "How did New York City get its name?";
const evaluator = new FaithfulnessEvaluator({
serviceContext: ctx,
});
const evaluator = new FaithfulnessEvaluator();
const response = await queryEngine.query({
query,
@@ -21,23 +21,15 @@ export OPENAI_API_KEY=your-api-key
Import the required modules:
```ts
import {
RelevancyEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
import { RelevancyEvaluator, OpenAI, Settings } from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
const llm = new OpenAI({
Settings.llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
@@ -59,6 +51,8 @@ const response = await queryEngine.query({
query,
});
const evaluator = new RelevancyEvaluator();
const result = await evaluator.evaluateResponse({
query,
response: response,
@@ -3,13 +3,11 @@
## Usage
```ts
import { Anthropic, serviceContextFromDefaults } from "llamaindex";
import { Anthropic, Settings } from "llamaindex";
const anthropicLLM = new Anthropic({
Settings.llm = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
```
## Load and index documents
@@ -19,9 +17,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -39,28 +35,17 @@ const results = await queryEngine.query({
## Full Example
```ts
import {
Anthropic,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { Anthropic, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
async function main() {
// Create an instance of the Anthropic LLM
const anthropicLLM = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// Create a query engine
const queryEngine = index.asQueryEngine({
@@ -15,11 +15,9 @@ export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
## Usage
```ts
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
import { OpenAI, Settings } from "llamaindex";
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
```
## Load and index documents
@@ -29,9 +27,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -49,26 +45,15 @@ const results = await queryEngine.query({
## Full Example
```ts
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
async function main() {
// Create an instance of the LLM
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
@@ -5,13 +5,11 @@ Fireworks.ai focus on production use cases for open source LLMs, offering speed
## Usage
```ts
import { FireworksLLM, serviceContextFromDefaults } from "llamaindex";
import { FireworksLLM, Settings } from "llamaindex";
const fireworksLLM = new FireworksLLM({
Settings.llm = new FireworksLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: fireworksLLM });
```
## Load and index documents
@@ -23,9 +21,7 @@ const reader = new PDFReader();
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments(documents);
```
## Query
@@ -14,15 +14,13 @@ export GROQ_API_KEY=<your-api-key>
The initialize the Groq module.
```ts
import { Groq, serviceContextFromDefaults } from "llamaindex";
import { Groq, Settings } from "llamaindex";
const groq = new Groq({
Settings.llm = new Groq({
// If you do not wish to set your API key in the environment, you may
// configure your API key when you initialize the Groq class.
// apiKey: "<your-api-key>",
});
const serviceContext = serviceContextFromDefaults({ llm: groq });
```
## Load and index documents
@@ -32,9 +30,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -3,11 +3,9 @@
## Usage
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
import { Ollama, Settings, DeuceChatStrategy } from "llamaindex";
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
```
## Usage with Replication
@@ -16,19 +14,18 @@ const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
import {
Ollama,
ReplicateSession,
serviceContextFromDefaults,
Settings,
DeuceChatStrategy,
} from "llamaindex";
const replicateSession = new ReplicateSession({
replicateKey,
});
const llama2LLM = new LlamaDeuce({
Settings.llm = new LlamaDeuce({
chatStrategy: DeuceChatStrategy.META,
replicateSession,
});
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
```
## Load and index documents
@@ -38,9 +35,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -62,22 +57,18 @@ import {
LlamaDeuce,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
Settings,
DeuceChatStrategy,
} from "llamaindex";
// Use the LlamaDeuce LLM
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
async function main() {
// Create an instance of the LLM
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
@@ -3,14 +3,12 @@
## Usage
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
import { Ollama, Settings } from "llamaindex";
const mistralLLM = new MistralAI({
Settings.llm = new MistralAI({
model: "mistral-tiny",
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
```
## Load and index documents
@@ -20,9 +18,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -40,26 +36,16 @@ const results = await queryEngine.query({
## Full Example
```ts
import {
MistralAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { MistralAI, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the MistralAI LLM
Settings.llm = new MistralAI({ model: "mistral-tiny" });
async function main() {
// Create an instance of the LLM
const mistralLLM = new MistralAI({ model: "mistral-tiny" });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
@@ -3,14 +3,10 @@
## Usage
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
import { Ollama, Settings } from "llamaindex";
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const serviceContext = serviceContextFromDefaults({
llm: ollamaLLM,
embedModel: ollamaLLM,
});
Settings.llm = ollamaLLM;
Settings.embedModel = ollamaLLM;
```
## Load and index documents
@@ -20,9 +16,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -40,33 +34,23 @@ const results = await queryEngine.query({
## Full Example
```ts
import {
Ollama,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { Ollama, Document, VectorStoreIndex, Settings } from "llamaindex";
import fs from "fs/promises";
const ollama = new Ollama({ model: "llama2", temperature: 0.75 });
// Use Ollama LLM and Embed Model
Settings.llm = ollama;
Settings.embedModel = ollama;
async function main() {
// Create an instance of the LLM
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const essay = await fs.readFile("./paul_graham_essay.txt", "utf-8");
// Create a service context
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaLLM, // prevent 'Set OpenAI Key in OPENAI_API_KEY env variable' error
llm: ollamaLLM,
});
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
@@ -1,11 +1,9 @@
# OpenAI
```ts
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
import { OpenAI, Settings } from "llamaindex";
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
```
You can setup the apiKey on the environment variables, like:
@@ -21,9 +19,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -41,26 +37,16 @@ const results = await queryEngine.query({
## Full Example
```ts
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the OpenAI LLM
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
async function main() {
// Create an instance of the LLM
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
@@ -3,13 +3,11 @@
## Usage
```ts
import { Portkey, serviceContextFromDefaults } from "llamaindex";
import { Portkey, Settings } from "llamaindex";
const portkeyLLM = new Portkey({
Settings.llm = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
```
## Load and index documents
@@ -19,9 +17,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -39,28 +35,19 @@ const results = await queryEngine.query({
## Full Example
```ts
import {
Portkey,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { Portkey, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the Portkey LLM
Settings.llm = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
async function main() {
// Create an instance of the LLM
const portkeyLLM = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
// Create a document
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
@@ -3,13 +3,11 @@
## Usage
```ts
import { TogetherLLM, serviceContextFromDefaults } from "llamaindex";
import { TogetherLLM, Settings } from "llamaindex";
const togetherLLM = new TogetherLLM({
Settings.llm = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
```
## Load and index documents
@@ -19,9 +17,7 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
@@ -39,28 +35,17 @@ const results = await queryEngine.query({
## Full Example
```ts
import {
TogetherLLM,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { TogetherLLM, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
async function main() {
// Create an instance of the LLM
const togetherLLM = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
+3 -6
View File
@@ -6,14 +6,12 @@ sidebar_position: 3
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
The LLM can be explicitly set in the `ServiceContext` object.
The LLM can be explicitly updated through `Settings`.
```typescript
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
import { OpenAI, Settings } from "llamaindex";
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
```
## Azure OpenAI
@@ -35,4 +33,3 @@ For local LLMs, currently we recommend the use of [Ollama](./available_llms/olla
## API Reference
- [OpenAI](../api/classes/OpenAI.md)
- [ServiceContext](../api/interfaces//ServiceContext.md)
+3 -4
View File
@@ -4,15 +4,14 @@ sidebar_position: 4
# NodeParser
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `ServiceContext` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `Settings` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
```typescript
import { Document, SimpleNodeParser } from "llamaindex";
const nodeParser = new SimpleNodeParser();
const nodes = nodeParser.getNodesFromDocuments([
new Document({ text: "I am 10 years old. John is 20 years old." }),
]);
Settings.nodeParser = nodeParser;
```
## TextSplitter
@@ -18,7 +18,7 @@ import {
Document,
OpenAI,
VectorStoreIndex,
serviceContextFromDefaults,
Settings,
} from "llamaindex";
```
@@ -29,13 +29,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Increase similarity topK to retrieve more results
@@ -36,7 +36,7 @@ const processor = new SimilarityPostprocessor({
similarityCutoff: 0.7,
});
const filteredNodes = processor.postprocessNodes(nodes);
const filteredNodes = await processor.postprocessNodes(nodes);
// cohere rerank: rerank nodes given query using trained model
const reranker = new CohereRerank({
@@ -58,7 +58,10 @@ Most commonly, node-postprocessors will be used in a query engine, where they ar
### Using Node Postprocessors in a Query Engine
```ts
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank } from "llamaindex";
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank, Settings } from "llamaindex";
// Use OpenAI LLM
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const nodes: NodeWithScore[] = [
{
@@ -79,14 +82,6 @@ const reranker = new CohereRerank({
const document = new Document({ text: "essay", id_: "essay" });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine({
nodePostprocessors: [processor, reranker],
});
@@ -0,0 +1,71 @@
# Jina AI Reranker
The Jina AI Reranker is a postprocessor that uses the Jina AI Reranker API to rerank the results of a search query.
## Setup
Firstly, you will need to install the `llamaindex` package.
```bash
pnpm install llamaindex
```
Now, you will need to sign up for an API key at [Jina AI](https://jina.ai/reranker). Once you have your API key you can import the necessary modules and create a new instance of the `JinaAIReranker` class.
```ts
import {
JinaAIReranker,
Document,
OpenAI,
VectorStoreIndex,
Settings,
} from "llamaindex";
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Increase similarity topK to retrieve more results
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
```ts
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
```
## Create a new instance of the JinaAIReranker class
Then you can create a new instance of the `JinaAIReranker` class and pass in the number of results you want to return.
The Jina AI Reranker API key is set in the `JINAAI_API_KEY` environment variable.
```bash
export JINAAI_API_KEY=<YOUR API KEY>
```
```ts
const nodePostprocessor = new JinaAIReranker({
topN: 5,
});
```
## Create a query engine with the retriever and node postprocessor
```ts
const queryEngine = index.asQueryEngine({
retriever,
nodePostprocessors: [nodePostprocessor],
});
// log the response
const response = await queryEngine.query("Where did the author grown up?");
```
+3 -7
View File
@@ -31,13 +31,11 @@ The first method is to create a new instance of `ResponseSynthesizer` (or the mo
```ts
// Create an instance of response synthesizer
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(serviceContext, newTextQaPrompt),
responseBuilder: new CompactAndRefine(undefined, newTextQaPrompt),
});
// Create index
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine({ responseSynthesizer });
@@ -53,9 +51,7 @@ The second method is that most of the modules in LlamaIndex have a `getPrompts`
```ts
// Create index
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
@@ -54,12 +54,13 @@ You can create a `ChromaVectorStore` to store the documents:
```ts
const chromaVS = new ChromaVectorStore({ collectionName });
const serviceContext = await storageContextFromDefaults({
const storageContext = await storageContextFromDefaults({
vectorStore: chromaVS,
});
const index = await VectorStoreIndex.fromDocuments(docs, {
storageContext: serviceContext,
storageContext: storageContext,
});
```
@@ -18,7 +18,7 @@ import {
SimpleNodeParser,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
Settings,
} from "llamaindex";
```
@@ -34,17 +34,13 @@ const documents = await new SimpleDirectoryReader().loadData({
## Service Context
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `ServiceContext` to define the rules (eg. LLM API key, chunk size, etc.):
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `Settings` to define the rules (eg. LLM API key, chunk size, etc.):
```ts
const nodeParser = new SimpleNodeParser({
Settings.llm = new OpenAI();
Settings.nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
const serviceContext = serviceContextFromDefaults({
nodeParser,
llm: new OpenAI(),
});
```
## Creating Indices
@@ -52,13 +48,8 @@ const serviceContext = serviceContextFromDefaults({
Next, we need to create some indices. We will create a `VectorStoreIndex` and a `SummaryIndex`:
```ts
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
serviceContext,
});
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
const summaryIndex = await SummaryIndex.fromDocuments(documents);
```
## Creating Query Engines
@@ -88,7 +79,6 @@ const queryEngine = RouterQueryEngine.fromDefaults({
description: "Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
```
@@ -117,34 +107,23 @@ import {
SimpleNodeParser,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
Settings,
} from "llamaindex";
Settings.llm = new OpenAI();
Settings.nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
async function main() {
// Load documents from a directory
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples",
});
// Parse the documents into nodes
const nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
// Create a service context
const serviceContext = serviceContextFromDefaults({
nodeParser,
llm: new OpenAI(),
});
// Create indices
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
serviceContext,
});
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
const summaryIndex = await SummaryIndex.fromDocuments(documents);
// Create query engines
const vectorQueryEngine = vectorIndex.asQueryEngine();
@@ -162,7 +141,6 @@ async function main() {
description: "Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
// Query the router query engine
+29
View File
@@ -14,6 +14,9 @@ Configure a variable once, and you'll be able to do things like the following:
Each provider has similarities and differences. Take a look below for the full set of guides for each one!
- [OpenLLMetry](#openllmetry)
- [Langtrace](#langtrace)
## OpenLLMetry
[OpenLLMetry](https://github.com/traceloop/openllmetry-js) is an open-source project based on OpenTelemetry for tracing and monitoring
@@ -33,3 +36,29 @@ traceloop.initialize({
disableBatch: true,
});
```
## Langtrace
Enhance your observability with Langtrace, a robust open-source tool supports OpenTelemetry and is designed to trace, evaluate, and manage LLM applications seamlessly. Langtrace integrates directly with LlamaIndex, offering detailed, real-time insights into performance metrics such as accuracy, evaluations, and latency.
#### Install
- Self-host or sign-up and generate an API key using [Langtrace](https://www.langtrace.ai) Cloud
```bash
npm install @langtrase/typescript-sdk
```
#### Initialize
```js
import * as Langtrace from "@langtrase/typescript-sdk";
Langtrace.init({ api_key: "<YOUR_API_KEY>" });
```
Features:
- OpenTelemetry compliant, ensuring broad compatibility with observability platforms.
- Provides comprehensive logs and detailed traces of all components.
- Real-time monitoring of accuracy, evaluations, usage, costs, and latency.
- For more configuration options and details, visit [Langtrace Docs](https://docs.langtrace.ai/introduction).
+2
View File
@@ -0,0 +1,2 @@
label: Recipes
position: 3
+14
View File
@@ -0,0 +1,14 @@
# Cost Analysis
This page shows how to track LLM cost using APIs.
## Callback Manager
The callback manager is a class that manages the callback functions.
You can register `llm-start`, `llm-end`, and `llm-stream` callbacks to the callback manager for tracking the cost.
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/recipes/cost-analysis";
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+1 -1
View File
@@ -163,7 +163,7 @@ const config = {
"docusaurus-plugin-typedoc",
{
entryPoints: ["../../packages/core/src/index.ts"],
tsconfig: "../../packages/core/tsconfig.json",
tsconfig: "../../tsconfig.json",
readme: "none",
sourceLinkTemplate:
"https://github.com/run-llama/LlamaIndexTS/blob/{gitRevision}/{path}#L{line}",
+15 -14
View File
@@ -1,6 +1,6 @@
{
"name": "docs",
"version": "0.0.4",
"version": "0.0.5",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@@ -15,28 +15,29 @@
"typecheck": "tsc"
},
"dependencies": {
"@docusaurus/core": "^3.1.1",
"@llamaindex/env": "workspace:*",
"@docusaurus/remark-plugin-npm2yarn": "^3.1.1",
"@mdx-js/react": "^3.0.0",
"@docusaurus/core": "^3.2.1",
"@docusaurus/remark-plugin-npm2yarn": "^3.2.1",
"@llamaindex/examples": "workspace:*",
"@mdx-js/react": "^3.0.1",
"clsx": "^2.1.0",
"postcss": "^8.4.33",
"llamaindex": "workspace:*",
"postcss": "^8.4.38",
"prism-react-renderer": "^2.3.1",
"raw-loader": "^4.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.1.0",
"@docusaurus/preset-classic": "^3.1.1",
"@docusaurus/theme-classic": "^3.1.1",
"@docusaurus/types": "^3.1.1",
"@tsconfig/docusaurus": "^2.0.2",
"@types/node": "^18.19.10",
"@docusaurus/module-type-aliases": "3.2.0",
"@docusaurus/preset-classic": "^3.2.1",
"@docusaurus/theme-classic": "^3.2.1",
"@docusaurus/types": "^3.2.1",
"@tsconfig/docusaurus": "^2.0.3",
"@types/node": "^20.12.7",
"docusaurus-plugin-typedoc": "^0.22.0",
"typedoc": "^0.25.7",
"typedoc": "^0.25.13",
"typedoc-plugin-markdown": "^3.17.1",
"typescript": "^5.3.3"
"typescript": "^5.4.4"
},
"browserslist": {
"production": [
+14
View File
@@ -0,0 +1,14 @@
# examples
## 0.0.4
### Patch Changes
- d2e8d0c: add support for Milvus vector store
- Updated dependencies [d2e8d0c]
- Updated dependencies [aefc326]
- Updated dependencies [484a710]
- Updated dependencies [d766bd0]
- Updated dependencies [dd95927]
- Updated dependencies [bf583a7]
- llamaindex@0.2.0
+29
View File
@@ -0,0 +1,29 @@
import fs from "node:fs/promises";
import { Document, OpenAI, Settings, VectorStoreIndex } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-4" });
async function main() {
// Load essay from abramov.txt in Node
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await fs.readFile(path, "utf-8");
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
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().catch(console.error);
+7 -17
View File
@@ -6,11 +6,11 @@ import {
OpenAI,
OpenAIAgent,
QueryEngineTool,
Settings,
SimpleNodeParser,
SimpleToolNodeMapping,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
@@ -18,6 +18,8 @@ import { extractWikipedia } from "./helpers/extractWikipedia";
const wikiTitles = ["Brazil", "Canada"];
Settings.llm = new OpenAI({ model: "gpt-4" });
async function main() {
await extractWikipedia(wikiTitles);
@@ -30,11 +32,6 @@ async function main() {
countryDocs[title] = document;
}
const llm = new OpenAI({
model: "gpt-4",
});
const serviceContext = serviceContextFromDefaults({ llm });
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
@@ -54,13 +51,11 @@ async function main() {
console.log(`Creating index for ${title}`);
const vectorIndex = await VectorStoreIndex.init({
serviceContext: serviceContext,
storageContext: storageContext,
nodes,
});
const summaryIndex = await SummaryIndex.init({
serviceContext: serviceContext,
nodes,
});
@@ -90,8 +85,7 @@ async function main() {
const agent = new OpenAIAgent({
tools: queryEngineTools,
llm,
verbose: true,
llm: new OpenAI({ model: "gpt-4" }),
});
documentAgents[title] = agent;
@@ -126,16 +120,12 @@ async function main() {
allTools,
toolMapping,
VectorStoreIndex,
{
serviceContext,
},
);
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm,
verbose: true,
prefixMessages: [
llm: new OpenAI({ model: "gpt-4" }),
chatHistory: [
{
content:
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
@@ -153,4 +143,4 @@ async function main() {
});
}
main();
void main();
+41 -56
View File
@@ -1,76 +1,61 @@
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, {
const sumNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a + b}`,
{
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
},
},
);
// Create a function tool from the divide function
const functionTool2 = new FunctionTool(divideNumbers, {
const divideNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a / b}`,
{
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
parameters: {
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"],
},
},
);
// Create an OpenAIAgent with the function tools
async function main() {
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: true,
tools: [sumNumbers, divideNumbers],
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+1 -2
View File
@@ -29,7 +29,6 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
// Chat with the agent
@@ -41,6 +40,6 @@ async function main() {
console.log(String(response));
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+17 -12
View File
@@ -1,13 +1,13 @@
import { FunctionTool, ReActAgent } from "llamaindex";
import { Anthropic, FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
function sumNumbers({ a, b }: { a: number; b: number }) {
return `${a + b}`;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
function divideNumbers({ a, b }: { a: number; b: number }) {
return `${a / b}`;
}
// Define the parameters of the sum function as a JSON schema
@@ -24,7 +24,7 @@ const sumJSON = {
},
},
required: ["a", "b"],
};
} as const;
const divideJSON = {
type: "object",
@@ -39,7 +39,7 @@ const divideJSON = {
},
},
required: ["a", "b"],
};
} as const;
async function main() {
// Create a function tool from the sum function
@@ -56,21 +56,26 @@ async function main() {
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-3-opus",
});
// Create an ReActAgent with the function tools
const agent = new ReActAgent({
llm: anthropic,
tools: [functionTool, functionTool2],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
const { response } = await agent.chat({
message: "Divide 16 by 2 then add 20",
});
// Print the response
console.log(String(response));
console.log(response.message);
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+13 -25
View File
@@ -1,13 +1,13 @@
import { FunctionTool, OpenAIAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
function sumNumbers({ a, b }: { a: number; b: number }) {
return `${a + b}`;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
function divideNumbers({ a, b }: { a: number; b: number }) {
return `${a / b}`;
}
// Define the parameters of the sum function as a JSON schema
@@ -24,22 +24,22 @@ const sumJSON = {
},
},
required: ["a", "b"],
};
} as const;
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend a to divide",
description: "The dividend",
},
b: {
type: "number",
description: "The divisor b to divide by",
description: "The divisor",
},
},
required: ["a", "b"],
};
} as const;
async function main() {
// Create a function tool from the sum function
@@ -59,37 +59,25 @@ async function main() {
// 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");
const task = await agent.createTask("How much is 5 + 5? then divide by 2");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
for await (const stepOutput of task) {
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(stepOutput.output.message.content);
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
console.log(stepOutput.output.message.content);
}
}
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+5 -26
View File
@@ -29,36 +29,15 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
const task = agent.createTask("What was his salary?");
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;
}
}
console.log(response.message.content);
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+15 -23
View File
@@ -1,13 +1,14 @@
import { FunctionTool, ReActAgent } from "llamaindex";
import { Anthropic, FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
function sumNumbers({ a, b }: { a: number; b: number }) {
return `${a + b}`;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
function divideNumbers({ a, b }: { a: number; b: number }) {
console.log("get input", a, b);
return `${a / b}`;
}
// Define the parameters of the sum function as a JSON schema
@@ -24,7 +25,7 @@ const sumJSON = {
},
},
required: ["a", "b"],
};
} as const;
const divideJSON = {
type: "object",
@@ -39,7 +40,7 @@ const divideJSON = {
},
},
required: ["a", "b"],
};
} as const;
async function main() {
// Create a function tool from the sum function
@@ -58,33 +59,24 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
llm: new Anthropic({
model: "claude-3-opus",
}),
tools: [functionTool, functionTool2],
verbose: true,
});
const task = agent.createTask("Divide 16 by 2 then add 20");
const task = await agent.createTask("Divide 16 by 2 then add 20");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
for await (const stepOutput of task) {
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
console.log(stepOutput.output);
console.log(stepOutput);
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+9 -10
View File
@@ -1,13 +1,13 @@
import { FunctionTool, OpenAIAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
function sumNumbers({ a, b }: { a: number; b: number }) {
return `${a + b}`;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
function divideNumbers({ a, b }: { a: number; b: number }) {
return `${a / b}`;
}
// Define the parameters of the sum function as a JSON schema
@@ -24,7 +24,7 @@ const sumJSON = {
},
},
required: ["a", "b"],
};
} as const;
const divideJSON = {
type: "object",
@@ -39,18 +39,18 @@ const divideJSON = {
},
},
required: ["a", "b"],
};
} as const;
async function main() {
// Create a function tool from the sum function
const functionTool = new FunctionTool(sumNumbers, {
const functionTool = FunctionTool.from(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, {
const functionTool2 = FunctionTool.from(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
@@ -59,7 +59,6 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: false,
});
const stream = await agent.chat({
@@ -72,6 +71,6 @@ async function main() {
}
}
main().then(() => {
void main().then(() => {
console.log("\nDone");
});
+27
View File
@@ -0,0 +1,27 @@
import { OpenAI, OpenAIAgent, WikipediaTool } from "llamaindex";
async function main() {
const llm = new OpenAI({ model: "gpt-4-turbo" });
const wikiTool = new WikipediaTool();
// Create an OpenAIAgent with the Wikipedia tool
const agent = new OpenAIAgent({
llm,
tools: [wikiTool],
});
// Chat with the agent
const response = await agent.chat({
message: "Who was Goethe?",
stream: true,
});
for await (const chunk of response.response) {
process.stdout.write(chunk.response);
}
}
(async function () {
await main();
console.log("\nDone");
})();
+43
View File
@@ -0,0 +1,43 @@
import { FunctionTool, Settings, WikipediaTool } from "llamaindex";
import { AnthropicAgent } from "llamaindex/agent/anthropic";
Settings.callbackManager.on("llm-tool-call", (event) => {
console.log("llm-tool-call", event.detail.payload.toolCall);
});
const agent = new AnthropicAgent({
tools: [
FunctionTool.from<{ location: string }>(
(query) => {
return `The weather in ${query.location} is sunny`;
},
{
name: "weather",
description: "Get the weather",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The location to get the weather for",
},
},
required: ["location"],
},
},
),
new WikipediaTool(),
],
});
async function main() {
// https://docs.anthropic.com/claude/docs/tool-use#tool-use-best-practices-and-limitations
const { response } = await agent.chat({
message:
"What is the weather in New York? What's the history of New York from Wikipedia in 3 sentences?",
});
console.log(response);
}
void main();
+1 -1
View File
@@ -13,7 +13,7 @@ Here are two sample scripts which work well with the sample data in the Astra Po
1. Set your env variables:
- `ASTRA_DB_APPLICATION_TOKEN`: The generated app token for your Astra database
- `ASTRA_DB_ENDPOINT`: The API endpoint for your Astra database
- `ASTRA_DB_API_ENDPOINT`: The API endpoint for your Astra database
- `ASTRA_DB_NAMESPACE`: (Optional) The namespace where your collection is stored defaults to `default_keyspace`
- `OPENAI_API_KEY`: Your OpenAI key
+2 -3
View File
@@ -34,10 +34,9 @@ async function main() {
];
const astraVS = new AstraDBVectorStore();
await astraVS.create(collectionName, {
await astraVS.createAndConnect(collectionName, {
vector: { dimension: 1536, metric: "cosine" },
});
await astraVS.connect(collectionName);
const ctx = await storageContextFromDefaults({ vectorStore: astraVS });
const index = await VectorStoreIndex.fromDocuments(docs, {
@@ -55,4 +54,4 @@ async function main() {
}
}
main();
void main();
+2 -2
View File
@@ -13,7 +13,7 @@ async function main() {
const docs = await reader.loadData("./data/movie_reviews.csv");
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
await astraVS.create(collectionName, {
await astraVS.createAndConnect(collectionName, {
vector: { dimension: 1536, metric: "cosine" },
});
await astraVS.connect(collectionName);
@@ -27,4 +27,4 @@ async function main() {
}
}
main();
void main();
+2 -2
View File
@@ -1,7 +1,7 @@
import {
AstraDBVectorStore,
serviceContextFromDefaults,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
const collectionName = "movie_reviews";
@@ -28,4 +28,4 @@ async function main() {
}
}
main();
void main();
+5 -5
View File
@@ -4,18 +4,18 @@ import readline from "node:readline/promises";
import {
ContextChatEngine,
Document,
serviceContextFromDefaults,
Settings,
VectorStoreIndex,
} from "llamaindex";
import essay from "./essay";
// Update chunk size
Settings.chunkSize = 512;
async function main() {
const document = new Document({ text: essay });
const serviceContext = serviceContextFromDefaults({ chunkSize: 512 });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
const chatEngine = new ContextChatEngine({ retriever });
+12 -1
View File
@@ -1,7 +1,18 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { OpenAI, SimpleChatEngine, SummaryChatHistory } from "llamaindex";
import {
OpenAI,
Settings,
SimpleChatEngine,
SummaryChatHistory,
} from "llamaindex";
if (process.env.NODE_ENV === "development") {
Settings.callbackManager.on("llm-end", (event) => {
console.log("callers chain", event.reason?.computedCallers);
});
}
async function main() {
// Set maxTokens to 75% of the context window size of 4096
+1 -1
View File
@@ -54,4 +54,4 @@ async function main() {
}
}
main();
void main();
+1 -1
View File
@@ -37,4 +37,4 @@ async function main() {
}
}
main();
void main();
+8
View File
@@ -31,3 +31,11 @@ This example shows how to use the managed index with a query engine.
```shell
pnpx ts-node cloud/query.ts
```
## Pipeline
This example shows how to create a managed index with a pipeline.
```shell
pnpx ts-node cloud/pipeline.ts
```
+44
View File
@@ -0,0 +1,44 @@
import fs from "node:fs/promises";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { Document, LlamaCloudIndex } from "llamaindex";
async function main() {
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await fs.readFile(path, "utf-8");
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
const index = await LlamaCloudIndex.fromDocuments({
documents: [document],
name: "test",
projectName: "default",
apiKey: process.env.LLAMA_CLOUD_API_KEY,
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
});
const queryEngine = index.asQueryEngine({
denseSimilarityTopK: 5,
});
const rl = readline.createInterface({ input, output });
while (true) {
const query = await rl.question("Query: ");
const stream = await queryEngine.query({
query,
stream: true,
});
console.log();
for await (const chunk of stream) {
process.stdout.write(chunk.response);
}
}
}
main().catch(console.error);
+34
View File
@@ -0,0 +1,34 @@
import fs from "node:fs/promises";
import {
Document,
IngestionPipeline,
OpenAIEmbedding,
SimpleNodeParser,
} from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await fs.readFile(path, "utf-8");
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
const pipeline = new IngestionPipeline({
name: "pipeline",
transformations: [
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
new OpenAIEmbedding({ apiKey: "api-key" }),
],
});
const pipelineId = await pipeline.register({
documents: [document],
verbose: true,
});
console.log(`Pipeline with id ${pipelineId} successfully created.`);
}
main().catch(console.error);
+6 -17
View File
@@ -1,21 +1,10 @@
import {
CorrectnessEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
// Update llm to use OpenAI
Settings.llm = new OpenAI({ model: "gpt-4" });
async function main() {
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
const evaluator = new CorrectnessEvaluator({
serviceContext: ctx,
});
const evaluator = new CorrectnessEvaluator();
const query =
"Can you explain the theory of relativity proposed by Albert Einstein in detail?";
@@ -33,4 +22,4 @@ However, general relativity, published in 1915, extended these ideas to include
console.log(result);
}
main();
void main();
+6 -13
View File
@@ -2,22 +2,15 @@ import {
Document,
FaithfulnessEvaluator,
OpenAI,
Settings,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
// Update llm to use OpenAI
Settings.llm = new OpenAI({ model: "gpt-4" });
async function main() {
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
const evaluator = new FaithfulnessEvaluator({
serviceContext: ctx,
});
const evaluator = new FaithfulnessEvaluator();
const documents = [
new Document({
@@ -43,4 +36,4 @@ async function main() {
console.log(result);
}
main();
void main();
+7 -13
View File
@@ -2,22 +2,16 @@ import {
Document,
OpenAI,
RelevancyEvaluator,
Settings,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
Settings.llm = new OpenAI({
model: "gpt-4",
});
async function main() {
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
const evaluator = new RelevancyEvaluator({
serviceContext: ctx,
});
const evaluator = new RelevancyEvaluator();
const documents = [
new Document({
@@ -43,4 +37,4 @@ async function main() {
console.log(result);
}
main();
void main();
+40
View File
@@ -0,0 +1,40 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { ChatMessage, OpenAI, ReplicateLLM } from "llamaindex";
(async () => {
const gpt4 = new OpenAI({ model: "gpt-4-turbo", temperature: 0.9 });
const l3 = new ReplicateLLM({
model: "llama-3-70b-instruct",
temperature: 0.9,
});
const rl = readline.createInterface({ input, output });
const start = await rl.question("Start: ");
const history: ChatMessage[] = [
{
content:
"Prefer shorter answers. Keep your response to 100 words or less.",
role: "system",
},
{ content: start, role: "user" },
];
while (true) {
const next = history.length % 2 === 1 ? gpt4 : l3;
const r = await next.chat({
messages: history.map(({ content, role }) => ({
content,
role: next === l3 ? role : role === "user" ? "assistant" : "user",
})),
});
history.push({
content: r.message.content,
role: next === l3 ? "assistant" : "user",
});
await rl.question(
(next === l3 ? "Llama 3: " : "GPT 4 Turbo: ") + r.message.content,
);
}
})();
+7 -17
View File
@@ -1,30 +1,20 @@
import fs from "node:fs/promises";
import {
Document,
Groq,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import { Document, Groq, Settings, VectorStoreIndex } from "llamaindex";
// Update llm to use Groq
Settings.llm = new Groq({
apiKey: process.env.GROQ_API_KEY,
});
async function main() {
// Create an instance of the LLM
const groq = new Groq({
apiKey: process.env.GROQ_API_KEY,
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: groq });
// Load essay from abramov.txt in Node
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await fs.readFile(path, "utf-8");
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// get retriever
const retriever = index.asRetriever();
+7 -12
View File
@@ -4,10 +4,15 @@ import {
Document,
HuggingFaceEmbedding,
HuggingFaceEmbeddingModelType,
Settings,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
// Update embed model
Settings.embedModel = new HuggingFaceEmbedding({
modelType: HuggingFaceEmbeddingModelType.XENOVA_ALL_MPNET_BASE_V2,
});
async function main() {
// Load essay from abramov.txt in Node
const path = "node_modules/llamaindex/examples/abramov.txt";
@@ -17,18 +22,8 @@ async function main() {
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
// Use Local embedding from HuggingFace
const embedModel = new HuggingFaceEmbedding({
modelType: HuggingFaceEmbeddingModelType.XENOVA_ALL_MPNET_BASE_V2,
});
const serviceContext = serviceContextFromDefaults({
embedModel,
});
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
+1 -3
View File
@@ -36,9 +36,7 @@ async function main() {
],
});
const json = JSON.parse(response.message.content);
console.log(json);
console.log(response.message.content);
}
main().catch(console.error);
+13
View File
@@ -0,0 +1,13 @@
import { ReplicateLLM } from "llamaindex";
(async () => {
const tres = new ReplicateLLM({ model: "llama-3-70b-instruct" });
const stream = await tres.chat({
messages: [{ content: "Hello, world!", role: "user" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
console.log("\n\ndone");
})();
+8 -13
View File
@@ -1,26 +1,21 @@
import {
Document,
Settings,
SimpleNodeParser,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
export const STORAGE_DIR = "./data";
// Update node parser
Settings.nodeParser = new SimpleNodeParser({
chunkSize: 512,
chunkOverlap: 20,
splitLongSentences: true,
});
(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,
});
await VectorStoreIndex.fromDocuments([document]);
})();
-101
View File
@@ -1,101 +0,0 @@
title,reviewid,creationdate,criticname,originalscore,reviewstate,reviewtext
Beavers,1145982,2003-05-23,Ivan M. Lincoln,3.5/4,fresh,"Timed to be just long enough for most youngsters' brief attention spans -- and it's packed with plenty of interesting activity, both on land and under the water."
Blood Mask,1636744,2007-06-02,The Foywonder,1/5,rotten,"It doesn't matter if a movie costs 300 million or only 300 dollars; good is good and bad is bad, and Bloodmask: The Possession of Nicole Lameroux is just plain bad."
City Hunter: Shinjuku Private Eyes,2590987,2019-05-28,Reuben Baron,,fresh,"The choreography is so precise and lifelike at points one might wonder whether the movie was rotoscoped, but no live-action reference footage was used. The quality is due to the skill of the animators and Kodama's love for professional wrestling."
City Hunter: Shinjuku Private Eyes,2558908,2019-02-14,Matt Schley,2.5/5,rotten,The film's out-of-touch attempts at humor may find them hunting for the reason the franchise was so popular in the first place.
Dangerous Men,2504681,2018-08-29,Pat Padua,,fresh,Its clumsy determination is endearing and sometimes wildly entertaining
Dangerous Men,2299284,2015-12-13,Eric Melin,4/5,fresh,"With every new minute, there's another head-scratching choice that's bound to elicit some amazing out-loud responses, so this feels like a true party flick."
Dangerous Men,2295858,2015-11-22,Matt Donato,7/10,fresh,"Emotionless reaction shots, zero characterization, guns that have absolutely no special effects when blasted - Dangerous Men is rare winning dish from a one star restaurant."
Dangerous Men,2295338,2015-11-19,Peter Keough,0.5/4,rotten,"Conceivably, it could serve as a primer for students on how not to make a movie, and perhaps as a deconstruction of filmic conventions for the more theoretical minded."
Dangerous Men,2294641,2015-11-16,Jason Wilson,3/10,rotten,"If you're not a fan of garbage cinema, even for the fun of it, Dangerous Men is best to be avoided."
Dangerous Men,2294129,2015-11-12,Soren Andersen,0/4,rotten,"""Dangerous Men,"" the picture's production notes inform, took 26 years to reach the big screen. After having seen it, I wonder: What was the rush?"
Dangerous Men,2293902,2015-11-12,Maitland McDonagh,,rotten,Will entertain some viewers and infuriate others with its clunky mix of feminist fury and awkward action sequences.
Dangerous Men,2293900,2015-11-12,Marjorie Baumgarten,1.5/5,rotten,"This is a bad movie, but one that awakens your senses every so often with flashes of originality and abundant self-belief."
Dangerous Men,2293815,2015-11-12,Katie Rife,B+,fresh,"Ridiculous, artless, and wildly entertaining, Dangerous Men is more than the sum of its fascinatingly misguided parts, although it will take a special sort of moviegoer to truly appreciate (or endure, depending on your perspective) its charms."
Dangerous Men,2293605,2015-11-11,Amy Nicholson,C,fresh,To sit through it feels like honoring the dreamers of the world who at least get shit done. Is it terrible? Of course. Is there belly-dancing? Duh.
Small Town Wisconsin,102711819,2022-07-22,Peter Gray,,fresh,Small Town Wisconsin could hit some home truths for viewers&#44; and though being faced with the truth isn&#8217;t always pleasant&#44; it feels necessary in growing towards a happier fruition&#46;
Small Town Wisconsin,102711545,2022-07-22,Tim Grierson,,fresh,"This low-key drama has lovely interludes and some nicely understated performances, although director Niels Mueller doesnt glean too many new insights from Jason Naczeks familiar story..."
Small Town Wisconsin,102700937,2022-06-16,Sumner Forbes,8.5/10,fresh,"Small Town Wisconsin is a success in almost every regard, and if you can see over the legions of cheeseheads in the rows ahead of you, it shouldnt be missed."
Small Town Wisconsin,102699897,2022-06-14,Tara McNamara,3/5,fresh,Just like Wayne&#44; Small Town Wisconsin has flaws&#44; but the poignancy of the story will stick with you for a long time&#46;
Small Town Wisconsin,102698744,2022-06-10,Rob Thomas,3/4,fresh,It&#8217;s a movie with its heart in the right place&#44; and does both small town and big city Wisconsin proud&#46;
Small Town Wisconsin,102698639,2022-06-10,Todd Jorgenson,,rotten,Despite some intriguing character dynamics and performances that generate sympathy for this fractured family&#44; the film stumbles when it veers into melodrama without the narrative dexterity to tackle its weightier ambitions&#46;
Small Town Wisconsin,102698482,2022-06-10,Jackie K. Cooper,7/10,fresh,This is the kind of movie that draws you so deeply into its story you are reluctant to let it end&#46;
Small Town Wisconsin,102698164,2022-06-09,Glenn Kenny,,fresh,"Muellers direction is patient and sensitive, the cast is accomplished and committed, and the pictures comedic aspects sometimes earn a chuckle."
Small Town Wisconsin,102697854,2022-06-08,Brian Orndorf,B+,fresh,Naczek isn&apos;t interested in making a soap opera with this examination of fallibility&#44; going somewhere much more authentic when exploring character aches and pains&#46;
Small Town Wisconsin,102695788,2022-06-02,Eddie Harrison,4/5,fresh,&#8230;a warm-hearted story of everyday life that&#8217;s easy to recommend for those who like films about people rather than portals and vortexes&#8230;
Small Town Wisconsin,102695250,2022-05-31,Laura Clifford,C,rotten,Debuting screenwriter Jason Naczek has concocted a manchild redemption story using metaphors as heavy as a hammer and a fairy godmother who makes everything alright with a seeming flip of the switch&#46;
Small Town Wisconsin,2733251,2020-10-12,Jared Mobarak,B,fresh,Small Town Wisconsin is always proving itself to be more than its familiar premise thanks to Naczek's ability to infuse a lot more drama into the mix than one custody battle.
Tejano,2564925,2019-03-07,Joe Friar,3/4,fresh,The story of a South Texas ranch hand who gets mixed up with a Mexican cartel moves with pulse-pounding velocity and features top performances from a talented cast of actors with Texas roots.
Tejano,2557738,2019-02-12,Cary Darling,4/5,fresh,"An entertaining blast of Texas noir that nods toward the work of the Coen brothers, Quentin Tarantino and fellow Austinite Greg Kwedar's 2016 low-budget thriller ""Transpecos"" as well as ""Breaking Bad."""
Tejano,2547231,2019-01-10,Danielle White,3/5,fresh,The story itself slithers with twists and turns and unexpected betrayals. It's almost ridiculous how many characters die in this film.
Tejano,2530119,2018-11-08,Chris Salce,9/10,fresh,"Tejano is one of those films that can be described as a hidden gem as it sneaks under the radar and will have you talking, telling your friends about it, and wanting to watch it again."
Death of a Salesman,2770637,2021-02-23,Michael Dougan,,fresh,"Miller has taken a small, intimate tale and expanded it into a treatise on larger themes, primarily the abuse of the American Dream."
Death of a Salesman,1950734,2011-01-02,Randy White,5/5,fresh,A classic American tragedy.
Death of a Salesman,1422415,2005-08-04,Jules Brenner,4/5,fresh,
Death of a Salesman,1409415,2005-07-05,Emanuel Levy,3/5,fresh,
Death of a Salesman,839546,2003-02-06,Frederic and Mary Ann Brussat,,fresh,"Death of a Salesman, directed by Volker Schlondorff, draws out the multiple meanings of this Pulitzer Prize-winning play by Arthur Miller about change, family and fatherhood, work and love."
Death of a Salesman,788410,2002-09-29,Dan Lybarger,4/5,fresh,"Schlndorff's artificial settings and some amazing performances help keep this from looking like a typical ""filmed play."""
Death of a Salesman,751951,2002-08-08,Cory Cheney,4/5,fresh,
Death of a Salesman,743794,2002-07-26,Bob Grimm,5/5,fresh,
Death of a Salesman,743291,2002-07-26,Scott Weinberg,5/5,fresh,They MAKE you watch it in English class for a good reason!
Sahara,1137710,2003-05-13,Dragan Antulov,5/10,fresh,
The Debt,2628192,2019-09-20,Diego Batlle,,fresh,A Bresson-esque movie that is always enigmatic. [Full Review in Spanish]
The Debt,2627988,2019-09-20,Gaspar Zimerman,,fresh,The story [Director Gustavo Fontán] tells is an excuse to give way to the exploration of feelings and sensations that avoid verbality. [Full review in Spanish]
Peppermint Candy,2725008,2020-09-16,A.S. Hamrah,,fresh,"South Korean political history of the previous twenty years, Peppermint Candy is not tempered by its hysterical edge, which adds unpredictable violence to its vignettes of romantic, domestic, and business failure."
Peppermint Candy,2541271,2018-12-16,Panos Kotzathanasis,,fresh,"Lee Chang-dong presents a melodrama that stands apart from the plethora of similar productions due to its intense political element, because it doesn't lose its seriousness at any point and because it doesn't become hyperbolic in his effort to draw tears"
Peppermint Candy,1883708,2010-05-11,Anton Bitel,,fresh,"This is Korea's millennial elegy, filtering its search for times past through a confection no less bittersweet than Proust's madeleine."
Peppermint Candy,1706014,2008-01-29,Beth Accomando,9/10,fresh,The film offers a heartbreaking drama told in reverse chronology and spanning twenty years in both the life of the main character and the political history of Korea.
Peppermint Candy,1231988,2003-12-22,Greg Muskewitz,2/5,rotten,
Peppermint Candy,1187104,2003-08-14,Joshua Tanzer,4/4,fresh,"It's a story about the original sin of a nation as well as one character. There has rarely been a better film made, ever"
Prison Girls,2475348,2018-05-03,Roger Ebert,,rotten,Prison Girls didn't have a lot of prison sets because it was a big-budget exploitation movie. Maybe.
Gimme the Power,2575688,2019-04-09,Afroxander,,fresh,"Rubio's film shows ambition where none is required, making Gimme the Power a lot like Molotov's music: politically engaged without having to take itself too seriously."
Paa,2673089,2020-02-27,Nikhat Kazmi,3.5/5,fresh,"The film, which peters off into vague sub-plots about slum redevelopment and unwarranted media-bashing in the first half, suddenly picks up and scales new heights in the second half."
Paa,2578129,2019-04-17,Shubhra Gupta,2/5,rotten,"Disappointingly, Paa is not as out-of-the-box as it could have been."
Paa,2429810,2017-10-24,Anil Sinanan,3/5,rotten,Will Auro survive to know his Pa and reunite his parents? Forget about the disease: this is a vanity vehicle designed to showcase the Big B's versatility.
Paa,1860476,2009-12-14,Frank Lovece,,rotten,This would-be tearjerker without the musical numbers of typical Bollywood fare is for die-hard Amitabh Bachchan fans only.
Paa,1860473,2009-12-14,David Chute,,fresh,"The film owes much of its interest to the alertness and sincerity of the younger Bachchan and the luminous Vidya Balan as the anguished parents, and to the soft wash of the tasteful playback songs supplied by Ilaiyaraaja."
Paa,1858964,2009-12-05,Avi Offer,5.85/10,rotten,"Well-acted, funny and occasionally witty with terrific make-up design. However, it's often convoluted, awkwardly paced and too uneven as a whole."
Paa,1858853,2009-12-04,Frank Lovece,,fresh,"A would-be tearjerker without the singing-dancing musical numbers of typical Bollywood fare seen in the U.S., the lackluster Paa is for die-hard Amitabh Bachchan fans only%u2014of which there is no small number."
Paa,1858816,2009-12-04,Rachel Saltz,3/5,fresh,Odd and sometimes oddly affecting.
Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love),2835964,2021-10-30,Erich Hellmund-Waldow,,fresh,"The acting is not only artistic, it is also as realistic as can be possible in such a film."
Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love),2357086,2016-10-17,C. Hooper Trask,,fresh,"Aimed straight for the gooseflesh, it strikes directly into the centre of the target."
Toorbos,2760593,2021-01-29,Neil Young,,fresh,Built around a luminous and intriguing central performance by dancer-actor Elani Dekker.
Toorbos,2752827,2020-12-21,Guy Lodge,,fresh,"A satisfying marriage of folky period romance and environmental parable from the misty, mossy depths of South Africa's Knysna forest region..."
Connors' War,1555113,2006-11-09,David Nusair,1.5/4,rotten,"...although Criss does show some potential as a performer, his efforts to step into the shoes of a blind character are laughable."
Connors' War,1539106,2006-09-19,Scott Weinberg,2/5,rotten,"Standard cable fodder all the way, with only a few solid action scenes and maybe one colorful performance in the whole thing."
Born to Kill,2710947,2020-08-05,Mike Massie,10/10,fresh,"One of the most acerbic of all films noir, boasting essentially no redeemable characters (or a wealth of deliciously evil villains) while also being utterly enthralling."
Born to Kill,2340106,2016-07-15,David Nusair,3/4,fresh,...a fairly typical film-noir premise that's employed to watchable yet entirely unmemorable effect by Robert Wise...
Born to Kill,1507021,2006-05-16,Nick Schager,B,fresh,Competent if slightly too tame for a supposedly sleazy story.
Born to Kill,1501617,2006-05-01,Fernando F. Croce,,fresh,"The usually meek Robert Wise trades his chameleonic tastefulness for full-on, jazzy misanthropy in this nasty melodrama."
Born to Kill,1433953,2005-09-09,Jeffrey M. Anderson,3/4,fresh,"Hard to watch, but effective and alluring nonetheless."
Born to Kill,1123980,2003-04-02,Dennis Schwartz,C,rotten,A revolting B film noir...
The Soong Sisters,1402087,2005-06-15,Emanuel Levy,3/5,fresh,
La Sapienza,102772380,2023-01-24,Vadim Rizov,,fresh,"Sapienza is a pretty lovely film. Symmetricities are everywhere, starting with that opening architectural showreel, which deliberately avoids perfect symmetricity..."
La Sapienza,2767839,2021-02-14,Dustin Chang,,fresh,Their sincere expression of these thoughts rings true and melts away its artificiality in its presentation soon enough. This is the beauty of La Sapienza and Green films in general.
La Sapienza,2598336,2019-06-18,C.J. Prince,,fresh,"It's a nice entry point into a peculiar cinematic universe, and those willing to open themselves to it will find a lot to enjoy."
La Sapienza,2503963,2018-08-28,Charles Mudede,,fresh,"If architecture aspires to the condition of music, the acting in La Sapienza aspires to the condition of architecture. You will love the ending of this very original and elegant and arty work."
La Sapienza,2314368,2016-03-12,Forrest Cardamenis,B,fresh,This startling architectural juxtaposition feels like a wake-up call.
La Sapienza,2275677,2015-08-03,Nicole Armour,,fresh,"While Green's film is dense with historical fact and theory, it's not averse to plumbing life's mysteries. Suffused with warmth, it expresses a potent admiration for human striving and accomplishment."
La Sapienza,2273804,2015-07-23,Norman Wilner,2/5,rotten,"The uncomplicated narrative resists stylization; Green's presentation turns everyone into mannequins, rendering their emotions theoretical. That may well be his point, but it didn't work for me."
La Sapienza,2269287,2015-06-26,Sam Lubell,,fresh,"On the surface, writer-director Eugne Green's film ""La Sapienza"" is slow, strange and awkward - but stick with it and it may win you over."
La Sapienza,2265997,2015-06-05,Rob Garratt,4/5,fresh,"Layered with reels of swirling shots of Rome's most beautiful buildings -- all crucially shot from the ground upwards, staring at the heavens-- La Sapienza is visually stunning."
La Sapienza,2265990,2015-06-05,Boyd van Hoeij,,fresh,"The Sapience juxtaposes insights on how people are emotionally connected with ruminations on the buildings and spaces through which they move, in which they live and, in Alexandre's case, which they also create."
La Sapienza,2265989,2015-06-05,Robert Horton,3/4,fresh,"If you can groove into this non-realistic mode, the film casts a spell."
La Sapienza,2265790,2015-06-04,Tom Keogh,3.5/4,fresh,A beautiful space for people and light.
La Sapienza,2255621,2015-04-09,Wesley Morris,,rotten,This kind of formalism needs to do more than walk through classical wonders. It should want to create cinema that can stand near or beside them. This movie defensively consecrates what's already there. You don't need a film to do that.
La Sapienza,2255195,2015-04-08,Scott Foundas,,fresh,"An exquisite rumination on life, love and art that tickles the heart and mind in equal measure."
La Sapienza,2252858,2015-03-23,Richard Brody,,fresh,"Green's richly textured, painterly images fuse with the story to evoke the essence of humane urbanity and the relationships that it fosters, whether educational, familial, or erotic."
La Sapienza,2252553,2015-03-20,Ignatiy Vishnevetsky,B+,fresh,"Green doesn't so much use his characters as mouthpieces as emotionally invest them in art, turning opinions into feelings."
La Sapienza,2252541,2015-03-20,Godfrey Cheshire,4/4,fresh,"""La Sapienza"" strikes this reviewer as easily the most astonishing and important movie to emerge from France in quite some time."
La Sapienza,2252452,2015-03-19,A.O. Scott,,fresh,The movie is an unapologetically rarefied undertaking and at the same time a gracious and inviting film.
La Sapienza,2252301,2015-03-19,David Noh,,rotten,"Pretentious, stuffy and slow. There's some beautiful scenery here but oh, what you must put up with to earn it!"
La Sapienza,2252028,2015-03-18,Noel Murray,3/5,fresh,"While La Sapienza is unsatisfying as drama, it's frequently beautiful just as a tour through architecturally significant Italian buildings."
La Sapienza,2251985,2015-03-17,David Ehrlich,3/5,fresh,La Sapienza alternately feels like a self-reflexive love story or a haunted history lesson -- its best scenes play like both.
La Sapienza,2251926,2015-03-17,Zachary Wigon,,fresh,A picture that balances heart and mind with nuance.
La Sapienza,2251650,2015-03-14,Harvey S. Karten,B+,fresh,"As in ""Who's Afraid of Virginia Woolf,"" both the younger couple and their older mentors are changed from a relationship."
La Sapienza,2250991,2015-03-12,Ben Sachs,,fresh,"This recalls Manoel de Oliveira and Eric Rohmer in its poker-faced style, deliberately archaic storytelling, and magisterial epiphanies."
La Sapienza,2225361,2014-09-28,Donald J. Levit,,fresh,"Although a love-fiction crossed with documentary lecture and superb Raphael O'Byrne cinematography, 'La Sapienza' is as close as celluloid can approach to architecture."
La Sapienza,2222032,2014-09-10,Carson Lund,3/4,fresh,"Eugne Green's mannered direction doesn't work for every situation it's homogenously applied to, but at its most effective it inspires an enhanced sensitivity to the import of every gesture, visual or verbal."
Uncle Tom,2713732,2020-08-14,Megan Basham,,fresh,Uncle Tom suffers from an overreliance on pundits. Its most compelling insights come from people who've never been quoted in a Twitter or Facebook battle.
Uncle Tom,2706229,2020-07-19,Matthew Pejkovic,4/5,fresh,"An incredibly relevant and insightful documentary that delves into the past, present, and future of the black American conservative movement."
Uncle Tom,2698525,2020-06-24,Dante James,7/10,fresh,"It's a little misleading in some areas, especially if you know the players involved in this doc, but there are a lot of interesting historical facts about the breakdown of the Black family and how the whole welfare system targeted the Black community."
1 title reviewid creationdate criticname originalscore reviewstate reviewtext
2 Beavers 1145982 2003-05-23 Ivan M. Lincoln 3.5/4 fresh Timed to be just long enough for most youngsters' brief attention spans -- and it's packed with plenty of interesting activity, both on land and under the water.
3 Blood Mask 1636744 2007-06-02 The Foywonder 1/5 rotten It doesn't matter if a movie costs 300 million or only 300 dollars; good is good and bad is bad, and Bloodmask: The Possession of Nicole Lameroux is just plain bad.
4 City Hunter: Shinjuku Private Eyes 2590987 2019-05-28 Reuben Baron fresh The choreography is so precise and lifelike at points one might wonder whether the movie was rotoscoped, but no live-action reference footage was used. The quality is due to the skill of the animators and Kodama's love for professional wrestling.
5 City Hunter: Shinjuku Private Eyes 2558908 2019-02-14 Matt Schley 2.5/5 rotten The film's out-of-touch attempts at humor may find them hunting for the reason the franchise was so popular in the first place.
6 Dangerous Men 2504681 2018-08-29 Pat Padua fresh Its clumsy determination is endearing and sometimes wildly entertaining
7 Dangerous Men 2299284 2015-12-13 Eric Melin 4/5 fresh With every new minute, there's another head-scratching choice that's bound to elicit some amazing out-loud responses, so this feels like a true party flick.
8 Dangerous Men 2295858 2015-11-22 Matt Donato 7/10 fresh Emotionless reaction shots, zero characterization, guns that have absolutely no special effects when blasted - Dangerous Men is rare winning dish from a one star restaurant.
9 Dangerous Men 2295338 2015-11-19 Peter Keough 0.5/4 rotten Conceivably, it could serve as a primer for students on how not to make a movie, and perhaps as a deconstruction of filmic conventions for the more theoretical minded.
10 Dangerous Men 2294641 2015-11-16 Jason Wilson 3/10 rotten If you're not a fan of garbage cinema, even for the fun of it, Dangerous Men is best to be avoided.
11 Dangerous Men 2294129 2015-11-12 Soren Andersen 0/4 rotten "Dangerous Men," the picture's production notes inform, took 26 years to reach the big screen. After having seen it, I wonder: What was the rush?
12 Dangerous Men 2293902 2015-11-12 Maitland McDonagh rotten Will entertain some viewers and infuriate others with its clunky mix of feminist fury and awkward action sequences.
13 Dangerous Men 2293900 2015-11-12 Marjorie Baumgarten 1.5/5 rotten This is a bad movie, but one that awakens your senses every so often with flashes of originality and abundant self-belief.
14 Dangerous Men 2293815 2015-11-12 Katie Rife B+ fresh Ridiculous, artless, and wildly entertaining, Dangerous Men is more than the sum of its fascinatingly misguided parts, although it will take a special sort of moviegoer to truly appreciate (or endure, depending on your perspective) its charms.
15 Dangerous Men 2293605 2015-11-11 Amy Nicholson C fresh To sit through it feels like honoring the dreamers of the world who at least get shit done. Is it terrible? Of course. Is there belly-dancing? Duh.
16 Small Town Wisconsin 102711819 2022-07-22 Peter Gray fresh Small Town Wisconsin could hit some home truths for viewers&#44; and though being faced with the truth isn&#8217;t always pleasant&#44; it feels necessary in growing towards a happier fruition&#46;
17 Small Town Wisconsin 102711545 2022-07-22 Tim Grierson fresh This low-key drama has lovely interludes and some nicely understated performances, although director Niels Mueller doesn’t glean too many new insights from Jason Naczek’s familiar story...
18 Small Town Wisconsin 102700937 2022-06-16 Sumner Forbes 8.5/10 fresh Small Town Wisconsin is a success in almost every regard, and if you can see over the legions of cheeseheads in the rows ahead of you, it shouldn’t be missed.
19 Small Town Wisconsin 102699897 2022-06-14 Tara McNamara 3/5 fresh Just like Wayne&#44; Small Town Wisconsin has flaws&#44; but the poignancy of the story will stick with you for a long time&#46;
20 Small Town Wisconsin 102698744 2022-06-10 Rob Thomas 3/4 fresh It&#8217;s a movie with its heart in the right place&#44; and does both small town and big city Wisconsin proud&#46;
21 Small Town Wisconsin 102698639 2022-06-10 Todd Jorgenson rotten Despite some intriguing character dynamics and performances that generate sympathy for this fractured family&#44; the film stumbles when it veers into melodrama without the narrative dexterity to tackle its weightier ambitions&#46;
22 Small Town Wisconsin 102698482 2022-06-10 Jackie K. Cooper 7/10 fresh This is the kind of movie that draws you so deeply into its story you are reluctant to let it end&#46;
23 Small Town Wisconsin 102698164 2022-06-09 Glenn Kenny fresh Mueller’s direction is patient and sensitive, the cast is accomplished and committed, and the picture’s comedic aspects sometimes earn a chuckle.
24 Small Town Wisconsin 102697854 2022-06-08 Brian Orndorf B+ fresh Naczek isn&apos;t interested in making a soap opera with this examination of fallibility&#44; going somewhere much more authentic when exploring character aches and pains&#46;
25 Small Town Wisconsin 102695788 2022-06-02 Eddie Harrison 4/5 fresh &#8230;a warm-hearted story of everyday life that&#8217;s easy to recommend for those who like films about people rather than portals and vortexes&#8230;
26 Small Town Wisconsin 102695250 2022-05-31 Laura Clifford C rotten Debuting screenwriter Jason Naczek has concocted a manchild redemption story using metaphors as heavy as a hammer and a fairy godmother who makes everything alright with a seeming flip of the switch&#46;
27 Small Town Wisconsin 2733251 2020-10-12 Jared Mobarak B fresh Small Town Wisconsin is always proving itself to be more than its familiar premise thanks to Naczek's ability to infuse a lot more drama into the mix than one custody battle.
28 Tejano 2564925 2019-03-07 Joe Friar 3/4 fresh The story of a South Texas ranch hand who gets mixed up with a Mexican cartel moves with pulse-pounding velocity and features top performances from a talented cast of actors with Texas roots.
29 Tejano 2557738 2019-02-12 Cary Darling 4/5 fresh An entertaining blast of Texas noir that nods toward the work of the Coen brothers, Quentin Tarantino and fellow Austinite Greg Kwedar's 2016 low-budget thriller "Transpecos" as well as "Breaking Bad."
30 Tejano 2547231 2019-01-10 Danielle White 3/5 fresh The story itself slithers with twists and turns and unexpected betrayals. It's almost ridiculous how many characters die in this film.
31 Tejano 2530119 2018-11-08 Chris Salce 9/10 fresh Tejano is one of those films that can be described as a hidden gem as it sneaks under the radar and will have you talking, telling your friends about it, and wanting to watch it again.
32 Death of a Salesman 2770637 2021-02-23 Michael Dougan fresh Miller has taken a small, intimate tale and expanded it into a treatise on larger themes, primarily the abuse of the American Dream.
33 Death of a Salesman 1950734 2011-01-02 Randy White 5/5 fresh A classic American tragedy.
34 Death of a Salesman 1422415 2005-08-04 Jules Brenner 4/5 fresh
35 Death of a Salesman 1409415 2005-07-05 Emanuel Levy 3/5 fresh
36 Death of a Salesman 839546 2003-02-06 Frederic and Mary Ann Brussat fresh Death of a Salesman, directed by Volker Schlondorff, draws out the multiple meanings of this Pulitzer Prize-winning play by Arthur Miller about change, family and fatherhood, work and love.
37 Death of a Salesman 788410 2002-09-29 Dan Lybarger 4/5 fresh Schlndorff's artificial settings and some amazing performances help keep this from looking like a typical "filmed play."
38 Death of a Salesman 751951 2002-08-08 Cory Cheney 4/5 fresh
39 Death of a Salesman 743794 2002-07-26 Bob Grimm 5/5 fresh
40 Death of a Salesman 743291 2002-07-26 Scott Weinberg 5/5 fresh They MAKE you watch it in English class for a good reason!
41 Sahara 1137710 2003-05-13 Dragan Antulov 5/10 fresh
42 The Debt 2628192 2019-09-20 Diego Batlle fresh A Bresson-esque movie that is always enigmatic. [Full Review in Spanish]
43 The Debt 2627988 2019-09-20 Gaspar Zimerman fresh The story [Director Gustavo Fontán] tells is an excuse to give way to the exploration of feelings and sensations that avoid verbality. [Full review in Spanish]
44 Peppermint Candy 2725008 2020-09-16 A.S. Hamrah fresh South Korean political history of the previous twenty years, Peppermint Candy is not tempered by its hysterical edge, which adds unpredictable violence to its vignettes of romantic, domestic, and business failure.
45 Peppermint Candy 2541271 2018-12-16 Panos Kotzathanasis fresh Lee Chang-dong presents a melodrama that stands apart from the plethora of similar productions due to its intense political element, because it doesn't lose its seriousness at any point and because it doesn't become hyperbolic in his effort to draw tears
46 Peppermint Candy 1883708 2010-05-11 Anton Bitel fresh This is Korea's millennial elegy, filtering its search for times past through a confection no less bittersweet than Proust's madeleine.
47 Peppermint Candy 1706014 2008-01-29 Beth Accomando 9/10 fresh The film offers a heartbreaking drama told in reverse chronology and spanning twenty years in both the life of the main character and the political history of Korea.
48 Peppermint Candy 1231988 2003-12-22 Greg Muskewitz 2/5 rotten
49 Peppermint Candy 1187104 2003-08-14 Joshua Tanzer 4/4 fresh It's a story about the original sin of a nation as well as one character. There has rarely been a better film made, ever
50 Prison Girls 2475348 2018-05-03 Roger Ebert rotten Prison Girls didn't have a lot of prison sets because it was a big-budget exploitation movie. Maybe.
51 Gimme the Power 2575688 2019-04-09 Afroxander fresh Rubio's film shows ambition where none is required, making Gimme the Power a lot like Molotov's music: politically engaged without having to take itself too seriously.
52 Paa 2673089 2020-02-27 Nikhat Kazmi 3.5/5 fresh The film, which peters off into vague sub-plots about slum redevelopment and unwarranted media-bashing in the first half, suddenly picks up and scales new heights in the second half.
53 Paa 2578129 2019-04-17 Shubhra Gupta 2/5 rotten Disappointingly, Paa is not as out-of-the-box as it could have been.
54 Paa 2429810 2017-10-24 Anil Sinanan 3/5 rotten Will Auro survive to know his Pa and reunite his parents? Forget about the disease: this is a vanity vehicle designed to showcase the Big B's versatility.
55 Paa 1860476 2009-12-14 Frank Lovece rotten This would-be tearjerker without the musical numbers of typical Bollywood fare is for die-hard Amitabh Bachchan fans only.
56 Paa 1860473 2009-12-14 David Chute fresh The film owes much of its interest to the alertness and sincerity of the younger Bachchan and the luminous Vidya Balan as the anguished parents, and to the soft wash of the tasteful playback songs supplied by Ilaiyaraaja.
57 Paa 1858964 2009-12-05 Avi Offer 5.85/10 rotten Well-acted, funny and occasionally witty with terrific make-up design. However, it's often convoluted, awkwardly paced and too uneven as a whole.
58 Paa 1858853 2009-12-04 Frank Lovece fresh A would-be tearjerker without the singing-dancing musical numbers of typical Bollywood fare seen in the U.S., the lackluster Paa is for die-hard Amitabh Bachchan fans only%u2014of which there is no small number.
59 Paa 1858816 2009-12-04 Rachel Saltz 3/5 fresh Odd and sometimes oddly affecting.
60 Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love) 2835964 2021-10-30 Erich Hellmund-Waldow fresh The acting is not only artistic, it is also as realistic as can be possible in such a film.
61 Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love) 2357086 2016-10-17 C. Hooper Trask fresh Aimed straight for the gooseflesh, it strikes directly into the centre of the target.
62 Toorbos 2760593 2021-01-29 Neil Young fresh Built around a luminous and intriguing central performance by dancer-actor Elani Dekker.
63 Toorbos 2752827 2020-12-21 Guy Lodge fresh A satisfying marriage of folky period romance and environmental parable from the misty, mossy depths of South Africa's Knysna forest region...
64 Connors' War 1555113 2006-11-09 David Nusair 1.5/4 rotten ...although Criss does show some potential as a performer, his efforts to step into the shoes of a blind character are laughable.
65 Connors' War 1539106 2006-09-19 Scott Weinberg 2/5 rotten Standard cable fodder all the way, with only a few solid action scenes and maybe one colorful performance in the whole thing.
66 Born to Kill 2710947 2020-08-05 Mike Massie 10/10 fresh One of the most acerbic of all films noir, boasting essentially no redeemable characters (or a wealth of deliciously evil villains) while also being utterly enthralling.
67 Born to Kill 2340106 2016-07-15 David Nusair 3/4 fresh ...a fairly typical film-noir premise that's employed to watchable yet entirely unmemorable effect by Robert Wise...
68 Born to Kill 1507021 2006-05-16 Nick Schager B fresh Competent if slightly too tame for a supposedly sleazy story.
69 Born to Kill 1501617 2006-05-01 Fernando F. Croce fresh The usually meek Robert Wise trades his chameleonic tastefulness for full-on, jazzy misanthropy in this nasty melodrama.
70 Born to Kill 1433953 2005-09-09 Jeffrey M. Anderson 3/4 fresh Hard to watch, but effective and alluring nonetheless.
71 Born to Kill 1123980 2003-04-02 Dennis Schwartz C rotten A revolting B film noir...
72 The Soong Sisters 1402087 2005-06-15 Emanuel Levy 3/5 fresh
73 La Sapienza 102772380 2023-01-24 Vadim Rizov fresh Sapienza is a pretty lovely film. Symmetricities are everywhere, starting with that opening architectural showreel, which deliberately avoids perfect symmetricity...
74 La Sapienza 2767839 2021-02-14 Dustin Chang fresh Their sincere expression of these thoughts rings true and melts away its artificiality in its presentation soon enough. This is the beauty of La Sapienza and Green films in general.
75 La Sapienza 2598336 2019-06-18 C.J. Prince fresh It's a nice entry point into a peculiar cinematic universe, and those willing to open themselves to it will find a lot to enjoy.
76 La Sapienza 2503963 2018-08-28 Charles Mudede fresh If architecture aspires to the condition of music, the acting in La Sapienza aspires to the condition of architecture. You will love the ending of this very original and elegant and arty work.
77 La Sapienza 2314368 2016-03-12 Forrest Cardamenis B fresh This startling architectural juxtaposition feels like a wake-up call.
78 La Sapienza 2275677 2015-08-03 Nicole Armour fresh While Green's film is dense with historical fact and theory, it's not averse to plumbing life's mysteries. Suffused with warmth, it expresses a potent admiration for human striving and accomplishment.
79 La Sapienza 2273804 2015-07-23 Norman Wilner 2/5 rotten The uncomplicated narrative resists stylization; Green's presentation turns everyone into mannequins, rendering their emotions theoretical. That may well be his point, but it didn't work for me.
80 La Sapienza 2269287 2015-06-26 Sam Lubell fresh On the surface, writer-director Eugne Green's film "La Sapienza" is slow, strange and awkward - but stick with it and it may win you over.
81 La Sapienza 2265997 2015-06-05 Rob Garratt 4/5 fresh Layered with reels of swirling shots of Rome's most beautiful buildings -- all crucially shot from the ground upwards, staring at the heavens-- La Sapienza is visually stunning.
82 La Sapienza 2265990 2015-06-05 Boyd van Hoeij fresh The Sapience juxtaposes insights on how people are emotionally connected with ruminations on the buildings and spaces through which they move, in which they live and, in Alexandre's case, which they also create.
83 La Sapienza 2265989 2015-06-05 Robert Horton 3/4 fresh If you can groove into this non-realistic mode, the film casts a spell.
84 La Sapienza 2265790 2015-06-04 Tom Keogh 3.5/4 fresh A beautiful space for people and light.
85 La Sapienza 2255621 2015-04-09 Wesley Morris rotten This kind of formalism needs to do more than walk through classical wonders. It should want to create cinema that can stand near or beside them. This movie defensively consecrates what's already there. You don't need a film to do that.
86 La Sapienza 2255195 2015-04-08 Scott Foundas fresh An exquisite rumination on life, love and art that tickles the heart and mind in equal measure.
87 La Sapienza 2252858 2015-03-23 Richard Brody fresh Green's richly textured, painterly images fuse with the story to evoke the essence of humane urbanity and the relationships that it fosters, whether educational, familial, or erotic.
88 La Sapienza 2252553 2015-03-20 Ignatiy Vishnevetsky B+ fresh Green doesn't so much use his characters as mouthpieces as emotionally invest them in art, turning opinions into feelings.
89 La Sapienza 2252541 2015-03-20 Godfrey Cheshire 4/4 fresh "La Sapienza" strikes this reviewer as easily the most astonishing and important movie to emerge from France in quite some time.
90 La Sapienza 2252452 2015-03-19 A.O. Scott fresh The movie is an unapologetically rarefied undertaking and at the same time a gracious and inviting film.
91 La Sapienza 2252301 2015-03-19 David Noh rotten Pretentious, stuffy and slow. There's some beautiful scenery here but oh, what you must put up with to earn it!
92 La Sapienza 2252028 2015-03-18 Noel Murray 3/5 fresh While La Sapienza is unsatisfying as drama, it's frequently beautiful just as a tour through architecturally significant Italian buildings.
93 La Sapienza 2251985 2015-03-17 David Ehrlich 3/5 fresh La Sapienza alternately feels like a self-reflexive love story or a haunted history lesson -- its best scenes play like both.
94 La Sapienza 2251926 2015-03-17 Zachary Wigon fresh A picture that balances heart and mind with nuance.
95 La Sapienza 2251650 2015-03-14 Harvey S. Karten B+ fresh As in "Who's Afraid of Virginia Woolf," both the younger couple and their older mentors are changed from a relationship.
96 La Sapienza 2250991 2015-03-12 Ben Sachs fresh This recalls Manoel de Oliveira and Eric Rohmer in its poker-faced style, deliberately archaic storytelling, and magisterial epiphanies.
97 La Sapienza 2225361 2014-09-28 Donald J. Levit fresh Although a love-fiction crossed with documentary lecture and superb Raphael O'Byrne cinematography, 'La Sapienza' is as close as celluloid can approach to architecture.
98 La Sapienza 2222032 2014-09-10 Carson Lund 3/4 fresh Eugne Green's mannered direction doesn't work for every situation it's homogenously applied to, but at its most effective it inspires an enhanced sensitivity to the import of every gesture, visual or verbal.
99 Uncle Tom 2713732 2020-08-14 Megan Basham fresh Uncle Tom suffers from an overreliance on pundits. Its most compelling insights come from people who've never been quoted in a Twitter or Facebook battle.
100 Uncle Tom 2706229 2020-07-19 Matthew Pejkovic 4/5 fresh An incredibly relevant and insightful documentary that delves into the past, present, and future of the black American conservative movement.
101 Uncle Tom 2698525 2020-06-24 Dante James 7/10 fresh It's a little misleading in some areas, especially if you know the players involved in this doc, but there are a lot of interesting historical facts about the breakdown of the Black family and how the whole welfare system targeted the Black community.
+2 -41
View File
@@ -1,4 +1,3 @@
import { DataType } from "@zilliz/milvus2-sdk-node";
import {
MilvusVectorStore,
PapaCSVReader,
@@ -13,45 +12,7 @@ async function main() {
const reader = new PapaCSVReader(false);
const docs = await reader.loadData("./data/movie_reviews.csv");
const vectorStore = new MilvusVectorStore({
contentKey: "content",
});
const milvus = vectorStore.client();
await milvus.createCollection({
collection_name: collectionName,
fields: [
{
name: "id",
data_type: DataType.VarChar,
is_primary_key: true,
max_length: 200,
},
{
name: "embedding",
data_type: DataType.FloatVector,
dim: 1536,
},
{
name: "content",
data_type: DataType.VarChar,
max_length: 9000,
},
{
name: "metadata",
data_type: DataType.JSON,
},
],
});
await milvus.createIndex({
collection_name: collectionName,
field_name: "embedding",
index_type: "HNSW",
params: { efConstruction: 10, M: 4 },
metric_type: "L2",
});
await vectorStore.connect(collectionName);
const vectorStore = new MilvusVectorStore({ collection: collectionName });
const ctx = await storageContextFromDefaults({ vectorStore });
const index = await VectorStoreIndex.fromDocuments(docs, {
@@ -62,4 +23,4 @@ async function main() {
}
}
main();
void main();
+4 -12
View File
@@ -1,20 +1,12 @@
import {
MilvusVectorStore,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
import { MilvusVectorStore, VectorStoreIndex } from "llamaindex";
const collectionName = "movie_reviews";
async function main() {
try {
const milvus = new MilvusVectorStore({
contentKey: "content",
});
await milvus.connect(collectionName);
const milvus = new MilvusVectorStore({ collection: collectionName });
const ctx = serviceContextFromDefaults();
const index = await VectorStoreIndex.fromVectorStore(milvus, ctx);
const index = await VectorStoreIndex.fromVectorStore(milvus);
const retriever = await index.asRetriever({ similarityTopK: 20 });
@@ -30,4 +22,4 @@ async function main() {
}
}
main();
void main();
+9 -15
View File
@@ -1,15 +1,18 @@
import * as fs from "fs/promises";
import {
BaseEmbedding,
Document,
LLM,
MistralAI,
MistralAIEmbedding,
Settings,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function rag(llm: LLM, embedModel: BaseEmbedding, query: string) {
// Update embed model
Settings.embedModel = new MistralAIEmbedding();
// Update llm to use MistralAI
Settings.llm = new MistralAI({ model: "mistral-tiny" });
async function rag(query: string) {
// Load essay from abramov.txt in Node
const path = "node_modules/llamaindex/examples/abramov.txt";
@@ -18,12 +21,7 @@ async function rag(llm: LLM, embedModel: BaseEmbedding, query: string) {
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
// Split text and create embeddings. Store them in a VectorStoreIndex
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
@@ -60,10 +58,6 @@ async function rag(llm: LLM, embedModel: BaseEmbedding, query: string) {
}
// rag
const ragResponse = await rag(
llm,
embedding,
"What did the author do in college?",
);
const ragResponse = await rag("What did the author do in college?");
console.log(ragResponse);
})();
+1 -1
View File
@@ -61,4 +61,4 @@ async function main() {
}
}
main();
void main();
+1 -1
View File
@@ -31,4 +31,4 @@ async function importJsonToMongo() {
}
// Run the import function
importJsonToMongo();
void importJsonToMongo();
+4 -8
View File
@@ -1,10 +1,6 @@
/* eslint-disable turbo/no-undeclared-env-vars */
import * as dotenv from "dotenv";
import {
MongoDBAtlasVectorSearch,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
import { MongoDBAtlasVectorSearch, VectorStoreIndex } from "llamaindex";
import { MongoClient } from "mongodb";
// Load environment variables from local .env file
@@ -12,7 +8,7 @@ dotenv.config();
async function query() {
const client = new MongoClient(process.env.MONGODB_URI!);
const serviceContext = serviceContextFromDefaults();
const store = new MongoDBAtlasVectorSearch({
mongodbClient: client,
dbName: process.env.MONGODB_DATABASE!,
@@ -20,7 +16,7 @@ async function query() {
indexName: process.env.MONGODB_VECTOR_INDEX!,
});
const index = await VectorStoreIndex.fromVectorStore(store, serviceContext);
const index = await VectorStoreIndex.fromVectorStore(store);
const retriever = index.asRetriever({ similarityTopK: 20 });
const queryEngine = index.asQueryEngine({ retriever });
@@ -31,4 +27,4 @@ async function query() {
await client.close();
}
query();
void query();
+1 -1
View File
@@ -30,4 +30,4 @@ async function main() {
console.log(`Similarity between "${text2}" and the image is ${sim2}`);
}
main();
void main();

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