🎨 use Ollama /chat and /show endpoints

This commit is contained in:
Nate Sesti 2024-01-05 15:48:25 -08:00
parent 7c5ce714e9
commit 4b304ee7d8
5 changed files with 128 additions and 27 deletions

View file

@ -0,0 +1,5 @@
project: extensions/vscode
kind: Changed
body: Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint
to gather model parameters like context length and stop tokens
time: 2024-01-05T15:47:54.05791-08:00

View file

@ -39,16 +39,13 @@ import {
zephyrEditPrompt,
} from "./templates/edit";
const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = ["lmstudio", "openai"];
function autodetectTemplateType(
model: string,
provider: ModelProvider
): TemplateType | undefined {
if (PROVIDER_HANDLES_TEMPLATING.includes(provider)) {
return "none";
}
const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"lmstudio",
"openai",
"ollama",
];
function autodetectTemplateType(model: string): TemplateType | undefined {
const lower = model.toLowerCase();
if (
@ -108,8 +105,14 @@ function autodetectTemplateFunction(
provider: ModelProvider,
explicitTemplate: TemplateType | undefined = undefined
) {
const templateType =
explicitTemplate || autodetectTemplateType(model, provider);
if (
explicitTemplate === undefined &&
PROVIDER_HANDLES_TEMPLATING.includes(provider)
) {
return null;
}
const templateType = explicitTemplate || autodetectTemplateType(model);
if (templateType) {
const mapping: Record<TemplateType, any> = {
@ -133,11 +136,9 @@ function autodetectTemplateFunction(
function autodetectPromptTemplates(
model: string,
provider: ModelProvider,
explicitTemplate: TemplateType | undefined = undefined
) {
const templateType =
explicitTemplate || autodetectTemplateType(model, provider);
const templateType = explicitTemplate || autodetectTemplateType(model);
const templates: Record<string, any> = {};
let editTemplate = null;
@ -214,8 +215,7 @@ export abstract class BaseLLM implements ILLM {
};
const templateType =
options.template ||
autodetectTemplateType(options.model, this.providerName);
options.template || autodetectTemplateType(options.model);
this.title = options.title;
this.uniqueId = options.uniqueId || "None";
@ -229,11 +229,7 @@ export abstract class BaseLLM implements ILLM {
};
this.requestOptions = options.requestOptions;
this.promptTemplates = {
...autodetectPromptTemplates(
options.model,
this.providerName,
templateType
),
...autodetectPromptTemplates(options.model, templateType),
...options.promptTemplates,
};
this.templateMessages =
@ -241,7 +237,7 @@ export abstract class BaseLLM implements ILLM {
autodetectTemplateFunction(
options.model,
this.providerName,
templateType
options.template
);
this.writeLog = options.writeLog;
this.llmRequestHook = options.llmRequestHook;

View file

@ -1,5 +1,10 @@
import { BaseLLM } from "..";
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../..";
import { streamResponse } from "../stream";
class Ollama extends BaseLLM {
@ -9,6 +14,48 @@ class Ollama extends BaseLLM {
model: "codellama-7b",
};
constructor(options: LLMOptions) {
super(options);
this.fetch(`${this.apiBase}/api/show`, {
method: "POST",
body: JSON.stringify({ name: this._getModel() }),
}).then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling Ollama /api/show endpoint: ",
await response.text()
);
return;
}
const body = await response.json();
if (body.parameters) {
const params = [];
for (let line of body.parameters.split("\n")) {
let parts = line.split(" ");
if (parts.length < 2) {
continue;
}
let key = parts[0];
let value = parts[parts.length - 1];
switch (key) {
case "num_ctx":
this.contextLength = parseInt(value);
break;
case "stop":
if (!this.completionOptions.stop) {
this.completionOptions.stop = [];
}
this.completionOptions.stop.push(value);
break;
default:
break;
}
}
}
});
}
private _getModel() {
return (
{
@ -32,9 +79,11 @@ class Ollama extends BaseLLM {
);
}
private _convertArgs(options: CompletionOptions, prompt: string) {
const finalOptions = {
prompt,
private _convertArgs(
options: CompletionOptions,
prompt: string | ChatMessage[]
) {
const finalOptions: any = {
model: this._getModel(),
raw: true,
options: {
@ -47,6 +96,12 @@ class Ollama extends BaseLLM {
},
};
if (typeof prompt === "string") {
finalOptions.prompt = prompt;
} else {
finalOptions.messages = prompt;
}
return finalOptions;
}
@ -87,6 +142,47 @@ class Ollama extends BaseLLM {
buffer = chunks[chunks.length - 1];
}
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const response = await this.fetch(`${this.apiBase}/api/chat`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(this._convertArgs(options, messages)),
});
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");
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
if (chunk.trim() !== "") {
try {
const j = JSON.parse(chunk);
if (j.message?.content) {
yield {
role: "assistant",
content: j.message.content,
};
} else if (j.error) {
throw new Error(j.error);
}
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
}
}
}
// Assign the last chunk to the buffer
buffer = chunks[chunks.length - 1];
}
}
}
export default Ollama;

View file

@ -11,6 +11,7 @@ Pre-release Changes
* support for .continuerc.json in root of workspace to override config.json
### Changed
* Allow LLM servers to handle templating
* Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint to gather model parameters like context length and stop tokens
## v0.6.16 - 2023-12-25

View file

@ -65,7 +65,10 @@
"caBundlePath": {
"title": "Ca Bundle Path",
"description": "Path to a custom CA bundle to use when making the HTTP request",
"type": "string"
"anyOf": [
{ "type": "string" },
{ "type": "array", "items": { "type": "string" } }
]
},
"proxy": {
"title": "Proxy",