Merge branch 'preview' into nate/litellm

This commit is contained in:
Nate Sesti 2023-11-29 19:00:20 -08:00
commit 7955bc130b
48 changed files with 647 additions and 854 deletions

View file

@ -81,6 +81,10 @@ VSCode is assumed for development as Continue is primarily a VSCode tool at the
2. Search for a method `sendHighlightedCode` and set a breakpoint in it, it is invoked on every selection change on the extension side
2. _In Host VSCode_: Select part of the `example.ts` file, your breakpoint should be hit. If you hit play at this point (or F5) you should see the original breakpoint hit again - congratulations, you debugged an end to end interaction from the extension to the server!
### Formatting
Continue uses the [Black Formatter](https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter) for Python and [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) for JavaScript/TypeScript. Please install these extensions in VSCode and enable "Format on Save" in your settings.
### Writing Steps
A Step can be used as a custom slash command, or called otherwise in a `Policy`. See the [steps README](./server/continuedev/plugins/steps/README.md) to learn how to write a Step.

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.7.11",
"version": "0.7.19",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.7.11",
"version": "0.7.19",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.7.11",
"version": "0.7.19",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -32,29 +32,46 @@ export type DisallowedSteps = string[];
*/
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
* The title you wish to give your model.
*/
export type Title = string;
/**
* The unique ID of the user.
* The provider of the model. This is used to determine the type of model, and how to interact with it.
*/
export type UniqueId = string;
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"
| "lmstudio";
/**
* The name of the model to be used (e.g. gpt-4, codellama)
* The name of the model. Used to autodetect prompt template.
*/
export type Model = string;
/**
* A system message that will always be followed by the LLM
* OpenAI, Anthropic, Together, or other API key
*/
export type SystemMessage1 = string;
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" | "deepseek";
/**
* Options for the completion endpoint. Read more about the completion options in the documentation.
*/
@ -87,6 +104,10 @@ export type Stop = string[];
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage1 = string;
/**
* Options for the HTTP request to the LLM.
*/
@ -107,21 +128,31 @@ export type CaBundlePath = string;
* Proxy URL to use when making the HTTP request
*/
export type Proxy = string;
export type Models = ModelDescription[];
/**
* The API key for the LLM provider.
* Roles for models. Each entry should be the title of a model in the models array.
*/
export type ApiKey = string;
export type ModelRoles = ModelRoles1;
/**
* The base URL of the LLM API.
* The default model. If other model roles are not set, they will fall back to default.
*/
export type ApiBase = string;
export type Saved = LLM[];
export type Temperature1 = number;
export type SystemMessage2 = string;
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;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage3 = string;
export type SystemMessage2 = string;
/**
* Options for the completion endpoint. Read more about the completion options in the documentation.
*/
@ -264,7 +295,8 @@ export interface ContinueConfig1 {
disallowed_steps?: DisallowedSteps;
allow_anonymous_telemetry?: AllowAnonymousTelemetry;
models?: Models;
system_message?: SystemMessage3;
model_roles?: ModelRoles;
system_message?: SystemMessage2;
completion_options?: CompletionOptions1;
custom_commands?: CustomCommands;
slash_commands?: SlashCommands;
@ -301,30 +333,17 @@ export interface FunctionCall {
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;
export interface ModelDescription {
title: Title;
provider: Provider;
model: Model;
system_message?: SystemMessage1;
context_length?: ContextLength;
completion_options?: CompletionOptions;
request_options?: RequestOptions;
prompt_templates?: PromptTemplates;
api_key?: ApiKey;
api_base?: ApiBase;
context_length?: ContextLength;
template?: Template;
completion_options?: CompletionOptions;
system_message?: SystemMessage1;
request_options?: RequestOptions;
[k: string]: unknown;
}
export interface BaseCompletionOptions {
@ -351,10 +370,11 @@ export interface RequestOptions1 {
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 {
export interface ModelRoles1 {
default: Default;
chat?: Chat;
edit?: Edit;
summarize?: Summarize;
[k: string]: unknown;
}
export interface CustomCommand {

View file

@ -95,9 +95,9 @@ export type SystemMessage1 = string;
*/
export interface Models1 {
default: LLM;
summarize?: LLM;
edit?: LLM;
chat?: LLM;
summarize: LLM;
edit: LLM;
chat: LLM;
saved?: Saved;
temperature?: Temperature1;
system_message?: SystemMessage1;

View file

@ -1,5 +1,6 @@
import * as vscode from "vscode";
import { machineIdSync } from "node-machine-id";
import * as path from "path";
export function translate(range: vscode.Range, lines: number): vscode.Range {
return new vscode.Range(
@ -74,6 +75,12 @@ export function openEditorAndRevealRange(
viewColumn?: vscode.ViewColumn
): Promise<vscode.TextEditor> {
return new Promise((resolve, _) => {
if (editorFilename.startsWith("~")) {
editorFilename = path.join(
process.env.HOME || process.env.USERPROFILE || "",
editorFilename.slice(1)
);
}
vscode.workspace.openTextDocument(editorFilename).then(async (doc) => {
try {
// An error is thrown mysteriously if you open two documents in parallel, hence this

View file

@ -221,8 +221,8 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
this.messenger?.send("add_model_for_role", { role, model });
}
setModelForRoleFromIndex(role: string, index: number): void {
this.messenger?.send("set_model_for_role_from_index", { role, index });
setModelForRoleFromTitle(role: string, title: string): void {
this.messenger?.send("set_model_for_role_from_title", { role, title });
}
saveContextGroup(title: string, contextItems: ContextItem[]): void {

View file

@ -71,6 +71,7 @@ import {
} from "../../redux/slices/sessionStateReducer";
import RingLoader from "../loaders/RingLoader";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
import { contextLengthSelector } from "../../redux/selectors/configSelectors";
const SEARCH_INDEX_NAME = "continue_context_items";
@ -372,7 +373,8 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
);
const selectedContextItems = useSelector((state: RootStore) => {
if (typeof props.index !== "undefined") {
return state.sessionState.contextItemsAtIndex[props.index] || [];
return (state.sessionState.history[props.index].params["context_items"] ||
[]) as ContextItem[];
} else {
return state.sessionState.context_items || [];
}
@ -802,10 +804,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
const [contextLengthFillPercentage, setContextLengthFillPercentage] =
useState<number>(0);
const contextLength = useSelector(
(store: RootStore) =>
store.serverState.config.models?.default?.context_length || 4096
);
const contextLength = useSelector(contextLengthSelector);
useEffect(() => {
let tokenEstimate = selectedContextItems.reduce((acc, item) => {

View file

@ -20,6 +20,7 @@ import { useNavigate } from "react-router-dom";
import { Listbox, Transition } from "@headlessui/react";
import ReactDOM from "react-dom";
import HeaderButtonWithText from "../HeaderButtonWithText";
import { defaultModelSelector } from "../../redux/selectors/configSelectors";
const GridDiv = styled.div`
display: grid;
@ -157,7 +158,7 @@ function ListBoxOption({ option, idx }: { option: Option; idx: number }) {
>
<div className="flex items-center justify-between gap-3 h-5 relative">
<span>{option.title}</span>
{idx > 0 && hovered && (
{hovered && (
<HeaderButtonWithText
text="Delete"
onClick={(e) => {
@ -195,51 +196,33 @@ interface Option {
function ModelSelect(props: {}) {
const client = useContext(GUIClientContext);
const defaultModel = useSelector(
(state: RootStore) => (state.serverState.config as any)?.models?.default
);
const savedModels = useSelector(
(state: RootStore) => (state.serverState.config as any)?.models?.saved
const defaultModel = useSelector(defaultModelSelector);
const allModels = useSelector(
(state: RootStore) => state.serverState.config.models
);
const navigate = useNavigate();
const DEFAULT_OPTION = {
value: JSON.stringify({
t: "default",
idx: -1,
}),
value: "GPT-4",
title: "GPT-4",
};
const [options, setOptions] = useState<Option[]>([DEFAULT_OPTION]);
useEffect(() => {
if (!defaultModel && !savedModels) {
if (!allModels) {
setOptions([DEFAULT_OPTION]);
return;
}
const newOptions: Option[] = [];
if (defaultModel) {
newOptions.push({
value: JSON.stringify({
t: "default",
idx: -1,
}),
title: modelSelectTitle(defaultModel),
});
}
savedModels?.forEach((model: any, idx: number) => {
newOptions.push({
value: JSON.stringify({
t: "saved",
idx,
}),
title: modelSelectTitle(model),
});
});
setOptions(newOptions);
}, [defaultModel, savedModels]);
setOptions(
allModels.map((model) => {
return {
value: model.title,
title: modelSelectTitle(model),
};
})
);
}, [allModels]);
const topDiv = document.getElementById("model-select-top-div");
@ -247,17 +230,12 @@ function ModelSelect(props: {}) {
<>
<GridDiv>
<StyledListbox
value={JSON.stringify({
t: "default",
idx: -1,
})}
value={"GPT-4"}
onChange={(val: string) => {
const value = JSON.parse(val);
if (value.t === "saved") {
client?.setModelForRoleFromIndex("*", value.idx);
}
if (val === defaultModel.title) return;
client?.setModelForRoleFromTitle("*", val);
}}
defaultValue={"0"}
defaultValue={"GPT-4"}
>
<div className="relative">
<StyledListboxButton>

View file

@ -49,6 +49,7 @@ import { useNavigate } from "react-router-dom";
import { setTakenActionTrue } from "../redux/slices/miscSlice";
import {
addContextItemAtIndex,
clearContextItems,
deleteAtIndex,
newSession,
setActive,
@ -305,7 +306,10 @@ function GUI(props: GUIProps) {
observations: [],
logs: [],
step_type: "UserInputStep",
params: { user_input: input },
params: {
user_input: input,
context_items: sessionState.context_items,
},
hide: false,
depth: 0,
},
@ -314,14 +318,6 @@ function GUI(props: GUIProps) {
history: newHistory,
context_items: sessionState.context_items,
};
for (let contextItem of sessionState.context_items) {
dispatch(
addContextItemAtIndex({
item: contextItem,
index: newHistory.length - 1,
})
);
}
client.runFromState(state);
newHistory.push({
name: "Generating Response...",
@ -335,6 +331,15 @@ function GUI(props: GUIProps) {
});
dispatch(setHistory(newHistory));
dispatch(setActive(true));
for (let contextItem of sessionState.context_items) {
dispatch(
addContextItemAtIndex({
item: contextItem,
index: newHistory.length - 1,
})
);
}
dispatch(clearContextItems());
// Increment localstorage counter for popup
const counter = localStorage.getItem("mainTextEntryCounter");
@ -742,7 +747,10 @@ function GUI(props: GUIProps) {
observations: [],
logs: [],
step_type: "UserInputStep",
params: { user_input: value },
params: {
user_input: value,
context_items: sessionState.context_items,
},
hide: false,
depth: 0,
},
@ -753,6 +761,7 @@ function GUI(props: GUIProps) {
history: newHistory,
context_items: sessionState.context_items,
};
dispatch(clearContextItems());
client.runFromState(state);
}

View file

@ -17,7 +17,8 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import Loader from "../components/loaders/Loader";
import InfoHover from "../components/InfoHover";
import { FormProvider, useForm } from "react-hook-form";
import { getFontSize } from "../util";
import { getFontSize, getPlatform } from "../util";
import { postToIde } from "../util/ide";
const Hr = styled.hr`
border: 0.5px solid ${lightGray};
@ -78,6 +79,19 @@ const Slider = styled.input.attrs({ type: "range" })`
border: none;
}
`;
const ConfigJsonButton = styled(Button)`
padding: 2px 4px;
margin-left: auto;
margin-right: 4px;
background-color: transparent;
color: white;
border: 1px solid ${lightGray};
&:hover {
background-color: ${lightGray};
}
`;
const ALL_MODEL_ROLES = ["default", "summarize", "edit", "chat"];
function Settings() {
@ -139,6 +153,18 @@ function Settings() {
className="inline-block ml-4 cursor-pointer"
/>
<h3 className="text-lg font-bold m-2 inline-block">Settings</h3>
<ConfigJsonButton
onClick={() => {
postToIde("showFile", {
filepath:
getPlatform() == "windows"
? "~\\.continue\\config.json"
: "~/.continue/config.json",
});
}}
>
Open config.json
</ConfigJsonButton>
</div>
<form onSubmit={formMethods.handleSubmit(onSubmit)}>
{config ? (

View file

@ -0,0 +1,18 @@
import { RootStore } from "../store";
export const contextLengthSelector = (state: RootStore) => {
return (
{
"gpt-4": 8096,
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-16k": 16384,
"gpt-4-32k": 32768,
"claude-2": 16384,
}[state.serverState.config.model_roles?.default] || 4096
);
};
export const defaultModelSelector = (state: RootStore) => {
const title = state.serverState.config.model_roles?.default;
return state.serverState.config.models.find((model) => model.title === title);
};

View file

@ -75,7 +75,6 @@ const TEST_CONTEXT_ITEMS: ContextItem[] = [
export interface SessionFullState {
history: StepDescription[];
contextItemsAtIndex: { [index: number]: ContextItem[] };
context_items: ContextItem[];
active: boolean;
title: string;
@ -89,7 +88,6 @@ export const sessionStateSlice = createSlice({
context_items: [],
active: false,
title: "New Session",
contextItemsAtIndex: {},
session_id: v4(),
},
reducers: {
@ -223,16 +221,22 @@ export const sessionStateSlice = createSlice({
state: SessionFullState,
{ payload }: { payload: { item: ContextItem; index: number } }
) => {
return {
...state,
contextItemsAtIndex: {
...state.contextItemsAtIndex,
[payload.index]: [
...(state.contextItemsAtIndex[payload.index] ?? []),
let history = [...state.history];
history[payload.index] = {
...history[payload.index],
params: {
...history[payload.index].params,
context_items: [
...((history[payload.index].params?.context_items as any) || []),
payload.item,
],
},
};
return {
...state,
history,
};
},
addHighlightedCode: (
state: SessionFullState,
@ -327,20 +331,32 @@ export const sessionStateSlice = createSlice({
} else {
return {
...state,
contextItemsAtIndex: {
...state.contextItemsAtIndex,
[payload.index]: (
state.contextItemsAtIndex[payload.index] ?? []
).filter(
(item) =>
!ids.includes(
`${item.description.id.provider_title}-${item.description.id.item_id}`
)
),
},
history: state.history.map((step, i) => {
if (i === payload.index) {
return {
...step,
params: {
...step.params,
context_items: (step.params?.context_items as any).filter(
(item: ContextItem) =>
!ids.includes(
`${item.description.id.provider_title}-${item.description.id.item_id}`
)
),
},
};
}
return step;
}),
};
}
},
clearContextItems: (state: SessionFullState) => {
return {
...state,
context_items: [],
};
},
setEditingAtIds: (
state: SessionFullState,
{
@ -362,17 +378,25 @@ export const sessionStateSlice = createSlice({
} else {
return {
...state,
contextItemsAtIndex: {
...state.contextItemsAtIndex,
[payload.index]: (
state.contextItemsAtIndex[payload.index] ?? []
).map((item) => {
history: state.history.map((step, i) => {
if (i === payload.index) {
return {
...item,
editing: ids.includes(item.description.id.item_id),
...step,
params: {
...step.params,
context_items: (step.params?.context_items as any).map(
(item: ContextItem) => {
return {
...item,
editing: ids.includes(item.description.id.item_id),
};
}
),
},
};
}),
},
}
return step;
}),
};
}
},
@ -391,5 +415,6 @@ export const {
deleteContextWithIds,
setTitle,
setEditingAtIds,
clearContextItems,
} = sessionStateSlice.actions;
export default sessionStateSlice.reducer;

View file

@ -32,29 +32,46 @@ export type DisallowedSteps = string[];
*/
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
* The title you wish to give your model.
*/
export type Title = string;
/**
* The unique ID of the user.
* The provider of the model. This is used to determine the type of model, and how to interact with it.
*/
export type UniqueId = string;
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"
| "lmstudio";
/**
* The name of the model to be used (e.g. gpt-4, codellama)
* The name of the model. Used to autodetect prompt template.
*/
export type Model = string;
/**
* A system message that will always be followed by the LLM
* OpenAI, Anthropic, Together, or other API key
*/
export type SystemMessage1 = string;
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" | "deepseek";
/**
* Options for the completion endpoint. Read more about the completion options in the documentation.
*/
@ -87,6 +104,10 @@ export type Stop = string[];
* The maximum number of tokens to generate.
*/
export type MaxTokens = number;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage1 = string;
/**
* Options for the HTTP request to the LLM.
*/
@ -107,21 +128,31 @@ export type CaBundlePath = string;
* Proxy URL to use when making the HTTP request
*/
export type Proxy = string;
export type Models = ModelDescription[];
/**
* The API key for the LLM provider.
* Roles for models. Each entry should be the title of a model in the models array.
*/
export type ApiKey = string;
export type ModelRoles = ModelRoles1;
/**
* The base URL of the LLM API.
* The default model. If other model roles are not set, they will fall back to default.
*/
export type ApiBase = string;
export type Saved = LLM[];
export type Temperature1 = number;
export type SystemMessage2 = string;
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;
/**
* A system message that will always be followed by the LLM
*/
export type SystemMessage3 = string;
export type SystemMessage2 = string;
/**
* Options for the completion endpoint. Read more about the completion options in the documentation.
*/
@ -264,7 +295,8 @@ export interface ContinueConfig1 {
disallowed_steps?: DisallowedSteps;
allow_anonymous_telemetry?: AllowAnonymousTelemetry;
models?: Models;
system_message?: SystemMessage3;
model_roles?: ModelRoles;
system_message?: SystemMessage2;
completion_options?: CompletionOptions1;
custom_commands?: CustomCommands;
slash_commands?: SlashCommands;
@ -301,30 +333,17 @@ export interface FunctionCall {
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;
export interface ModelDescription {
title: Title;
provider: Provider;
model: Model;
system_message?: SystemMessage1;
context_length?: ContextLength;
completion_options?: CompletionOptions;
request_options?: RequestOptions;
prompt_templates?: PromptTemplates;
api_key?: ApiKey;
api_base?: ApiBase;
context_length?: ContextLength;
template?: Template;
completion_options?: CompletionOptions;
system_message?: SystemMessage1;
request_options?: RequestOptions;
[k: string]: unknown;
}
export interface BaseCompletionOptions {
@ -351,10 +370,11 @@ export interface RequestOptions1 {
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 {
export interface ModelRoles1 {
default: Default;
chat?: Chat;
edit?: Edit;
summarize?: Summarize;
[k: string]: unknown;
}
export interface CustomCommand {

View file

@ -95,9 +95,9 @@ export type SystemMessage1 = string;
*/
export interface Models1 {
default: LLM;
summarize?: LLM;
edit?: LLM;
chat?: LLM;
summarize: LLM;
edit: LLM;
chat: LLM;
saved?: Saved;
temperature?: Temperature1;
system_message?: SystemMessage1;

View file

@ -177,28 +177,48 @@
}
}
},
"LLM": {
"title": "LLM",
"ModelDescription": {
"title": "ModelDescription",
"type": "object",
"properties": {
"title": {
"title": "Title",
"description": "A title that will identify this model in the model selection dropdown",
"description": "The title you wish to give your model.",
"type": "string"
},
"unique_id": {
"title": "Unique Id",
"description": "The unique ID of the user.",
"provider": {
"title": "Provider",
"description": "The provider of the model. This is used to determine the type of model, and how to interact with it.",
"enum": [
"openai",
"openai-free-trial",
"openai-aiohttp",
"anthropic",
"together",
"ollama",
"huggingface-tgi",
"huggingface-inference-api",
"llama.cpp",
"replicate",
"text-gen-webui",
"google-palm",
"lmstudio"
],
"type": "string"
},
"model": {
"title": "Model",
"description": "The name of the model to be used (e.g. gpt-4, codellama)",
"description": "The name of the model. Used to autodetect prompt template.",
"type": "string"
},
"system_message": {
"title": "System Message",
"description": "A system message that will always be followed by the LLM",
"api_key": {
"title": "Api Key",
"description": "OpenAI, Anthropic, Together, or other API key",
"type": "string"
},
"api_base": {
"title": "Api Base",
"description": "The base URL of the LLM API.",
"type": "string"
},
"context_length": {
@ -207,6 +227,20 @@
"default": 2048,
"type": "integer"
},
"template": {
"title": "Template",
"description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here.",
"enum": [
"llama2",
"alpaca",
"zephyr",
"phind",
"anthropic",
"chatml",
"deepseek"
],
"type": "string"
},
"completion_options": {
"title": "Completion Options",
"description": "Options for the completion endpoint. Read more about the completion options in the documentation.",
@ -225,6 +259,11 @@
}
]
},
"system_message": {
"title": "System Message",
"description": "A system message that will always be followed by the LLM",
"type": "string"
},
"request_options": {
"title": "Request Options",
"description": "Options for the HTTP request to the LLM.",
@ -240,59 +279,36 @@
"$ref": "#/definitions/RequestOptions"
}
]
},
"prompt_templates": {
"title": "Prompt Templates",
"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.",
"default": {},
"type": "object"
},
"api_key": {
"title": "Api Key",
"description": "The API key for the LLM provider.",
"type": "string"
},
"api_base": {
"title": "Api Base",
"description": "The base URL of the LLM API.",
"type": "string"
}
},
"required": [
"title",
"provider",
"model"
]
},
"Models": {
"title": "Models",
"description": "Main class that holds the current model configuration",
"ModelRoles": {
"title": "ModelRoles",
"type": "object",
"properties": {
"default": {
"$ref": "#/definitions/LLM"
},
"summarize": {
"$ref": "#/definitions/LLM"
},
"edit": {
"$ref": "#/definitions/LLM"
"title": "Default",
"description": "The default model. If other model roles are not set, they will fall back to default.",
"type": "string"
},
"chat": {
"$ref": "#/definitions/LLM"
"title": "Chat",
"description": "The model to use for chat. If not set, will fall back to default.",
"type": "string"
},
"saved": {
"title": "Saved",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/LLM"
}
"edit": {
"title": "Edit",
"description": "The model to use for editing. If not set, will fall back to default.",
"type": "string"
},
"temperature": {
"title": "Temperature",
"type": "number"
},
"system_message": {
"title": "System Message",
"summarize": {
"title": "Summarize",
"description": "The model to use for summarization. If not set, will fall back to default.",
"type": "string"
}
},
@ -591,231 +607,51 @@
},
"models": {
"title": "Models",
"description": "Configuration for the models used by Continue. Read more about how to configure models in the documentation.",
"default": [
{
"title": "GPT-4 (trial)",
"provider": "openai-free-trial",
"model": "gpt-4",
"api_key": "",
"api_base": null,
"context_length": 2048,
"template": null,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"system_message": null,
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
}
}
],
"type": "array",
"items": {
"$ref": "#/definitions/ModelDescription"
}
},
"model_roles": {
"title": "Model Roles",
"description": "Roles for models. Each entry should be the title of a model in the models array.",
"default": {
"default": {
"title": null,
"model": "gpt-4",
"system_message": null,
"context_length": 8192,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"llm": {
"title": null,
"model": "gpt-4",
"system_message": null,
"context_length": 2048,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"class_name": "ProxyServer"
},
"class_name": "OpenAIFreeTrial"
},
"summarize": {
"title": null,
"model": "gpt-3.5-turbo",
"system_message": null,
"context_length": 4096,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"llm": {
"title": null,
"model": "gpt-3.5-turbo",
"system_message": null,
"context_length": 2048,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"class_name": "ProxyServer"
},
"class_name": "OpenAIFreeTrial"
},
"edit": {
"title": null,
"model": "gpt-4",
"system_message": null,
"context_length": 8192,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"llm": {
"title": null,
"model": "gpt-4",
"system_message": null,
"context_length": 2048,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"class_name": "ProxyServer"
},
"class_name": "OpenAIFreeTrial"
},
"chat": {
"title": null,
"model": "gpt-4",
"system_message": null,
"context_length": 8192,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"llm": {
"title": null,
"model": "gpt-4",
"system_message": null,
"context_length": 2048,
"completion_options": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 1023
},
"request_options": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"prompt_templates": {},
"template_messages": null,
"api_key": null,
"api_base": null,
"class_name": "ProxyServer"
},
"class_name": "OpenAIFreeTrial"
},
"saved": [],
"temperature": null,
"system_message": null
"default": "GPT-4 (trial)",
"chat": null,
"edit": null,
"summarize": null
},
"allOf": [
{
"$ref": "#/definitions/Models"
"$ref": "#/definitions/ModelRoles"
}
]
},

View file

@ -202,7 +202,10 @@
}
},
"required": [
"default"
"default",
"summarize",
"edit",
"chat"
]
}
}

View file

@ -320,14 +320,14 @@ class Autopilot:
)
)
logger_id = self.config.models.add_logger(add_log)
logger_id = self.sdk.models.add_logger(add_log)
if step is not None:
await self.run_step(step)
while next_step := self.policy.next(self.sdk.config, self.session_state): # type: ignore (stub type)
await self.run_step(next_step)
self.config.models.remove_logger(logger_id)
self.sdk.models.remove_logger(logger_id)
async def get_session_title(self) -> str:
if self.sdk.config.disable_summaries:

View file

@ -8,14 +8,12 @@ from pydantic import BaseModel, Field, validator
from ..libs.constants.default_config import default_config_json
from ..libs.llm.base import LLM
from ..libs.llm.openai_free_trial import OpenAIFreeTrial
from ..libs.util.logging import logger
from ..libs.util.paths import getConfigFilePath, getGlobalFolderPath
from ..libs.util.telemetry import posthog_logger
from ..models.llm import BaseCompletionOptions, RequestOptions
from .config_utils.context import CONTEXT_PROVIDER_NAME_TO_CLASS, ContextProviderName
from .config_utils.shared import (
MODEL_CLASS_TO_MODEL_PROVIDER,
MODEL_PROVIDER_TO_MODEL_CLASS,
ModelProvider,
StepName,
@ -298,50 +296,6 @@ class SerializedContinueConfig(BaseModel):
if config.model_roles.summarize == title:
config.model_roles.summarize = None
def construct_models(self) -> Models:
def model_with_title(title: Optional[str], fallback: ModelDescription):
return next(filter(lambda x: x.title == title, self.models), fallback)
default = model_with_title(self.model_roles.default, self.models[0])
chat = model_with_title(self.model_roles.chat, default)
edit = model_with_title(self.model_roles.edit, default)
summarize = model_with_title(self.model_roles.summarize, default)
saved = [
model_with_title(model.title, default)
for model in self.models
if model.title
not in [default.title, chat.title, edit.title, summarize.title]
]
def create_llm(model: ModelDescription) -> LLM:
model_class = MODEL_CLASSES[MODEL_PROVIDER_TO_MODEL_CLASS[model.provider]]
completion_options = self.completion_options.dict(
exclude_none=True, exclude_defaults=True
)
completion_options.update(
model.completion_options.dict(exclude_none=True, exclude_defaults=True)
)
if "max_tokens" not in completion_options:
completion_options["max_tokens"] = min(2048, model.context_length // 2)
# Allow extra fields to be passed through
kwargs = {**model.dict(exclude_none=True)}
kwargs["completion_options"] = completion_options
kwargs["template_messages"] = autodetect_template_function(model.model)
kwargs["prompt_templates"] = autodetect_prompt_templates(model.model)
return model_class(**kwargs)
return Models(
default=create_llm(default),
chat=create_llm(chat),
edit=create_llm(edit),
summarize=create_llm(summarize),
saved=[create_llm(model) for model in saved],
)
class ContinueConfig(BaseModel):
"""
@ -360,12 +314,19 @@ class ContinueConfig(BaseModel):
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(
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.",
models: List[ModelDescription] = Field(
default=[
ModelDescription(
title="GPT-4 (trial)",
provider="openai-free-trial",
model="gpt-4",
api_key="",
)
]
)
model_roles: ModelRoles = Field(
default=ModelRoles(default="GPT-4 (trial)"),
description="Roles for models. Each entry should be the title of a model in the models array.",
)
system_message: Optional[str] = Field(
default=None,
@ -432,7 +393,8 @@ class ContinueConfig(BaseModel):
allow_anonymous_telemetry=config.allow_anonymous_telemetry
if config.allow_anonymous_telemetry is not None
else True,
models=config.construct_models(),
models=config.models,
model_roles=config.model_roles,
system_message=config.system_message,
completion_options=config.completion_options,
custom_commands=config.custom_commands,
@ -611,76 +573,6 @@ class ContinueConfig(BaseModel):
def to_serialized_continue_config(self) -> SerializedContinueConfig:
# For migration purposes
pre_models = self.models.saved + [
self.models.default,
self.models.chat,
self.models.edit,
self.models.summarize,
]
seen = set()
models: List[LLM] = []
for model in pre_models:
if model is None or (model.title, model.model) in seen:
# Remove duplicate models
continue # : )
seen.add((model.title, model.model))
models.append(model)
completion_options_keys = [
"temperature",
"top_p",
"top_k",
"max_tokens",
"presence_penalty",
"frequency_penalty",
]
request_options_keys = [
"timeout",
"verify_ssl",
"ca_bundle_path",
"proxy",
"headers",
]
for model in models:
for key in completion_options_keys:
if hasattr(model, key):
setattr(model.completion_options, key, getattr(model, key))
delattr(model, key)
for key in request_options_keys:
if hasattr(model, key):
setattr(model.request_options, key, getattr(model, key))
delattr(model, key)
for key in completion_options_keys:
if hasattr(self, key):
setattr(self.completion_options, key, getattr(self, key))
delattr(self, key)
BACKUP_TITLE = "LLM"
serialized_models = [
ModelDescription(
title=model.title or BACKUP_TITLE,
provider=MODEL_CLASS_TO_MODEL_PROVIDER[model.__class__.__name__],
api_base=model.api_base,
model=model.model,
completion_options=model.completion_options,
api_key=model.api_key,
context_length=model.context_length,
system_message=model.system_message,
)
for model in models
if model is not None
]
model_roles = ModelRoles(
default=self.models.default.title or BACKUP_TITLE,
chat=(self.models.chat or self.models.default).title,
edit=(self.models.edit or self.models.default).title,
summarize=(self.models.summarize or self.models.default).title,
)
slash_commands = []
for slash_command in self.slash_commands or []:
@ -691,8 +583,8 @@ class ContinueConfig(BaseModel):
return SerializedContinueConfig(
disallowed_steps=self.disallowed_steps,
allow_anonymous_telemetry=self.allow_anonymous_telemetry,
models=serialized_models,
model_roles=model_roles,
models=self.models,
model_roles=self.model_roles,
system_message=self.system_message,
completion_options=self.completion_options,
custom_commands=self.custom_commands,
@ -711,3 +603,48 @@ class ContinueConfig(BaseModel):
disable_indexing=self.disable_indexing,
retrieval_settings=self.retrieval_settings,
)
def create_llm(self, model: ModelDescription) -> LLM:
model_class = MODEL_CLASSES[MODEL_PROVIDER_TO_MODEL_CLASS[model.provider]]
completion_options = self.completion_options.dict(
exclude_none=True, exclude_defaults=True
)
completion_options.update(
model.completion_options.dict(exclude_none=True, exclude_defaults=True)
)
if "max_tokens" not in completion_options:
completion_options["max_tokens"] = min(2048, model.context_length // 2)
# Allow extra fields to be passed through
kwargs = {**model.dict(exclude_none=True)}
kwargs["completion_options"] = completion_options
kwargs["template_messages"] = autodetect_template_function(model.model)
kwargs["prompt_templates"] = autodetect_prompt_templates(model.model)
return model_class(**kwargs)
def construct_models(self) -> Models:
def model_with_title(title: Optional[str], fallback: ModelDescription):
return next(filter(lambda x: x.title == title, self.models), fallback)
default = model_with_title(self.model_roles.default, self.models[0])
chat = model_with_title(self.model_roles.chat, default)
edit = model_with_title(self.model_roles.edit, default)
summarize = model_with_title(self.model_roles.summarize, default)
saved = [
model_with_title(model.title, default)
for model in self.models
if model.title
not in [default.title, chat.title, edit.title, summarize.title]
]
models = Models(
default=self.create_llm(default),
chat=self.create_llm(chat),
edit=self.create_llm(edit),
summarize=self.create_llm(summarize),
saved=[self.create_llm(model) for model in saved],
)
return models

View file

@ -340,7 +340,7 @@ class Step(ContinueBaseModel):
return "Running step: " + self.name
def on_stop(self, sdk: ContinueSDK) -> Optional[StepGenerator]:
pass
return None
def dict(self, *args, **kwargs):
d = super().dict(*args, **kwargs)

View file

@ -70,9 +70,9 @@ class Models(BaseModel):
"""Main class that holds the current model configuration"""
default: LLM
summarize: LLM = Field(default=None)
edit: LLM = Field(default=None)
chat: LLM = Field(default=None)
summarize: LLM
edit: LLM
chat: LLM
saved: List[LLM] = []
@ -108,7 +108,7 @@ class Models(BaseModel):
for model in self.all_models:
model.set_main_config_params(system_msg, temperature)
async def start(
def start(
self,
unique_id: str,
system_message: Optional[str],
@ -117,11 +117,9 @@ class Models(BaseModel):
"""Start each of the LLMs, or fall back to default"""
for role in ALL_MODEL_ROLES:
model: LLM = getattr(self, role)
if model is None:
setattr(self, role, self.default)
else:
await model.start(unique_id)
model.write_log = self.write_log
model.start(unique_id)
model.write_log = self.write_log
self.set_main_config_params(system_message, temperature)

View file

@ -74,7 +74,12 @@ class ContinueSDK(AbstractContinueSDK):
self.ide = ide
self.gui = gui
self.config = config
self.models = config.models
self.models = config.construct_models()
self.models.start(
self.ide.window_info.unique_id,
self.config.system_message,
self.config.completion_options.temperature,
)
self.__autopilot = autopilot
@property
@ -215,27 +220,28 @@ class ContinueSDK(AbstractContinueSDK):
raise ContinueCustomException(message, title, with_step)
async def get_chat_context(self) -> List[ChatMessage]:
history_context = list(
map(
lambda step: ChatMessage(
role="user" if step.step_type == "UserInputStep" else "assistant",
msgs = []
for step in filter(lambda x: x.hide is False, self.history):
role = "assistant"
if step.step_type == "UserInputStep":
role = "user"
msgs.extend(
await self.__autopilot.context_manager.get_chat_messages(
[ContextItem(**itm) for itm in step.params["context_items"]]
)
)
msgs.append(
ChatMessage(
role=role,
name=step.step_type,
content=step.description or f"Ran function {step.name}",
summary=f"Called function {step.name}",
),
filter(lambda x: x.hide is False, self.history[:-1]),
)
)
)
context_messages: List[
ChatMessage
] = await self.__autopilot.context_manager.get_chat_messages(self.context_items)
# Insert at the end, but don't insert after latest user message or function call
for msg in context_messages:
history_context.insert(-1, msg)
return history_context
return msgs
async def get_context_item_chat_messages(
self, exclude: Optional[str] = None

View file

@ -3,7 +3,7 @@ import difflib
import subprocess
import time
from textwrap import dedent
from typing import Any, Dict, List, Optional, Union
from typing import Any, AsyncGenerator, Dict, List, Optional, Union
from pydantic import Field
@ -20,7 +20,15 @@ from ..libs.util.templating import render_prompt_template
from ..models.filesystem import FileSystem, RangeInFile, RangeInFileWithContents
from ..models.filesystem_edit import EditDiff, FileEditWithFullContents, FileSystemEdit
from .abstract_sdk import AbstractContinueSDK
from .main import ChatMessage, ContinueCustomException, SessionUpdate, SetStep, Step
from .main import (
ChatMessage,
ContextItem,
ContinueCustomException,
DeltaStep,
SessionUpdate,
SetStep,
Step,
)
from .observation import TextObservation, UserInputObservation
@ -373,7 +381,9 @@ Please output the code to be inserted at the cursor in order to fulfill the user
or "<code_to_edit>" in line
)
async def stream_rif(self, rif: RangeInFileWithContents, sdk: AbstractContinueSDK):
async def stream_rif(
self, rif: RangeInFileWithContents, sdk: AbstractContinueSDK
) -> AsyncGenerator[SetStep, None]:
await sdk.ide.saveFile(rif.filepath)
full_file_contents = await sdk.ide.readFile(rif.filepath)
@ -615,7 +625,7 @@ Please output the code to be inserted at the cursor in order to fulfill the user
params.update(template.dict(exclude={"prompt"})) # type: ignore
params.update(
{"max_tokens": min(max_tokens, model_to_use.context_length // 2)}
{"max_tokens": min(max_tokens, model_to_use.context_length // 2, 4096)}
)
generator = model_to_use.stream_complete(**params)
@ -643,6 +653,10 @@ Please output the code to be inserted at the cursor in order to fulfill the user
try:
last_task_time = time.time()
async for chunk in generator:
yield SetStep(
hide=False
) # Doing this so that there are breakpoints for cancellation
# Stop early if it is repeating the file_suffix or the step was deleted
if repeating_file_suffix:
break
@ -757,7 +771,8 @@ Please output the code to be inserted at the cursor in order to fulfill the user
for rif in rif_with_contents:
await sdk.ide.setSuggestionsLocked(rif.filepath, True)
await self.stream_rif(rif, sdk)
async for update in self.stream_rif(rif, sdk):
yield update
await sdk.ide.setSuggestionsLocked(rif.filepath, False)
changes = "\n".join(
@ -857,6 +872,7 @@ class ManualEditStep(ReversibleStep):
class UserInputStep(Step):
user_input: str
context_items: List[ContextItem] = []
name: str = "User Input"
hide: bool = False

View file

@ -25,9 +25,9 @@ async def get_headless_autopilot(
ide = LocalIdeProtocol(workspace_directory=directory)
context_manager = ContextManager()
# await context_manager.start(context_providers=context_providers, ide=ide)
await _config.models.start(
"HEADLESS", _config.system_message, _config.completion_options.temperature
)
# await _config.models.start(
# "HEADLESS", _config.system_message, _config.completion_options.temperature
# )
return Autopilot(
session_state=state or SessionState.from_empty(),

View file

@ -61,7 +61,10 @@ async def build_index(
chroma_task = asyncio.create_task(chroma_task())
meilisearch_task = asyncio.create_task(meilisearch_task())
async for chunk, progress in stream_chunk_directory(ide, MAX_CHUNK_SIZE):
ignore_files = settings.ignore_files if settings else []
async for chunk, progress in stream_chunk_directory(
ide, MAX_CHUNK_SIZE, ignore_files=ignore_files
):
if chunk is not None:
buffers[0].append(chunk)
buffers[1].append(chunk)

View file

@ -4,9 +4,8 @@ from typing import AsyncGenerator, Callable, List, Optional, Tuple
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from ...util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path
from .chunk import Chunk
from . import chunk_document
from .chunk import Chunk
FILE_IGNORE_PATTERNS = [
# File Names
@ -150,9 +149,11 @@ async def stream_file_contents(
async def stream_chunk_directory(
ide: AbstractIdeProtocolServer, max_chunk_size: int
ide: AbstractIdeProtocolServer, max_chunk_size: int, ignore_files: List[str] = []
) -> AsyncGenerator[Tuple[Optional[Chunk], float], None]:
async for file, contents, progress in stream_file_contents(ide):
async for file, contents, progress in stream_file_contents(
ide, ignore_files=ignore_files
):
if contents is None:
yield (None, progress)
continue

View file

@ -35,8 +35,8 @@ class AnthropicLLM(LLM):
class Config:
arbitrary_types_allowed = True
async def start(self, *args, **kwargs):
await super().start(*args, **kwargs)
def start(self, *args, **kwargs):
super().start(*args, **kwargs)
if self.model == "claude-2":
self.context_length = 100_000

View file

@ -112,7 +112,7 @@ class LLM(ContinueBaseModel):
original_dict["class_name"] = self.__class__.__name__
return original_dict
async def start(self, unique_id: Optional[str] = None):
def start(self, unique_id: Optional[str] = None):
"""Start the connection to the LLM."""
self.unique_id = unique_id

View file

@ -53,6 +53,14 @@ class GGML(LLM):
default=None, description="OpenAI engine. For use with Azure OpenAI Service."
)
chat_endpoint: str = Field(
default="chat/completions", description="The endpoint to call for chat completions"
)
completions_endpoint: str = Field(
default="completions", description="The endpoint to call for chat completions"
)
class Config:
arbitrary_types_allowed = True
@ -86,7 +94,7 @@ class GGML(LLM):
async with self.create_client_session() as client_session:
async with client_session.post(
self.get_full_server_url(endpoint="completions"),
self.get_full_server_url(endpoint=self.completions_endpoint),
json={
"prompt": prompt,
"stream": True,
@ -131,7 +139,7 @@ class GGML(LLM):
async def generator() -> AsyncGenerator[Any, None]:
async with self.create_client_session() as client_session:
async with client_session.post(
self.get_full_server_url(endpoint="chat/completions"),
self.get_full_server_url(endpoint=self.chat_endpoint),
json={
"messages": [msg.to_dict() for msg in messages],
"stream": True,
@ -196,7 +204,7 @@ class GGML(LLM):
async with self.create_client_session() as client_session:
async with client_session.post(
self.get_full_server_url(endpoint="completions"),
self.get_full_server_url(endpoint=self.completions_endpoint),
json={
"prompt": prompt,
**args,

View file

@ -1,6 +1,7 @@
import json
from typing import Any, Dict, Optional
import requests
from pydantic import Field, validator
from ...core.main import ContinueCustomException
@ -61,19 +62,16 @@ class Ollama(LLM):
"codeup-13b": "codeup:13b",
}.get(self.model, self.model)
async def start(self, *args, **kwargs):
await super().start(*args, **kwargs)
def start(self, *args, **kwargs):
super().start(*args, **kwargs)
try:
async with self.create_client_session() as session:
async with session.post(
f"{self.api_base}/api/generate",
proxy=self.request_options.proxy,
json={
"prompt": "",
"model": self.get_model_name(),
},
) as _:
pass
requests.post(
f"{self.api_base}/api/generate",
json={
"prompt": "",
"model": self.get_model_name(),
},
)
except Exception as e:
logger.warning(f"Error pre-loading Ollama model: {e}")
@ -116,7 +114,7 @@ class Ollama(LLM):
elif resp.status != 200:
raise ContinueCustomException(
f"Ollama returned an error: {await resp.text()}",
"Invalid request to Ollama",
f"Ollama returned an error: {await resp.text()}",
)
async for line in resp.content.iter_any():
if line:

View file

@ -89,8 +89,8 @@ class OpenAI(LLM):
def context_length_for_model(cls, v, values):
return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096)
async def start(self, unique_id: Optional[str] = None):
await super().start(unique_id=unique_id)
def start(self, unique_id: Optional[str] = None):
super().start(unique_id=unique_id)
if self.context_length is None:
self.context_length = CONTEXT_LENGTH_FOR_MODEL.get(self.model, 4096)

View file

@ -74,9 +74,9 @@ class OpenAIFreeTrial(LLM):
def update_llm_properties(self):
self.llm.system_message = self.system_message
async def start(self, unique_id: Optional[str] = None):
await super().start(unique_id=unique_id)
await self.llm.start(unique_id=unique_id)
def start(self, unique_id: Optional[str] = None):
super().start(unique_id=unique_id)
self.llm.start(unique_id=unique_id)
async def stop(self):
await self.llm.stop()

View file

@ -76,13 +76,18 @@ def template_alpaca_messages(msgs: List[ChatMessage]) -> str:
def deepseek_template_messages(msgs: List[ChatMessage]) -> str:
prompt = ""
system = None
prompt += "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n"
if msgs[0].role == "system":
prompt += f"{msgs.pop(0).content}\n"
else:
prompt += "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n"
system = msgs.pop(0).content
for msg in msgs:
for i in range(len(msgs)):
msg = msgs[i]
prompt += "### Instruction:\n" if msg.role == "user" else "### Response:\n"
if system and msg.role == "user" and i == len(msgs) - 1:
prompt += system + "\n"
prompt += f"{msg.content}"
prompt += "\n" if msg.role == "user" else "<|EOT|>\n"

View file

@ -18,11 +18,11 @@ class ProxyServer(LLM):
class Config:
arbitrary_types_allowed = True
async def start(
def start(
self,
**kwargs,
):
await super().start(**kwargs)
super().start(**kwargs)
self.context_length = CONTEXT_LENGTH_FOR_MODEL[self.model]
def get_headers(self):

View file

@ -33,9 +33,9 @@ class QueuedLLM(LLM):
def dict(self, **kwargs):
return self.llm.dict(**kwargs)
async def start(self, *args, **kwargs):
await super().start(*args, **kwargs)
await self.llm.start(*args, **kwargs)
def start(self, *args, **kwargs):
super().start(*args, **kwargs)
self.llm.start(*args, **kwargs)
self._lock = asyncio.Lock()
self.model = self.llm.model
self.template_messages = self.llm.template_messages

View file

@ -84,7 +84,13 @@ class HighlightedCodeContextProvider(ContextProvider):
filepath=item.description.description,
range=Range.from_shorthand(int(lines[0]) - 1, 0, int(lines[1]), 0),
)
contents = await ide.readRangeInFile(rif)
# Temporary fix because reading the range in the file returns the raw JSON of the notebook
# , but we have the actual contents from when it was originally highlighted
if item.description.description.endswith(".ipynb"):
contents = item.content
else:
contents = await ide.readRangeInFile(rif)
return rif.with_contents(contents)
async def get_chat_message(self, item: ContextItem) -> ChatMessage:

View file

@ -24,6 +24,8 @@ class SimpleChatStep(Step):
messages: Optional[List[ChatMessage]] = None
prompt: Optional[str] = None
hide: bool = True
completion_options: Optional[CompletionOptions] = None
async def run(self, sdk: ContinueSDK):
@ -50,7 +52,7 @@ class SimpleChatStep(Step):
kwargs = self.completion_options.dict() if self.completion_options else {}
generator = sdk.models.chat.stream_chat(messages, **kwargs)
yield SetStep(description="")
yield SetStep(description="", hide=False)
async for chunk in generator:
if chunk.content != "":
yield chunk.content

View file

@ -2,7 +2,7 @@ import asyncio
import os
from typing import List, Optional, Union
from ...core.config import RetrievalSettings
from ...core.config import ModelDescription, RetrievalSettings
from ...core.main import (
ContextItem,
ContextItemDescription,
@ -24,37 +24,42 @@ PROMPT = """Use the above code to answer the following question. You should not
async def get_faster_model(sdk: ContinueSDK) -> Optional[LLM]:
# First, check for GPT-3/3.5
models = sdk.config.models.all_models
if gpt3_model := next(filter(lambda m: "gpt-3" in m.model, models), None):
return gpt3_model
def get_model_description() -> Optional[ModelDescription]:
# First, check for GPT-3/3.5
models = sdk.config.models
if gpt3_model := next(filter(lambda m: "gpt-3" in m.model, models), None):
return gpt3_model
# Then, check for OpenAIFreeTrial
if openai_free_trial_model := next(
filter(lambda m: m.__class__.__name__ == "OpenAIFreeTrial", models), None
):
new_model = openai_free_trial_model.copy()
new_model.model = "gpt-3.5-turbo"
await new_model.start(sdk.ide.window_info.unique_id)
return new_model
# Then, check for OpenAIFreeTrial
if openai_free_trial_model := next(
filter(lambda m: m.__class__.__name__ == "OpenAIFreeTrial", models), None
):
new_model = openai_free_trial_model.copy()
new_model.model = "gpt-3.5-turbo"
return new_model
# Then, check for an API Key
if openai_model := next(
filter(
lambda m: hasattr(m, "api_key")
and m.api_key is not None
and m.api_key.startswith("sk-"),
models,
),
None,
):
new_model = openai_model.copy()
new_model.model = "gpt-3.5-turbo"
await new_model.start(sdk.ide.window_info.unique_id)
return new_model
# Then, check for an API Key
if openai_model := next(
filter(
lambda m: hasattr(m, "api_key")
and m.api_key is not None
and m.api_key.startswith("sk-"),
models,
),
None,
):
new_model = openai_model.copy()
new_model.model = "gpt-3.5-turbo"
return new_model
# Return None, so re-ranking probably shouldn't happen
return None
# Return None, so re-ranking probably shouldn't happen
return None
if desc := get_model_description():
llm = sdk.config.create_llm(desc)
llm.start(sdk.ide.window_info.unique_id)
else:
return None
class AnswerQuestionChroma(Step):

View file

@ -4,7 +4,7 @@ from typing import List, Optional, Union
from pydantic import BaseModel, Field
from ...core.main import ContinueCustomException, SetStep, Step
from ...core.main import ContextItem, ContinueCustomException, SetStep, Step
from ...core.sdk import ContinueSDK, Models
from ...core.steps import DefaultModelEditCodeStep
from ...libs.llm.base import LLM
@ -371,6 +371,7 @@ class EditHighlightedCodeStep(Step):
class UserInputStep(Step):
user_input: str
context_items: List[ContextItem] = []
class SolveTracebackStep(Step):

View file

@ -89,23 +89,20 @@ class GUIProtocolServer(AbstractGUIProtocolServer):
data["role"], ModelDescription(**data["model"])
)
await self.open_config()
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 == "set_model_for_role_from_title":
await self.set_model_for_role_from_title(data["role"], data["title"])
elif msg.message_type == "delete_model_at_index":
await self.delete_model_at_index(data["index"])
async def set_model_for_role_from_index(self, role: str, index: int):
if config := self.get_config():
models = config.models
if title := models.saved[index].title:
SerializedContinueConfig.set_model_for_role(title, role)
await self.reload_config()
await self.send_config_update()
async def set_model_for_role_from_title(self, role: str, title: str):
SerializedContinueConfig.set_model_for_role(title, role)
await self.reload_config()
await self.send_config_update()
async def delete_model_at_index(self, index: int):
if config := self.get_config():
models = config.models
if title := models.saved[index].title:
if title := models[index].title:
SerializedContinueConfig.delete_model(title)
await self.reload_config()
await self.send_config_update()

View file

@ -33,7 +33,7 @@ from ...models.filesystem_edit import (
from ...models.main import Position, Range
from ...models.websockets import WebsocketsMessage
from ..websockets_messenger import SocketIOMessenger
from .ide_protocol import AbstractIdeProtocolServer
from .ide_protocol import AbstractIdeProtocolServer, WindowInfo
# region: Types
@ -118,13 +118,6 @@ class FoldingRangeResponse(BaseModel):
# endregion
class WindowInfo(BaseModel):
window_id: str
workspace_directory: str
unique_id: str
ide_info: Dict[str, Any]
class cached_property_no_none:
def __init__(self, func):
self.func = func

View file

@ -1,7 +1,8 @@
from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Optional, Union
from typing import Any, Callable, Dict, List, Optional, Union
from fastapi import WebSocket
from pydantic import BaseModel
from ...models.filesystem import RangeInFile, RangeInFileWithContents
from ...models.filesystem_edit import EditDiff, FileEdit, FileSystemEdit
@ -9,10 +10,18 @@ from ...models.main import Position
from ...models.websockets import WebsocketsMessage
class WindowInfo(BaseModel):
window_id: str
workspace_directory: str
unique_id: str
ide_info: Dict[str, Any]
class AbstractIdeProtocolServer(ABC):
websocket: WebSocket
session_id: Union[str, None]
ide_info: Optional[Dict[str, str]] = None
window_info: WindowInfo
@abstractmethod
async def handle_json(self, msg: WebsocketsMessage):

View file

@ -70,12 +70,6 @@ class Window:
async def reload_config(self):
self.config = self.load_config()
if self.ide is not None:
await self.config.models.start(
self.ide.window_info.unique_id,
self.config.system_message,
self.config.completion_options.temperature,
)
async def display_config_error(self):
if self._error_loading_config is not None:
@ -136,13 +130,6 @@ class Window:
create_async_task(index(), on_error=self.on_error)
# Start models
await self.config.models.start(
self.ide.window_info.unique_id,
self.config.system_message,
self.config.completion_options.temperature,
)
# When the config is loaded, setup posthog logger
posthog_logger.setup(
self.ide.window_info.unique_id,

View file

@ -4,6 +4,7 @@ version = "0.1.99"
description = ""
authors = ["Nate Sesti <sestinj@gmail.com>"]
readme = "README.md"
license = "Apache-2.0"
[tool.poetry.dependencies]
python = "^3.8.1"

View file

@ -51,7 +51,7 @@ def temp_clear_config():
"config_filename",
[
# "config_1.py",
"config_2.py",
# "config_2.py",
],
)
def test_load_old_config(config_filename):
@ -66,14 +66,6 @@ def test_load_old_config(config_filename):
config = ContinueConfig.load_default()
validate_continue_config(config)
if config_filename == "config_2.py":
model = config.models.default
assert model.completion_options.temperature == 0.1
assert model.completion_options.top_p == 0.75
assert model.completion_options.top_k == 40
assert model.context_length == 16384
assert model.request_options.timeout == 8000
def validate_continue_config(config: ContinueConfig):
ctx_provs = config.get_context_provider_descriptions()

View file

@ -1,113 +0,0 @@
"""
This is the Continue configuration file.
See https://continue.dev/docs/customization to for documentation of the available options.
"""
from continuedev.core.config import ContinueConfig, CustomCommand, SlashCommand
from continuedev.core.models import Models
from continuedev.libs.llm.llamacpp import LlamaCpp
from continuedev.libs.llm.openai_free_trial import OpenAIFreeTrial
from continuedev.libs.llm.prompts.chat import (
llama2_template_messages,
phind_template_messages,
)
from continuedev.plugins.context_providers.diff import DiffContextProvider
from continuedev.plugins.context_providers.github import GitHubIssuesContextProvider
from continuedev.plugins.context_providers.terminal import TerminalContextProvider
from continuedev.plugins.context_providers.url import URLContextProvider
from continuedev.plugins.steps.clear_history import ClearHistoryStep
from continuedev.plugins.steps.cmd import GenerateShellCommandStep
from continuedev.plugins.steps.comment_code import CommentCodeStep
from continuedev.plugins.steps.main import EditHighlightedCodeStep
from continuedev.plugins.steps.open_config import OpenConfigStep
from continuedev.plugins.steps.share_session import ShareSessionStep
config = ContinueConfig(
allow_anonymous_telemetry=False,
models=Models(
saved=[
LlamaCpp(
model="serverone",
system_message="",
timeout=3600,
server_url="http://serverone.local:8080",
),
LlamaCpp(
model="servertwo",
system_message="",
timeout=3600,
api_base="http://servertwo.local:8080",
),
LlamaCpp(
model="desktopone",
system_message="",
server_url="http://desktopone.local:8080",
),
],
default=LlamaCpp(
model="serverone Phind",
system_message="",
timeout=8000,
template_messages=phind_template_messages,
temperature=0.1,
top_p=0.75,
top_k=40,
context_length=16384,
server_url="http://serverone.local:8080",
),
),
system_message="",
temperature=0.1,
custom_commands=[
CustomCommand(
name="test",
description="Write unit tests for highlighted code",
prompt="Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
)
],
slash_commands=[
SlashCommand(
name="edit",
description="Edit highlighted code",
step=EditHighlightedCodeStep,
),
SlashCommand(
name="config",
description="Customize Continue",
step=OpenConfigStep,
),
SlashCommand(
name="comment",
description="Write comments for the highlighted code",
step=CommentCodeStep,
),
SlashCommand(
name="clear",
description="Clear step history",
step=ClearHistoryStep,
),
SlashCommand(
name="share",
description="Download and share this session",
step=ShareSessionStep,
),
SlashCommand(
name="cmd",
description="Generate a shell command",
step=GenerateShellCommandStep,
),
],
context_providers=[
# GitHubIssuesContextProvider(
# repo_name="<your github username or organization>/<your repo name>",
# auth_token="<your github auth token>"
# ),
DiffContextProvider(),
URLContextProvider(
preset_urls=[
# Add any common urls you reference here so they appear in autocomplete
]
),
TerminalContextProvider(),
],
)

View file

@ -21,7 +21,7 @@ SPEND_MONEY = False
def start_model(model: LLM):
asyncio.run(model.start(unique_id="test_unique_id"))
model.start(unique_id="test_unique_id")
def async_test(func):

View file

@ -1,18 +1,14 @@
from continuedev.core.config import ContinueConfig
from continuedev.core.models import Models
from continuedev.libs.llm.openai_free_trial import OpenAIFreeTrial
from continuedev.core.config import ContinueConfig, ModelDescription
config = ContinueConfig(
allow_anonymous_telemetry=False,
models=Models(
default=OpenAIFreeTrial(api_key="", model="gpt-4"),
summarize=OpenAIFreeTrial(
api_key="",
model="gpt-3.5-turbo",
models=[
ModelDescription(model="gpt-4", title="GPT-4", provider="openai-free-trial"),
ModelDescription(
model="gpt-3.5-turbo", title="GPT-3.5 Turbo", provider="openai-free-trial"
),
),
],
system_message=None,
temperature=0.5,
custom_commands=[],
slash_commands=[],
context_providers=[],