Use native Ollama FIM

This commit is contained in:
Nate 2024-09-25 16:24:53 -07:00
parent 58c03e9a91
commit 6e5c475754
3 changed files with 49 additions and 3 deletions

View file

@ -430,7 +430,7 @@ export abstract class BaseLLM implements ILLM {
return formatted;
}
async *_streamFim(
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,

View file

@ -61,7 +61,7 @@ class Ollama extends BaseLLM {
this.completionOptions.stop.push(JSON.parse(value));
} catch (e) {
console.warn(
"Error parsing stop parameter value \"{value}: ${e}",
'Error parsing stop parameter value "{value}: ${e}',
);
}
break;
@ -132,11 +132,13 @@ class Ollama extends BaseLLM {
private _convertArgs(
options: CompletionOptions,
prompt: string | ChatMessage[],
suffix?: string,
) {
const finalOptions: any = {
model: this._getModel(),
raw: true,
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
suffix,
options: {
temperature: options.temperature,
top_p: options.topP,
@ -248,6 +250,50 @@ class Ollama extends BaseLLM {
}
}
supportsFim(): boolean {
return true;
}
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, prefix, suffix)),
});
let buffer = "";
for await (const value of streamResponse(response)) {
// Append the received chunk to the buffer
buffer += value;
// Split the buffer into individual JSON chunks
const chunks = buffer.split("\n");
buffer = chunks.pop() ?? "";
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
if (chunk.trim() !== "") {
try {
const j = JSON.parse(chunk);
if ("response" in j) {
yield j.response;
} else if ("error" in j) {
throw new Error(j.error);
}
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
}
}
}
}
}
async listModels(): Promise<string[]> {
const response = await this.fetch(
// localhost was causing fetch failed in pkg binary only for this Ollama endpoint

View file

@ -264,7 +264,7 @@ class OpenAI extends BaseLLM {
}
}
async *_streamFim(
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,