diff --git a/.changes/unreleased/Added-20240107-090812.yaml b/.changes/unreleased/Added-20240107-090812.yaml new file mode 100644 index 000000000..ba73bfb44 --- /dev/null +++ b/.changes/unreleased/Added-20240107-090812.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: disableSessionTitles option in config.json +time: 2024-01-07T09:08:12.16135-08:00 diff --git a/.changes/unreleased/Changed-20240105-154754.yaml b/.changes/unreleased/Changed-20240105-154754.yaml new file mode 100644 index 000000000..5ab43d583 --- /dev/null +++ b/.changes/unreleased/Changed-20240105-154754.yaml @@ -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 diff --git a/README.md b/README.md index c1eeb8421..dffca7596 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ ### Answer coding questions -Highlight sections of code and ask Continue for another perspective +Highlight (select and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) sections of code and ask Continue for another perspective - “what does this forRoot() static function do in nestjs?” - “why is the first left join in this query necessary here?” @@ -40,7 +40,7 @@ Highlight sections of code and ask Continue for another perspective ### Edit in natural language -Highlight a section of code and instruct Continue to refactor it +Highlight (select and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) a section of code and instruct Continue to refactor it - “/edit rewrite this to return a flattened list from a 3x3 matrix” - “/edit refactor these into an angular flex layout on one line" diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index 3c2f76cdf..5db8f96a3 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -210,7 +210,7 @@ const EditSlashCommand: SlashCommand = { ); if (!contextItemToEdit) { - yield "Highlight the code that you want to edit first"; + yield "Highlight (select and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) the code that you want to edit first"; return; } @@ -552,6 +552,25 @@ const EditSlashCommand: SlashCommand = { } await sendDiffUpdate(lines, true); + + if (params?.recap) { + const prompt = `This is the code before editing: +\`\`\` +${contents} +\`\`\` + +This is the code after editing: + +\`\`\` +${lines.join("\n")} +\`\`\` + +Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; + + for await (const update of llm.streamComplete(prompt)) { + yield update; + } + } }, }; diff --git a/core/config/types.ts b/core/config/types.ts index 7f22b468f..2a8c31801 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -2,10 +2,10 @@ const Types = ` declare global { export interface ILLM extends LLMOptions { get providerName(): ModelProvider; - + uniqueId: string; model: string; - + title?: string; systemMessage?: string; contextLength: number; @@ -17,35 +17,35 @@ declare global { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; - + engine?: string; apiVersion?: string; apiType?: string; region?: string; projectId?: string; - + _fetch?: (input: any, init?: any) => Promise; - + complete(prompt: string, options?: LLMFullCompletionOptions): Promise; - + streamComplete( prompt: string, options?: LLMFullCompletionOptions ): AsyncGenerator; - + streamChat( messages: ChatMessage[], options?: LLMFullCompletionOptions ): AsyncGenerator; - + chat( messages: ChatMessage[], options?: LLMFullCompletionOptions ): Promise; - + countTokens(text: string): number; } - + export interface ContextProviderDescription { title: string; displayTitle: string; @@ -53,39 +53,39 @@ declare global { dynamic: boolean; requiresQuery: boolean; } - + export interface CustomContextProvider { title: string; displayTitle?: string; description?: string; getContextItems(query: string): Promise; } - + export interface IContextProvider { get description(): ContextProviderDescription; - + getContextItems(query: string): Promise; } - + export interface PersistedSessionInfo { history: ChatHistory; title: string; workspaceDirectory: string; sessionId: string; } - + export interface SessionInfo { sessionId: string; title: string; dateCreated: string; workspaceDirectory: string; } - + export interface RangeInFile { filepath: string; range: Range; } - + export interface Range { start: Position; end: Position; @@ -99,15 +99,15 @@ declare global { range: Range; replacement: string; } - + export interface ContinueError { title: string; message: string; } - + export interface CompletionOptions { model: string; - + maxTokens: number; temperature?: number; topP?: number; @@ -117,19 +117,19 @@ declare global { frequencyPenalty?: number; stop?: string[]; } - + export type ChatMessageRole = "user" | "assistant" | "system"; - + export interface ChatMessage { role: ChatMessageRole; content: string; } - + export interface ContextItemId { providerTitle: string; itemId: string; } - + export interface ContextItem { content: string; name: string; @@ -137,7 +137,7 @@ declare global { editing?: boolean; editable?: boolean; } - + export interface ContextItemWithId { content: string; name: string; @@ -146,24 +146,24 @@ declare global { editing?: boolean; editable?: boolean; } - + export interface ChatHistoryItem { message: ChatMessage; editorState?: any; contextItems: ContextItemWithId[]; promptLogs?: [string, string][]; // [prompt, completion] } - + export type ChatHistory = ChatHistoryItem[]; - + // LLM - + export interface LLMFullCompletionOptions { raw?: boolean; log?: boolean; - + model?: string; - + temperature?: number; topP?: number; topK?: number; @@ -175,7 +175,7 @@ declare global { } export interface LLMOptions { model: string; - + title?: string; uniqueId?: string; systemMessage?: string; @@ -189,12 +189,12 @@ declare global { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; - + // Azure options engine?: string; apiVersion?: string; apiType?: string; - + // GCP Options region?: string; projectId?: string; @@ -206,7 +206,7 @@ declare global { { [K in Keys]-?: Required> & Partial>>; }[Keys]; - + export interface CustomLLMWithOptionals { options?: LLMOptions; streamCompletion?: ( @@ -220,7 +220,7 @@ declare global { fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise ) => AsyncGenerator; } - + /** * The LLM interface requires you to specify either \`streamCompletion\` or \`streamChat\` (or both). */ @@ -228,14 +228,14 @@ declare global { CustomLLMWithOptionals, "streamCompletion" | "streamChat" >; - + // IDE - + export interface DiffLine { type: "new" | "old" | "same"; line: string; } - + export interface IDE { getSerializedConfig(): Promise; getConfigJsUrl(): Promise; @@ -262,10 +262,11 @@ declare global { diffLine: DiffLine ): Promise; getOpenFiles(): Promise; + getSearchResults(query: string): Promise; } - + // Slash Commands - + export interface ContinueSDK { ide: IDE; llm: ILLM; @@ -275,20 +276,20 @@ declare global { params?: any; contextItems: ContextItemWithId[]; } - + export interface SlashCommand { name: string; description: string; params?: { [key: string]: any }; run: (sdk: ContinueSDK) => AsyncGenerator; - + // If true, this command will be run in NodeJs and have access to the filesystem and other Node-only APIs // You must make sure to dynamically import any Node-only dependencies in your command so that it doesn't break in the browser runInNodeJs?: boolean; } - + // Config - + type StepName = | "AnswerQuestionChroma" | "GenerateShellCommandStep" @@ -300,7 +301,7 @@ declare global { | "OpenConfigStep" | "GenerateShellCommandStep" | "DraftIssueStep"; - + type ContextProviderName = | "diff" | "github" @@ -311,7 +312,7 @@ declare global { | "url" | "tree" | "http"; - + type TemplateType = | "llama2" | "alpaca" @@ -321,8 +322,9 @@ declare global { | "chatml" | "none" | "openchat" - | "deepseek"; - + | "deepseek" + | "xwin-coder"; + type ModelProvider = | "openai" | "openai-free-trial" @@ -339,8 +341,9 @@ declare global { | "llamafile" | "gemini" | "mistral" - | "bedrock"; - + | "bedrock" + | "deepinfra"; + export type ModelName = // OpenAI | "gpt-3.5-turbo" @@ -376,7 +379,7 @@ declare global { | "mistral-tiny" | "mistral-small" | "mistral-medium"; - + export interface RequestOptions { timeout?: number; verifySsl?: boolean; @@ -384,24 +387,23 @@ declare global { proxy?: string; headers?: { [key: string]: string }; } - + export interface StepWithParams { name: StepName; params: { [key: string]: any }; } - + export interface ContextProviderWithParams { name: ContextProviderName; params: { [key: string]: any }; } - + export interface SlashCommandDescription { name: string; description: string; - step: StepName | string; params?: { [key: string]: any }; } - + export interface CustomCommand { name: string; prompt: string; @@ -419,7 +421,7 @@ declare global { apiVersion?: string; organizationId?: string; } - + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -430,7 +432,7 @@ declare global { stop?: string[]; maxTokens: number; } - + export interface ModelDescription { title: string; provider: ModelProvider; @@ -444,14 +446,14 @@ declare global { requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; } - + export interface ModelRoles { default: string; chat?: string; edit?: string; summarize?: string; } - + export interface SerializedContinueConfig { disallowedSteps?: string[]; allowAnonymousTelemetry?: boolean; @@ -463,9 +465,10 @@ declare global { contextProviders?: ContextProviderWithParams[]; retrievalSettings?: RetrievalSettings; disableIndexing?: boolean; + disableSessionTitles?: boolean; userToken?: string; } - + export interface Config { /** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://continue.dev/docs/telemetry */ allowAnonymousTelemetry?: boolean; @@ -488,10 +491,12 @@ declare global { retrievalSettings?: RetrievalSettings; /** If set to true, Continue will not index your codebase for retrieval */ disableIndexing?: boolean; + /** If set to true, Continue will not make extra requests to the LLM to generate a summary title of each session. */ + disableSessionTitles?: boolean; /** An optional token to identify a user. Not used by Continue unless you write custom coniguration that requires such a token */ userToken?: string; } - + export interface ContinueConfig { allowAnonymousTelemetry?: boolean; models: ILLM[]; @@ -500,6 +505,7 @@ declare global { slashCommands?: SlashCommand[]; contextProviders?: IContextProvider[]; retrievalSettings?: RetrievalSettings; + disableSessionTitles?: boolean; disableIndexing?: boolean; userToken?: string; } diff --git a/core/ide/messaging.ts b/core/ide/messaging.ts index 4ab5d1686..56e0d9d89 100644 --- a/core/ide/messaging.ts +++ b/core/ide/messaging.ts @@ -75,8 +75,6 @@ export async function* ideStreamRequest( let index = 0; let done = false; - let staleTimeout: any; - const handler = (event: any) => { if (event.data.messageId === messageId) { if (event.data.message.done) { @@ -85,11 +83,6 @@ export async function* ideStreamRequest( } else { buffer += event.data.message.content; } - clearTimeout(staleTimeout); - staleTimeout = setTimeout(() => { - console.warn("Stream request timed out."); - done = true; - }, 20_000); } }; window.addEventListener("message", handler); @@ -108,6 +101,4 @@ export async function* ideStreamRequest( index = buffer.length; yield chunk; } - - clearTimeout(staleTimeout); } diff --git a/core/index.d.ts b/core/index.d.ts index b69dab1b8..ea0aa8985 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -340,7 +340,8 @@ type ModelProvider = | "llamafile" | "gemini" | "mistral" - | "bedrock"; + | "bedrock" + | "deepinfra"; export type ModelName = // OpenAI @@ -464,6 +465,7 @@ export interface SerializedContinueConfig { contextProviders?: ContextProviderWithParams[]; retrievalSettings?: RetrievalSettings; disableIndexing?: boolean; + disableSessionTitles?: boolean; userToken?: string; } @@ -489,6 +491,8 @@ export interface Config { retrievalSettings?: RetrievalSettings; /** If set to true, Continue will not index your codebase for retrieval */ disableIndexing?: boolean; + /** If set to true, Continue will not make extra requests to the LLM to generate a summary title of each session. */ + disableSessionTitles?: boolean; /** An optional token to identify a user. Not used by Continue unless you write custom coniguration that requires such a token */ userToken?: string; } @@ -501,6 +505,7 @@ export interface ContinueConfig { slashCommands?: SlashCommand[]; contextProviders?: IContextProvider[]; retrievalSettings?: RetrievalSettings; + disableSessionTitles?: boolean; disableIndexing?: boolean; userToken?: string; } diff --git a/core/llm/index.ts b/core/llm/index.ts index 4f546935d..61842c4ed 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -41,16 +41,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 ( @@ -114,8 +111,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 = { @@ -140,11 +143,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 = {}; let editTemplate = null; @@ -223,8 +224,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"; @@ -238,11 +238,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 = @@ -250,7 +246,7 @@ export abstract class BaseLLM implements ILLM { autodetectTemplateFunction( options.model, this.providerName, - templateType + options.template ); this.writeLog = options.writeLog; this.llmRequestHook = options.llmRequestHook; diff --git a/core/llm/llms/DeepInfra.ts b/core/llm/llms/DeepInfra.ts new file mode 100644 index 000000000..a3723afb6 --- /dev/null +++ b/core/llm/llms/DeepInfra.ts @@ -0,0 +1,11 @@ +import { LLMOptions, ModelProvider } from "../.."; +import OpenAI from "./OpenAI"; + +class DeepInfra extends OpenAI { + static providerName: ModelProvider = "deepinfra"; + static defaultOptions: Partial = { + apiBase: "https://api.deepinfra.com/v1/openai", + }; +} + +export default DeepInfra; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index b9d568e06..57d483be4 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -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 ( { @@ -33,9 +80,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: { @@ -48,6 +97,12 @@ class Ollama extends BaseLLM { }, }; + if (typeof prompt === "string") { + finalOptions.prompt = prompt; + } else { + finalOptions.messages = prompt; + } + return finalOptions; } @@ -88,6 +143,47 @@ class Ollama extends BaseLLM { buffer = chunks[chunks.length - 1]; } } + + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions + ): AsyncGenerator { + 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; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 3b08c49d4..859cb0a27 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -138,7 +138,8 @@ class OpenAI extends BaseLLM { url = url.slice(0, -1); } - if (!url.endsWith("/v1")) { + if (!url.includes("/v1")) { + // includes instead of endsWith becuase DeepInfra uses /v1/openai/chat/completions url += "/v1"; } return url + "/chat/completions"; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 828798b6c..1cbb95ffa 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -7,6 +7,7 @@ import { } from "../.."; import Anthropic from "./Anthropic"; import Bedrock from "./Bedrock"; +import DeepInfra from "./DeepInfra"; import FreeTrial from "./FreeTrial"; import Gemini from "./Gemini"; import GooglePalm from "./GooglePalm"; @@ -39,6 +40,7 @@ const LLMs = [ Gemini, Mistral, Bedrock, + DeepInfra, ]; export function llmFromDescription( diff --git a/docs/docs/how-to-use-continue.md b/docs/docs/how-to-use-continue.md index 5bd4fcb98..31cd80249 100644 --- a/docs/docs/how-to-use-continue.md +++ b/docs/docs/how-to-use-continue.md @@ -18,6 +18,8 @@ As you use Continue more, you will learn when to trust it. A great way to get st If you are trying to use it for a new task and don’t have a sense of how much Continue can help you complete it, it can often be helpful to start like this: +'Highlight' refers to the act of selecting a text range in a file and pressing 'cmd+shift+M' (Macos) or 'ctrl+shift+M' (Windows) to include it in the Continue chat message. + 1. Highlight the code section(s) that you don’t understand and type "tell me how this code works" in the input box 2. If the explanation seems reasonable, then, while still highlighting the code section(s), type "how would you change this code to [INSERT TASK]?" 3. If this explanation is also pretty good, then, while still highlighting the code section(s), type `/edit [INSERT TASK]`. If you like the suggested diff, use `cmd+shift+enter` to accept the changes. diff --git a/docs/docs/reference/Model Providers/deepinfra.md b/docs/docs/reference/Model Providers/deepinfra.md new file mode 100644 index 000000000..0745232ca --- /dev/null +++ b/docs/docs/reference/Model Providers/deepinfra.md @@ -0,0 +1,18 @@ +# DeepInfra + +[DeepInfra](https://deepinfra.com) provides inference for open-source models at very low cost. To get started with DeepInfra, obtain your API key [here](https://deepinfra.com/dash). Then, find the model you want to use [here](https://deepinfra.com/models?type=text-generation) and copy the name of the model. Continue can then be configured to use the `DeepInfra` LLM class, like the example here: + +```json title="~/.continue/config.json" +{ + "models": [ + { + "provider": "deepinfra", + "title": "DeepInfra", + "model": "mistralai/Mixtral-8x7B-Instruct-v0.1", + "apiKey": "" + } + ] +} +``` + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/DeepInfra.ts) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 97f47712f..1230ee60e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -127,6 +127,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { val settings = ServiceManager.getService(ContinueExtensionSettings::class.java) if (!settings.continueState.shownWelcomeDialog) { + settings.continueState.shownWelcomeDialog = true // Open continue_tutorial.py ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` -> if (`is` == null) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Proxy.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Proxy.kt index bac9ea451..b34dd1d7a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Proxy.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Proxy.kt @@ -8,8 +8,9 @@ import io.ktor.server.response.* import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.server.plugins.cors.routing.* -import io.ktor.util.Identity.decode +import io.ktor.util.* import io.ktor.utils.io.jvm.javaio.* +import kotlinx.coroutines.withTimeout import okhttp3.OkHttpClient import okhttp3.Request import org.apache.commons.io.IOUtils.byteArray @@ -17,7 +18,9 @@ import java.io.ByteArrayOutputStream import java.net.URL fun startProxyServer() { - embeddedServer(Netty, port = 65433, module = Application::proxyServer).start(wait = true) + embeddedServer(Netty, port = 65433, module = Application::proxyServer, configure = { + responseWriteTimeoutSeconds = 7200 + }).start(wait = true) } fun Application.proxyServer() { @@ -70,7 +73,11 @@ fun Application.proxyServer() { } // Create OkHttpClient instance - val client = OkHttpClient() + val client = OkHttpClient.Builder() + .callTimeout(7200, java.util.concurrent.TimeUnit.SECONDS) + .connectTimeout(7200, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(7200, java.util.concurrent.TimeUnit.SECONDS) + .build() val requestBody = body?.let { okhttp3.RequestBody.create(null, it) } val okhttpHeaders = okhttp3.Headers.Builder() diff --git a/extensions/intellij/src/main/resources/tool-window-icon.png b/extensions/intellij/src/main/resources/tool-window-icon.png index 200a67f3e..e4bae1052 100644 Binary files a/extensions/intellij/src/main/resources/tool-window-icon.png and b/extensions/intellij/src/main/resources/tool-window-icon.png differ diff --git a/extensions/intellij/src/main/resources/tool-window-icon_dark.png b/extensions/intellij/src/main/resources/tool-window-icon_dark.png new file mode 100644 index 000000000..200a67f3e Binary files /dev/null and b/extensions/intellij/src/main/resources/tool-window-icon_dark.png differ diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 3813e25f5..d19c14173 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -9,14 +9,11 @@ and is generated by [Changie](https://github.com/miniscruff/changie). ## v0.6.19 - 2024-01-05 ### Added - -- support for .continuerc.json in root of workspace to override config.json -- Inline context providers -- cmd+shift+L with new diff streaming UI for edits - +* support for .continuerc.json in root of workspace to override config.json +* disableSessionTitles option in config.json ### Changed - -- Allow certain LLM servers to handle templating +* 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 diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index fd85cd5a5..0d56f6ca4 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -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", @@ -104,11 +107,27 @@ "huggingface-inference-api", "llama.cpp", "replicate", - "text-gen-webui", "google-palm", "lmstudio", "llamafile", - "mistral" + "mistral", + "deepinfra" + ], + "markdownEnumDescriptions": [ + "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)", + "### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)", + "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)", + "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)", + "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)", + "### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)", + "### Huggingface Inference API\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfaceinferenceapi)", + "### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamacpp)", + "### Replicate\nReplicate is a hosted service that makes it easy to run ML models. To get started with Replicate:\n1. Obtain an API key from [here](https://replicate.com)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/replicatellm)", + "### Google PALM\nTo get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/googlepalmapi)", + "### LMStudio\nLMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/lmstudio)", + "### Llamafile\nTo get started with llamafiles, find and download a binary on their [GitHub repo](https://github.com/Mozilla-Ocho/llamafile#binary-instructions). Then run it with the following command:\n\n```shell\nchmod +x ./llamafile\n./llamafile\n```\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamafile)", + "### Mistral API\n\nTo get access to the Mistral API, obtain your API key from the [Mistral platform](https://docs.mistral.ai/)", + "### DeepInfra\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/deepinfra)" ], "type": "string" }, @@ -479,6 +498,23 @@ } } }, + { + "if": { + "properties": { + "provider": { + "enum": ["deepinfra"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "description": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation)." + } + } + } + }, { "if": { "properties": { @@ -692,7 +728,17 @@ "http", "commit" ], - "type": "string" + "type": "string", + "markdownEnumDescriptions": [ + "Generate a link to a drafted GitHub issue", + "Export the current chat session to markdown", + "Reference StackOverflow to answer the question", + "Generate a terminal command and paste it into the terminal", + "Edit the highlighted code with given instructions", + "Add comments to the highlighted code", + "Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", + "Generate a commit message for the current changes" + ] }, { "type": "string" } ] @@ -735,6 +781,27 @@ }, "required": ["params"] } + }, + { + "if": { + "properties": { + "name": { + "enum": ["edit"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "recap": { + "type": "boolean", + "description": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit." + } + } + } + } + } } ], "required": ["name", "description"] @@ -775,6 +842,14 @@ "url", "http" ], + "markdownEnumDescriptions": [ + "Reference the contents of the current changes as given by `git diff`", + "Reference the contents of the terminal", + "Reference the contents of all open files.", + "Enter a search phrase and include the Google search results as context", + "Enter a URL and use the contents of the webpage as context", + "Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup." + ], "type": "string" }, { "type": "string" } @@ -881,15 +956,6 @@ "title": "SerializedContinueConfig", "type": "object", "properties": { - "disallowedSteps": { - "title": "Disallowed Steps", - "description": "Steps that are not allowed to be run, and will be skipped if attempted", - "default": [], - "type": "array", - "items": { - "type": "string" - } - }, "allowAnonymousTelemetry": { "title": "Allow Anonymous Telemetry", "description": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to False, we will not collect any data.", @@ -990,6 +1056,12 @@ "default": false, "type": "boolean" }, + "disableSessionTitles": { + "title": "Disable Session Titles", + "description": "If set to `True`, Continue will not make extra requests to the LLM to generate a summary title of each session.", + "default": false, + "type": "boolean" + }, "retrievalSettings": { "title": "Retrieval Settings", "description": "Settings for the retrieval system. Read more about the retrieval system in the documentation.", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index bdbd87f87..a81450817 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.8.1", + "version": "0.9.4", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "continue", - "version": "0.8.1", + "version": "0.9.4", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 376c61b50..431f3a556 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -1,7 +1,7 @@ { "name": "continue", "icon": "media/icon.png", - "version": "0.8.1", + "version": "0.9.4", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/server/.gitignore b/extensions/vscode/server/.gitignore deleted file mode 100644 index 62d82aec9..000000000 --- a/extensions/vscode/server/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -**.whl -exe/** -exe \ No newline at end of file diff --git a/extensions/vscode/server/README.md b/extensions/vscode/server/README.md deleted file mode 100644 index 56208b5a8..000000000 --- a/extensions/vscode/server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# server - -These are the files that get copied over to `~/.continue/server` in order to create the Python environment and start the Continue server. diff --git a/extensions/vscode/server/requirements.txt b/extensions/vscode/server/requirements.txt deleted file mode 100644 index eb1f37388..000000000 --- a/extensions/vscode/server/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -./continuedev-0.1.2-py3-none-any.whl \ No newline at end of file diff --git a/extensions/vscode/server/run_continue_server.py b/extensions/vscode/server/run_continue_server.py deleted file mode 100644 index 089cc54dc..000000000 --- a/extensions/vscode/server/run_continue_server.py +++ /dev/null @@ -1,4 +0,0 @@ -from continuedev.server.main import run_server - -if __name__ == "__main__": - run_server() diff --git a/extensions/vscode/src/activation/inlineTips.ts b/extensions/vscode/src/activation/inlineTips.ts index 016588a1e..4137a55d7 100644 --- a/extensions/vscode/src/activation/inlineTips.ts +++ b/extensions/vscode/src/activation/inlineTips.ts @@ -4,7 +4,7 @@ import { getMetaKeyLabel } from "../util/util"; const inlineTipDecoration = vscode.window.createTextEditorDecorationType({ after: { contentText: `${getMetaKeyLabel()} M to select code, ${getMetaKeyLabel()} ⇧ L to edit`, - color: "#d3d3d340", + color: "#c0c0c060", margin: "0 0 0 6em", }, }); diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index b0dab2424..bdc235cd3 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -519,9 +519,16 @@ export function getSidebarContent( } } } catch (e) { - vscode.window.showErrorMessage( - `Error handling message from Continue side panel: ${e}` - ); + vscode.window + .showErrorMessage( + `Error handling message from Continue side panel: ${e}`, + "Show Logs" + ) + .then((selection) => { + if (selection === "Show Logs") { + vscode.commands.executeCommand("workbench.action.toggleDevTools"); + } + }); respond({ done: true }); } }); diff --git a/extensions/vscode/src/history.ts b/extensions/vscode/src/history.ts index d1126db01..87ed290d9 100644 --- a/extensions/vscode/src/history.ts +++ b/extensions/vscode/src/history.ts @@ -76,7 +76,18 @@ class HistoryManager { const sessionsListFilePath = getSessionsListPath(); try { const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8"); - const sessionsList: SessionInfo[] = JSON.parse(rawSessionsList); + + let sessionsList: SessionInfo[]; + try { + sessionsList = JSON.parse(rawSessionsList); + } catch (e) { + if (rawSessionsList.trim() === "") { + fs.writeFileSync(sessionsListFilePath, JSON.stringify([])); + sessionsList = []; + } else { + throw e; + } + } let found = false; for (const sessionInfo of sessionsList) { diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index edf828df1..933948e6a 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -58,6 +58,9 @@ class VsCodeIde implements IDE { const configPath = getConfigJsonPath(); let contents = fs.readFileSync(configPath, "utf8"); let config = JSON.parse(contents) as SerializedContinueConfig; + if (config.allowAnonymousTelemetry === undefined) { + config.allowAnonymousTelemetry = true; + } config.allowAnonymousTelemetry = config.allowAnonymousTelemetry && vscode.workspace.getConfiguration("continue").get("telemetryEnabled"); diff --git a/extensions/vscode/src/loadConfig.ts b/extensions/vscode/src/loadConfig.ts index e49e53312..8b34d0eb7 100644 --- a/extensions/vscode/src/loadConfig.ts +++ b/extensions/vscode/src/loadConfig.ts @@ -23,6 +23,8 @@ class VsCodeConfigHandler { export const configHandler = new VsCodeConfigHandler(); +const TIMEOUT = 7200; // 7200 seconds = 2 hours + export async function llmFromTitle(title?: string): Promise { let config = await configHandler.loadConfig(new VsCodeIde()); @@ -46,41 +48,44 @@ export async function llmFromTitle(title?: string): Promise { } } - if (llm.requestOptions) { - // Since we know this is happening in Node.js, we can add requestOptions through a custom agent - const ca = [...tls.rootCertificates]; - const customCerts = - typeof llm.requestOptions?.caBundlePath === "string" - ? [llm.requestOptions?.caBundlePath] - : llm.requestOptions?.caBundlePath; - if (customCerts) { - ca.push( - ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")) - ); + // Since we know this is happening in Node.js, we can add requestOptions through a custom agent + const ca = [...tls.rootCertificates]; + const customCerts = + typeof llm.requestOptions?.caBundlePath === "string" + ? [llm.requestOptions?.caBundlePath] + : llm.requestOptions?.caBundlePath; + if (customCerts) { + ca.push( + ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")) + ); + } + + let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms + + const agent = new Agent({ + connect: { + ca, + rejectUnauthorized: llm.requestOptions?.verifySsl, + timeout, + }, + bodyTimeout: timeout, + connectTimeout: timeout, + headersTimeout: timeout, + }); + + llm._fetch = (input, init) => { + const headers: { [key: string]: string } = + llm!.requestOptions?.headers || {}; + for (const [key, value] of Object.entries(init?.headers || {})) { + headers[key] = value as string; } - const agent = new Agent({ - connect: { - ca, - rejectUnauthorized: llm.requestOptions?.verifySsl, - timeout: llm.requestOptions?.timeout, - }, + return fetch(input, { + ...init, + dispatcher: agent, + headers, }); - - llm._fetch = (input, init) => { - const headers: { [key: string]: string } = - llm!.requestOptions?.headers || {}; - for (const [key, value] of Object.entries(init?.headers || {})) { - headers[key] = value as string; - } - - return fetch(input, { - ...init, - dispatcher: agent, - headers, - }); - }; - } + }; return llm; } diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 89d4573c6..cf85e8586 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -331,10 +331,10 @@ function TipTapEditor(props: TipTapEditorProps) { item, }, }) - .focus("end") .run(); - await new Promise((resolve) => setTimeout(resolve, 100)); - editor.commands.focus("end"); + setTimeout(() => { + editor.commands.focus("end"); + }, 100); } setIgnoreHighlightedCode(false); } diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index dd50691c1..4218782eb 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -83,7 +83,7 @@ function getFileItems( ): ComboBoxItem[] { let res: any[] = miniSearch.search(query.trim() === "" ? "/" : query, { prefix: true, - fuzzy: 1, + fuzzy: 5, }); if (res.length === 0) { res = firstResults; diff --git a/gui/src/hooks/CustomPostHogProvider.tsx b/gui/src/hooks/CustomPostHogProvider.tsx index 5ab383585..eaace76a3 100644 --- a/gui/src/hooks/CustomPostHogProvider.tsx +++ b/gui/src/hooks/CustomPostHogProvider.tsx @@ -6,7 +6,7 @@ import { RootStore } from "../redux/store"; const CustomPostHogProvider = ({ children }: PropsWithChildren) => { const allowAnonymousTelemetry = useSelector( - (store: RootStore) => store?.serverState?.config.allowAnonymousTelemetry + (store: RootStore) => store?.state?.config.allowAnonymousTelemetry ); const [client, setClient] = React.useState(undefined); @@ -21,8 +21,10 @@ const CustomPostHogProvider = ({ children }: PropsWithChildren) => { disable_session_recording: true, }); posthog.identify((window as any).vscMachineId); + posthog.opt_in_capturing(); setClient(client); } else { + posthog.opt_out_capturing(); setClient(undefined); } }, [allowAnonymousTelemetry]); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 120468b1c..7ba2f21b3 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -16,6 +16,9 @@ function truncateText(text: string, maxLength: number) { function useHistory(dispatch: Dispatch) { const state = useSelector((state: RootStore) => state.state); const defaultModel = useSelector(defaultModelSelector); + const disableSessionTitles = useSelector( + (store: RootStore) => store.state.config.disableSessionTitles + ); async function getHistory(): Promise { return await ideRequest("history", {}); @@ -28,21 +31,25 @@ function useHistory(dispatch: Dispatch) { dispatch(newSession()); await new Promise((resolve) => setTimeout(resolve, 10)); - const { content: title } = await defaultModel.chat( - [ - ...stateCopy.history.map((item) => item.message), - { - role: "user", - content: - "Give a maximum 40 character title to describe this conversation so far. The title should help me recall the conversation if I look for it later. DO NOT PUT QUOTES AROUND THE TITLE", - }, - ], - { maxTokens: 20 } - ); + let title = truncateText(stateCopy.history[0].message.content, 50); + if (!disableSessionTitles) { + let { content } = await defaultModel.chat( + [ + ...stateCopy.history.map((item) => item.message), + { + role: "user", + content: + "Give a maximum 40 character title to describe this conversation so far. The title should help me recall the conversation if I look for it later. DO NOT PUT QUOTES AROUND THE TITLE", + }, + ], + { maxTokens: 20 } + ); + title = content; + } const sessionInfo: PersistedSessionInfo = { history: stateCopy.history, - title: title || truncateText(stateCopy.history[0].message.content, 50), + title: title, sessionId: stateCopy.sessionId, workspaceDirectory: (window as any).workspacePaths?.[0] || "", }; diff --git a/gui/src/util/modelData.ts b/gui/src/util/modelData.ts index 219a5e303..7ceab9632 100644 --- a/gui/src/util/modelData.ts +++ b/gui/src/util/modelData.ts @@ -712,8 +712,7 @@ After it's up and running, you can start using Continue.`, provider: "google-palm", description: "Try out the Google PaLM API, which is currently in public preview, using an API key from Google Makersuite. Includes the Gemini Pro model", - longDescription: `To get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below. -> Note: Google's PaLM language models do not support streaming, so the response will appear all at once after a few seconds.`, + longDescription: `To get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below.`, icon: "google-palm.png", tags: [ModelProviderTag["Requires API Key"]], collectInputFor: [