Skip to content

Commit

Permalink
feat: async load binding
Browse files Browse the repository at this point in the history
  • Loading branch information
hans00 committed Apr 29, 2024
1 parent a342e38 commit 28e36a6
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ npm install @fugood/llama.node
import { loadModel } from '@fugood/llama.node'

// Initial a Llama context with the model (may take a while)
const context = loadModel({
const context = await loadModel({
model: 'path/to/gguf/model',
use_mlock: true,
n_ctx: 2048,
Expand Down
6 changes: 3 additions & 3 deletions lib/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ export interface Module {
LlamaContext: LlamaContext
}

export const loadModule = (variant?: string): Module => {
export const loadModule = async (variant?: string): Promise<Module> => {
try {
if (variant) {
return require(`../bin/${process.platform}-${variant}/${process.arch}/llama-node.node`) as Module
return await import(`../bin/${process.platform}-${variant}/${process.arch}/llama-node.node`) as Module
}
} catch {} // ignore errors and try the common path
return require(`../bin/${process.platform}/${process.arch}/llama-node.node`) as Module
return await import(`../bin/${process.platform}/${process.arch}/llama-node.node`) as Module
}
10 changes: 6 additions & 4 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { loadModule, LlamaModelOptions } from './binding'
import type { LlamaContext } from './binding'
import type { Module, LlamaContext } from './binding'

export * from './binding'

export interface LlamaModelOptionsExtended extends LlamaModelOptions {
lib_variant?: string
}

export const loadModel = (options: LlamaModelOptionsExtended): LlamaContext => {
const { LlamaContext } = loadModule(options.lib_variant)
return new LlamaContext(options)
let module: Module | null = null

export const loadModel = async (options: LlamaModelOptionsExtended): Promise<LlamaContext> => {
module ??= await loadModule(options.lib_variant)
return new module.LlamaContext(options)
}
2 changes: 1 addition & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import path from 'path'
import { loadModel } from '../lib'

it('work fine', async () => {
const model = loadModel({ model: path.resolve(__dirname, './tiny-random-llama.gguf') })
const model = await loadModel({ model: path.resolve(__dirname, './tiny-random-llama.gguf') })
const result = await model.completion({
prompt: 'My name is Merve and my favorite',
n_samples: 1,
Expand Down

0 comments on commit 28e36a6

Please sign in to comment.