Procházet zdrojové kódy

allow create from browser

Bruce MacDonald před 1 rokem
rodič
revize
8e185e0a45
2 změnil soubory, kde provedl 32 přidání a 10 odebrání
  1. 22 4
      src/browser.ts
  2. 10 6
      src/index.ts

+ 22 - 4
src/browser.ts

@@ -20,6 +20,7 @@ import type {
   ShowRequest,
   ChatRequest,
   ChatResponse,
+  CreateRequest
 } from './interfaces.js'
 
 export class Ollama {
@@ -93,11 +94,13 @@ export class Ollama {
     }
   }
 
-  async encodeImage(image: Uint8Array | Buffer | string): Promise<string> {
+  async encodeImage(image: Uint8Array | string): Promise<string> {
     if (typeof image !== 'string') {
-      // image is Uint8Array or Buffer, convert it to base64
-      const result = Buffer.from(image).toString('base64')
-      return result
+      // image is Uint8Array convert it to base64
+      const uint8Array = new Uint8Array(image);
+      const numberArray = Array.from(uint8Array);
+      const base64String = btoa(String.fromCharCode.apply(null, numberArray));
+      return base64String;
     }
     // the string may be base64 encoded
     return image
@@ -133,6 +136,21 @@ export class Ollama {
     return this.processStreamableRequest<ChatResponse>('chat', request)
   }
 
+  create(
+    request: CreateRequest & { stream: true },
+  ): Promise<AsyncGenerator<ProgressResponse>>
+  create(request: CreateRequest & { stream?: false }): Promise<ProgressResponse>
+
+  async create(
+    request: CreateRequest,
+  ): Promise<ProgressResponse | AsyncGenerator<ProgressResponse>> {
+    return this.processStreamableRequest<ProgressResponse>('create', {
+      name: request.model,
+      stream: request.stream,
+      modelfile: request.modelfile,
+    })
+  }
+
   pull(request: PullRequest & { stream: true }): Promise<AsyncGenerator<ProgressResponse>>
   pull(request: PullRequest & { stream?: false }): Promise<ProgressResponse>
 

+ 10 - 6
src/index.ts

@@ -14,7 +14,9 @@ export class Ollama extends OllamaBrowser {
 
   async encodeImage(image: Uint8Array | Buffer | string): Promise<string> {
     if (typeof image !== 'string') {
-      return super.encodeImage(image)
+      // image is Uint8Array or Buffer, convert it to base64
+      const result = Buffer.from(image).toString('base64')
+      return result
     }
     try {
       if (fs.existsSync(image)) {
@@ -141,12 +143,14 @@ export class Ollama extends OllamaBrowser {
     } else {
       throw new Error('Must provide either path or modelfile to create a model')
     }
+    request.modelfile = modelfileContent
 
-    return this.processStreamableRequest<ProgressResponse>('create', {
-      name: request.model,
-      stream: request.stream,
-      modelfile: modelfileContent,
-    })
+    // check stream here so that typescript knows which overload to use
+    if (request.stream) {
+      return super.create(request as CreateRequest & { stream: true });
+    } else {
+      return super.create(request as CreateRequest & { stream: false });
+    }
   }
 }