Skip to content
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

enable ollama-js use in an environment without whatwg #125

Merged
merged 1 commit into from
Aug 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as utils from './utils.js'
import { AbortableAsyncIterator, parseJSON, post } from './utils.js'
import 'whatwg-fetch'

import type {
ChatRequest,
Expand Down Expand Up @@ -39,9 +38,24 @@
this.config.host = utils.formatHost(config?.host ?? 'http://127.0.0.1:11434')
}

this.fetch = fetch
if (config?.fetch != null) {
this.fetch = config.fetch
this.fetch = config?.fetch || this.getFetch();
}

private getFetch(): Fetch {
if (typeof window !== 'undefined' && window.fetch) {
return window.fetch.bind(window);
}

if (typeof global !== 'undefined' && global.fetch) {
return global.fetch;
}

try {
// Use dynamic import for Node.js environments
return require('node-fetch');
} catch (error) {
console.error('Failed to import node-fetch:', error);
throw new Error('Fetch is not available. Please provide a fetch implementation in the config.');
}
}

Expand All @@ -66,7 +80,7 @@
*/
protected async processStreamableRequest<T extends object>(
endpoint: string,
request: { stream?: boolean } & Record<string, any>,

Check warning on line 83 in src/browser.ts

View workflow job for this annotation

GitHub Actions / test (16)

Unexpected any. Specify a different type

Check warning on line 83 in src/browser.ts

View workflow job for this annotation

GitHub Actions / test (18)

Unexpected any. Specify a different type

Check warning on line 83 in src/browser.ts

View workflow job for this annotation

GitHub Actions / test (20)

Unexpected any. Specify a different type
): Promise<T | AbortableAsyncIterator<T>> {
request.stream = request.stream ?? false
const host = `${this.config.host}/api/${endpoint}`
Expand Down
Loading