Skip to content

Commit

Permalink
add an abort controller (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
BruceMacD authored Feb 6, 2024
1 parent 5c36185 commit 1417b60
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
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 @@ import type {
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 @@ export class Ollama {
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>,
): 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 Down
2 changes: 2 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export const post = async (
fetch: Fetch,
host: string,
data?: Record<string, unknown> | BodyInit,
options?: { signal: AbortSignal },
): Promise<Response> => {
const isRecord = (input: any): input is Record<string, unknown> => {
return input !== null && typeof input === 'object' && !Array.isArray(input)
Expand All @@ -72,6 +73,7 @@ export const post = async (
const response = await fetch(host, {
method: 'POST',
body: formattedData,
signal: options?.signal,
})

await checkOk(response)
Expand Down

0 comments on commit 1417b60

Please sign in to comment.