Compare commits

...

156 Commits

Author SHA1 Message Date
github-actions[bot] c517f35526 Release 0.3.11 (#835)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-16 16:35:57 -07:00
Alex Yang e072c45393 fix: remove non-standard API pipeline (#850) 2024-05-16 16:31:48 -07:00
Alex Yang 51241865f8 feat: improve BaseNode (#848) 2024-05-16 16:29:16 -07:00
Thuc Pham 10c83485d2 fix: allow custom task query for agents (#846) 2024-05-16 12:48:50 -07:00
Alex Yang 1e6a18ad2d build: fix jsr release 2024-05-15 18:03:22 -07:00
Alex Yang 9e133ac10d refactor: remove defaultFS from parameters (#841) 2024-05-15 17:37:51 -07:00
Alex Yang ba217eec2c chore: remove test.py (#842) 2024-05-15 16:47:39 -07:00
Alex Yang 64ef70b735 build: ignore example project 2024-05-15 16:10:08 -07:00
Alex Yang 6615aaa4ab chore: use pnpm format
Using `pnpm format:write` will cause two commits which is not expected
2024-05-15 13:11:53 -07:00
Parham Saidi 447105a6dc fix: Gemini text chat - prevent sending broken messageContent and history (#822) 2024-05-15 16:33:55 +07:00
Huu Le (Lee) 320be3fab6 chore: rollback chromadb version to 1.7.3 (#834)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-05-14 16:07:44 +07:00
Alex Yang bbd9f85a45 chore: bump openai (#833) 2024-05-13 12:53:12 -07:00
github-actions[bot] 5f29ba5e2c Release 0.3.10 (#832)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-13 10:53:59 -07:00
Alex Yang 4aba02eb82 feat: support gpt4-o (#831) 2024-05-13 10:51:10 -07:00
Alex Yang 75736ad01b build: release output files 2024-05-10 14:08:21 -07:00
Alex Yang 68a508fcd0 test: fix check host (#829) 2024-05-10 11:07:40 -07:00
github-actions[bot] 6281fc8c91 Release 0.3.9 (#828)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-09 11:16:08 -07:00
Alex Yang c3747d092a feat: add nextjs plugin for llamaindex (#824) 2024-05-09 02:29:11 -05:00
Marcus Schiesser 24a39aefb8 feat: send retrieve start and end events (#827) 2024-05-09 14:16:34 +07:00
Alex Yang 0b1299036d chore: bump version (#826) 2024-05-09 00:11:21 -05:00
Alex Yang 2c8d7941f0 ci: fix publish (#825) 2024-05-08 23:30:17 -05:00
Fabian Wimmer a1a72ab223 feat: LlamaParseReader: update Supported File Types to match python version (#823) 2024-05-09 09:51:01 +07:00
Alex Yang b99ab056d1 feat: init @llamaindex/autotool (#819) 2024-05-08 02:56:42 -05:00
github-actions[bot] 1a45b44307 Release 0.3.8 (#816)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-07 13:05:08 -05:00
JT-Dev-215 804c57519f fix: PGVector similarity score (#817) 2024-05-07 12:54:13 -05:00
Marcus Schiesser ce94780b95 feat: add page number to read PDFs (#815) 2024-05-07 10:45:55 +07:00
ezirmusitua 645fcf6c24 fix: use sha256 hash value as the Document.id_ in MarkdownReader (#768)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-05-07 10:07:39 +07:00
Marcus Schiesser e37fa5d9ca docs: add retriever tool example (#814) 2024-05-07 09:41:14 +07:00
github-actions[bot] 97e4ecd5b8 Release 0.3.7 (#812)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-05 22:11:54 -05:00
Alex Yang b6a660651b feat: allow to change ollama port (#811) 2024-05-05 19:08:00 -05:00
github-actions[bot] 456d3fb0b3 Release 0.3.6 (#810)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-05 18:40:58 -05:00
Alex Yang efa326a871 chore: update package.json and usage of lodash (#809) 2024-05-05 18:30:46 -05:00
Alex Yang 5765b637ce build: fix jsr release 2024-05-03 18:21:08 -05:00
github-actions[bot] 72687b4f69 Release 0.3.5 (#805)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-03 18:16:39 -05:00
Alex Yang 0c67e1f8f3 build: fix new version script 2024-05-03 18:13:24 -05:00
Alex Yang 4a0619758a chore: fix jsr.json 2024-05-03 18:09:05 -05:00
Alex Yang bc7a11cdbe fix: inline ollama build (#807) 2024-05-03 18:03:23 -05:00
Alex Yang 5596e31947 feat: improve @llamaindex/env (#787) 2024-05-03 18:03:14 -05:00
Alex Yang 2fe2b813ba fix: filter with multiple filters in ChromaDB (#784) 2024-05-03 17:07:45 -05:00
Alex Yang be5df5b01b fix(core): multple chat on anthropic agent (#799) 2024-05-03 16:18:46 -05:00
JT-Dev-215 e74fe88342 fix: change <-> to <=> in the SELECT query (#804)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-05-03 12:10:36 -05:00
github-actions[bot] f1862ccab1 Release 0.3.4 (#797)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-02 20:02:06 -05:00
Yi Ding 9e74a4327f feat: add top k to asQueryEngine (#801)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-05-02 19:59:36 -05:00
Alex Yang 5e61934d5a fix: remove clone object in CallbackManager.dispatchEvent (#802) 2024-05-02 19:55:41 -05:00
Alex Yang 2008efe0ee feat: add verbose mode to Agent (#800) 2024-05-02 19:54:05 -05:00
Alex Yang ee719a1fda fix: streaming for ReAct Agent (#798) 2024-05-02 18:52:18 -05:00
Alex Yang 1dce275a7c fix: export StorageContext on edge runtime (#793) 2024-05-02 14:52:16 -05:00
Thuc Pham d10533ef77 feat: add hugging face llm (#796) 2024-05-02 18:43:05 +08:00
github-actions[bot] 8aeb8ae690 Release 0.3.3 (#792)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-01 21:47:16 -05:00
Thuc Pham e8c41c5c27 fix: wrong gemini streaming chat response (#791) 2024-05-02 08:39:57 +07:00
github-actions[bot] 051b4ddfa2 Release 0.3.2 (#790)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-01 19:30:09 -05:00
Alex Yang 61103b677b fix: streaming for Agent.createTask (#788) 2024-05-01 19:26:06 -05:00
Alex Yang e69cac672a docs: update blog post 2024-05-01 13:01:55 -05:00
Alex Yang 94246a3ca8 chore: bump jsr.json 2024-05-01 12:59:03 -05:00
github-actions[bot] b440a008e5 Release 0.3.1 (#786)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-01 12:39:37 -05:00
Alex Yang 46227f2a70 fix: build error on next.js nodejs runtime (#785) 2024-05-01 12:37:43 -05:00
Alex Yang 77f0298f6f chore: update jsr.json 2024-04-30 22:47:09 -05:00
github-actions[bot] c14e112236 Release 0.3.0 (#783)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-04-30 22:46:10 -05:00
Alex Yang 62b035fdc1 build: fix test package naming 2024-04-30 22:42:06 -05:00
Alex Yang aa0be1469b build: update expectedMinorVersion 2024-04-30 22:37:14 -05:00
Alex Yang 5016f21d52 feat(core): better next.js/cloudflare/vite support 2024-04-30 22:34:54 -05:00
Marcus Schiesser 130b7992a1 refactor: clean gemini embedding (#781) 2024-04-30 10:51:22 +07:00
Yi Ding 0d50b22dbf fix(core): add more exports on llm/index (#780) 2024-04-28 20:43:14 -05:00
Alex Yang db1d1f57c9 build(wasm-tools): fix type check 2024-04-28 20:29:01 -05:00
Alex Yang dccb8163d8 fix(core): polyfill Web Stream APIs (#777) 2024-04-28 18:35:33 -05:00
Fabian Wimmer 1ab3ba407e feat: add Language and parsingInstruction to LlamaParseReader (#779)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-28 17:00:58 -05:00
Alex Yang b03f765733 chore: update husky script (#776) 2024-04-27 01:10:34 -05:00
Alex Yang 7488d3c235 fix: agent callback with step infomation (#774) 2024-04-26 18:13:05 -05:00
github-actions[bot] 5cb270d07f Release 0.2.13 (#773)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-04-26 13:26:12 -05:00
Alex Yang 62771058aa fix: empty tools (#772) 2024-04-26 13:10:57 -05:00
github-actions[bot] ca348a6570 Release 0.2.12 (#770)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-04-26 13:11:23 +07:00
Marcus Schiesser 44a7fd72e8 ci: publish github release on tag pushes (#771) 2024-04-26 13:09:25 +07:00
Thuc Pham d8d952d937 feat: init gemini llm (#769) 2024-04-26 11:04:33 +07:00
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
440 changed files with 46632 additions and 16654 deletions
+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:
+1 -1
View File
@@ -14,7 +14,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:
+37
View File
@@ -0,0 +1,37 @@
name: Publish to GitHub Releases
on:
push:
tags:
- "llamaindex@*"
jobs:
build-and-publish:
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: Build tarball
run: |
pnpm pack
working-directory: packages/core
- name: Create release
uses: ncipollo/release-action@v1
with:
artifacts: "packages/core/llamaindex-*.tgz"
name: Release ${{ github.ref }}
bodyFile: "packages/core/CHANGELOG.md"
token: ${{ secrets.GITHUB_TOKEN }}
+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 -16
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:
@@ -32,24 +69,33 @@ jobs:
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm run build --filter llamaindex
run: pnpm run build
- 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
run: pnpm run circular-check
working-directory: ./packages/core
run: pnpm dlx turbo run circular-check
- uses: actions/upload-artifact@v3
if: failure()
with:
name: typecheck-build-dist
path: ./packages/core/dist
if-no-files-found: error
core-edge-runtime:
e2e-core-examples:
strategy:
matrix:
packages:
- cloudflare-worker-agent
- nextjs-agent
- nextjs-edge-runtime
- waku-query-engine
runs-on: ubuntu-latest
name: Build Core Example (${{ matrix.packages }})
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:
@@ -57,17 +103,18 @@ jobs:
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm run build --filter @llamaindex/edge
- name: Build Edge Runtime
- name: Build llamaindex
run: pnpm run build
working-directory: ./packages/edge/e2e/test-edge-runtime
- name: Build ${{ matrix.packages }}
run: pnpm run build
working-directory: packages/core/e2e/examples/${{ matrix.packages }}
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:
@@ -76,7 +123,7 @@ jobs:
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm run build --filter llamaindex
run: pnpm run build
- name: Copy examples
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
- name: Pack @llamaindex/env
-1
View File
@@ -1 +0,0 @@
pnpm test
+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
+1 -1
View File
@@ -1 +1 @@
18
20
+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}"]
}
]
}
+5 -11
View File
@@ -91,16 +91,10 @@ Please send a descriptive changeset for each PR.
## Publishing (maintainers only)
To publish a new version of the library, first create a new version:
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
PR called "Release {version}".
```shell
pnpm new-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 everything looks good, commit the generated files and release the new version:
```shell
pnpm release
git push # push to the main branch
git push --tags
```
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)
+142 -74
View File
@@ -19,25 +19,29 @@ Try examples online:
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
## Getting started with an example:
## Multiple JS Environment Support
LlamaIndex.TS requires Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
LlamaIndex.TS supports multiple JS environments, including:
In a new folder:
- Node.js (18, 20, 22) ✅
- Deno ✅
- Bun ✅
- React Server Components (Next.js) ✅
```bash
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
pnpm init
pnpm install typescript
pnpm exec tsc --init # if needed
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
## Getting started
```shell
npm install llamaindex
pnpm install llamaindex
pnpm install @types/node
yarn add llamaindex
jsr install @llamaindex/core
```
Create the file example.ts
### Node.js
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
@@ -67,10 +71,121 @@ async function main() {
main();
```
Then you can run it using
```bash
pnpm dlx ts-node example.ts
# `pnpm install tsx` before running the script
node --import tsx ./main.ts
```
### Next.js
First, you will need to add a llamaindex plugin to your Next.js project.
```js
// next.config.js
const withLlamaIndex = require("llamaindex/next");
module.exports = withLlamaIndex({
// your next.js config
});
```
You can combine `ai` with `llamaindex` in Next.js with RSC (React Server Components).
```tsx
// src/apps/page.tsx
"use client";
import { chatWithAgent } from "@/actions";
import type { JSX } from "react";
import { useFormState } from "react-dom";
// You can use the Edge runtime in Next.js by adding this line:
// export const runtime = "edge";
export default function Home() {
const [ui, action] = useFormState<JSX.Element | null>(async () => {
return chatWithAgent("hello!", []);
}, null);
return (
<main>
{ui}
<form action={action}>
<button>Chat</button>
</form>
</main>
);
}
```
```tsx
// src/actions/index.ts
"use server";
import { createStreamableUI } from "ai/rsc";
import { OpenAIAgent } from "llamaindex";
import type { ChatMessage } from "llamaindex/llm/types";
export async function chatWithAgent(
question: string,
prevMessages: ChatMessage[] = [],
) {
const agent = new OpenAIAgent({
tools: [
// ... adding your tools here
],
});
const responseStream = await agent.chat({
stream: true,
message: question,
chatHistory: prevMessages,
});
const uiStream = createStreamableUI(<div>loading...</div>);
responseStream
.pipeTo(
new WritableStream({
start: () => {
uiStream.update("response:");
},
write: async (message) => {
uiStream.append(message.response.delta);
},
}),
)
.catch(console.error);
return uiStream.value;
}
```
### Cloudflare Workers
```ts
// src/index.ts
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const { setEnvs } = await import("@llamaindex/env");
// set environment variables so that the OpenAIAgent can use them
setEnvs(env);
const { OpenAIAgent } = await import("llamaindex");
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: "Hello? What is the weather today?",
});
const textEncoder = new TextEncoder();
const response = responseStream.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(textEncoder.encode(chunk.response.delta));
},
}),
);
return new Response(response);
},
};
```
## Playground
@@ -93,72 +208,25 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
- [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.
## Using NextJS
## Tips when using in non-Node.js environments
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).
When you are importing `llamaindex` in a non-Node.js environment(such as React Server Components, Cloudflare Workers, etc.)
Some classes are not exported from top-level entry file.
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:
The reason is that some classes are only compatible with Node.js runtime,(e.g. `PDFReader`) which uses Node.js specific APIs(like `fs`, `child_process`, `crypto`).
If you need any of those classes, you have to import them instead directly though their file path in the package.
Here's an example for importing the `PineconeVectorStore` class:
```typescript
export const runtime = "edge";
import { PineconeVectorStore } from "llamaindex/storage/vectorStore/PineconeVectorStore";
```
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", "@zilliz/milvus2-sdk-node"],
},
webpack: (config) => {
config.resolve.alias = {
...config.resolve.alias,
sharp$: false,
"onnxruntime-node$": false,
};
return config;
},
};
module.exports = nextConfig;
```
### Using the Edge runtime
We publish a dedicated package (`@llamaindex/edge` instead of `llamaindex`) for using the Edge runtime. To use it, first install the package:
```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:
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
```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 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";
import { SimpleDirectoryReader } from "llamaindex/readers/SimpleDirectoryReader";
import { LlamaParseReader } from "llamaindex/readers/LlamaParseReader";
export const DATA_DIR = "./data";
@@ -176,14 +244,14 @@ export async function getDocuments() {
> _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
You'll find a complete example 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 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
+120
View File
@@ -1,5 +1,125 @@
# docs
## 0.0.19
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
## 0.0.18
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
## 0.0.17
### Patch Changes
- Updated dependencies [c3747d0]
- llamaindex@0.3.9
## 0.0.16
### Patch Changes
- Updated dependencies [ce94780]
- llamaindex@0.3.8
## 0.0.15
### Patch Changes
- Updated dependencies [b6a6606]
- Updated dependencies [b6a6606]
- llamaindex@0.3.7
## 0.0.14
### Patch Changes
- Updated dependencies [efa326a]
- llamaindex@0.3.6
## 0.0.13
### Patch Changes
- Updated dependencies [bc7a11c]
- Updated dependencies [2fe2b81]
- Updated dependencies [5596e31]
- Updated dependencies [e74fe88]
- Updated dependencies [be5df5b]
- llamaindex@0.3.5
## 0.0.12
### Patch Changes
- Updated dependencies [1dce275]
- Updated dependencies [d10533e]
- Updated dependencies [2008efe]
- Updated dependencies [5e61934]
- Updated dependencies [9e74a43]
- Updated dependencies [ee719a1]
- llamaindex@0.3.4
## 0.0.11
### Patch Changes
- Updated dependencies [e8c41c5]
- llamaindex@0.3.3
## 0.0.10
### Patch Changes
- Updated dependencies [61103b6]
- llamaindex@0.3.2
## 0.0.9
### Patch Changes
- Updated dependencies [46227f2]
- llamaindex@0.3.1
## 0.0.8
### Patch Changes
- Updated dependencies [5016f21]
- llamaindex@0.3.0
## 0.0.7
### Patch Changes
- Updated dependencies [6277105]
- llamaindex@0.2.13
## 0.0.6
### Patch Changes
- Updated dependencies [d8d952d]
- llamaindex@0.2.12
## 0.0.5
### Patch Changes
- Updated dependencies [87142b2]
- Updated dependencies [5a6cc0e]
- Updated dependencies [87142b2]
- llamaindex@0.2.11
## 0.0.4
### Patch Changes
+493
View File
@@ -0,0 +1,493 @@
---
title: LlamaIndexTS v0.3.0
description: This is my first post on Docusaurus.
slug: welcome-llamaindexts-v0.3
authors:
- name: Alex Yang
title: LlamaIndexTS maintainer, Node.js Member
url: https://github.com/himself65
image_url: https://github.com/himself65.png
tags: [llamaindex, agent]
hide_table_of_contents: false
---
- [What's new in LlamaIndexTS v0.3.0](#whats-new-in-llamaindexts-v030)
- [Improvement in LlamaIndexTS v0.3.0](#improvement-in-llamaindexts-v030)
- [What's the next?](#whats-the-next)
## What's new in LlamaIndexTS v0.3.0
## Agents
In this release, we've not only ported the Agent module from the LlamaIndex Python version but have significantly
enhanced it to be more powerful and user-friendly for JavaScript/TypeScript applications.
Starting from v0.3.0, we are introducing multiple agents specifically designed for RAG applications, including:
- `OpenAIAgent`
- `AnthropicAgent`
- `ReActAgent`:
```ts
import { OpenAIAgent } from "llamaindex";
import { tools } from "./tools";
const agent = new OpenAIAgent({
tools: [...tools],
});
const { response } = await agent.chat({
message: "What is weather today?",
stream: false,
});
console.log(response.message.content);
```
We are also introducing the abstract AgentRunner class, which allows you to create your own agent by simply implementing
the task handler.
```ts
import { AgentRunner, OpenAI } from "llamaindex";
class MyLLM extends OpenAI {}
export class MyAgentWorker extends AgentWorker<MyLLM> {
taskHandler = MyAgent.taskHandler;
}
export class MyAgent extends AgentRunner<MyLLM> {
constructor(params: Params) {
super({
llm: params.llm,
chatHistory: params.chatHistory ?? [],
systemPrompt: params.systemPrompt ?? null,
runner: new MyAgentWorker(),
tools:
"tools" in params
? params.tools
: params.toolRetriever.retrieve.bind(params.toolRetriever),
});
}
// create store is a function to create a store for each task, by default it only includes `messages` and `toolOutputs`
createStore = AgentRunner.defaultCreateStore;
static taskHandler: TaskHandler<Anthropic> = async (step, enqueueOutput) => {
const { llm, stream } = step.context;
// initialize the input
const response = await llm.chat({
stream,
messages: step.context.store.messages,
});
// store the response for next task step
step.context.store.messages = [
...step.context.store.messages,
response.message,
];
// your logic here to decide whether to continue the task
const shouldContinue = Math.random(); /* <-- replace with your logic here */
enqueueOutput({
taskStep: step,
output: response,
isLast: !shouldContinue,
});
if (shouldContinue) {
const content = await someHeavyFunctionCall();
// if you want to continue the task, you can insert your new context for the next task step
step.context.store.messages = [
...step.context.store.messages,
{
content,
role: "user",
},
];
}
};
}
```
### Web Stream API for Streaming response
Web Stream is a web standard utilized in many modern web frameworks and libraries (like React 19, Deno, Node 22). We
have migrated streaming responses to Web Stream to ensure broader compatibility.
For instance, you can use the streaming response in a simple HTTP Server:
```ts
import { createServer } from "http";
import { OpenAIAgent } from "llamaindex";
import { OpenAIStream, streamToResponse } from "ai";
import { tools } from "./tools";
const agent = new OpenAIAgent({
tools: [...tools],
});
const server = createServer(async (req, res) => {
const response = await agent.chat({
message: "What is weather today?",
stream: true,
});
// Transform the response into a string readable stream
const stream: ReadableStream<string> = response.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(chunk.response.delta);
},
}),
);
// Pipe the stream to the response
streamToResponse(stream, res);
});
server.listen(3000);
```
Or it can be integrated into React Server Components (RSC) in Next.js:
```tsx
// app/actions/index.tsx
"use server";
import { createStreamableUI } from "ai/rsc";
import { OpenAIAgent } from "llamaindex";
import type { ChatMessage } from "llamaindex/llm/types";
export async function chatWithAgent(
question: string,
prevMessages: ChatMessage[] = [],
) {
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: question,
chatHistory: prevMessages,
});
const uiStream = createStreamableUI(<div>loading...</div>);
responseStream
.pipeTo(
new WritableStream({
start: () => {
uiStream.update("response:");
},
write: async (message) => {
uiStream.append(message.response.delta);
},
}),
)
.catch(uiStream.error);
return uiStream.value;
}
```
```tsx
// app/src/page.tsx
"use client";
import { chatWithAgent } from "@/actions";
import type { JSX } from "react";
import { useFormState } from "react-dom";
export const runtime = "edge";
export default function Home() {
const [state, action] = useFormState<JSX.Element | null>(async () => {
return chatWithAgent("hello!", []);
}, null);
return (
<main>
{state}
<form action={action}>
<button>Chat</button>
</form>
</main>
);
}
```
## Improvement in LlamaIndexTS v0.3.0
### Better TypeScript support
We have made significant improvements to the type system to ensure that all code is thoroughly checked before it is
published. This ongoing enhancement has already resulted in better module reliability and developer experience.
For example, we have improved `FunctionTool` type with generic support:
```ts
type Input = {
a: number;
b: number;
};
const sumNumbers = FunctionTool.from<Input>(
({ a, b }) => `${a + b}`, // a and b will be checked as number
// JSON schema will be an error if you type wrong.
{
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
},
},
);
```
![type checking](./img/function_tool_example.png)
### Better Next.js, Deno, Cloudflare Worker, and Waku(Vite) support
In addition to Node.js, LlamaIndexTS now offers enhanced support for Next.js, Deno, and Cloudflare Workers, making it
more versatile across different platforms.
For now, you can install llamaindex and directly import it into your existing Next.js, Deno or Cloudflare Worker project
**without any extra configuration**.
#### [Deno](https://deno.com/)
You can use LlamaIndexTS in Deno by installation through JSR:
```sh
jsr add @llamaindex/core
```
#### [Cloudflare Worker](https://developers.cloudflare.com/workers/)
For Cloudflare Workers, here is a starter template:
```typescript
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const { setEnvs } = await import("@llamaindex/env");
setEnvs(env);
const { OpenAIAgent } = await import("llamaindex");
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: "Hello? What is the weather today?",
});
const textEncoder = new TextEncoder();
const response = responseStream.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(textEncoder.encode(chunk.response.delta));
},
}),
);
return new Response(response);
},
};
```
### [Waku (Vite)](https://waku.gg/)
Waku powered by Vite is a minimal React framework that supports multiple JS environments, including Deno, Cloudflare, and
Node.js.
You can use LlamaIndexTS with Node.js output to enable full Node.js support with React.
```sh
npm install llamaindex
```
```ts
// file: src/actions.ts
"use server";
import { Document, VectorStoreIndex } from "llamaindex";
import { readFile } from "node:fs/promises";
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await readFile(path, "utf-8");
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
export async function chatWithAI(question: string): Promise<string> {
const { response } = await queryEngine.query({ query: question });
return response;
}
```
```tsx
// file: src/pages/index.tsx
import { chatWithAI } from "./actions";
export default async function HomePage() {
return (
<div>
<Chat askQuestion={chatWithAI} />
</div>
);
}
```
```tsx
// file: src/components/Chat.tsx
"use client";
export type ChatProps = {
askQuestion: (question: string) => Promise<string>;
};
export const Chat = (props: ChatProps) => {
const [response, setResponse] = useState<string | null>(null);
return (
<section className="border-blue-400 -mx-4 mt-4 rounded border border-dashed p-4">
<h2 className="text-lg font-bold">Chat with AI</h2>
{response ? (
<p className="text-sm text-gray-600 max-w-sm">{response}</p>
) : null}
<form
action={async (formData) => {
const question = formData.get("question") as string | null;
if (question) {
setResponse(await props.askQuestion(question));
}
}}
>
<input
type="text"
name="question"
className="border border-gray-400 rounded-sm px-2 py-0.5 text-sm"
/>
<button className="rounded-sm bg-black px-2 py-0.5 text-sm text-white">
Ask
</button>
</form>
</section>
);
};
```
```shell
waku dev # development mode
waku build # build for production
waku start # start the production server
```
Note that not all the modules are supported in all JS environments because of
lack of the file system, network API,
and incompatibility with the Node.js API by upstream dependencies.
But we are trying to make it more compatible with all the environments.
## What's the next?
As we continue to develop LlamaIndexTS, our focus remains on providing more comprehensive and powerful tools for
creating custom agents.
### Align with the Python `llama-index`
We aim to align LlamaIndexTS with the Python version to ensure API consistency and ease of use for developers familiar
with the Python ecosystem.
### Align with the Web Standard and JS development
Not all python APIs are compatible and easy to use in JavaScript/TypeScript.
We are trying to make the API more compatible with the Web Standard and JavaScript modern development.
### More Agents
Future releases will introduce more agents from the Python Llama-Index and explore APIs tailored to real-world use
cases.
### 🧪 `@llamaindex/tool`
We are exploring innovative ways to create tools for agents. The `@llamaindex/tool` library allows you to transform any
function into a tool for an agent, simplifying the development process and reducing runtime costs.
```ts
export function getWeather(city: string) {
return `The weather in ${city} is sunny.`;
}
// you don't need to worry about the shcema with different llm tools
export function getTemperature(city: string) {
return `The temperature in ${city} is 25°C.`;
}
export function getCurrentCity() {
return "New York";
}
```
These functions can be easily integrated into your applications, such as Next.js:
```ts
"use server";
import { OpenAI } from "openai";
import { getTools } from "@llamaindex/tool";
export async function chat(message: string) {
const openai = new OpenAI();
openai.chat.completions.create({
messages: [
{
role: "user",
content: "What is the weather in the current city?",
},
],
tools: getTools("openai"),
});
}
```
```ts
// next.config.js
const withTool = require("@llamaindex/tool/next");
const config = {
// Your original Next.js config
};
module.exports = withTool(config);
```
The functions are automatically transformed into tools for the agent at compile time, which eliminates any extra runtime
costs. This feature is particularly beneficial when you need to debug or deploy your assistant.
For deploying your local functions into OpenAI, you can use a simple command:
```sh
npm install -g @llamaindex/tool
mkai --tools ./src/index.llama.ts
# Successfully created assistant: asst_XXX
# chat with your assistant by `chatai --assistant asst_XXX`
chatai --assistant asst_XXX
# Open your browser and chat with your assistant
# Running at http://localhost:3000
```
This deployment process simplifies the testing and implementation of your custom tools in a live environment.
As this project is still in its early stages, we continue to explore the best ways to create and integrate tools for
agents. For more information and updates, visit the @llamaindex/tool repository.
This release of LlamaIndexTS v0.3.0 marks a significant step forward in our journey to provide developers with robust,
flexible tools for building advanced agents. We are excited to see how our community utilizes these new capabilities to
create innovative solutions and look forward to continuing to support and enhance LlamaIndexTS in future updates.
Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

+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,309 +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,
Settings,
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
Settings.llm = new OpenAI({
model: "gpt-4",
});
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({
storageContext: storageContext,
nodes,
});
// create the summary index for broader search
const summaryIndex = await SummaryIndex.init({
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,
{
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");
});
```
@@ -0,0 +1,33 @@
# Gemini
To use Gemini embeddings, you need to import `GeminiEmbedding` from `llamaindex`.
```ts
import { GeminiEmbedding, Settings } from "llamaindex";
// Update Embed Model
Settings.embedModel = new GeminiEmbedding();
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,
});
```
Per default, `GeminiEmbedding` is using the `gemini-pro` model. You can change the model by passing the `model` parameter to the constructor.
For example:
```ts
import { GEMINI_MODEL, GeminiEmbedding } from "llamaindex";
Settings.embedModel = new GeminiEmbedding({
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
});
```
@@ -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,
});
```
@@ -1,11 +1,19 @@
# 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, Settings } from "llamaindex";
import { OllamaEmbedding, Settings } from "llamaindex";
Settings.embedModel = new Ollama();
Settings.embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
const document = new Document({ text: essay, id_: "essay" });
@@ -0,0 +1,71 @@
# Gemini
## Usage
```ts
import { Gemini, Settings, GEMINI_MODEL } from "llamaindex";
Settings.llm = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
```
## 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" });
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
Gemini,
Document,
VectorStoreIndex,
Settings,
GEMINI_MODEL,
} from "llamaindex";
Settings.llm = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
async function main() {
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -3,7 +3,7 @@
## Usage
```ts
import { Ollama, Settings } from "llamaindex";
import { Ollama, Settings, DeuceChatStrategy } from "llamaindex";
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
```
@@ -11,7 +11,12 @@ Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
## Usage with Replication
```ts
import { Ollama, ReplicateSession, Settings } from "llamaindex";
import {
Ollama,
ReplicateSession,
Settings,
DeuceChatStrategy,
} from "llamaindex";
const replicateSession = new ReplicateSession({
replicateKey,
@@ -48,7 +53,13 @@ const results = await queryEngine.query({
## Full Example
```ts
import { LlamaDeuce, Document, VectorStoreIndex, Settings } from "llamaindex";
import {
LlamaDeuce,
Document,
VectorStoreIndex,
Settings,
DeuceChatStrategy,
} from "llamaindex";
// Use the LlamaDeuce LLM
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
@@ -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?");
```
+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).
+1 -1
View File
@@ -6,7 +6,7 @@ This page shows how to track LLM cost using APIs.
The callback manager is a class that manages the callback functions.
You can register `llm-start`, and `llm-end` callbacks to the callback manager for tracking the cost.
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";
+7 -2
View File
@@ -66,7 +66,11 @@ const config = {
[require("@docusaurus/remark-plugin-npm2yarn"), { sync: true }],
],
},
blog: false,
blog: {
blogTitle: "LlamaIndexTS blog",
blogDescription: "The official blog of LlamaIndexTS",
postsPerPage: "ALL",
},
gtag: {
trackingID: "G-NB9B8LW9W5",
anonymizeIP: true,
@@ -97,6 +101,7 @@ const config = {
type: "localeDropdown",
position: "left",
},
{ to: "blog", label: "Blog", position: "right" },
{
href: "https://github.com/run-llama/LlamaIndexTS",
label: "GitHub",
@@ -163,7 +168,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}",
+18 -17
View File
@@ -1,6 +1,6 @@
{
"name": "docs",
"version": "0.0.4",
"version": "0.0.19",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@@ -15,28 +15,29 @@
"typecheck": "tsc"
},
"dependencies": {
"@docusaurus/core": "^3.2.0",
"@docusaurus/remark-plugin-npm2yarn": "^3.2.0",
"@docusaurus/core": "^3.3.2",
"@docusaurus/remark-plugin-npm2yarn": "^3.3.2",
"@llamaindex/examples": "workspace:*",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.1.0",
"postcss": "^8.4.33",
"@mdx-js/react": "^3.0.1",
"clsx": "^2.1.1",
"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"
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.2.0",
"@docusaurus/preset-classic": "^3.2.0",
"@docusaurus/theme-classic": "^3.2.0",
"@docusaurus/types": "^3.2.0",
"@docusaurus/module-type-aliases": "3.3.2",
"@docusaurus/preset-classic": "^3.3.2",
"@docusaurus/theme-classic": "^3.3.2",
"@docusaurus/types": "^3.3.2",
"@tsconfig/docusaurus": "^2.0.3",
"@types/node": "^18.19.10",
"docusaurus-plugin-typedoc": "^0.22.0",
"typedoc": "^0.25.12",
"typedoc-plugin-markdown": "^3.17.1",
"typescript": "^5.4.3"
"@types/node": "^20.12.11",
"docusaurus-plugin-typedoc": "^1.0.1",
"typedoc": "^0.25.13",
"typedoc-plugin-markdown": "^4.0.1",
"typescript": "^5.4.5"
},
"browserslist": {
"production": [
+1
View File
@@ -0,0 +1 @@
DEBUG=llamaindex
+2 -4
View File
@@ -86,7 +86,6 @@ async function main() {
const agent = new OpenAIAgent({
tools: queryEngineTools,
llm: new OpenAI({ model: "gpt-4" }),
verbose: true,
});
documentAgents[title] = agent;
@@ -126,8 +125,7 @@ async function main() {
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm: new OpenAI({ model: "gpt-4" }),
verbose: true,
prefixMessages: [
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.",
@@ -145,4 +143,4 @@ async function main() {
});
}
main();
void main();
+39
View File
@@ -0,0 +1,39 @@
import { ChatResponseChunk, OpenAIAgent } from "llamaindex";
import { ReadableStream } from "node:stream/web";
import {
getCurrentIDTool,
getUserInfoTool,
getWeatherTool,
} from "./utils/tools";
async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [getCurrentIDTool, getUserInfoTool, getWeatherTool],
});
const task = await agent.createTask(
"What is my current address weather based on my profile?",
true,
);
for await (const stepOutput of task) {
const stream = stepOutput.output as ReadableStream<ChatResponseChunk>;
if (stepOutput.isLast) {
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
process.stdout.write("\n");
} else {
// handing function call
console.log("handling function call...");
for await (const chunk of stream) {
console.log("debug:", JSON.stringify(chunk.raw));
}
}
}
}
void main().then(() => {
console.log("Done");
});
+42 -57
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));
console.log(response.response.message);
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+3 -3
View File
@@ -34,13 +34,13 @@ async function main() {
// Chat with the agent
const response = await agent.chat({
message: "What was his salary?",
message: "What was his first salary?",
});
// Print the response
console.log(String(response));
console.log(response.response);
}
main().then(() => {
void main().then(() => {
console.log("Done");
});
+40
View File
@@ -0,0 +1,40 @@
import { ChatResponseChunk, ReActAgent } from "llamaindex";
import { ReadableStream } from "node:stream/web";
import {
getCurrentIDTool,
getUserInfoTool,
getWeatherTool,
} from "./utils/tools";
async function main() {
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
tools: [getCurrentIDTool, getUserInfoTool, getWeatherTool],
});
const task = await agent.createTask(
"What is my current address weather based on my profile?",
true,
);
for await (const stepOutput of task) {
const stream = stepOutput.output as ReadableStream<ChatResponseChunk>;
if (stepOutput.isLast) {
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
process.stdout.write("\n");
} else {
// handing function call
console.log("handling function call...");
for await (const chunk of stream) {
console.log("debug:", JSON.stringify(chunk.raw));
}
}
console.log("---");
}
}
void main().then(() => {
console.log("Done");
});
+9 -10
View File
@@ -1,13 +1,13 @@
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
@@ -65,18 +65,17 @@ async function main() {
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");
});
+65
View File
@@ -0,0 +1,65 @@
import {
FunctionTool,
MetadataMode,
NodeWithScore,
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
} 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);
const retriever = vectorIndex.asRetriever({ similarityTopK: 3 });
const retrieverTool = FunctionTool.from(
async ({ query }: { query: string }) => {
const nodesWithScores = await retriever.retrieve({
query,
});
return nodesWithScores
.map((nodeWithScore: NodeWithScore) =>
nodeWithScore.node.getContent(MetadataMode.NONE),
)
.join("\n");
},
{
name: "get_abramov_info",
description: "Get information about the Abramov documents",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The query about Abramov",
},
},
required: ["query"],
},
},
);
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [retrieverTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "What was his first salary?",
});
// Print the response
console.log(response.response);
}
void main().then(() => {
console.log("Done");
});
-95
View File
@@ -1,95 +0,0 @@
import { FunctionTool, OpenAIAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend a to divide",
},
b: {
type: "number",
description: "The divisor b to divide by",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const functionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const functionTool2 = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
// Create a task to sum and divide numbers
const task = agent.createTask("How much is 5 + 5? then divide by 2");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
if (stepOutput.output.response) {
console.log(stepOutput.output.response);
} else {
console.log(stepOutput.output.sources);
}
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
main().then(() => {
console.log("Done");
});
+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");
});
+15 -12
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({
@@ -67,11 +66,15 @@ async function main() {
stream: true,
});
for await (const chunk of stream.response) {
process.stdout.write(chunk.response);
console.log("Response:");
for await (const {
response: { delta },
} of stream) {
process.stdout.write(delta);
}
}
main().then(() => {
void main().then(() => {
console.log("\nDone");
});
+54
View File
@@ -0,0 +1,54 @@
import { FunctionTool } from "llamaindex";
export const getCurrentIDTool = FunctionTool.from(
() => {
console.log("Getting user id...");
return crypto.randomUUID();
},
{
name: "get_user_id",
description: "Get a random user id",
},
);
export const getUserInfoTool = FunctionTool.from(
({ userId }: { userId: string }) => {
console.log("Getting user info...", userId);
return `Name: Alex; Address: 1234 Main St, CA; User ID: ${userId}`;
},
{
name: "get_user_info",
description: "Get user info",
parameters: {
type: "object",
properties: {
userId: {
type: "string",
description: "The user id",
},
},
required: ["userId"],
},
},
);
export const getWeatherTool = FunctionTool.from(
({ address }: { address: string }) => {
console.log("Getting weather...", address);
return `${address} is in a sunny location!`;
},
{
name: "get_weather",
description: "Get the current weather for a location",
parameters: {
type: "object",
properties: {
address: {
type: "string",
description: "The address",
},
},
required: ["address"],
},
},
);
+29
View File
@@ -0,0 +1,29 @@
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 {
response: { delta },
} of response) {
process.stdout.write(delta);
}
}
(async function () {
await main();
console.log("\nDone");
})();
-23
View File
@@ -1,23 +0,0 @@
import { OpenAIAgent, WikipediaTool } from "llamaindex";
async function main() {
const wikipediaTool = new WikipediaTool();
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [wikipediaTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "Where is Ho Chi Minh City?",
});
// Print the response
console.log(response);
}
main().then(() => {
console.log("Done");
});
+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();
+8 -3
View File
@@ -1,4 +1,8 @@
import { AstraDBVectorStore, VectorStoreIndex } from "llamaindex";
import {
AstraDBVectorStore,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
const collectionName = "movie_reviews";
@@ -7,7 +11,8 @@ async function main() {
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
await astraVS.connect(collectionName);
const index = await VectorStoreIndex.fromVectorStore(astraVS);
const ctx = serviceContextFromDefaults();
const index = await VectorStoreIndex.fromVectorStore(astraVS, ctx);
const retriever = await index.asRetriever({ similarityTopK: 20 });
@@ -23,4 +28,4 @@ async function main() {
}
}
main();
void main();
+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();
+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);
Binary file not shown.
+1 -1
View File
@@ -22,4 +22,4 @@ However, general relativity, published in 1915, extended these ideas to include
console.log(result);
}
main();
void main();
+1 -1
View File
@@ -36,4 +36,4 @@ async function main() {
console.log(result);
}
main();
void main();
+1 -1
View File
@@ -37,4 +37,4 @@ async function main() {
console.log(result);
}
main();
void main();
+21
View File
@@ -0,0 +1,21 @@
import { Gemini, GEMINI_MODEL } from "llamaindex";
(async () => {
if (!process.env.GOOGLE_API_KEY) {
throw new Error("Please set the GOOGLE_API_KEY environment variable.");
}
const gemini = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
const result = await gemini.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
});
console.log(result);
})();
+15
View File
@@ -0,0 +1,15 @@
import { GEMINI_EMBEDDING_MODEL, GeminiEmbedding } from "llamaindex";
async function main() {
if (!process.env.GOOGLE_API_KEY) {
throw new Error("Please set the GOOGLE_API_KEY environment variable.");
}
const embedModel = new GeminiEmbedding({
model: GEMINI_EMBEDDING_MODEL.EMBEDDING_001,
});
const texts = ["hello", "world"];
const embeddings = await embedModel.getTextEmbeddingsBatch(texts);
console.log(`\nWe have ${embeddings.length} embeddings`);
}
main().catch(console.error);
+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,
);
}
})();
+22
View File
@@ -0,0 +1,22 @@
import { HuggingFaceInferenceAPI } from "llamaindex";
(async () => {
if (!process.env.HUGGING_FACE_TOKEN) {
throw new Error("Please set the HUGGING_FACE_TOKEN environment variable.");
}
const hf = new HuggingFaceInferenceAPI({
accessToken: process.env.HUGGING_FACE_TOKEN,
model: "mistralai/Mixtral-8x7B-Instruct-v0.1",
});
const result = await hf.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
});
console.log(result);
})();
+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");
})();
+1 -1
View File
@@ -23,4 +23,4 @@ async function main() {
}
}
main();
void main();
+1 -1
View File
@@ -22,4 +22,4 @@ async function main() {
}
}
main();
void main();
+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();
+1 -1
View File
@@ -27,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();
+1 -1
View File
@@ -13,7 +13,7 @@ Settings.chunkSize = 512;
Settings.chunkOverlap = 20;
// Update llm
Settings.llm = new OpenAI({ model: "gpt-4-vision-preview", maxTokens: 512 });
Settings.llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 512 });
// Update callbackManager
Settings.callbackManager = new CallbackManager({
+1 -1
View File
@@ -21,4 +21,4 @@ Sub-header content
console.log(splits);
}
main();
void main();
+9 -2
View File
@@ -1,7 +1,14 @@
import { OllamaEmbedding } from "llamaindex";
import { Ollama } from "llamaindex/llm/ollama";
(async () => {
const llm = new Ollama({ model: "llama2", temperature: 0.75 });
const llm = new Ollama({
model: "llama3",
config: {
host: "http://localhost:11434",
},
});
const embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
{
const response = await llm.chat({
messages: [{ content: "Tell me a joke.", role: "user" }],
@@ -35,7 +42,7 @@ import { Ollama } from "llamaindex/llm/ollama";
console.log(); // newline
}
{
const embedding = await llm.getTextEmbedding("Hello world!");
const embedding = await embedModel.getTextEmbedding("Hello world!");
console.log("Embedding:", embedding);
}
})();
+16 -12
View File
@@ -4,24 +4,28 @@
"version": "0.0.4",
"dependencies": {
"@aws-crypto/sha256-js": "^5.2.0",
"@datastax/astra-db-ts": "^0.1.4",
"@notionhq/client": "^2.2.14",
"@pinecone-database/pinecone": "^1.1.3",
"@zilliz/milvus2-sdk-node": "^2.3.5",
"chromadb": "^1.8.1",
"commander": "^11.1.0",
"dotenv": "^16.4.1",
"js-tiktoken": "^1.0.10",
"llamaindex": "latest",
"mongodb": "^6.2.0",
"@datastax/astra-db-ts": "^1.1.0",
"@notionhq/client": "^2.2.15",
"@pinecone-database/pinecone": "^2.2.0",
"@zilliz/milvus2-sdk-node": "^2.4.2",
"chromadb": "^1.7.3",
"commander": "^12.0.0",
"dotenv": "^16.4.5",
"js-tiktoken": "^1.0.11",
"llamaindex": "*",
"mongodb": "^6.6.1",
"pathe": "^1.1.2"
},
"devDependencies": {
"@types/node": "^18.19.10",
"@types/node": "^20.12.11",
"ts-node": "^10.9.2",
"typescript": "^5.4.3"
"tsx": "^4.9.3",
"typescript": "^5.4.5"
},
"scripts": {
"lint": "eslint ."
},
"stackblitz": {
"startCommand": "npm start"
}
}
+3 -3
View File
@@ -32,7 +32,7 @@ async function main(args: any) {
console.log(`Found ${count} files`);
console.log(`Importing contents from ${count} files in ${sourceDir}`);
var fileName = "";
const fileName = "";
try {
// Passing callback fn to the ctor here
// will enable looging to console.
@@ -42,7 +42,7 @@ async function main(args: any) {
const pgvs = new PGVectorStore();
pgvs.setCollection(sourceDir);
pgvs.clearCollection();
await pgvs.clearCollection();
const ctx = await storageContextFromDefaults({ vectorStore: pgvs });
@@ -65,4 +65,4 @@ async function main(args: any) {
process.exit(0);
}
main(process.argv).catch((err) => console.error(err));
void main(process.argv).catch((err) => console.error(err));
+2 -2
View File
@@ -32,7 +32,7 @@ async function main(args: any) {
console.log(`Found ${count} files`);
console.log(`Importing contents from ${count} files in ${sourceDir}`);
var fileName = "";
const fileName = "";
try {
// Passing callback fn to the ctor here
// will enable looging to console.
@@ -63,4 +63,4 @@ async function main(args: any) {
process.exit(0);
}
main(process.argv).catch((err) => console.error(err));
void main(process.argv).catch((err) => console.error(err));
+1 -1
View File
@@ -45,4 +45,4 @@ async function main() {
await queryEngine.query({ query });
}
main();
void main();
+1 -1
View File
@@ -79,4 +79,4 @@ async function main() {
}
}
main();
void main();
+13 -11
View File
@@ -3,20 +3,22 @@
"private": true,
"type": "module",
"scripts": {
"start": "node --loader ts-node/esm ./src/simple-directory-reader.ts",
"start:csv": "node --loader ts-node/esm ./src/csv.ts",
"start:docx": "node --loader ts-node/esm ./src/docx.ts",
"start:html": "node --loader ts-node/esm ./src/html.ts",
"start:markdown": "node --loader ts-node/esm ./src/markdown.ts",
"start:pdf": "node --loader ts-node/esm ./src/pdf.ts",
"start:llamaparse": "node --loader ts-node/esm ./src/llamaparse.ts"
"start": "node --import tsx ./src/simple-directory-reader.ts",
"start:csv": "node --import tsx ./src/csv.ts",
"start:docx": "node --import tsx ./src/docx.ts",
"start:html": "node --import tsx ./src/html.ts",
"start:markdown": "node --import tsx ./src/markdown.ts",
"start:pdf": "node --import tsx ./src/pdf.ts",
"start:llamaparse": "node --import tsx ./src/llamaparse.ts",
"start:notion": "node --import tsx ./src/notion.ts",
"start:llamaparse2": "node --import tsx ./src/llamaparse_2.ts"
},
"dependencies": {
"llamaindex": "latest"
"llamaindex": "*"
},
"devDependencies": {
"@types/node": "^20.11.14",
"ts-node": "^10.9.2",
"typescript": "^5.4.3"
"@types/node": "^20.12.11",
"tsx": "^4.9.3",
"typescript": "^5.4.5"
}
}
+1 -1
View File
@@ -20,4 +20,4 @@ async function main() {
console.log(`Test query > ${SAMPLE_QUERY}:\n`, response.toString());
}
main();
void main();
+26
View File
@@ -0,0 +1,26 @@
import fs from "fs/promises";
import { LlamaParseReader } from "llamaindex";
async function main() {
// Load PDF using LlamaParse. set apiKey here or in environment variable LLAMA_CLOUD_API_KEY
const reader = new LlamaParseReader({
resultType: "markdown",
language: "en",
parsingInstruction:
"The provided document is a manga comic book. Most pages do NOT have title. It does not contain tables. Try to reconstruct the dialogue happening in a cohesive way. Output any math equation in LATEX markdown (between $$)",
});
const documents = await reader.loadData("../data/manga.pdf"); // The manga.pdf in the data folder is just a copy of the TOS, due to copyright laws. You have to place your own. I used "The Manga Guide to Calculus" by Hiroyuki Kojima
// Assuming documents contain an array of pages or sections
const parsedManga = documents.map((page) => page.text).join("\n---\n");
// Output the parsed manga to .md file. Will be placed in ../example/readers/
try {
await fs.writeFile("./parsedManga.md", parsedManga);
console.log("Output successfully written to parsedManga.md");
} catch (err) {
console.error("Error writing to file:", err);
}
}
main().catch(console.error);
+1 -1
View File
@@ -20,4 +20,4 @@ async function main() {
console.log(`Test query > ${SAMPLE_QUERY}:\n`, response.toString());
}
main();
void main();
+2 -2
View File
@@ -7,7 +7,7 @@ import { createInterface } from "node:readline/promises";
program
.argument("[page]", "Notion page id (must be provided)")
.action(async (page, _options, command) => {
.action(async (page, _options) => {
// Initializing a client
if (!process.env.NOTION_TOKEN) {
@@ -55,7 +55,7 @@ program
.filter((page) => page !== null);
console.log("Found pages:");
console.table(pages);
console.log(`To run, run ts-node ${command.name()} [page id]`);
console.log(`To run, run with [page id]`);
return;
}
}
View File
+25 -16
View File
@@ -1,37 +1,46 @@
import { encodingForModel } from "js-tiktoken";
import { OpenAI } from "llamaindex";
import { ChatMessage, OpenAI, type LLMStartEvent } from "llamaindex";
import { Settings } from "llamaindex/Settings";
import { extractText } from "llamaindex/llm/utils";
const encoding = encodingForModel("gpt-4-0125-preview");
const llm = new OpenAI({
model: "gpt-4-0125-preview",
// currently is "gpt-4-turbo-2024-04-09"
model: "gpt-4-turbo",
});
let tokenCount = 0;
Settings.callbackManager.on("llm-start", (event) => {
Settings.callbackManager.on("llm-start", (event: LLMStartEvent) => {
const { messages } = event.detail.payload;
tokenCount += messages.reduce((count, message) => {
return count + encoding.encode(message.content).length;
messages.reduce((count: number, message: ChatMessage) => {
return count + encoding.encode(extractText(message.content)).length;
}, 0);
console.log("Token count:", tokenCount);
// https://openai.com/pricing
// $10.00 / 1M tokens
console.log(`Price: $${(tokenCount / 1_000_000) * 10}`);
});
Settings.callbackManager.on("llm-end", (event) => {
const { response } = event.detail.payload;
tokenCount += encoding.encode(response.message.content).length;
console.log("Token count:", tokenCount);
// https://openai.com/pricing
// $30.00 / 1M tokens
console.log(`Price: $${(tokenCount / 1_000_000) * 30}`);
console.log(`Total Price: $${(tokenCount / 1_000_000) * 10}`);
});
const question = "Hello, how are you?";
Settings.callbackManager.on("llm-stream", (event) => {
const { chunk } = event.detail.payload;
const { delta } = chunk;
tokenCount += encoding.encode(extractText(delta)).length;
if (tokenCount > 20) {
// This is just an example, you can set your own limit or handle it differently
throw new Error("Token limit exceeded!");
}
});
Settings.callbackManager.on("llm-end", () => {
// https://openai.com/pricing
// $30.00 / 1M tokens
console.log(`Total Price: $${(tokenCount / 1_000_000) * 30}`);
});
const question = "Hello, how are you? Please response about 50 tokens.";
console.log("Question:", question);
llm
void llm
.chat({
stream: true,
messages: [
+1 -1
View File
@@ -65,4 +65,4 @@ async function main() {
});
}
main().then(() => console.log("Done"));
void main().then(() => console.log("Done"));
+1 -1
View File
@@ -13,4 +13,4 @@ async function main() {
console.log(chunks);
}
main();
void main();
+48
View File
@@ -0,0 +1,48 @@
import { OpenAI } from "llamaindex";
async function main() {
const llm = new OpenAI({ model: "gpt-4-turbo" });
const args: Parameters<typeof llm.chat>[0] = {
additionalChatOptions: {
tool_choice: "auto",
},
messages: [
{
content: "Who was Goethe?",
role: "user",
},
],
tools: [
{
metadata: {
name: "wikipedia_tool",
description: "A tool that uses a query engine to search Wikipedia.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The query to search for",
},
},
required: ["query"],
},
},
},
],
};
const stream = await llm.chat({ ...args, stream: true });
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
if (chunk.options && "toolCall" in chunk.options) {
console.log("Tool call:");
console.log(chunk.options.toolCall);
}
}
}
(async function () {
await main();
console.log("Done");
})();
+3 -1
View File
@@ -1,12 +1,14 @@
{
"compilerOptions": {
"target": "es2017",
"target": "ES2022",
"module": "esnext",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"lib": ["ES2022"],
"types": ["node"],
"outDir": "./lib",
"tsBuildInfoFile": "./lib/.tsbuildinfo",
"incremental": true,
+17 -4
View File
@@ -1,6 +1,11 @@
import fs from "node:fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
import {
Document,
MetadataMode,
NodeWithScore,
VectorStoreIndex,
} from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
@@ -16,12 +21,20 @@ async function main() {
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
const { response, sourceNodes } = await queryEngine.query({
query: "What did the author do in college?",
});
// Output response
console.log(response.toString());
// Output response with sources
console.log(response);
if (sourceNodes) {
sourceNodes.forEach((source: NodeWithScore, index: number) => {
console.log(
`\n${index}: Score: ${source.score} - ${source.node.getContent(MetadataMode.NONE).substring(0, 50)}...\n`,
);
});
}
}
main().catch(console.error);
+1 -1
View File
@@ -1,7 +1,7 @@
import { OpenAI } from "llamaindex";
(async () => {
const llm = new OpenAI({ model: "gpt-4-vision-preview", temperature: 0.1 });
const llm = new OpenAI({ model: "gpt-4-turbo", temperature: 0.1 });
// complete api
const response1 = await llm.complete({ prompt: "How are you?" });
+18 -12
View File
@@ -2,38 +2,44 @@
"name": "@llamaindex/monorepo",
"private": true,
"scripts": {
"build": "turbo run build",
"build:release": "turbo run build lint test --filter=\"!docs\"",
"build": "turbo run build --filter=\"!docs\" --filter=\"!*-test\" --filter=\"!*-example\"",
"build:release": "turbo run build lint test --filter=\"!docs\" --filter=\"!*-test\" --filter=\"!*-example\"",
"dev": "turbo run dev",
"format": "prettier --ignore-unknown --cache --check .",
"format:write": "prettier --ignore-unknown --write .",
"lint": "turbo run lint",
"prepare": "husky",
"e2e": "turbo run e2e",
"test": "turbo run test",
"type-check": "tsc -b --diagnostics",
"release": "pnpm run check-minor-version && pnpm run build:release && changeset publish",
"release-snapshot": "pnpm run check-minor-version && pnpm run build:release && changeset publish --tag snapshot",
"check-minor-version": "node ./scripts/check-minor-version",
"update-version": "node ./scripts/update-version",
"new-version": "pnpm run build:release && changeset version && pnpm run check-minor-version && pnpm run update-version",
"new-snapshot": "pnpm run build:release && changeset version --snapshot && pnpm run update-version"
"new-version": "changeset version && pnpm run check-minor-version && pnpm format:write && pnpm run build:release",
"new-snapshot": "pnpm run build:release && changeset version --snapshot"
},
"devDependencies": {
"@changesets/cli": "^2.27.1",
"eslint": "^8.56.0",
"eslint-config-custom": "workspace:*",
"husky": "^9.0.10",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"eslint": "^8.57.0",
"eslint-config-next": "^14.2.3",
"eslint-config-prettier": "^9.1.0",
"eslint-config-turbo": "^1.13.3",
"eslint-plugin-react": "7.34.1",
"husky": "^9.0.11",
"lint-staged": "^15.2.2",
"madge": "^7.0.0",
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^3.2.4",
"turbo": "^1.12.3",
"typescript": "^5.4.3"
"turbo": "^1.13.3",
"typescript": "^5.4.5"
},
"packageManager": "pnpm@8.15.1",
"packageManager": "pnpm@9.0.5",
"pnpm": {
"overrides": {
"trim": "1.0.1",
"@babel/traverse": "7.23.2"
"@babel/traverse": "7.23.2",
"protobufjs": "7.2.6"
}
},
"lint-staged": {
+83
View File
@@ -0,0 +1,83 @@
# @llamaindex/autotool
> Auto transpile your JS function to LLM Agent compatible
## Usage
First, Install the package
```shell
npm install @llamaindex/autotool
pnpm add @llamaindex/autotool
yarn add @llamaindex/autotool
```
Second, Add the plugin/loader to your configuration:
### Next.js
```javascript
import { withNext } from "@llamaindex/autotool/next";
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default withNext(nextConfig);
```
### Node.js
```shell
node --import @llamaindex/autotool/node ./path/to/your/script.js
```
Third, add `"use tool"` on top of your tool file or change to `.tool.ts`.
```typescript
"use tool";
export function getWeather(city: string) {
// ...
}
// ...
```
Finally, export a chat handler function to the frontend using `llamaindex` Agent
```typescript
"use server";
// imports ...
export async function chatWithAI(message: string): Promise<JSX.Element> {
const agent = new OpenAIAgent({
tools: convertTools("llamaindex"),
});
const uiStream = createStreamableUI();
agent
.chat({
stream: true,
message,
})
.then(async (responseStream) => {
return responseStream.pipeTo(
new WritableStream({
start: () => {
uiStream.append("\n");
},
write: async (message) => {
uiStream.append(message.response.delta);
},
close: () => {
uiStream.done();
},
}),
);
});
return uiStream.value;
}
```
## License
MIT
@@ -0,0 +1,28 @@
# @llamaindex/autotool-01-node-example
## null
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
- @llamaindex/autotool@0.0.1
## null
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
- @llamaindex/autotool@0.0.1
## null
### Patch Changes
- Updated dependencies [c3747d0]
- llamaindex@0.3.9
- @llamaindex/autotool@0.0.1
@@ -0,0 +1,17 @@
{
"name": "@llamaindex/autotool-01-node-example",
"private": true,
"type": "module",
"dependencies": {
"@llamaindex/autotool": "workspace:*",
"llamaindex": "workspace:*",
"openai": "^4.43.0"
},
"devDependencies": {
"tsx": "^4.9.3"
},
"scripts": {
"start": "node --import tsx --import @llamaindex/autotool/node ./src/index.ts"
},
"version": null
}
@@ -0,0 +1,11 @@
import { getWeather } from "./utils.js";
/**
* Get current location
*/
export function getCurrentLocation() {
console.log("Getting current location");
return "London";
}
export { getWeather };

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