♻️ more refactoring for .json

This commit is contained in:
Nate Sesti 2023-11-13 23:24:17 -08:00
parent 2acf5c2a3f
commit 31a4e5cb35
25 changed files with 974 additions and 1180 deletions

View file

@ -1,406 +0,0 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type ContinueConfig = ContinueConfig1;
export type Name = string;
export type Hide = boolean;
export type Description = string;
export type ClassName = string;
export type SystemMessage = string;
export type Role = "assistant" | "user" | "system" | "function";
export type Content = string;
export type Name1 = string;
export type Summary = string;
export type Name2 = string;
export type Arguments = string;
export type ChatContext = ChatMessage[];
export type ManageOwnChatContext = boolean;
/**
* Steps that will be automatically run at the beginning of a new session
*/
export type StepsOnStartup = Step[];
/**
* Steps that are not allowed to be run, and will be skipped if attempted
*/
export type DisallowedSteps = string[];
/**
* 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.
*/
export type AllowAnonymousTelemetry = boolean;
/**
* Configuration for the models used by Continue. Read more about how to configure models in the documentation.
*/
export type Models = Models1;
/**
* A title that will identify this model in the model selection dropdown
*/
export type Title = string;
/**
* The unique ID of the user.
*/
export type UniqueId = string;
/**
* The name of the model to be used (e.g. gpt-4, codellama)
*/
export type Model = string;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage1 = string;
/**
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* Tokens that will stop the completion.
*/
export type StopTokens = string[];
/**
* The temperature of the completion.
*/
export type Temperature = number;
/**
* The top_p of the completion.
*/
export type TopP = number;
/**
* The top_k of the completion.
*/
export type TopK = number;
/**
* The presence penalty Aof the completion.
*/
export type PresencePenalty = number;
/**
* The frequency penalty of the completion.
*/
export type FrequencyPenalty = number;
/**
* Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.
*/
export type Timeout = number;
/**
* Whether to verify SSL certificates for requests.
*/
export type VerifySsl = boolean;
/**
* Path to a custom CA bundle to use when making the HTTP request
*/
export type CaBundlePath = string;
/**
* Proxy URL to use when making the HTTP request
*/
export type Proxy = string;
/**
* The API key for the LLM provider.
*/
export type ApiKey = string;
export type Saved = LLM[];
export type Temperature1 = number;
export type SystemMessage2 = string;
/**
* The temperature parameter for sampling from the LLM. Higher temperatures will result in more random output, while lower temperatures will result in more predictable output. This value ranges from 0 to 1.
*/
export type Temperature2 = number;
export type Name3 = string;
export type Prompt = string;
export type Description1 = string;
/**
* An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.
*/
export type CustomCommands = CustomCommand[];
export type Name4 = string;
export type Description2 = string;
/**
* An array of slash commands that let you map custom Steps to a shortcut.
*/
export type SlashCommands = SlashCommand[];
/**
* The step that will be run when a traceback is detected (when you use the shortcut cmd+shift+R)
*/
export type OnTraceback = Step;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage3 = string;
/**
* A Policy object that can be used to override the default behavior of Continue, for example in order to build custom agents that take multiple steps at a time.
*/
export type PolicyOverride = Policy;
/**
* The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.
*/
export type Title1 = string;
/**
* The display title of the ContextProvider shown in the dropdown menu
*/
export type DisplayTitle = string;
/**
* A description of the ContextProvider displayed in the dropdown menu
*/
export type Description3 = string;
/**
* Indicates whether the ContextProvider is dynamic
*/
export type Dynamic = boolean;
/**
* Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.
*/
export type RequiresQuery = boolean;
export type Name5 = string;
export type Description4 = string;
export type ProviderTitle = string;
export type ItemId = string;
export type Content1 = string;
export type Editing = boolean;
export type Editable = boolean;
/**
* List of selected items in the ContextProvider
*/
export type SelectedItems = ContextItem[];
/**
* A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.
*/
export type ContextProviders = ContextProvider[];
/**
* An optional token to identify the user.
*/
export type UserToken = string;
/**
* The URL of the server where development data is sent. No data is sent unless a valid user token is provided.
*/
export type DataServerUrl = string;
/**
* If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.
*/
export type DisableSummaries = boolean;
/**
* If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.
*/
export type DisableIndexing = boolean;
/**
* Settings for the retrieval system. Read more about the retrieval system in the documentation.
*/
export type RetrievalSettings = RetrievalSettings1;
/**
* Number of results to initially retrieve from vector database
*/
export type NRetrieve = number;
/**
* Final number of results to use after re-ranking
*/
export type NFinal = number;
/**
* Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results
*/
export type UseReranking = boolean;
/**
* Number of results to group together when re-ranking. Each group will be processed in parallel.
*/
export type RerankGroupSize = number;
/**
* Files to ignore when indexing the codebase. You can use glob patterns, such as ** /*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.
*/
export type IgnoreFiles = string[];
/**
* OpenAI API key
*/
export type OpenaiApiKey = string;
/**
* OpenAI API base URL
*/
export type ApiBase = string;
/**
* OpenAI API type
*/
export type ApiType = string;
/**
* OpenAI API version
*/
export type ApiVersion = string;
/**
* OpenAI organization ID
*/
export type OrganizationId = string;
/**
* Continue can be deeply customized by editing the `ContinueConfig` object in `~/.continue/config.py` (`%userprofile%\.continue\config.py` for Windows) on your machine. This class is instantiated from the config file for every new session.
*/
export interface ContinueConfig1 {
steps_on_startup?: StepsOnStartup;
disallowed_steps?: DisallowedSteps;
allow_anonymous_telemetry?: AllowAnonymousTelemetry;
models?: Models;
temperature?: Temperature2;
custom_commands?: CustomCommands;
slash_commands?: SlashCommands;
on_traceback?: OnTraceback;
system_message?: SystemMessage3;
policy_override?: PolicyOverride;
context_providers?: ContextProviders;
user_token?: UserToken;
data_server_url?: DataServerUrl;
disable_summaries?: DisableSummaries;
disable_indexing?: DisableIndexing;
retrieval_settings?: RetrievalSettings;
[k: string]: unknown;
}
export interface Step {
name?: Name;
hide?: Hide;
description?: Description;
class_name?: ClassName;
system_message?: SystemMessage;
chat_context?: ChatContext;
manage_own_chat_context?: ManageOwnChatContext;
[k: string]: unknown;
}
export interface ChatMessage {
role: Role;
content?: Content;
name?: Name1;
summary: Summary;
function_call?: FunctionCall;
[k: string]: unknown;
}
export interface FunctionCall {
name: Name2;
arguments: Arguments;
[k: string]: unknown;
}
/**
* Main class that holds the current model configuration
*/
export interface Models1 {
default: LLM;
summarize?: LLM;
edit?: LLM;
chat?: LLM;
saved?: Saved;
temperature?: Temperature1;
system_message?: SystemMessage2;
[k: string]: unknown;
}
export interface LLM {
title?: Title;
unique_id?: UniqueId;
model: Model;
system_message?: SystemMessage1;
context_length?: ContextLength;
stop_tokens?: StopTokens;
temperature?: Temperature;
top_p?: TopP;
top_k?: TopK;
presence_penalty?: PresencePenalty;
frequency_penalty?: FrequencyPenalty;
timeout?: Timeout;
verify_ssl?: VerifySsl;
ca_bundle_path?: CaBundlePath;
proxy?: Proxy;
headers?: Headers;
prompt_templates?: PromptTemplates;
api_key?: ApiKey;
[k: string]: unknown;
}
/**
* Headers to use when making the HTTP request
*/
export interface Headers {
[k: string]: string;
}
/**
* A dictionary of prompt templates that can be used to customize the behavior of the LLM in certain situations. For example, set the "edit" key in order to change the prompt that is used for the /edit slash command. Each value in the dictionary is a string templated in mustache syntax, and filled in at runtime with the variables specific to the situation. See the documentation for more information.
*/
export interface PromptTemplates {
[k: string]: unknown;
}
export interface CustomCommand {
name: Name3;
prompt: Prompt;
description: Description1;
[k: string]: unknown;
}
export interface SlashCommand {
name: Name4;
description: Description2;
step: Step1;
params?: Params;
[k: string]: unknown;
}
export interface Step1 {
[k: string]: unknown;
}
export interface Params {
[k: string]: unknown;
}
/**
* A rule that determines which step to take next
*/
export interface Policy {
[k: string]: unknown;
}
/**
* The ContextProvider class is a plugin that lets you provide new information to the LLM by typing '@'.
* When you type '@', the context provider will be asked to populate a list of options.
* These options will be updated on each keystroke.
* When you hit enter on an option, the context provider will add that item to the autopilot's list of context (which is all stored in the ContextManager object).
*/
export interface ContextProvider {
title: Title1;
ide?: Ide;
display_title: DisplayTitle;
description: Description3;
dynamic: Dynamic;
requires_query?: RequiresQuery;
selected_items?: SelectedItems;
[k: string]: unknown;
}
export interface Ide {
[k: string]: unknown;
}
/**
* A ContextItem is a single item that is stored in the ContextManager.
*/
export interface ContextItem {
description: ContextItemDescription;
content: Content1;
editing?: Editing;
editable?: Editable;
[k: string]: unknown;
}
/**
* A ContextItemDescription is a description of a ContextItem that is displayed to the user when they type '@'.
*
* The id can be used to retrieve the ContextItem from the ContextManager.
*/
export interface ContextItemDescription {
name: Name5;
description: Description4;
id: ContextItemId;
[k: string]: unknown;
}
/**
* A ContextItemId is a unique identifier for a ContextItem.
*/
export interface ContextItemId {
provider_title: ProviderTitle;
item_id: ItemId;
[k: string]: unknown;
}
export interface RetrievalSettings1 {
n_retrieve?: NRetrieve;
n_final?: NFinal;
use_reranking?: UseReranking;
rerank_group_size?: RerankGroupSize;
ignore_files?: IgnoreFiles;
openai_api_key?: OpenaiApiKey;
api_base?: ApiBase;
api_type?: ApiType;
api_version?: ApiVersion;
organization_id?: OrganizationId;
[k: string]: unknown;
}

