-
Notifications
You must be signed in to change notification settings - Fork 402
create model from local file #269
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
maifeeulasad
wants to merge
16
commits into
ollama:main
Choose a base branch
from
maifeeulasad:modelfile-local-maifee
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 all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
edf7ce1
interface: support for creating model from local file;
maifeeulasad 582feb3
util: file upload util;
maifeeulasad 3635035
util: blob upload functionality;
maifeeulasad 0bff23c
feat: create model from local file;
maifeeulasad c2bb227
refactor: detailed error message for missing file(s);
maifeeulasad 449de4c
test: file upload util test;
maifeeulasad 4144196
test: create file upload mock test;
maifeeulasad 75ac565
example: create modal from local file;
maifeeulasad c3692b1
example: stress testing create model from file;
maifeeulasad 9bdd10f
cleanup: remove stress test;
maifeeulasad 2b68481
refactor: simplify import without projection for `node:path`;
maifeeulasad 30b9dc5
fix: validation for file and blob digest count;
maifeeulasad 92848a7
refactor: streamline create request handling from review;
maifeeulasad bb994a0
[fix]: removed `replaceModelfilePathsWithBlobs` as per reivew require…
maifeeulasad 9c6812c
[cleanup]: removed non existing test for `replaceModelfilePathsWithBl…
maifeeulasad feafd1f
[fix]: updated test as per new file and digest length validation;
maifeeulasad 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import ollama from 'ollama' | ||
| import path from 'path' | ||
|
|
||
| // download | ||
| // - https://huggingface.co/ggml-org/tinygemma3-GGUF/blob/main/tinygemma3-Q8_0.gguf | ||
| // - https://huggingface.co/ggml-org/tinygemma3-GGUF/blob/main/mmproj-tinygemma3.gguf | ||
|
|
||
| const GGUF_1 = path.join(__dirname, './tinygemma3-Q8_0.gguf') | ||
| const GGUF_2 = path.join(__dirname, './mmproj-tinygemma3.gguf') | ||
|
|
||
| async function main() { | ||
| console.log('Example: Creating a model from local files\n') | ||
|
|
||
| // Example 1: Create a model from a local GGUF file with modelfile | ||
| console.log('Example 1: Creating model from local file with modelfile') | ||
| try { | ||
| const response = await ollama.create({ | ||
| model: 'custom-model', | ||
| modelfile: ` | ||
| FROM ${GGUF_1} | ||
| SYSTEM "You are mario from super mario bros." | ||
| PARAMETER temperature 0.7 | ||
| `, | ||
| files: [ | ||
| { | ||
| filepath: GGUF_1, | ||
| // sha256 is optional - will be computed automatically if not provided | ||
| }, | ||
| ], | ||
| stream: true, | ||
| }) | ||
|
|
||
| for await (const progress of response) { | ||
| console.log(`Progress: ${progress.status}`) | ||
| } | ||
| console.log('Model created successfully!\n') | ||
| } catch (error) { | ||
| console.error('Error creating model:', error) | ||
| } | ||
|
|
||
| // Example 2: Create a model from multiple files (e.g., base model + adapter) | ||
| console.log('Example 2: Creating model from multiple files') | ||
| try { | ||
| const response = await ollama.create({ | ||
| model: 'fusion-model', | ||
| modelfile: `FROM ${GGUF_1}`, | ||
| files: [ | ||
| { | ||
| filepath: GGUF_1, | ||
| }, | ||
| { | ||
| filepath: GGUF_2, | ||
| }, | ||
| ], | ||
| stream: false, // Non-streaming response | ||
| }) | ||
|
|
||
| console.log(`Status: ${response.status}`) | ||
| console.log('Model created successfully!\n') | ||
| } catch (error) { | ||
| console.error('Error creating model with multiple files:', error) | ||
| } | ||
|
|
||
| // Example 3: Create a model using the Ollama class directly (for more control) | ||
| console.log('Example 3: Using Ollama class directly') | ||
| try { | ||
| const { Ollama } = await import('ollama') | ||
| const ollamaClient = new Ollama({ | ||
| host: 'http://localhost:11434', | ||
| }) | ||
|
|
||
| const response = await ollamaClient.create({ | ||
| model: 'nude-model', | ||
| modelfile: `FROM ${GGUF_1}`, | ||
| files: [ | ||
| { | ||
| filepath: GGUF_1, | ||
| }, | ||
| ], | ||
| stream: false, | ||
| }) | ||
|
|
||
| console.log(`Status: ${(response as any).status || 'completed'}`) | ||
| console.log('Model created successfully!') | ||
| } catch (error) { | ||
| console.error('Error with direct client:', error) | ||
| } | ||
| } | ||
|
|
||
| main().catch(console.error) | ||
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,127 @@ | ||
| import { createHash } from 'node:crypto' | ||
| import { createReadStream, promises } from 'node:fs' | ||
| import { basename } from 'node:path' | ||
|
|
||
| /** | ||
| * Computes the SHA256 hash of a file in a memory-efficient way. | ||
| * | ||
| * @param filepath - The path to the file | ||
| * @returns A promise that resolves to the hex-encoded SHA256 hash | ||
| */ | ||
| export async function computeFileSHA256(filepath: string): Promise<string> { | ||
| const hash = createHash('sha256') | ||
| const stream = createReadStream(filepath, { highWaterMark: 64 * 1024 }) // 64KB chunks | ||
| const reader = stream[Symbol.asyncIterator]() | ||
|
|
||
| while (true) { | ||
| const { done, value } = await reader.next() | ||
| if (done) break | ||
| hash.update(value) | ||
| } | ||
|
|
||
| return hash.digest('hex') | ||
| } | ||
|
|
||
| /** | ||
| * Checks if a path exists and is a file. | ||
| * | ||
| * @param filepath - The path to check | ||
| * @returns A promise that resolves to true if the path exists and is a file | ||
| */ | ||
| export async function isFile(filepath: string): Promise<boolean> { | ||
| try { | ||
| const stats = await promises.stat(filepath) | ||
| return stats.isFile() | ||
| } catch { | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Uploads a file as a blob to Ollama server. | ||
| * | ||
| * @param host - The Ollama server host URL | ||
| * @param filepath - Path to the file to upload | ||
| * @param sha256 - SHA256 digest of the file | ||
| * @param fetchFn - The fetch function to use for HTTP requests | ||
| * @param headers - Optional headers to include in requests | ||
| * @returns A promise that resolves when upload is complete | ||
| */ | ||
| export async function uploadBlob( | ||
| host: string, | ||
| filepath: string, | ||
| sha256: string, | ||
| fetchFn: typeof fetch, | ||
| headers?: Record<string, string> | ||
| ): Promise<void> { | ||
| const digest = `sha256:${sha256}` | ||
| const url = `${host}/api/blobs/${digest}` | ||
|
|
||
| // Check if blob already exists | ||
| try { | ||
| const headResponse = await fetchFn(url, { | ||
| method: 'HEAD', | ||
| headers: headers, | ||
| }) | ||
| if (headResponse.ok) { | ||
| // Blob already exists, no need to upload | ||
| return | ||
| } | ||
| } catch { | ||
| // Blob doesn't exist, proceed with upload | ||
| } | ||
|
|
||
| // Stream the file for upload | ||
| const fileStream = createReadStream(filepath) | ||
|
|
||
| const response = await fetchFn(url, { | ||
| method: 'POST', | ||
| body: fileStream as any, | ||
| headers: { | ||
| ...headers, | ||
| 'Content-Type': 'application/octet-stream', | ||
| }, | ||
| // @ts-expect-error - duplex is required for streaming bodies in Node.js fetch | ||
| duplex: 'half', | ||
| }) | ||
|
|
||
| if (!response.ok) { | ||
| let message = `Failed to upload blob: ${response.status} ${response.statusText}` | ||
| try { | ||
| const errorData = await response.json() | ||
| message = errorData.error || message | ||
| } catch { | ||
| // Ignore JSON parse errors | ||
| } | ||
| throw new Error(message) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Creates a map of filenames to blob digests for the Ollama create request. | ||
| * | ||
| * @param files - Array of file objects with filepath and optional sha256 | ||
| * @param blobDigests - Array of blob digests (sha256:hash format) | ||
| * @returns A map of filename to blob digest | ||
| */ | ||
| export function createBlobFileMap( | ||
| files: Array<{ filepath: string; sha256?: string }>, | ||
| blobDigests: string[] | ||
| ): Record<string, string> { | ||
| if (files.length !== blobDigests.length) { | ||
| throw new Error( | ||
| `Mismatch between number of files (${files.length}) and blob digests (${blobDigests.length})` | ||
| ) | ||
| } | ||
|
|
||
| const fileMap: Record<string, string> = {} | ||
maifeeulasad marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| for (let i = 0; i < files.length; i++) { | ||
| const filename = basename(files[i].filepath) | ||
| fileMap[filename] = blobDigests[i] | ||
| } | ||
|
|
||
| return fileMap | ||
| } | ||
|
|
||
|
|
||
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
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.