-
Notifications
You must be signed in to change notification settings - Fork 444
feat: build wasm with extism #1155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
thucpn
wants to merge
31
commits into
main
Choose a base branch
from
feat/build-wasm-with-extism
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 16 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
ccfc11c
feat: build wasm with extism
thucpn 02c8198
feat: detach packages for extism
thucpn ecc54cb
fix: lock
thucpn efbd61f
install extism-js
thucpn de4d8ff
install extism for all actions
thucpn fbb5ece
fix: install extism for all tests
thucpn 5c34d3a
create abstract ExtismTool
thucpn 9df0d63
feat: make agent example
thucpn dfb6c25
feat: add js example
thucpn 4b74096
update readme
thucpn 507012a
feat: ExtismToolFactory
thucpn 54abd70
feat: example with agent
thucpn 1eddb6e
export type
thucpn 7710d96
add getMetadata to wiki python example
thucpn 6cc8595
fix: typo and use same d.ts file for all tools
thucpn 879c15f
fix: lint
thucpn d48724f
fix: update doc
thucpn f7b666e
refactor: add package.json to examples
thucpn 8a73dac
test wiki
thucpn d95ed78
fix: lint depend on build
thucpn 660eab8
fix: e2e
thucpn fda48fa
fix: wrong path ts config.json
thucpn f34ea45
Merge branch 'main' into feat/build-wasm-with-extism
thucpn d718f43
fix: upgrade extism to fix worker bug
thucpn 191986b
refactor: create tool class params
thucpn f76abce
refactor: remove enum
thucpn 92d0d09
add todo tool example
thucpn 33d57d1
update test
thucpn 3293c22
Merge branch 'main' into feat/build-wasm-with-extism
thucpn 9447654
Create shy-bottles-shop.md
thucpn 951f215
Merge branch 'main' into feat/build-wasm-with-extism
marcusschiesser File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
## Extism Tools | ||
|
||
### Prerequisites for Development | ||
|
||
- [Extism PDK](https://github.com/extism/js-pdk?tab=readme-ov-file#linux-macos) | ||
|
||
### Build WASM files | ||
|
||
```bash | ||
cd packages/wasm-tools/extism/wiki | ||
extism-js wiki.js -i wiki.d.ts -o wiki.wasm | ||
``` | ||
|
||
### Run WASM files in Node.js using Extism SDK (https://github.com/extism/js-sdk) | ||
|
||
```bash | ||
node examples/wasm/wiki.js | ||
thucpn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
### Test using WASM tool with OpenAI Agent | ||
|
||
```bash | ||
node examples/tool/WikipediaTool.js | ||
``` | ||
|
||
### Run WASM files in Python using Extism SDK (https://github.com/extism/python-sdk) | ||
|
||
```bash | ||
python examples/wasm/wiki.py | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
// needed as extism-js doesn't support compiling multiple files | ||
import { execSync } from "child_process"; | ||
thucpn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import { mkdirSync, readdirSync } from "fs"; | ||
|
||
const WASM_SRC_FOLDER = "wasm"; | ||
const WASM_OUTPUT_FOLDER = "dist/wasm"; | ||
|
||
// get list of tools from files (except index.d.ts) | ||
const tools = readdirSync(WASM_SRC_FOLDER) | ||
.filter((file) => !file.includes("index.d.ts")) | ||
.map((file) => file.split(".")[0]); | ||
|
||
// create dist/wasm folder if it doesn't exist using fs | ||
try { | ||
mkdirSync(WASM_OUTPUT_FOLDER, { recursive: true }); | ||
} catch (error) { | ||
console.error("Error creating dist/wasm folder:", error.message); | ||
process.exit(1); | ||
} | ||
|
||
// loop through each tool, compile it to wasm using extism-js | ||
tools.forEach((tool) => { | ||
try { | ||
execSync( | ||
`extism-js ${WASM_SRC_FOLDER}/${tool}.js -i ${WASM_SRC_FOLDER}/index.d.ts -o ${WASM_OUTPUT_FOLDER}/${tool}.wasm`, | ||
|
||
); | ||
} catch (error) { | ||
console.error(`Error compiling module ${tool}:`, error.message); | ||
process.exit(1); | ||
} | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { OpenAIAgent } from "llamaindex"; | ||
import { ExtismToolFactory } from "../../dist/ExtismToolFactory.js"; | ||
thucpn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
async function main() { | ||
const WikiTool = await ExtismToolFactory.createToolClass("wiki"); | ||
const wikiTool = new WikiTool(); | ||
const agent = new OpenAIAgent({ tools: [wikiTool] }); | ||
const result = await agent.chat({ message: "Ho Chi Minh City" }); | ||
console.log(result.message); | ||
} | ||
|
||
void main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import createPlugin from "@extism/extism"; | ||
|
||
async function main() { | ||
const plugin = await createPlugin("./dist/wasm/wiki.wasm", { | ||
useWasi: true, | ||
functions: {}, | ||
runInWorker: true, | ||
allowedHosts: ["*.wikipedia.org"], | ||
memory: { maxHttpResponseBytes: 100 * 1024 * 1024 }, | ||
}); | ||
|
||
try { | ||
const params = { query: "Ho Chi Minh City" }; | ||
const data = await plugin.call("summary", JSON.stringify(params)); | ||
console.log(data.json()); | ||
} catch (e) { | ||
console.error(e); | ||
} finally { | ||
await plugin.close(); | ||
} | ||
} | ||
|
||
void main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import extism | ||
import json | ||
from os.path import join, dirname | ||
|
||
|
||
def read_local_wasm(file_name): | ||
path = join(dirname(__file__), file_name) # Change this to your wasm file path | ||
with open(path, "rb") as wasm_file: | ||
return wasm_file.read() | ||
|
||
|
||
def _manifest(file_name): | ||
wasm = read_local_wasm(file_name) | ||
return { | ||
"wasm": [{"data": wasm}], | ||
"allowed_hosts": ["*.wikipedia.org"], | ||
} | ||
|
||
|
||
manifest = _manifest("wiki.wasm") | ||
with extism.Plugin(manifest, wasi=True) as plugin: | ||
metadata = plugin.call( | ||
"getMetadata", | ||
"", | ||
parse=lambda output: json.loads(bytes(output).decode("utf-8")), | ||
) | ||
data = plugin.call( | ||
"call", | ||
json.dumps({"query": "Ho Chi Minh City"}), | ||
parse=lambda output: json.loads(bytes(output).decode("utf-8")), | ||
) | ||
|
||
print(metadata) | ||
print(data) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
{ | ||
"name": "@llamaindex/extism-tools", | ||
"version": "0.0.1", | ||
"license": "MIT", | ||
"type": "module", | ||
"dependencies": { | ||
"@extism/extism": "^2.0.0-rc7", | ||
"ajv": "^8.17.1", | ||
"@llamaindex/core": "workspace:*", | ||
"@llamaindex/env": "workspace:*", | ||
"llamaindex": "workspace:*" | ||
}, | ||
"devDependencies": { | ||
"@swc/cli": "^0.4.0", | ||
"@swc/core": "^1.7.22", | ||
"typescript": "^5.5.4", | ||
"@types/node": "^22.5.1" | ||
}, | ||
"engines": { | ||
"node": ">=18.0.0" | ||
}, | ||
"types": "./dist/index.d.ts", | ||
"main": "./dist/cjs/index.js", | ||
"exports": { | ||
".": { | ||
"import": { | ||
"types": "./dist/index.d.ts", | ||
"default": "./dist/index.js" | ||
}, | ||
"require": { | ||
"types": "./dist/index.d.ts", | ||
"default": "./dist/cjs/index.js" | ||
} | ||
}, | ||
"./*": { | ||
"import": { | ||
"types": "./dist/*.d.ts", | ||
"default": "./dist/*.js" | ||
}, | ||
"require": { | ||
"types": "./dist/*.d.ts", | ||
"default": "./dist/cjs/*.js" | ||
} | ||
} | ||
}, | ||
"files": [ | ||
"dist", | ||
"CHANGELOG.md" | ||
], | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/run-llama/LlamaIndexTS.git", | ||
"directory": "packages/extism-tools" | ||
}, | ||
"scripts": { | ||
"build": "rm -rf ./dist && pnpm run build:wasm && pnpm run build:esm && pnpm run build:cjs && pnpm run build:type", | ||
"build:esm": "swc src -d dist --strip-leading-paths --config-file ../../.swcrc", | ||
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file ../../.cjs.swcrc", | ||
"build:type": "tsc -p tsconfig.json", | ||
"build:wasm": "node bin/compile.js" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
import createPlugin, { type Plugin } from "@extism/extism"; | ||
import type { JSONSchemaType } from "ajv"; | ||
import type { BaseTool, ToolMetadata } from "llamaindex"; | ||
|
||
export const WASM_DIRECTORY = "./dist/wasm"; | ||
export const DEFAULT_MAX_HTTP_RESPONSE_BYTES = 100 * 1024 * 1024; // 100 MB | ||
|
||
export type ToolParams = Record<string, any>; | ||
|
||
export type ToolClassParams = { | ||
metadata?: ToolMetadata<JSONSchemaType<ToolParams>>; | ||
}; | ||
|
||
export type CreateToolClassParams = { | ||
wasmFilename: string; | ||
allowedHosts: string[]; | ||
maxHttpResponseBytes: number; | ||
transformResponse: (response: any) => any; | ||
}; | ||
|
||
export enum ExtismTool { | ||
WIKI = "wiki", | ||
} | ||
|
||
export const ToolMap: Record<`${ExtismTool}`, CreateToolClassParams> = { | ||
[ExtismTool.WIKI]: { | ||
wasmFilename: "wiki.wasm", | ||
allowedHosts: ["*.wikipedia.org"], | ||
maxHttpResponseBytes: DEFAULT_MAX_HTTP_RESPONSE_BYTES, | ||
transformResponse: (response: any) => response.extract, | ||
}, | ||
marcusschiesser marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}; | ||
|
||
export const createPluginInstance = async ( | ||
params: Omit<CreateToolClassParams, "transformResponse">, | ||
): Promise<Plugin> => { | ||
const { wasmFilename, allowedHosts, maxHttpResponseBytes } = params; | ||
const plugin = await createPlugin(`${WASM_DIRECTORY}/${wasmFilename}`, { | ||
useWasi: true, | ||
runInWorker: true, | ||
allowedHosts, | ||
memory: { maxHttpResponseBytes }, | ||
}); | ||
return plugin; | ||
}; | ||
|
||
export class ExtismToolFactory { | ||
static async createToolClass( | ||
toolName: `${ExtismTool}`, | ||
): Promise<new (params: ToolClassParams) => BaseTool<ToolParams>> { | ||
const config = ToolMap[toolName]; | ||
marcusschiesser marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (!config) throw new Error(`Tool ${toolName} not supported yet`); | ||
|
||
const plugin = await createPluginInstance(config); | ||
try { | ||
const wasmMetadata = await plugin.call("getMetadata"); | ||
if (!wasmMetadata) { | ||
throw new Error("The WASM plugin did not return metadata."); | ||
} | ||
const defaultMetadata = wasmMetadata.json(); | ||
|
||
return class implements BaseTool<ToolParams> { | ||
metadata: ToolMetadata<JSONSchemaType<ToolParams>>; | ||
|
||
constructor(params: ToolClassParams) { | ||
this.metadata = params?.metadata || defaultMetadata; | ||
} | ||
|
||
async call(input: ToolParams): Promise<string> { | ||
const pluginInstance = await createPluginInstance(config); | ||
const data = await pluginInstance.call("call", JSON.stringify(input)); | ||
if (!data) return "No result"; | ||
const result = config.transformResponse(data.json()); | ||
await pluginInstance.close(); | ||
return result; | ||
} | ||
}; | ||
} catch (e) { | ||
console.error(e); | ||
throw new Error("Failed to create Tool instance."); | ||
} finally { | ||
await plugin.close(); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
{ | ||
"extends": "../../tsconfig.json", | ||
"compilerOptions": { | ||
"rootDir": "./src", | ||
"outDir": "./dist", | ||
"tsBuildInfoFile": "./dist/.tsbuildinfo", | ||
"emitDeclarationOnly": true, | ||
"module": "node16", | ||
"moduleResolution": "node16", | ||
"skipLibCheck": true, | ||
"strict": true, | ||
"types": ["node"] | ||
}, | ||
"include": ["./src"], | ||
"exclude": ["node_modules"], | ||
"references": [ | ||
{ | ||
"path": "../env/tsconfig.json" | ||
} | ||
] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
declare module "main" { | ||
export function getMetadata(): I32; | ||
export function call(): I32; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.