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

add an abort controller #40

Merged
merged 1 commit into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions examples/abort/abort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import ollama from 'ollama'

// Set a timeout to abort the request after 1 second
setTimeout(() => {
console.log('\nAborting request...\n')
ollama.abort()
}, 1000) // 1000 milliseconds = 1 second

try {
const stream = await ollama.generate({
model: 'llama2',
prompt: 'Write a long story',
stream: true,
})
for await (const chunk of stream) {
process.stdout.write(chunk.response)
}
} catch (error) {
if (error.name === 'AbortError') {
console.log('The request has been aborted')
} else {
console.error('An error occurred:', error)
}
}
20 changes: 17 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
export class Ollama {
private readonly config: Config
private readonly fetch: Fetch
private abortController: AbortController

constructor(config?: Partial<Config>) {
this.config = {
Expand All @@ -43,16 +44,29 @@
if (config?.fetch != null) {
this.fetch = config.fetch
}

this.abortController = new AbortController()
}

// Abort any ongoing requests to Ollama
public abort() {
this.abortController.abort()
this.abortController = new AbortController()
}

private async processStreamableRequest<T extends object>(
endpoint: string,
request: { stream?: boolean } & Record<string, any>,

Check warning on line 59 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (16)

Unexpected any. Specify a different type

Check warning on line 59 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (18)

Unexpected any. Specify a different type

Check warning on line 59 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (20)

Unexpected any. Specify a different type
): Promise<T | AsyncGenerator<T>> {
request.stream = request.stream ?? false
const response = await utils.post(this.fetch, `${this.config.host}/api/${endpoint}`, {
...request,
})
const response = await utils.post(
this.fetch,
`${this.config.host}/api/${endpoint}`,
{
...request,
},
{ signal: this.abortController.signal },
)

if (!response.body) {
throw new Error('Missing body')
Expand All @@ -69,7 +83,7 @@
yield message
// message will be done in the case of chat and generate
// message will be success in the case of a progress response (pull, push, create)
if ((message as any).done || (message as any).status === 'success') {

Check warning on line 86 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (16)

Unexpected any. Specify a different type

Check warning on line 86 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (16)

Unexpected any. Specify a different type

Check warning on line 86 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (18)

Unexpected any. Specify a different type

Check warning on line 86 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (18)

Unexpected any. Specify a different type

Check warning on line 86 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (20)

Unexpected any. Specify a different type

Check warning on line 86 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (20)

Unexpected any. Specify a different type
return
}
}
Expand All @@ -77,7 +91,7 @@
})()
} else {
const message = await itr.next()
if (!message.value.done && (message.value as any).status !== 'success') {

Check warning on line 94 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (16)

Unexpected any. Specify a different type

Check warning on line 94 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (18)

Unexpected any. Specify a different type

Check warning on line 94 in src/index.ts

View workflow job for this annotation

GitHub Actions / test (20)

Unexpected any. Specify a different type
throw new Error('Expected a completed response.')
}
return message.value
Expand Down
2 changes: 2 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,9 @@
fetch: Fetch,
host: string,
data?: Record<string, unknown> | BodyInit,
options?: { signal: AbortSignal },
): Promise<Response> => {
const isRecord = (input: any): input is Record<string, unknown> => {

Check warning on line 67 in src/utils.ts

View workflow job for this annotation

GitHub Actions / test (16)

Unexpected any. Specify a different type

Check warning on line 67 in src/utils.ts

View workflow job for this annotation

GitHub Actions / test (18)

Unexpected any. Specify a different type

Check warning on line 67 in src/utils.ts

View workflow job for this annotation

GitHub Actions / test (20)

Unexpected any. Specify a different type
return input !== null && typeof input === 'object' && !Array.isArray(input)
}

Expand All @@ -72,6 +73,7 @@
const response = await fetch(host, {
method: 'POST',
body: formattedData,
signal: options?.signal,
})

await checkOk(response)
Expand Down
Loading