Merge branch 'main' into ollama-num-gpu

This commit is contained in:
Nate 2025-03-08 08:40:50 -08:00
commit e7a1b1f01d
23 changed files with 335 additions and 129 deletions

View file

@ -303,7 +303,13 @@ jobs:
cd extensions/vscode
npm ci
npm run e2e:compile
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then
# Exclude SSH tests for forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .)
else
# Include all tests for non-forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
fi
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT

View file

@ -272,7 +272,7 @@ async function intermediateToFinalConfig(
{
...desc,
model: modelName,
title: `${llm.title} - ${modelName}`,
title: modelName,
},
ide.readFile.bind(ide),
uniqueId,

View file

@ -127,7 +127,7 @@ async function autodetectModels(
{
...model,
model: modelName,
name: `${llm.title} - ${modelName}`,
name: modelName,
},
uniqueId,
ideSettings,

6
core/index.d.ts vendored
View file

@ -163,6 +163,10 @@ export interface ILLM extends LLMOptions {
): string | ChatMessage[];
}
export interface ModelInstaller {
installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise<any>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
@ -543,7 +547,7 @@ export interface CustomLLMWithOptionals {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => Promise<string[]>;

View file

@ -19,6 +19,7 @@ import {
LLMFullCompletionOptions,
LLMOptions,
ModelCapability,
ModelInstaller,
PromptLog,
PromptTemplate,
RequestOptions,
@ -58,6 +59,17 @@ import {
toFimBody,
} from "./openaiTypeConverters.js";
export class LLMError extends Error {
constructor(message: string, public llm: ILLM) {
super(message);
}
}
export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === 'function';
}
export abstract class BaseLLM implements ILLM {
static providerName: string;
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
@ -380,9 +392,11 @@ export abstract class BaseLLM implements ILLM {
if (!resp.ok) {
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
if (text.includes("try pulling it first")) {
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
const error = JSON.parse(text)?.error?.replace(/"/g, "'");
let model = error?.match(/model '(.*)' not found/)?.[1];
if (model && resp.url.match("127.0.0.1:11434")) {
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
throw new LLMError(text, this);// No need to add HTTP status details
} else if (text.includes("/api/chat")) {
text =
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
@ -442,6 +456,10 @@ export abstract class BaseLLM implements ILLM {
throw new Error(message);
}
}
//if e instance of LLMError, rethrow
if (e instanceof LLMError) {
throw e;
}
throw new Error(e.message);
}
};
@ -763,6 +781,7 @@ export abstract class BaseLLM implements ILLM {
}
let completion = "";
let citations: null | string[] = null
try {
if (this.templateMessages) {
@ -790,6 +809,8 @@ export abstract class BaseLLM implements ILLM {
completion = renderChatMessage(msg);
} else {
// Stream true
console.log("Streaming");
const stream = this.openaiAdapter.chatCompletionStream(
{
...body,
@ -802,6 +823,9 @@ export abstract class BaseLLM implements ILLM {
if (result) {
yield result;
}
if (!citations && (chunk as any).citations && Array.isArray((chunk as any).citations)) {
citations = (chunk as any).citations;
}
}
}
} else {
@ -824,6 +848,10 @@ export abstract class BaseLLM implements ILLM {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
if (citations) {
await this.writeLog(`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`);
}
}
return {

View file

@ -1,4 +1,5 @@
import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
class CustomLLMClass extends BaseLLM {
@ -18,7 +19,7 @@ class CustomLLMClass extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
constructor(custom: CustomLLM) {
super(custom.options || { model: "custom" });
@ -38,7 +39,11 @@ class CustomLLMClass extends BaseLLM {
options,
(...args) => this.fetch(...args),
)) {
yield { role: "assistant", content };
if (typeof content === "string") {
yield { role: "assistant", content };
} else {
yield content;
}
}
} else {
for await (const update of super._streamChat(messages, signal, options)) {
@ -68,7 +73,11 @@ class CustomLLMClass extends BaseLLM {
options,
(...args) => this.fetch(...args),
)) {
yield content;
if (typeof content === "string") {
yield content;
} else {
yield renderChatMessage(content);
}
}
} else {
throw new Error(

View file

@ -1,9 +1,10 @@
import { JSONSchema7, JSONSchema7Object } from "json-schema";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { ChatMessage, CompletionOptions, ModelInstaller, LLMOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
type OllamaChatMessage = {
role: "tool" | "user" | "assistant" | "system";
@ -123,7 +124,7 @@ interface OllamaTool {
};
}
class Ollama extends BaseLLM {
class Ollama extends BaseLLM implements ModelInstaller{
static providerName = "ollama";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:11434/",
@ -575,6 +576,38 @@ class Ollama extends BaseLLM {
}
return embedding;
}
public async installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise<any> {
const modelInfo = await getRemoteModelInfo(modelName, signal);
if (!modelInfo) {
throw new Error(`'${modelName}' not found in the Ollama registry!`);
}
const response = await fetch(this.getEndpoint("api/pull"), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ name: modelName }),
signal
});
const reader = response.body?.getReader();
//TODO: generate proper progress based on modelInfo size
while (true) {
const { done, value } = await reader?.read() || { done: true, value: undefined };
if (done) {
break;
}
const chunk = new TextDecoder().decode(value);
const lines = chunk.split('\n').filter(Boolean);
for (const line of lines) {
const data = JSON.parse(line);
progressReporter?.(data.status, data.completed, data.total);
}
}
}
}
export default Ollama;

View file

@ -57,9 +57,18 @@ export const PROVIDER_TOOL_SUPPORT: Record<
},
// https://ollama.com/search?c=tools
ollama: (model) => {
let modelName = "";
// Extract the model name after the last slash to support other registries
if(model.includes("/")) {
let parts = model.split('/');
modelName = parts[parts.length - 1];
} else {
modelName = model;
}
if (
["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
(part) => model.toLowerCase().includes(part),
(part) => modelName.toLowerCase().includes(part),
)
) {
return false;
@ -79,10 +88,11 @@ export const PROVIDER_TOOL_SUPPORT: Record<
"nemotron",
"llama3-groq",
"granite3",
"granite-3",
"aya-expanse",
"firefunction-v2",
"mistral",
].some((part) => model.toLowerCase().startsWith(part))
].some((part) => modelName.toLowerCase().includes(part))
) {
return true;
}

View file

@ -1,6 +1,13 @@
import crypto from "crypto";
import { exec } from "node:child_process";
import path from "node:path";
import { IDE } from "..";
import { exec } from "node:child_process";
export interface ModelInfo {
id: string;
size: number;
digest: string;
}
export async function isOllamaInstalled(): Promise<boolean> {
return new Promise((resolve, _reject) => {
@ -39,3 +46,54 @@ export async function startLocalOllama(ide: IDE): Promise<any> {
});
}
}
export async function getRemoteModelInfo(
modelId: string,
signal?: AbortSignal,
): Promise<ModelInfo | undefined> {
const start = Date.now();
const [modelName, tag = "latest"] = modelId.split(":");
const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
try {
const sig = signal ? signal : AbortSignal.timeout(3000);
const response = await fetch(url, { signal: sig });
if (!response.ok) {
throw new Error(`Failed to fetch the model page: ${response.statusText}`);
}
// First, read the response body as an ArrayBuffer to compute the digest
const buffer = await response.arrayBuffer();
const digest = getDigest(buffer);
// Then, decode the ArrayBuffer into a string and parse it as JSON
const text = new TextDecoder().decode(buffer);
const manifest = JSON.parse(text) as {
config: { size: number };
layers: { size: number }[];
};
const modelSize =
manifest.config.size +
manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
const data: ModelInfo = {
id: modelId,
size: modelSize,
digest,
};
// Cache the successful result
return data;
} catch (error) {
console.error(`Error fetching or parsing model info: ${error}`);
} finally {
const elapsed = Date.now() - start;
console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
}
return undefined;
}
function getDigest(buffer: ArrayBuffer): string {
const hash = crypto.createHash("sha256");
hash.update(new Uint8Array(buffer));
return hash.digest("hex");
}

6
core/util/text.ts Normal file
View file

@ -0,0 +1,6 @@
export const capitalizeFirstLetter = (val: string) => {
if (val.length === 0) {
return "";
}
return val[0].toUpperCase() + val.slice(1);
};

View file

@ -137,7 +137,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo
context:
- provider: docs
params:
nRetrieve: 25 # The number of docs to retreive from the embeddings query
nRetrieve: 25 # The number of docs to retrieve from the embeddings query
nFinal: 5 # The number of docs chunks to return IF reranking
useReranking: true # use reranking if a reranker is configured (defaults to true)
```
@ -149,7 +149,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo
{
"name": "docs",
"params": {
"nRetrieve": 25, // The number of docs to retreive from the embeddings query
"nRetrieve": 25, // The number of docs to retrieve from the embeddings query
"nFinal": 5, // The number of docs chunks to return IF reranking
"useReranking": true // use reranking if a reranker is configured (defaults to true)
}

View file

@ -41,7 +41,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c
1. Open the "Output" panel (right next to the terminal)
2. In the dropdown, select "Continue - LLM Prompts/Completions"
3. View the exact prompts that were sent to the LLM and the completions recieved
3. View the exact prompts that were sent to the LLM and the completions received
### JetBrains

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.3",
"version": "1.1.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.3",
"version": "1.1.4",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/fetch": "^1.0.3",

View file

@ -21,8 +21,8 @@ import {
stopStatusBarLoading,
} from "./statusBar";
import { startLocalOllama } from "core/util/ollamaHelper";
import type { IDE } from "core";
import { handleLLMError } from "../util/errorHandling";
const Diff = require("diff");
@ -43,16 +43,13 @@ export class ContinueCompletionProvider
implements vscode.InlineCompletionItemProvider
{
private onError(e: any) {
let options = ["Documentation"];
if (e.message.includes("Ollama may not be installed")) {
options.push("Download Ollama");
} else if (e.message.includes("Ollama may not be running")) {
options = ["Start Ollama"]; // We want "Start" to be the only choice
if (handleLLMError(e)) {
return;
}
if (e.message.includes("Please sign in with GitHub")) {
let message = e.message;
if (message.includes("Please sign in with GitHub")) {
showFreeTrialLoginMessage(
e.message,
message,
this.configHandler.reloadConfig.bind(this.configHandler),
() => {
void this.webviewProtocol.request("openOnboardingCard", undefined);
@ -60,17 +57,13 @@ export class ContinueCompletionProvider
);
return;
}
vscode.window.showErrorMessage(e.message, ...options).then((val) => {
vscode.window.showErrorMessage(message, "Documentation").then((val) => {
if (val === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/features/tab-autocomplete",
),
);
} else if (val === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
} else if (val === "Start Ollama") {
startLocalOllama(this.ide);
}
});
}

View file

@ -47,7 +47,7 @@ export class RecentlyEditedTracker {
editedRange: Omit<VsCodeRecentlyEditedRange, "lines" | "symbols">,
): Promise<void> {
if (editedRange.uri.scheme === "output") {
if (editedRange.uri.scheme !== "file") {
return;
}
@ -83,7 +83,6 @@ export class RecentlyEditedTracker {
RecentlyEditedTracker.maxRecentlyEditedRanges,
);
}
}
private insertDocument(uri: vscode.Uri): void {

View file

@ -1,7 +1,12 @@
/* eslint-disable @typescript-eslint/naming-convention */
import * as os from "node:os";
import { ContextMenuConfig, RangeInFileWithContents } from "core";
import {
ContextMenuConfig,
ILLM,
ModelInstaller,
RangeInFileWithContents,
} from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { ConfigHandler } from "core/config/ConfigHandler";
import { ContinueServerClient } from "core/continueServer/stubs/client";
@ -14,13 +19,13 @@ import readLastLines from "read-last-lines";
import * as vscode from "vscode";
import {
StatusBarStatus,
getAutocompleteStatusBarDescription,
getAutocompleteStatusBarTitle,
getStatusBarStatus,
getStatusBarStatusFromQuickPickItemLabel,
quickPickStatusText,
setupStatusBar,
StatusBarStatus,
} from "./autocomplete/statusBar";
import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";
@ -32,6 +37,7 @@ import { getMetaKeyLabel } from "./util/util";
import { VsCodeIde } from "./VsCodeIde";
import { LOCAL_DEV_DATA_VERSION } from "core/data/log";
import { isModelInstaller } from "core/llm";
import { startLocalOllama } from "core/util/ollamaHelper";
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
@ -996,6 +1002,25 @@ const getCommandsMap: (
"continue.startLocalOllama": () => {
startLocalOllama(ide);
},
"continue.installModel": async (
modelName: string,
llmProvider: ILLM | undefined,
) => {
try {
if (!isModelInstaller(llmProvider)) {
const msg = llmProvider
? `LLM provider '${llmProvider.providerName}' does not support installing models`
: "Missing LLM Provider";
throw new Error(msg);
}
await installModelWithProgress(modelName, llmProvider);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
vscode.window.showErrorMessage(
`Failed to install '${modelName}': ${message}`,
);
}
},
};
};
@ -1037,6 +1062,45 @@ const registerCopyBufferSpy = (
context.subscriptions.push(typeDisposable);
};
async function installModelWithProgress(
modelName: string,
modelInstaller: ModelInstaller,
) {
return vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Installing model '${modelName}'`,
cancellable: true,
},
async (windowProgress, token) => {
let currentProgress: number = 0;
const progressWrapper = (
details: string,
worked?: number,
total?: number,
) => {
let increment = 0;
if (worked && total) {
const progressValue = Math.round((worked / total) * 100);
increment = progressValue - currentProgress;
currentProgress = progressValue;
}
windowProgress.report({ message: details, increment });
};
const abortController = new AbortController();
token.onCancellationRequested(() => {
console.log(`Pulling ${modelName} model was cancelled`);
abortController.abort();
});
await modelInstaller.installModel(
modelName,
abortController.signal,
progressWrapper,
);
},
);
}
export function registerAllCommands(
context: vscode.ExtensionContext,
ide: VsCodeIde,

View file

@ -9,6 +9,7 @@ import * as vscode from "vscode";
import EditDecorationManager from "../../quickEdit/EditDecorationManager";
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
import { handleLLMError } from "../../util/errorHandling";
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
export interface VerticalDiffCodeLens {
@ -230,7 +231,7 @@ export class VerticalDiffManager {
);
if (!diffHandler) {
console.warn("Issue occured while creating new vertical diff handler");
console.warn("Issue occurred while creating new vertical diff handler");
return;
}
@ -255,7 +256,9 @@ export class VerticalDiffManager {
this.enableDocumentChangeListener();
} catch (e) {
this.disableDocumentChangeListener();
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
if (!handleLLMError(e)) {
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
}
} finally {
vscode.commands.executeCommand(
"setContext",
@ -353,7 +356,7 @@ export class VerticalDiffManager {
);
if (!diffHandler) {
console.warn("Issue occured while creating new vertical diff handler");
console.warn("Issue occurred while creating new vertical diff handler");
return undefined;
}
@ -446,7 +449,9 @@ export class VerticalDiffManager {
return `${prefix}${streamedLines.join("\n")}${suffix}`;
} catch (e) {
this.disableDocumentChangeListener();
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
if (!handleLLMError(e)) {
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
}
return undefined;
} finally {
vscode.commands.executeCommand(

View file

@ -0,0 +1,49 @@
import * as vscode from "vscode";
function supportSpecialHandling(error: any): boolean {
let message: string | undefined = error.message;
return message !== undefined && message.toLowerCase().includes("ollama");
}
/**
* @param error Handles common LLM errors. Currently only handles Ollama-related errors.
* @returns true if error is handled, false otherwise
*/
export function handleLLMError(error: any): boolean {
if (!supportSpecialHandling(error)) {
return false;
}
let message: string = error.message;
let options: string[] | undefined;
let modelName = undefined;
if (message.includes("Ollama may not be installed")) {
options = ["Download Ollama"];
} else if (message.includes("Ollama may not be running")) {
options = ["Start Ollama"]; // We want "Start" to be the only choice
} else if (message.includes("ollama run") && error.llm) {
//extract model name from error message matching the pattern "ollama run <model-name>"
modelName = message.match(/`ollama run (.*)`/)?.[1];
message = `Model "${modelName}" is not found in Ollama. You need to install it.`;
options = [`Install Model`];
}
if (options === undefined) {
console.log("Found an unhandled Ollama error: ", message);
return false;
}
vscode.window.showErrorMessage(message, ...options).then((val) => {
if (val === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
} else if (val === "Start Ollama") {
vscode.commands.executeCommand("continue.startLocalOllama");
} else if (val === "Install Model" && error.llm) {
//Eventually, we might be able to support installing models for other LLM providers than Ollama
vscode.commands.executeCommand(
"continue.installModel",
modelName,
error.llm,
);
}
});
return true;
}

View file

@ -7,6 +7,7 @@ import * as vscode from "vscode";
import { IMessenger } from "../../../core/protocol/messenger";
import { handleLLMError } from "./util/errorHandling";
import { showFreeTrialLoginMessage } from "./util/messages";
export class VsCodeWebviewProtocol
@ -86,31 +87,12 @@ export class VsCodeWebviewProtocol
respond({ done: true, content: response, status: "success" });
}
} catch (e: any) {
let message = e.message;
//Intercept Ollama errors for special handling
if (message.includes("Ollama may not")) {
const options = [];
if (message.includes("be installed")) {
options.push("Download Ollama");
} else if (message.includes("be running")) {
options.push("Start Ollama");
}
if (options.length > 0) {
// Respond without an error, so the UI doesn't show the error component
respond({ done: true, status: "error" });
// Show native vscode error message instead, with options to download/start Ollama
vscode.window.showErrorMessage(e.message, ...options).then(async (val) => {
if (val === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
} else if (val === "Start Ollama") {
vscode.commands.executeCommand("continue.startLocalOllama");
}
});
return;
}
if (handleLLMError(e)) {
// Respond without an error, so the UI doesn't show the error component
respond({ done: true, status: "error" });
}
respond({ done: true, error: e.message, status: "error" });
let message = e.message;
respond({ done: true, error: message, status: "error" });
const stringified = JSON.stringify({ msg }, null, 2);
console.error(

View file

@ -8,9 +8,8 @@
// TODO support github-specific markdown as well, edge case
*/
export const patchNestedMarkdown = (source: string): string => {
if (!source.match(/```(md|markdown)/)) return source; // For performance
if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance
// const start = Date.now();
let nestCount = 0;
const lines = source.split("\n");
@ -28,9 +27,17 @@ export const patchNestedMarkdown = (source: string): string => {
}
} else {
// Enter the markdown block, start tracking nesting
if (line.startsWith("```md") || line.startsWith("```markdown")) {
nestCount = 1;
lines[i] = lines[i].replace(/```(md|markdown)/, "~~~"); // Replace backticks with tildes
if (line.startsWith("```")) {
const header = line.replaceAll("`", "");
const file = header.split(" ")[0];
if (file) {
const ext = file.split(".").at(-1);
if (ext === "md" || ext === "markdown") {
nestCount = 1;
lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes
}
}
}
}
}
@ -38,53 +45,3 @@ export const patchNestedMarkdown = (source: string): string => {
// console.log(`patched in ${Date.now() - start}ms`);
return out;
};
// This version tries to detect if a codeblock without a language specified is a starter codeblock
// It tries again if didn't come back to root nesting, without checking for that ^
// I didn't use for performance and also because the root nest check doesn't make sense mid-generation
// export const patchNestedMarkdown = (source: string): string => {
// const start = Date.now();
// let attempts = 0;
// while (attempts <= 2) {
// let nestCount = 0;
// const lines = source.split("\n");
// const trimmedLines = lines.map((l) => l.trim());
// for (let i = 0; i < trimmedLines.length; i++) {
// const line = trimmedLines[i];
// if (nestCount) {
// if (line.match(/^`+$/)) {
// if (attempts === 0 && i !== lines.length && lines[i + 1] !== "") {
// nestCount++;
// continue;
// }
// if (nestCount === 1) lines[i] = "~~~";
// nestCount--;
// } else if (line.startsWith("```")) {
// // Going into a nested codeblock
// nestCount++;
// }
// } else {
// // Enter the markdown block, start tracking nesting
// if (line.startsWith("```md") || line.startsWith("```markdown")) {
// nestCount = 1;
// lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes
// }
// }
// }
// if (nestCount === 0) {
// console.log(
// `patch successful in ${Date.now() - start} ms with ${attempts} attempts`,
// );
// return lines.join("\n");
// }
// attempts++;
// }
// console.log(
// `patch failed in ${Date.now() - start} ms with ${attempts} attempts`,
// );
// return source;
// };

View file

@ -1,11 +1,10 @@
import { Transition } from "@headlessui/react";
import { Listbox, Transition } from "@headlessui/react";
import {
CheckIcon,
ChevronUpDownIcon,
CubeIcon,
} from "@heroicons/react/24/outline";
import { Fragment } from "react";
import { Listbox } from "@headlessui/react";
import styled from "styled-components";
import {
defaultBorderRadius,

View file

@ -66,11 +66,13 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
) {
message = error["message"];
const parts = message?.split(" ") ?? [];
const status = parts[0] === "HTTP" ? parts[1] : parts[0];
if (status) {
const code = Number(status);
if (!Number.isNaN(statusCode)) {
statusCode = code;
if (parts.length > 1) {
const status = parts[0] === "HTTP" ? parts[1] : parts[0];
if (status) {
const code = Number(status);
if (!Number.isNaN(code)) {
statusCode = code;
}
}
}
}

View file

@ -40,8 +40,10 @@ export class AzureOpenAIApi implements BaseLlmApi {
if (PROXY) {
const url = new URL(PROXY);
proxyOptions = {
host: url.hostname,
port: Number(url.port),
host: (url.protocol ? url.protocol + "//" : "") + url.hostname,
port: Number(url.port || 80),
username: url.username,
password: url.password,
};
}