View file

@ -26,6 +26,10 @@ export type SystemMessage = string;
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* Tokens that will stop the completion.
*/
@ -77,6 +81,7 @@ export interface LLM1 {
model: Model;
system_message?: SystemMessage;
context_length?: ContextLength;
max_tokens?: MaxTokens;
stop_tokens?: StopTokens;
temperature?: Temperature;
top_p?: TopP;

View file

@ -26,6 +26,10 @@ export type SystemMessage = string;
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* Tokens that will stop the completion.
*/
@ -93,6 +97,7 @@ export interface LLM {
model: Model;
system_message?: SystemMessage;
context_length?: ContextLength;
max_tokens?: MaxTokens;
stop_tokens?: StopTokens;
temperature?: Temperature;
top_p?: TopP;

View file

@ -0,0 +1,323 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type SerializedContinueConfig = SerializedContinueConfig1;
export type Step =
| "AnswerQuestionChroma"
| "GenerateShellCommandStep"
| "EditHighlightedCodeStep"
| "ShareSessionStep"
| "CommentCodeStep"
| "ClearHistoryStep"
| "StackOverflowStep";
/**
* Steps that will be automatically run at the beginning of a new session
*/
export type StepsOnStartup = StepWithParams[];
/**
* Steps that are not allowed to be run, and will be skipped if attempted
*/
export type DisallowedSteps = string[];
/**
* 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.
*/
export type AllowAnonymousTelemetry = boolean;
/**
* The title you wish to give your model.
*/
export type Title = string;
/**
* The provider of the model. This is used to determine the type of model, and how to interact with it.
*/
export type Provider =
| "openai"
| "openai-free-trial"
| "openai-aiohttp"
| "anthropic"
| "together"
| "ollama"
| "huggingface-tgi"
| "huggingface-inference-api"
| "llama.cpp"
| "replicate"
| "text-gen-webui"
| "google-palm";
/**
* The name of the model. Used to autodetect prompt template.
*/
export type Model = string;
/**
* OpenAI, Anthropic, Together, or other API key
*/
export type ApiKey = string;
/**
* The base URL of the LLM API.
*/
export type ApiBase = string;
/**
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* The chat template used to format messages. This is auto-detected for most models, but can be overridden here.
*/
export type Template = "llama2" | "alpaca" | "zephyr" | "phind" | "anthropic" | "chatml";
/**
* Options for the completion endpoint. Read more about the completion options in the documentation.
*/
export type CompletionOptions = BaseCompletionOptions;
/**
* The temperature of the completion.
*/
export type Temperature = number;
/**
* The top_p of the completion.
*/
export type TopP = number;
/**
* The top_k of the completion.
*/
export type TopK = number;
/**
* The presence penalty Aof the completion.
*/
export type PresencePenalty = number;
/**
* The frequency penalty of the completion.
*/
export type FrequencyPenalty = number;
/**
* The stop tokens of the completion.
*/
export type Stop = string[];
/**
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* Options for the HTTP request to the LLM.
*/
export type RequestOptions = RequestOptions1;
/**
* Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.
*/
export type Timeout = number;
/**
* Whether to verify SSL certificates for requests.
*/
export type VerifySsl = boolean;
/**
* Path to a custom CA bundle to use when making the HTTP request
*/
export type CaBundlePath = string;
/**
* Proxy URL to use when making the HTTP request
*/
export type Proxy = string;
export type Models = ModelDescription[];
/**
* Roles for models. Each entry should be the title of a model in the models array.
*/
export type ModelRoles = ModelRoles1;
/**
* The default model. If other model roles are not set, they will fall back to default.
*/
export type Default = string;
/**
* The model to use for chat. If not set, will fall back to default.
*/
export type Chat = string;
/**
* The model to use for editing. If not set, will fall back to default.
*/
export type Edit = string;
/**
* The model to use for summarization. If not set, will fall back to default.
*/
export type Summarize = string;
/**
* Default options for completion. These will be overriden by any options set for a specific model.
*/
export type CompletionOptions1 = BaseCompletionOptions;
export type Name = string;
export type Description = string;
/**
* An array of slash commands that let you map custom Steps to a shortcut.
*/
export type SlashCommands = SlashCommand[];
export type Name1 = string;
export type Prompt = string;
export type Description1 = string;
/**
* An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.
*/
export type CustomCommands = CustomCommand[];
/**
* A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.
*/
export type ContextProviders = StepWithParams[];
/**
* An optional token to identify the user.
*/
export type UserToken = string;
/**
* The URL of the server where development data is sent. No data is sent unless a valid user token is provided.
*/
export type DataServerUrl = string;
/**
* If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.
*/
export type DisableSummaries = boolean;
/**
* If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.
*/
export type DisableIndexing = boolean;
/**
* Settings for the retrieval system. Read more about the retrieval system in the documentation.
*/
export type RetrievalSettings = RetrievalSettings1;
/**
* Number of results to initially retrieve from vector database
*/
export type NRetrieve = number;
/**
* Final number of results to use after re-ranking
*/
export type NFinal = number;
/**
* Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results
*/
export type UseReranking = boolean;
/**
* Number of results to group together when re-ranking. Each group will be processed in parallel.
*/
export type RerankGroupSize = number;
/**
* Files to ignore when indexing the codebase. You can use glob patterns, such as ** /*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.
*/
export type IgnoreFiles = string[];
/**
* OpenAI API key
*/
export type OpenaiApiKey = string;
/**
* OpenAI API base URL
*/
export type ApiBase1 = string;
/**
* OpenAI API type
*/
export type ApiType = string;
/**
* OpenAI API version
*/
export type ApiVersion = string;
/**
* OpenAI organization ID
*/
export type OrganizationId = string;
export interface SerializedContinueConfig1 {
steps_on_startup?: StepsOnStartup;
disallowed_steps?: DisallowedSteps;
allow_anonymous_telemetry?: AllowAnonymousTelemetry;
models?: Models;
model_roles?: ModelRoles;
completion_options?: CompletionOptions1;
slash_commands?: SlashCommands;
custom_commands?: CustomCommands;
context_providers?: ContextProviders;
user_token?: UserToken;
data_server_url?: DataServerUrl;
disable_summaries?: DisableSummaries;
disable_indexing?: DisableIndexing;
retrieval_settings?: RetrievalSettings;
[k: string]: unknown;
}
export interface StepWithParams {
step: Step;
params: Params;
[k: string]: unknown;
}
export interface Params {
[k: string]: unknown;
}
export interface ModelDescription {
title: Title;
provider: Provider;
model: Model;
api_key?: ApiKey;
api_base?: ApiBase;
context_length?: ContextLength;
template?: Template;
completion_options?: CompletionOptions;
request_options?: RequestOptions;
[k: string]: unknown;
}
export interface BaseCompletionOptions {
temperature?: Temperature;
top_p?: TopP;
top_k?: TopK;
presence_penalty?: PresencePenalty;
frequency_penalty?: FrequencyPenalty;
stop?: Stop;
max_tokens?: MaxTokens;
[k: string]: unknown;
}
export interface RequestOptions1 {
timeout?: Timeout;
verify_ssl?: VerifySsl;
ca_bundle_path?: CaBundlePath;
proxy?: Proxy;
headers?: Headers;
[k: string]: unknown;
}
/**
* Headers to use when making the HTTP request
*/
export interface Headers {
[k: string]: string;
}
export interface ModelRoles1 {
default: Default;
chat?: Chat;
edit?: Edit;
summarize?: Summarize;
[k: string]: unknown;
}
export interface SlashCommand {
name: Name;
description: Description;
step: Step1;
params?: Params1;
[k: string]: unknown;
}
export interface Step1 {
[k: string]: unknown;
}
export interface Params1 {
[k: string]: unknown;
}
export interface CustomCommand {
name: Name1;
prompt: Prompt;
description: Description1;
[k: string]: unknown;
}
export interface RetrievalSettings1 {
n_retrieve?: NRetrieve;
n_final?: NFinal;
use_reranking?: UseReranking;
rerank_group_size?: RerankGroupSize;
ignore_files?: IgnoreFiles;
openai_api_key?: OpenaiApiKey;
api_base?: ApiBase1;
api_type?: ApiType;
api_version?: ApiVersion;
organization_id?: OrganizationId;
[k: string]: unknown;
}

View file

@ -1091,16 +1091,6 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
{selectedContextItems.length} snippets selected
</div>
)}
{/* {selectedContextItems.length > 0 && (
<HeaderButtonWithText
onClick={() => {
client?.showContextVirtualFile(props.index);
}}
text="View Current Context"
>
<MagnifyingGlassIcon width="1.4em" height="1.4em" />
</HeaderButtonWithText>
)} */}
</div>
) : (
selectedContextItems.length > 0 && (

View file

@ -27,8 +27,6 @@ abstract class AbstractContinueGUIClientProtocol {
abstract toggleAddingHighlightedCode(): void;
abstract showContextVirtualFile(): void;
abstract selectContextItem(id: string, query: string): void;
abstract getContextItem(id: string, query: string): Promise<ContextItem>;

View file

@ -181,10 +181,6 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
this.messenger?.send("toggle_adding_highlighted_code", {});
}
showContextVirtualFile(index?: number): void {
this.messenger?.send("show_context_virtual_file", { index });
}
selectContextItem(id: string, query: string): void {
this.messenger?.send("select_context_item", { id, query });
}

View file

@ -1,406 +0,0 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type ContinueConfig = ContinueConfig1;
export type Name = string;
export type Hide = boolean;
export type Description = string;
export type ClassName = string;
export type SystemMessage = string;
export type Role = "assistant" | "user" | "system" | "function";
export type Content = string;
export type Name1 = string;
export type Summary = string;
export type Name2 = string;
export type Arguments = string;
export type ChatContext = ChatMessage[];
export type ManageOwnChatContext = boolean;
/**
* Steps that will be automatically run at the beginning of a new session
*/
export type StepsOnStartup = Step[];
/**
* Steps that are not allowed to be run, and will be skipped if attempted
*/
export type DisallowedSteps = string[];
/**
* 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.
*/
export type AllowAnonymousTelemetry = boolean;
/**
* Configuration for the models used by Continue. Read more about how to configure models in the documentation.
*/
export type Models = Models1;
/**
* A title that will identify this model in the model selection dropdown
*/
export type Title = string;
/**
* The unique ID of the user.
*/
export type UniqueId = string;
/**
* The name of the model to be used (e.g. gpt-4, codellama)
*/
export type Model = string;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage1 = string;
/**
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* Tokens that will stop the completion.
*/
export type StopTokens = string[];
/**
* The temperature of the completion.
*/
export type Temperature = number;
/**
* The top_p of the completion.
*/
export type TopP = number;
/**
* The top_k of the completion.
*/
export type TopK = number;
/**
* The presence penalty Aof the completion.
*/
export type PresencePenalty = number;
/**
* The frequency penalty of the completion.
*/
export type FrequencyPenalty = number;
/**
* Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.
*/
export type Timeout = number;
/**
* Whether to verify SSL certificates for requests.
*/
export type VerifySsl = boolean;
/**
* Path to a custom CA bundle to use when making the HTTP request
*/
export type CaBundlePath = string;
/**
* Proxy URL to use when making the HTTP request
*/
export type Proxy = string;
/**
* The API key for the LLM provider.
*/
export type ApiKey = string;
export type Saved = LLM[];
export type Temperature1 = number;
export type SystemMessage2 = string;
/**
* The temperature parameter for sampling from the LLM. Higher temperatures will result in more random output, while lower temperatures will result in more predictable output. This value ranges from 0 to 1.
*/
export type Temperature2 = number;
export type Name3 = string;
export type Prompt = string;
export type Description1 = string;
/**
* An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.
*/
export type CustomCommands = CustomCommand[];
export type Name4 = string;
export type Description2 = string;
/**
* An array of slash commands that let you map custom Steps to a shortcut.
*/
export type SlashCommands = SlashCommand[];
/**
* The step that will be run when a traceback is detected (when you use the shortcut cmd+shift+R)
*/
export type OnTraceback = Step;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage3 = string;
/**
* A Policy object that can be used to override the default behavior of Continue, for example in order to build custom agents that take multiple steps at a time.
*/
export type PolicyOverride = Policy;
/**
* The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.
*/
export type Title1 = string;
/**
* The display title of the ContextProvider shown in the dropdown menu
*/
export type DisplayTitle = string;
/**
* A description of the ContextProvider displayed in the dropdown menu
*/
export type Description3 = string;
/**
* Indicates whether the ContextProvider is dynamic
*/
export type Dynamic = boolean;
/**
* Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.
*/
export type RequiresQuery = boolean;
export type Name5 = string;
export type Description4 = string;
export type ProviderTitle = string;
export type ItemId = string;
export type Content1 = string;
export type Editing = boolean;
export type Editable = boolean;
/**
* List of selected items in the ContextProvider
*/
export type SelectedItems = ContextItem[];
/**
* A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.
*/
export type ContextProviders = ContextProvider[];
/**
* An optional token to identify the user.
*/
export type UserToken = string;
/**
* The URL of the server where development data is sent. No data is sent unless a valid user token is provided.
*/
export type DataServerUrl = string;
/**
* If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.
*/
export type DisableSummaries = boolean;
/**
* If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.
*/
export type DisableIndexing = boolean;
/**
* Settings for the retrieval system. Read more about the retrieval system in the documentation.
*/
export type RetrievalSettings = RetrievalSettings1;
/**
* Number of results to initially retrieve from vector database
*/
export type NRetrieve = number;
/**
* Final number of results to use after re-ranking
*/
export type NFinal = number;
/**
* Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results
*/
export type UseReranking = boolean;
/**
* Number of results to group together when re-ranking. Each group will be processed in parallel.
*/
export type RerankGroupSize = number;
/**
* Files to ignore when indexing the codebase. You can use glob patterns, such as ** /*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.
*/
export type IgnoreFiles = string[];
/**
* OpenAI API key
*/
export type OpenaiApiKey = string;
/**
* OpenAI API base URL
*/
export type ApiBase = string;
/**
* OpenAI API type
*/
export type ApiType = string;
/**
* OpenAI API version
*/
export type ApiVersion = string;
/**
* OpenAI organization ID
*/
export type OrganizationId = string;
/**
* Continue can be deeply customized by editing the `ContinueConfig` object in `~/.continue/config.py` (`%userprofile%\.continue\config.py` for Windows) on your machine. This class is instantiated from the config file for every new session.
*/
export interface ContinueConfig1 {
steps_on_startup?: StepsOnStartup;
disallowed_steps?: DisallowedSteps;
allow_anonymous_telemetry?: AllowAnonymousTelemetry;
models?: Models;
temperature?: Temperature2;
custom_commands?: CustomCommands;
slash_commands?: SlashCommands;
on_traceback?: OnTraceback;
system_message?: SystemMessage3;
policy_override?: PolicyOverride;
context_providers?: ContextProviders;
user_token?: UserToken;
data_server_url?: DataServerUrl;
disable_summaries?: DisableSummaries;
disable_indexing?: DisableIndexing;
retrieval_settings?: RetrievalSettings;
[k: string]: unknown;
}
export interface Step {
name?: Name;
hide?: Hide;
description?: Description;
class_name?: ClassName;
system_message?: SystemMessage;
chat_context?: ChatContext;
manage_own_chat_context?: ManageOwnChatContext;
[k: string]: unknown;
}
export interface ChatMessage {
role: Role;
content?: Content;
name?: Name1;
summary: Summary;
function_call?: FunctionCall;
[k: string]: unknown;
}
export interface FunctionCall {
name: Name2;
arguments: Arguments;
[k: string]: unknown;
}
/**
* Main class that holds the current model configuration
*/
export interface Models1 {
default: LLM;
summarize?: LLM;
edit?: LLM;
chat?: LLM;
saved?: Saved;
temperature?: Temperature1;
system_message?: SystemMessage2;
[k: string]: unknown;
}
export interface LLM {
title?: Title;
unique_id?: UniqueId;
model: Model;
system_message?: SystemMessage1;
context_length?: ContextLength;
stop_tokens?: StopTokens;
temperature?: Temperature;
top_p?: TopP;
top_k?: TopK;
presence_penalty?: PresencePenalty;
frequency_penalty?: FrequencyPenalty;
timeout?: Timeout;
verify_ssl?: VerifySsl;
ca_bundle_path?: CaBundlePath;
proxy?: Proxy;
headers?: Headers;
prompt_templates?: PromptTemplates;
api_key?: ApiKey;
[k: string]: unknown;
}
/**
* Headers to use when making the HTTP request
*/
export interface Headers {
[k: string]: string;
}
/**
* A dictionary of prompt templates that can be used to customize the behavior of the LLM in certain situations. For example, set the "edit" key in order to change the prompt that is used for the /edit slash command. Each value in the dictionary is a string templated in mustache syntax, and filled in at runtime with the variables specific to the situation. See the documentation for more information.
*/
export interface PromptTemplates {
[k: string]: unknown;
}
export interface CustomCommand {
name: Name3;
prompt: Prompt;
description: Description1;
[k: string]: unknown;
}
export interface SlashCommand {
name: Name4;
description: Description2;
step: Step1;
params?: Params;
[k: string]: unknown;
}
export interface Step1 {
[k: string]: unknown;
}
export interface Params {
[k: string]: unknown;
}
/**
* A rule that determines which step to take next
*/
export interface Policy {
[k: string]: unknown;
}
/**
* The ContextProvider class is a plugin that lets you provide new information to the LLM by typing '@'.
* When you type '@', the context provider will be asked to populate a list of options.
* These options will be updated on each keystroke.
* When you hit enter on an option, the context provider will add that item to the autopilot's list of context (which is all stored in the ContextManager object).
*/
export interface ContextProvider {
title: Title1;
ide?: Ide;
display_title: DisplayTitle;
description: Description3;
dynamic: Dynamic;
requires_query?: RequiresQuery;
selected_items?: SelectedItems;
[k: string]: unknown;
}
export interface Ide {
[k: string]: unknown;
}
/**
* A ContextItem is a single item that is stored in the ContextManager.
*/
export interface ContextItem {
description: ContextItemDescription;
content: Content1;
editing?: Editing;
editable?: Editable;
[k: string]: unknown;
}
/**
* A ContextItemDescription is a description of a ContextItem that is displayed to the user when they type '@'.
*
* The id can be used to retrieve the ContextItem from the ContextManager.
*/
export interface ContextItemDescription {
name: Name5;
description: Description4;
id: ContextItemId;
[k: string]: unknown;
}
/**
* A ContextItemId is a unique identifier for a ContextItem.
*/
export interface ContextItemId {
provider_title: ProviderTitle;
item_id: ItemId;
[k: string]: unknown;
}
export interface RetrievalSettings1 {
n_retrieve?: NRetrieve;
n_final?: NFinal;
use_reranking?: UseReranking;
rerank_group_size?: RerankGroupSize;
ignore_files?: IgnoreFiles;
openai_api_key?: OpenaiApiKey;
api_base?: ApiBase;
api_type?: ApiType;
api_version?: ApiVersion;
organization_id?: OrganizationId;
[k: string]: unknown;
}

View file

@ -26,6 +26,10 @@ export type SystemMessage = string;
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* Tokens that will stop the completion.
*/
@ -77,6 +81,7 @@ export interface LLM1 {
model: Model;
system_message?: SystemMessage;
context_length?: ContextLength;
max_tokens?: MaxTokens;
stop_tokens?: StopTokens;
temperature?: Temperature;
top_p?: TopP;

View file

@ -26,6 +26,10 @@ export type SystemMessage = string;
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* Tokens that will stop the completion.
*/
@ -93,6 +97,7 @@ export interface LLM {
model: Model;
system_message?: SystemMessage;
context_length?: ContextLength;
max_tokens?: MaxTokens;
stop_tokens?: StopTokens;
temperature?: Temperature;
top_p?: TopP;

View file

@ -0,0 +1,323 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export type SerializedContinueConfig = SerializedContinueConfig1;
export type Step =
| "AnswerQuestionChroma"
| "GenerateShellCommandStep"
| "EditHighlightedCodeStep"
| "ShareSessionStep"
| "CommentCodeStep"
| "ClearHistoryStep"
| "StackOverflowStep";
/**
* Steps that will be automatically run at the beginning of a new session
*/
export type StepsOnStartup = StepWithParams[];
/**
* Steps that are not allowed to be run, and will be skipped if attempted
*/
export type DisallowedSteps = string[];
/**
* 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.
*/
export type AllowAnonymousTelemetry = boolean;
/**
* The title you wish to give your model.
*/
export type Title = string;
/**
* The provider of the model. This is used to determine the type of model, and how to interact with it.
*/
export type Provider =
| "openai"
| "openai-free-trial"
| "openai-aiohttp"
| "anthropic"
| "together"
| "ollama"
| "huggingface-tgi"
| "huggingface-inference-api"
| "llama.cpp"
| "replicate"
| "text-gen-webui"
| "google-palm";
/**
* The name of the model. Used to autodetect prompt template.
*/
export type Model = string;
/**
* OpenAI, Anthropic, Together, or other API key
*/
export type ApiKey = string;
/**
* The base URL of the LLM API.
*/
export type ApiBase = string;
/**
* The maximum context length of the LLM in tokens, as counted by count_tokens.
*/
export type ContextLength = number;
/**
* The chat template used to format messages. This is auto-detected for most models, but can be overridden here.
*/
export type Template = "llama2" | "alpaca" | "zephyr" | "phind" | "anthropic" | "chatml";
/**
* Options for the completion endpoint. Read more about the completion options in the documentation.
*/
export type CompletionOptions = BaseCompletionOptions;
/**
* The temperature of the completion.
*/
export type Temperature = number;
/**
* The top_p of the completion.
*/
export type TopP = number;
/**
* The top_k of the completion.
*/
export type TopK = number;
/**
* The presence penalty Aof the completion.
*/
export type PresencePenalty = number;
/**
* The frequency penalty of the completion.
*/
export type FrequencyPenalty = number;
/**
* The stop tokens of the completion.
*/
export type Stop = string[];
/**
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* Options for the HTTP request to the LLM.
*/
export type RequestOptions = RequestOptions1;
/**
* Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.
*/
export type Timeout = number;
/**
* Whether to verify SSL certificates for requests.
*/
export type VerifySsl = boolean;
/**
* Path to a custom CA bundle to use when making the HTTP request
*/
export type CaBundlePath = string;
/**
* Proxy URL to use when making the HTTP request
*/
export type Proxy = string;
export type Models = ModelDescription[];
/**
* Roles for models. Each entry should be the title of a model in the models array.
*/
export type ModelRoles = ModelRoles1;
/**
* The default model. If other model roles are not set, they will fall back to default.
*/
export type Default = string;
/**
* The model to use for chat. If not set, will fall back to default.
*/
export type Chat = string;
/**
* The model to use for editing. If not set, will fall back to default.
*/
export type Edit = string;
/**
* The model to use for summarization. If not set, will fall back to default.
*/
export type Summarize = string;
/**
* Default options for completion. These will be overriden by any options set for a specific model.
*/
export type CompletionOptions1 = BaseCompletionOptions;
export type Name = string;
export type Description = string;
/**
* An array of slash commands that let you map custom Steps to a shortcut.
*/
export type SlashCommands = SlashCommand[];
export type Name1 = string;
export type Prompt = string;
export type Description1 = string;
/**
* An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.
*/
export type CustomCommands = CustomCommand[];
/**
* A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.
*/
export type ContextProviders = StepWithParams[];
/**
* An optional token to identify the user.
*/
export type UserToken = string;
/**
* The URL of the server where development data is sent. No data is sent unless a valid user token is provided.
*/
export type DataServerUrl = string;
/**
* If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.
*/
export type DisableSummaries = boolean;
/**
* If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.
*/
export type DisableIndexing = boolean;
/**
* Settings for the retrieval system. Read more about the retrieval system in the documentation.
*/
export type RetrievalSettings = RetrievalSettings1;
/**
* Number of results to initially retrieve from vector database
*/
export type NRetrieve = number;
/**
* Final number of results to use after re-ranking
*/
export type NFinal = number;
/**
* Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results
*/
export type UseReranking = boolean;
/**
* Number of results to group together when re-ranking. Each group will be processed in parallel.
*/
export type RerankGroupSize = number;
/**
* Files to ignore when indexing the codebase. You can use glob patterns, such as ** /*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.
*/
export type IgnoreFiles = string[];
/**
* OpenAI API key
*/
export type OpenaiApiKey = string;
/**
* OpenAI API base URL
*/
export type ApiBase1 = string;
/**
* OpenAI API type
*/
export type ApiType = string;
/**
* OpenAI API version
*/
export type ApiVersion = string;
/**
* OpenAI organization ID
*/
export type OrganizationId = string;
export interface SerializedContinueConfig1 {
steps_on_startup?: StepsOnStartup;
disallowed_steps?: DisallowedSteps;
allow_anonymous_telemetry?: AllowAnonymousTelemetry;
models?: Models;
model_roles?: ModelRoles;
completion_options?: CompletionOptions1;
slash_commands?: SlashCommands;
custom_commands?: CustomCommands;
context_providers?: ContextProviders;
user_token?: UserToken;
data_server_url?: DataServerUrl;
disable_summaries?: DisableSummaries;
disable_indexing?: DisableIndexing;
retrieval_settings?: RetrievalSettings;
[k: string]: unknown;
}
export interface StepWithParams {
step: Step;
params: Params;
[k: string]: unknown;
}
export interface Params {
[k: string]: unknown;
}
export interface ModelDescription {
title: Title;
provider: Provider;
model: Model;
api_key?: ApiKey;
api_base?: ApiBase;
context_length?: ContextLength;
template?: Template;
completion_options?: CompletionOptions;
request_options?: RequestOptions;
[k: string]: unknown;
}
export interface BaseCompletionOptions {
temperature?: Temperature;
top_p?: TopP;
top_k?: TopK;
presence_penalty?: PresencePenalty;
frequency_penalty?: FrequencyPenalty;
stop?: Stop;
max_tokens?: MaxTokens;
[k: string]: unknown;
}
export interface RequestOptions1 {
timeout?: Timeout;
verify_ssl?: VerifySsl;
ca_bundle_path?: CaBundlePath;
proxy?: Proxy;
headers?: Headers;
[k: string]: unknown;
}
/**
* Headers to use when making the HTTP request
*/
export interface Headers {
[k: string]: string;
}
export interface ModelRoles1 {
default: Default;
chat?: Chat;
edit?: Edit;
summarize?: Summarize;
[k: string]: unknown;
}
export interface SlashCommand {
name: Name;
description: Description;
step: Step1;
params?: Params1;
[k: string]: unknown;
}
export interface Step1 {
[k: string]: unknown;
}
export interface Params1 {
[k: string]: unknown;
}
export interface CustomCommand {
name: Name1;
prompt: Prompt;
description: Description1;
[k: string]: unknown;
}
export interface RetrievalSettings1 {
n_retrieve?: NRetrieve;
n_final?: NFinal;
use_reranking?: UseReranking;
rerank_group_size?: RerankGroupSize;
ignore_files?: IgnoreFiles;
openai_api_key?: OpenaiApiKey;
api_base?: ApiBase1;
api_type?: ApiType;
api_version?: ApiVersion;
organization_id?: OrganizationId;
[k: string]: unknown;
}

View file

@ -1,7 +1,7 @@
import asyncio
from typing import Union
from .core.config.serialized_config import ContinueConfig
from .core.config.config import ContinueConfig
from .core.main import Step
# from .headless import start_headless_session

View file

@ -1,14 +1,9 @@
from typing import Dict, List, Optional, Type
from pydantic import BaseModel, Field, validator
from ...libs.llm.base import BaseCompletionOptions
from .serialized_config import (
CustomCommand,
RetrievalSettings,
SerializedContinueConfig,
SlashCommand,
)
from ...libs.llm.openai_free_trial import OpenAIFreeTrial
from ...libs.util.edit_config import (
create_bool_node,
create_obj_node,
@ -16,14 +11,17 @@ from ...libs.util.edit_config import (
edit_config_property,
)
from ...libs.util.paths import convertConfigImports, getConfigFilePath
from pydantic import BaseModel, Field, validator
from ...libs.llm.openai_free_trial import OpenAIFreeTrial
from ...libs.util.telemetry import posthog_logger
from ..context import ContextProvider
from ..main import ContextProviderDescription, Policy, SlashCommandDescription, Step
from ..models import Models
from ...libs.util.telemetry import posthog_logger
from .context import CONTEXT_PROVIDER_NAME_TO_CLASS
from .serialized_config import (
CustomCommand,
RetrievalSettings,
SerializedContinueConfig,
SlashCommand,
)
class ContinueConfig(BaseModel):
@ -32,30 +30,30 @@ class ContinueConfig(BaseModel):
"""
steps_on_startup: List[Step] = Field(
[],
default=[],
description="Steps that will be automatically run at the beginning of a new session",
)
disallowed_steps: Optional[List[str]] = Field(
[],
default=[],
description="Steps that are not allowed to be run, and will be skipped if attempted",
)
allow_anonymous_telemetry: Optional[bool] = Field(
True,
default=True,
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.",
)
models: Models = Field(
Models(
default=Models(
default=OpenAIFreeTrial(model="gpt-4"),
summarize=OpenAIFreeTrial(model="gpt-3.5-turbo"),
),
description="Configuration for the models used by Continue. Read more about how to configure models in the documentation.",
)
completion_options: BaseCompletionOptions = Field(
BaseCompletionOptions(),
default=BaseCompletionOptions(),
description="Options for the completion endpoint. Read more about the completion options in the documentation.",
)
custom_commands: Optional[List[CustomCommand]] = Field(
[
default=[
CustomCommand(
name="test",
description="This is an example custom command. Use /config to edit it and create more",
@ -65,38 +63,38 @@ class ContinueConfig(BaseModel):
description="An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
)
slash_commands: Optional[List[SlashCommand]] = Field(
[],
default=[],
description="An array of slash commands that let you map custom Steps to a shortcut.",
)
on_traceback: Optional[Step] = Field(
None,
default=None,
description="The step that will be run when a traceback is detected (when you use the shortcut cmd+shift+R)",
)
policy_override: Optional[Policy] = Field(
None,
default=None,
description="A Policy object that can be used to override the default behavior of Continue, for example in order to build custom agents that take multiple steps at a time.",
)
context_providers: List[ContextProvider] = Field(
[],
default=[],
description="A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
)
user_token: Optional[str] = Field(
None, description="An optional token to identify the user."
default=None, description="An optional token to identify the user."
)
data_server_url: Optional[str] = Field(
"https://us-west1-autodebug.cloudfunctions.net",
default="https://us-west1-autodebug.cloudfunctions.net",
description="The URL of the server where development data is sent. No data is sent unless a valid user token is provided.",
)
disable_summaries: Optional[bool] = Field(
False,
default=False,
description="If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.",
)
disable_indexing: Optional[bool] = Field(
False,
default=False,
description="If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.",
)
retrieval_settings: Optional[RetrievalSettings] = Field(
RetrievalSettings(),
default=RetrievalSettings(),
description="Settings for the retrieval system. Read more about the retrieval system in the documentation.",
)
@ -106,6 +104,10 @@ class ContinueConfig(BaseModel):
@staticmethod
def from_serialized_config(config: SerializedContinueConfig) -> "ContinueConfig":
context_providers = [
CONTEXT_PROVIDER_NAME_TO_CLASS[provider.name](**provider.params)
for provider in config.context_providers
]
return ContinueConfig(
disallowed_steps=config.disallowed_steps,
allow_anonymous_telemetry=config.allow_anonymous_telemetry,
@ -113,7 +115,7 @@ class ContinueConfig(BaseModel):
completion_options=config.completion_options,
custom_commands=config.custom_commands,
slash_commands=config.slash_commands,
context_providers=config.context_providers,
context_providers=context_providers,
user_token=config.user_token,
data_server_url=config.data_server_url,
disable_summaries=config.disable_summaries,

View file

@ -0,0 +1,17 @@
from ...plugins.context_providers.diff import DiffContextProvider
from ...plugins.context_providers.github import GitHubIssuesContextProvider
from ...plugins.context_providers.google import GoogleContextProvider
from ...plugins.context_providers.open_tabs import OpenTabsContextProvider
from ...plugins.context_providers.search import SearchContextProvider
from ...plugins.context_providers.terminal import TerminalContextProvider
from ...plugins.context_providers.url import URLContextProvider
CONTEXT_PROVIDER_NAME_TO_CLASS = {
"diff": DiffContextProvider,
"github": GitHubIssuesContextProvider,
"terminal": TerminalContextProvider,
"open": OpenTabsContextProvider,
"google": GoogleContextProvider,
"search": SearchContextProvider,
"url": URLContextProvider,
}

View file

@ -1,13 +1,15 @@
from typing import Any, Dict, List, Literal, Optional, Type
from .shared import ModelProvider, RequestOptions, StepName, TemplateType
from typing import Any, Dict, List, Optional, Type
from anthropic import RequestOptions
from pydantic import BaseModel, Field
from ...libs.llm.base import BaseCompletionOptions
from ...models.llm import BaseCompletionOptions
from ..main import SlashCommandDescription, Step
from .shared import ModelProvider, StepName, TemplateType
class StepWithParams(BaseModel):
step: StepName
name: StepName
params: Dict[str, Any]
@ -46,102 +48,105 @@ class CustomCommand(BaseModel):
class RetrievalSettings(BaseModel):
n_retrieve: Optional[int] = Field(
50, description="Number of results to initially retrieve from vector database"
default=50,
description="Number of results to initially retrieve from vector database",
)
n_final: Optional[int] = Field(
10, description="Final number of results to use after re-ranking"
default=10, description="Final number of results to use after re-ranking"
)
use_reranking: bool = Field(
True,
default=True,
description="Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results",
)
rerank_group_size: int = Field(
5,
default=5,
description="Number of results to group together when re-ranking. Each group will be processed in parallel.",
)
ignore_files: List[str] = Field(
[],
default=[],
description="Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.",
)
openai_api_key: Optional[str] = Field(None, description="OpenAI API key")
api_base: Optional[str] = Field(None, description="OpenAI API base URL")
api_type: Optional[str] = Field(None, description="OpenAI API type")
api_version: Optional[str] = Field(None, description="OpenAI API version")
organization_id: Optional[str] = Field(None, description="OpenAI organization ID")
openai_api_key: Optional[str] = Field(default=None, description="OpenAI API key")
api_base: Optional[str] = Field(default=None, description="OpenAI API base URL")
api_type: Optional[str] = Field(default=None, description="OpenAI API type")
api_version: Optional[str] = Field(default=None, description="OpenAI API version")
organization_id: Optional[str] = Field(
default=None, description="OpenAI organization ID"
)
class ModelDescription(BaseModel):
title: str = Field(
...,
default=...,
description="The title you wish to give your model.",
)
provider: ModelProvider = Field(
...,
default=...,
description="The provider of the model. This is used to determine the type of model, and how to interact with it.",
)
model: str = Field(
...,
default=...,
description="The name of the model. Used to autodetect prompt template.",
)
api_key: Optional[str] = Field(
None, description="OpenAI, Anthropic, Together, or other API key"
default=None, description="OpenAI, Anthropic, Together, or other API key"
)
api_base: Optional[str] = Field(None, description="The base URL of the LLM API.")
context_length: int = Field(
2048,
default=2048,
description="The maximum context length of the LLM in tokens, as counted by count_tokens.",
)
template: Optional[TemplateType] = Field(
None,
default=None,
description="The chat template used to format messages. This is auto-detected for most models, but can be overridden here.",
)
completion_options: BaseCompletionOptions = Field(
BaseCompletionOptions(),
default=BaseCompletionOptions(),
description="Options for the completion endpoint. Read more about the completion options in the documentation.",
)
system_message: Optional[str] = Field(
None,
default=None,
description="A system message that will always be followed by the LLM",
)
request_options: RequestOptions = Field(
RequestOptions(),
default=RequestOptions(),
description="Options for the HTTP request to the LLM.",
)
class ModelRoles(BaseModel):
default: str = Field(
...,
default=...,
description="The default model. If other model roles are not set, they will fall back to default.",
)
chat: Optional[str] = Field(
None,
default=None,
description="The model to use for chat. If not set, will fall back to default.",
)
edit: Optional[str] = Field(
None,
default=None,
description="The model to use for editing. If not set, will fall back to default.",
)
summarize: Optional[str] = Field(
None,
default=None,
description="The model to use for summarization. If not set, will fall back to default.",
)
class SerializedContinueConfig(BaseModel):
disallowed_steps: Optional[List[str]] = Field(
[],
default=[],
description="Steps that are not allowed to be run, and will be skipped if attempted",
)
allow_anonymous_telemetry: Optional[bool] = Field(
True,
default=True,
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.",
)
models: List[ModelDescription] = Field(
[
default=[
{
"title": "GPT-4 (trial)",
"provider": "openai-free-trial",
@ -151,19 +156,19 @@ class SerializedContinueConfig(BaseModel):
]
)
model_roles: ModelRoles = Field(
ModelRoles(default="GPT-4 (trial)"),
default=ModelRoles(default="GPT-4 (trial)"),
description="Roles for models. Each entry should be the title of a model in the models array.",
)
completion_options: BaseCompletionOptions = Field(
BaseCompletionOptions(),
default=BaseCompletionOptions(),
description="Default options for completion. These will be overriden by any options set for a specific model.",
)
slash_commands: Optional[List[SlashCommand]] = Field(
[],
default=[],
description="An array of slash commands that let you map custom Steps to a shortcut.",
)
custom_commands: Optional[List[CustomCommand]] = Field(
[
default=[
CustomCommand(
name="test",
description="This is an example custom command. Use /config to edit it and create more",
@ -173,25 +178,25 @@ class SerializedContinueConfig(BaseModel):
description="An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
)
context_providers: List[StepWithParams] = Field(
[],
default=[],
description="A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
)
user_token: Optional[str] = Field(
None, description="An optional token to identify the user."
default=None, description="An optional token to identify the user."
)
data_server_url: Optional[str] = Field(
"https://us-west1-autodebug.cloudfunctions.net",
default="https://us-west1-autodebug.cloudfunctions.net",
description="The URL of the server where development data is sent. No data is sent unless a valid user token is provided.",
)
disable_summaries: Optional[bool] = Field(
False,
default=False,
description="If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.",
)
disable_indexing: Optional[bool] = Field(
False,
default=False,
description="If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.",
)
retrieval_settings: Optional[RetrievalSettings] = Field(
RetrievalSettings(),
default=RetrievalSettings(),
description="Settings for the retrieval system. Read more about the retrieval system in the documentation.",
)

View file

@ -1,21 +1,18 @@
from typing import Dict, Literal, Optional
from pydantic import BaseModel, Field
from typing import Any, Dict, Literal, Optional
from ...libs.llm.prompts.chat import (
llama2_template_messages,
template_alpaca_messages,
phind_template_messages,
zephyr_template_messages,
chatml_template_messages,
anthropic_template_messages,
chatml_template_messages,
llama2_template_messages,
phind_template_messages,
template_alpaca_messages,
zephyr_template_messages,
)
from ...libs.llm.prompts.edit import (
codellama_edit_prompt,
alpaca_edit_prompt,
codellama_edit_prompt,
simplest_edit_prompt,
) # TODO: Prompts for the rest of the template types
)
StepName = Literal[
"AnswerQuestionChroma",
@ -54,15 +51,17 @@ def autodetect_template_type(model: str) -> Optional[TemplateType]:
def autodetect_template_function(model: str):
template_type = autodetect_template_type(model)
return {
"llama2": llama2_template_messages,
"alpaca": template_alpaca_messages,
"phind": phind_template_messages,
"zephyr": zephyr_template_messages,
"anthropic": anthropic_template_messages,
"chatml": chatml_template_messages,
}[template_type]
if template_type := autodetect_template_type(model):
mapping: Dict[TemplateType, Any] = {
"llama2": llama2_template_messages,
"alpaca": template_alpaca_messages,
"phind": phind_template_messages,
"zephyr": zephyr_template_messages,
"anthropic": anthropic_template_messages,
"chatml": chatml_template_messages,
}
return mapping[template_type]
return None
def autodetect_prompt_templates(model: str):
@ -113,25 +112,3 @@ MODEL_PROVIDER_TO_MODEL_CLASS = {
"text-gen-webui": "TextGenWebUI",
"google-palm": "GooglePaLMAPI",
}
class RequestOptions(BaseModel):
timeout: Optional[int] = Field(
300,
description="Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.",
)
verify_ssl: Optional[bool] = Field(
None, description="Whether to verify SSL certificates for requests."
)
ca_bundle_path: str = Field(
None,
description="Path to a custom CA bundle to use when making the HTTP request",
)
proxy: Optional[str] = Field(
None,
description="Proxy URL to use when making the HTTP request",
)
headers: Optional[Dict[str, str]] = Field(
None,
description="Headers to use when making the HTTP request",
)

View file

@ -3,25 +3,24 @@ import time
from abc import abstractmethod
from typing import Any, Awaitable, Callable, List, Optional
from ..libs.util.paths import migration
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from meilisearch_python_async import Client
from pydantic import BaseModel, Field
from ..libs.util.create_async_task import create_async_task
from ..libs.util.devdata import dev_data_logger
from ..libs.util.logging import logger
from ..libs.util.paths import migration
from ..libs.util.telemetry import posthog_logger
from ..server.global_config import global_config
from ..server.meilisearch_server import (
check_meilisearch_running,
get_meilisearch_url,
poll_meilisearch_running,
remove_meilisearch_disallowed_chars,
restart_meilisearch,
start_meilisearch,
remove_meilisearch_disallowed_chars,
)
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from .main import (
ChatMessage,
ContextItem,
@ -139,7 +138,7 @@ class ContextProvider(BaseModel):
summary=item.description.description,
)
async def get_item(self, id: ContextItemId, query: str) -> ContextItem:
async def get_item(self, id: ContextItemId, query: str) -> Optional[ContextItem]:
"""
Returns the ContextItem with the given id.
@ -463,13 +462,13 @@ class ContextManager:
"""
Opens a virtual file or otherwise previews the contents of the context provider in the IDE.
"""
id: ContextItemId = ContextItemId.from_string(id)
if id.provider_title not in self.provider_titles:
item_id: ContextItemId = ContextItemId.from_string(id)
if item_id.provider_title not in self.provider_titles:
raise ValueError(
f"Context provider with title {id.provider_title} not found"
f"Context provider with title {item_id.provider_title} not found"
)
await self.context_providers[id.provider_title].preview_contents(id)
await self.context_providers[item_id.provider_title].preview_contents(item_id)
"""

View file

@ -1,11 +1,15 @@
from typing import Callable, Dict, List, Optional
import uuid
from .config.serialized_config import ModelDescription, SerializedContinueConfig
from typing import Callable, Dict, List, Optional, Type, cast
from pydantic import BaseModel, validator
from ..core.config.shared import (
MODEL_PROVIDER_TO_MODEL_CLASS,
autodetect_prompt_templates,
autodetect_template_function,
)
from ..libs.llm.anthropic import AnthropicLLM
from ..libs.llm.base import LLM
from ..libs.llm.base import LLM, BaseCompletionOptions
from ..libs.llm.ggml import GGML
from ..libs.llm.google_palm_api import GooglePaLMAPI
from ..libs.llm.hf_inference_api import HuggingFaceInferenceAPI
@ -15,13 +19,9 @@ from ..libs.llm.ollama import Ollama
from ..libs.llm.openai import OpenAI
from ..libs.llm.openai_free_trial import OpenAIFreeTrial
from ..libs.llm.replicate import ReplicateLLM
from ..libs.llm.together import TogetherLLM
from ..libs.llm.text_gen_webui import TextGenWebUI
from ..core.config.shared import (
MODEL_PROVIDER_TO_MODEL_CLASS,
autodetect_prompt_templates,
autodetect_template_function,
)
from ..libs.llm.together import TogetherLLM
from .config.serialized_config import ModelDescription, SerializedContinueConfig
class ContinueSDK(BaseModel):
@ -35,7 +35,7 @@ ALL_MODEL_ROLES = [
"chat",
]
MODEL_CLASSES: Dict[str, LLM] = {
MODEL_CLASSES: Dict[str, Type[LLM]] = {
cls.__name__: cls
for cls in [
OpenAI,
@ -96,7 +96,7 @@ class Models(BaseModel):
@staticmethod
def from_serialized_config(config: SerializedContinueConfig) -> "Models":
def model_with_title(title: str, fallback: ModelDescription):
def model_with_title(title: Optional[str], fallback: ModelDescription):
return next(filter(lambda x: x.title == title, config.models), fallback)
default = model_with_title(config.model_roles.default, config.models[0])
@ -111,7 +111,7 @@ class Models(BaseModel):
model_class.system_message = model.system_message
return LLM(
api_key=model.api_key,
completion_options=completion_options,
completion_options=cast(BaseCompletionOptions, completion_options),
request_options=model.request_options,
system_message=model.system_message,
api_base=model.api_base, # TODO

View file

@ -1,4 +1,4 @@
from typing import Any, Callable, Coroutine
from typing import Any, Callable, Coroutine, Optional
from anthropic import AI_PROMPT, HUMAN_PROMPT, AsyncAnthropic
@ -25,21 +25,16 @@ class AnthropicLLM(LLM):
"""
api_key: str
api_key: Optional[str]
"Anthropic API key"
model: str = "claude-2"
_async_client: AsyncAnthropic = None
template_messages: Callable = anthropic_template_messages
class Config:
arbitrary_types_allowed = True
async def start(self, *args, **kwargs):
await super().start(*args, **kwargs)
self._async_client = AsyncAnthropic(api_key=self.api_key)
if self.model == "claude-2":
self.context_length = 100_000
@ -61,14 +56,16 @@ class AnthropicLLM(LLM):
args = self.collect_args(options)
prompt = f"{HUMAN_PROMPT} {prompt} {AI_PROMPT}"
async for chunk in await self._async_client.completions.create(
prompt=prompt, stream=True, **args
):
async for chunk in await AsyncAnthropic(
api_key=self.api_key
).completions.create(prompt=prompt, stream=True, **args):
yield chunk.completion
async def _complete(self, prompt: str, options) -> Coroutine[Any, Any, str]:
args = self.collect_args(options)
prompt = f"{HUMAN_PROMPT} {prompt} {AI_PROMPT}"
return (
await self._async_client.completions.create(prompt=prompt, **args)
await AsyncAnthropic(api_key=self.api_key).completions.create(
prompt=prompt, **args
)
).completion

View file

@ -1,128 +1,87 @@
import os
import ssl
from time import time
from typing import Any, Callable, Coroutine, Dict, Generator, List, Optional, Union
from typing import Any, AsyncGenerator, Callable, Coroutine, Dict, List, Optional, Union
import aiohttp
import certifi
from ...core.config.shared import RequestOptions
from ..util.templating import render_templated_string
from pydantic import Field, validator
from pydantic import Field
from ...core.main import ChatMessage
from ...models.llm import (
BaseCompletionOptions,
CompletionOptions,
RequestOptions,
)
from ...models.main import ContinueBaseModel
from ..util.count_tokens import (
DEFAULT_ARGS,
DEFAULT_MAX_TOKENS,
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
compile_chat_messages,
count_tokens,
format_chat_messages,
prune_raw_prompt_from_top,
)
from ..util.devdata import dev_data_logger
from ..util.telemetry import posthog_logger
from ..util.logging import logger
class BaseCompletionOptions(ContinueBaseModel):
@validator(
"*",
pre=True,
always=True,
)
def ignore_none_and_set_default(cls, value, field):
return value if value is not None else field.default
temperature: Optional[float] = Field(
None, description="The temperature of the completion."
)
top_p: Optional[float] = Field(None, description="The top_p of the completion.")
top_k: Optional[int] = Field(None, description="The top_k of the completion.")
presence_penalty: Optional[float] = Field(
None, description="The presence penalty Aof the completion."
)
frequency_penalty: Optional[float] = Field(
None, description="The frequency penalty of the completion."
)
stop: Optional[List[str]] = Field(
None, description="The stop tokens of the completion."
)
max_tokens: int = Field(
DEFAULT_MAX_TOKENS, description="The maximum number of tokens to generate."
)
class CompletionOptions(BaseCompletionOptions):
"""Options for the completion."""
@validator(
"*",
pre=True,
always=True,
)
def ignore_none_and_set_default(cls, value, field):
return value if value is not None else field.default
model: Optional[str] = Field(None, description="The model name")
functions: Optional[List[Any]] = Field(
None, description="The functions/tools to make available to the model."
)
class PromptTemplate(CompletionOptions):
prompt: str = Field(description="The prompt to be used for the completion.")
raw: bool = Field(False, description="Whether to use the raw prompt or not.")
from ..util.telemetry import posthog_logger
from ..util.templating import render_templated_string
class LLM(ContinueBaseModel):
title: Optional[str] = Field(
None,
default=None,
description="A title that will identify this model in the model selection dropdown",
)
unique_id: Optional[str] = Field(None, description="The unique ID of the user.")
unique_id: Optional[str] = Field(
default=None, description="The unique ID of the user."
)
model: str = Field(
..., description="The name of the model to be used (e.g. gpt-4, codellama)"
default=...,
description="The name of the model to be used (e.g. gpt-4, codellama)",
)
system_message: Optional[str] = Field(
None, description="A system message that will always be followed by the LLM"
default=None,
description="A system message that will always be followed by the LLM",
)
context_length: int = Field(
2048,
default=2048,
description="The maximum context length of the LLM in tokens, as counted by count_tokens.",
)
completion_options: BaseCompletionOptions = Field(
BaseCompletionOptions(),
default=BaseCompletionOptions(),
description="Options for the completion endpoint. Read more about the completion options in the documentation.",
)
request_options: RequestOptions = Field(
RequestOptions(),
default=RequestOptions(),
description="Options for the HTTP request to the LLM.",
)
prompt_templates: dict = Field(
{},
default={},
description='A dictionary of prompt templates that can be used to customize the behavior of the LLM in certain situations. For example, set the "edit" key in order to change the prompt that is used for the /edit slash command. Each value in the dictionary is a string templated in mustache syntax, and filled in at runtime with the variables specific to the situation. See the documentation for more information.',
)
template_messages: Optional[Callable[[List[Dict[str, str]]], str]] = Field(
None,
default=None,
description="A function that takes a list of messages and returns a prompt. This ensures that models like llama2, which are trained on specific chat formats, will always receive input in that format.",
)
write_log: Optional[Callable[[str], None]] = Field(
None,
write_log: Optional[Callable[[str], Coroutine]] = Field(
default=None,
description="A function that is called upon every prompt and completion, by default to log to the file which can be viewed by clicking on the magnifying glass.",
)
api_key: Optional[str] = Field(
None, description="The API key for the LLM provider."
default=None, description="The API key for the LLM provider."
)
api_base: Optional[str] = Field(
default=None, description="The base URL of the LLM API."
)
api_base: Optional[str] = Field(None, description="The base URL of the LLM API.")
class Config:
arbitrary_types_allowed = True
@ -264,13 +223,13 @@ Settings:
0,
{
"role": "system",
"content": render_templated_string(self.get_system_message()),
"content": render_templated_string(self.get_system_message() or ""),
},
)
return self.template_messages(msgs)
def log_tokens_generated(self, model: str, completion: int):
def log_tokens_generated(self, model: str, completion: str):
tokens = self.count_tokens(completion)
dev_data_logger.capture(
"tokens_generated",
@ -285,17 +244,17 @@ Settings:
self,
prompt: str,
raw: bool = False,
model: str = None,
temperature: float = None,
top_p: float = None,
top_k: int = None,
presence_penalty: float = None,
frequency_penalty: float = None,
model: Optional[str] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
presence_penalty: Optional[float] = None,
frequency_penalty: Optional[float] = None,
stop: Optional[List[str]] = None,
max_tokens: Optional[int] = None,
functions: Optional[List[Any]] = None,
log: bool = True,
) -> Generator[Union[Any, List, Dict], None, None]:
) -> AsyncGenerator[Union[Any, List, Dict], None]:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
@ -335,12 +294,12 @@ Settings:
self,
prompt: str,
raw: bool = False,
model: str = None,
temperature: float = None,
top_p: float = None,
top_k: int = None,
presence_penalty: float = None,
frequency_penalty: float = None,
model: Optional[str] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
presence_penalty: Optional[float] = None,
frequency_penalty: Optional[float] = None,
stop: Optional[List[str]] = None,
max_tokens: Optional[int] = None,
functions: Optional[List[Any]] = None,
@ -383,17 +342,17 @@ Settings:
async def stream_chat(
self,
messages: List[ChatMessage],
model: str = None,
temperature: float = None,
top_p: float = None,
top_k: int = None,
presence_penalty: float = None,
frequency_penalty: float = None,
model: Optional[str] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
presence_penalty: Optional[float] = None,
frequency_penalty: Optional[float] = None,
stop: Optional[List[str]] = None,
max_tokens: Optional[int] = None,
functions: Optional[List[Any]] = None,
log: bool = True,
) -> Generator[Union[Any, List, Dict], None, None]:
) -> AsyncGenerator[Union[Any, List, Dict], None]:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
@ -469,22 +428,21 @@ Settings:
def _stream_complete(
self, prompt, options: CompletionOptions
) -> Generator[str, None, None]:
) -> AsyncGenerator[str, None]:
"""Stream the completion through generator."""
raise NotImplementedError
async def _complete(
self, prompt: str, options: CompletionOptions
) -> Coroutine[Any, Any, str]:
async def _complete(self, prompt: str, options: CompletionOptions) -> str:
"""Return the completion of the text with the given temperature."""
completion = ""
async for chunk in self._stream_complete(prompt=prompt, options=options):
completion += chunk
return completion
async def _stream_chat(
self, messages: List[ChatMessage], options: CompletionOptions
) -> Generator[Union[Any, List, Dict], None, None]:
) -> AsyncGenerator[Dict[str, str], None]:
"""Stream the chat through generator."""
if self.template_messages is None:
raise NotImplementedError(

View file

@ -1,6 +1,6 @@
from textwrap import dedent
from ...llm.base import PromptTemplate
from ....models.llm import PromptTemplate
simplified_edit_prompt = dedent(
"""\

View file

@ -0,0 +1,4 @@
from typing import Any, Awaitable, Callable
AsyncFunc = Callable[..., Awaitable[Any]]

View file

@ -2,22 +2,23 @@ import os
from pydantic import schema_json_of
from ..core.config.config import ContinueConfig
from ..core.config.serialized_config import SerializedContinueConfig
from ..core.context import ContextItem, ContextItemId
from ..core.main import (
ContextProviderDescription,
ContinueError,
SessionInfo,
SessionState,
SessionUpdate,
ContinueError,
SlashCommandDescription,
ContextProviderDescription,
)
from ..core.models import Models
from ..libs.llm.base import LLM
from ..server.sessions import PersistedSessionInfo
from .filesystem import FileEdit, RangeInFile, RangeInFileWithContents
from .filesystem_edit import FileEditWithFullContents
from .main import Position, Range, Traceback, TracebackFrame
from ..server.sessions import PersistedSessionInfo
MODELS_TO_GENERATE = (
[Position, Range, Traceback, TracebackFrame]
@ -32,6 +33,7 @@ MODELS_TO_GENERATE = (
ContextProviderDescription,
]
+ [SerializedContinueConfig]
+ [ContinueConfig]
+ [ContextItem, ContextItemId]
+ [Models]
+ [LLM]

View file

@ -0,0 +1,87 @@
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, validator
from ..libs.util.count_tokens import DEFAULT_MAX_TOKENS
from .main import ContinueBaseModel
class RequestOptions(BaseModel):
timeout: Optional[int] = Field(
default=300,
description="Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.",
)
verify_ssl: Optional[bool] = Field(
default=None, description="Whether to verify SSL certificates for requests."
)
ca_bundle_path: str = Field(
default=None,
description="Path to a custom CA bundle to use when making the HTTP request",
)
proxy: Optional[str] = Field(
default=None,
description="Proxy URL to use when making the HTTP request",
)
headers: Optional[Dict[str, str]] = Field(
default=None,
description="Headers to use when making the HTTP request",
)
class BaseCompletionOptions(ContinueBaseModel):
@validator(
"*",
pre=True,
always=True,
)
def ignore_none_and_set_default(cls, value, field):
return value if value is not None else field.default
temperature: Optional[float] = Field(
default=None, description="The temperature of the completion."
)
top_p: Optional[float] = Field(
default=None, description="The top_p of the completion."
)
top_k: Optional[int] = Field(
default=None, description="The top_k of the completion."
)
presence_penalty: Optional[float] = Field(
default=None, description="The presence penalty Aof the completion."
)
frequency_penalty: Optional[float] = Field(
default=None, description="The frequency penalty of the completion."
)
stop: Optional[List[str]] = Field(
default=None, description="The stop tokens of the completion."
)
max_tokens: int = Field(
default=DEFAULT_MAX_TOKENS,
description="The maximum number of tokens to generate.",
)
class CompletionOptions(BaseCompletionOptions):
"""Options for the completion."""
@validator(
"*",
pre=True,
always=True,
)
def ignore_none_and_set_default(cls, value, field):
return value if value is not None else field.default
model: str = Field(default=None, description="The model name")
functions: Optional[List[Any]] = Field(
default=None, description="The functions/tools to make available to the model."
)
class PromptTemplate(CompletionOptions):
prompt: str = Field(
default=..., description="The prompt to be used for the completion."
)
raw: bool = Field(
default=False, description="Whether to use the raw prompt or not."
)

View file

@ -1,24 +1,20 @@
from typing import Any, Callable, Dict, List, Optional, TypeVar
from ...core.config.serialized_config import ContinueConfig
from ...core.autopilot import Autopilot
import socketio
import uuid
from typing import Any, Awaitable, Callable, Dict, List, Optional, TypeVar
import socketio
from pydantic import BaseModel
from ...models.websockets import WebsocketsMessage
from ...core.autopilot import Autopilot
from ...core.config.config import ContinueConfig
from ...core.main import ContextItem, SessionState, SessionUpdate, Step, StepDescription
from ...core.models import ALL_MODEL_ROLES, MODEL_CLASSES, MODEL_MODULE_NAMES
from ...core.steps import DisplayErrorStep
from ...libs.llm.prompts.chat import (
llama2_template_messages,
phind_template_messages,
sqlcoder_template_messages,
template_alpaca_messages,
phind_template_messages,
)
from ...libs.llm.prompts.edit import codellama_edit_prompt, alpaca_edit_prompt
from ...libs.util.create_async_task import create_async_task
from ...libs.llm.prompts.edit import alpaca_edit_prompt, codellama_edit_prompt
from ...libs.util.edit_config import (
add_config_import,
create_obj_node,
@ -26,9 +22,10 @@ from ...libs.util.edit_config import (
edit_config_property,
)
from ...libs.util.telemetry import posthog_logger
from ...libs.util.types import AsyncFunc
from ...models.websockets import WebsocketsMessage
from ..websockets_messenger import SocketIOMessenger
T = TypeVar("T", bound=BaseModel)
# You should probably abstract away the websocket stuff into a separate class
@ -39,9 +36,9 @@ class GUIProtocolServer:
messenger: SocketIOMessenger
get_autopilot: Callable[[SessionState], Autopilot]
get_context_item: Callable[[str, str], ContextItem]
get_context_item: Callable[[str, str], Awaitable[ContextItem]]
get_config: Callable[[], ContinueConfig]
reload_config: Callable[[], None]
reload_config: AsyncFunc
def __init__(
self,
@ -49,9 +46,9 @@ class GUIProtocolServer:
sio: socketio.AsyncServer,
sid: str,
get_autopilot: Callable[[SessionState], Autopilot],
get_context_item: Callable[[str, str], ContextItem],
get_context_item: Callable[[str, str], Awaitable[ContextItem]],
get_config: Callable[[], ContinueConfig],
reload_config: Callable[[], None],
reload_config: AsyncFunc,
):
self.window_id = window_id
self.messenger = SocketIOMessenger(sio, sid)
@ -60,10 +57,6 @@ class GUIProtocolServer:
self.get_config = get_config
self.reload_config = reload_config
def on_error(self, e: Exception):
# TODO
return self.session.autopilot.sdk.run_step(DisplayErrorStep.from_exception(e))
async def handle_json(self, msg: WebsocketsMessage):
data = msg.data
if msg.message_type == "run_from_state":
@ -79,10 +72,6 @@ class GUIProtocolServer:
elif msg.message_type == "get_config":
return self.get_config().dict()
elif msg.message_type == "show_context_virtual_file":
self.show_context_virtual_file(data.get("index", None))
elif msg.message_type == "load_session":
self.load_session(data.get("session_id", None))
elif msg.message_type == "set_system_message":
sys_message = data["system_message"]
ContinueConfig.set_system_message(sys_message)
@ -101,76 +90,9 @@ class GUIProtocolServer:
)
elif msg.message_type == "set_model_for_role_from_index":
await self.set_model_for_role_from_index(data["role"], data["index"])
elif msg.message_type == "save_context_group":
self.save_context_group(
data["title"], [ContextItem(**item) for item in data["context_items"]]
)
elif msg.message_type == "select_context_group":
self.select_context_group(data["id"])
elif msg.message_type == "delete_context_group":
self.delete_context_group(data["id"])
elif msg.message_type == "preview_context_item":
self.preview_context_item(data["id"])
elif msg.message_type == "delete_model_at_index":
await self.delete_model_at_index(data["index"])
def show_context_virtual_file(self, index: Optional[int] = None):
async def async_stuff():
if index is None:
context_items = (
await self.session.autopilot.context_manager.get_selected_items()
)
elif index < len(self.session.autopilot.sdk.history.timeline):
context_items = self.session.autopilot.sdk.history.timeline[
index
].context_used
ctx = "\n\n-----------------------------------\n\n".join(
["These are the context items that will be passed to the LLM"]
+ list(map(lambda x: x.content, context_items))
)
await self.session.autopilot.ide.showVirtualFile(
"Continue - Selected Context", ctx
)
create_async_task(
async_stuff(),
self.on_error,
)
def select_context_item(self, id: str, query: str):
"""Called when user selects an item from the dropdown"""
create_async_task(
self.session.autopilot.select_context_item(id, query), self.on_error
)
def select_context_item_at_index(self, id: str, query: str, index: int):
"""Called when user selects an item from the dropdown for prev UserInputStep"""
create_async_task(
self.session.autopilot.select_context_item_at_index(id, query, index),
self.on_error,
)
def preview_context_item(self, id: str):
"""Called when user clicks on an item from the dropdown"""
create_async_task(
self.session.autopilot.context_manager.preview_context_item(id),
self.on_error,
)
# def load_session(self, session_id: Optional[str] = None):
# async def load_and_tell_to_reconnect():
# new_session_id = await session_manager.load_session(
# self.session.session_id, session_id
# )
# await self._send_json(
# "reconnect_at_session", {"session_id": new_session_id}
# )
# create_async_task(load_and_tell_to_reconnect(), self.on_error)
# posthog_logger.capture_event("load_session", {"session_id": session_id})
async def set_model_for_role_from_index(self, role: str, index: int):
models = self.get_config().models
temp = models.default
@ -276,22 +198,6 @@ class GUIProtocolServer:
# TODO
pass
def save_context_group(self, title: str, context_items: List[ContextItem]):
create_async_task(
self.session.autopilot.save_context_group(title, context_items),
self.on_error,
)
def select_context_group(self, id: str):
create_async_task(
self.session.autopilot.select_context_group(id), self.on_error
)
def delete_context_group(self, id: str):
create_async_task(
self.session.autopilot.delete_context_group(id), self.on_error
)
# region: Send data to GUI
_running_autopilots: Dict[str, Autopilot] = {}
@ -303,7 +209,9 @@ class GUIProtocolServer:
"step run",
{
"step_name": step_to_log.name,
"params": step_to_log.params if step is None else step.dict(),
"params": step.dict()
if step is not None
else state.history[-1].params,
"context": list(
map(
lambda item: item.dict(),