diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 7e6517718..e32750cf5 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -233,7 +233,7 @@ function ModelSelect(props: {}) { value={"GPT-4"} onChange={(val: string) => { if (val === defaultModel?.title) return; - client?.setModelForRoleFromTitle("*", val); + client?.setModelForRoleFromTitle("default", val); }} defaultValue={"GPT-4"} > diff --git a/gui/src/redux/selectors/configSelectors.ts b/gui/src/redux/selectors/configSelectors.ts index 3abcfd232..8d1cbf1db 100644 --- a/gui/src/redux/selectors/configSelectors.ts +++ b/gui/src/redux/selectors/configSelectors.ts @@ -14,6 +14,7 @@ export const contextLengthSelector = (state: RootStore) => { export const defaultModelSelector = (state: RootStore) => { const title = state.serverState.config.model_roles?.default; + if (!Array.isArray(state.serverState.config.models)) return; return state.serverState.config.models?.find( (model) => model.title === title ); diff --git a/server/continuedev/core/config.py b/server/continuedev/core/config.py index 905da4b1b..32436a680 100644 --- a/server/continuedev/core/config.py +++ b/server/continuedev/core/config.py @@ -8,18 +8,21 @@ 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.paths import getConfigFilePath, getGlobalFolderPath, sync_migrate 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, TemplateType, autodetect_prompt_templates, autodetect_template_function, + autodetect_template_type, ) from .context import ContextProvider from .main import ContextProviderDescription, Policy, SlashCommandDescription, Step @@ -273,6 +276,12 @@ class SerializedContinueConfig(BaseModel): else: config.model_roles.__setattr__(role, title) + def migrate_func(): + if role == "default" and config.model_roles.chat is not None: + config.model_roles.chat = None + + sync_migrate("select_default_model_001", migrate_func) + @staticmethod def add_model(model: ModelDescription): with SerializedContinueConfig.edit_config() as config: @@ -314,11 +323,10 @@ 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: List[ModelDescription] = Field( + models: List[LLM] = Field( default=[ - ModelDescription( + OpenAIFreeTrial( title="GPT-4 (trial)", - provider="openai-free-trial", model="gpt-4", api_key="", ) @@ -393,7 +401,10 @@ class ContinueConfig(BaseModel): allow_anonymous_telemetry=config.allow_anonymous_telemetry if config.allow_anonymous_telemetry is not None else True, - models=config.models, + models=[ + ContinueConfig.create_llm(config.completion_options, model) + for model in config.models + ], model_roles=config.model_roles, system_message=config.system_message, completion_options=config.completion_options, @@ -583,7 +594,9 @@ class ContinueConfig(BaseModel): return SerializedContinueConfig( disallowed_steps=self.disallowed_steps, allow_anonymous_telemetry=self.allow_anonymous_telemetry, - models=self.models, + models=[ + ContinueConfig.model_description_from(model) for model in self.models + ], model_roles=self.model_roles, system_message=self.system_message, completion_options=self.completion_options, @@ -604,28 +617,46 @@ class ContinueConfig(BaseModel): retrieval_settings=self.retrieval_settings, ) - def create_llm(self, model: ModelDescription) -> LLM: + @staticmethod + def create_llm( + completion_options: BaseCompletionOptions, 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( + options = completion_options.dict(exclude_none=True, exclude_defaults=True) + 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) + if "max_tokens" not in options: + 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["completion_options"] = options kwargs["template_messages"] = autodetect_template_function(model.model) kwargs["prompt_templates"] = autodetect_prompt_templates(model.model) return model_class(**kwargs) + @staticmethod + def model_description_from(llm: LLM) -> ModelDescription: + return ModelDescription( + title=llm.title or "LLM", + provider=MODEL_CLASS_TO_MODEL_PROVIDER.get( + llm.__class__.__name__, "custom" # type: ignore + ), + model=llm.model, + api_key=llm.api_key, + api_base=llm.api_base, + context_length=llm.context_length, + template=autodetect_template_type(llm.model), + completion_options=llm.completion_options, + system_message=llm.system_message, + request_options=llm.request_options, + ) + def construct_models(self) -> Models: - def model_with_title(title: Optional[str], fallback: ModelDescription): + def model_with_title(title: Optional[str], fallback: LLM): return next(filter(lambda x: x.title == title, self.models), fallback) default = model_with_title(self.model_roles.default, self.models[0]) @@ -640,11 +671,10 @@ class ContinueConfig(BaseModel): 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( + default=default, + chat=chat, + edit=edit, + summarize=summarize, + saved=saved, ) - return models diff --git a/server/continuedev/core/models.py b/server/continuedev/core/models.py index 36587a047..cb1da7d80 100644 --- a/server/continuedev/core/models.py +++ b/server/continuedev/core/models.py @@ -1,5 +1,5 @@ import uuid -from typing import Any, Callable, Dict, List, Optional, Type +from typing import Any, Callable, Dict, List, Optional, Type, Union from pydantic import BaseModel, validator @@ -72,12 +72,12 @@ MODEL_MODULE_NAMES = { class Models(BaseModel): """Main class that holds the current model configuration""" - default: LLM - summarize: LLM - edit: LLM - chat: LLM + default: Union[Any, LLM] + summarize: Union[Any, LLM] + edit: Union[Any, LLM] + chat: Union[Any, LLM] - saved: List[LLM] = [] + saved: List[Union[Any, LLM]] = [] temperature: Optional[float] = None system_message: Optional[str] = None diff --git a/server/continuedev/libs/llm/base.py b/server/continuedev/libs/llm/base.py index da3bf3a1e..b3674dab5 100644 --- a/server/continuedev/libs/llm/base.py +++ b/server/continuedev/libs/llm/base.py @@ -5,8 +5,12 @@ from typing import Any, AsyncGenerator, Callable, Coroutine, Dict, List, Optiona import aiohttp import certifi -from pydantic import Field +from pydantic import Field, validator +from ...core.config_utils.shared import ( + autodetect_prompt_templates, + autodetect_template_function, +) from ...core.main import ChatMessage from ...models.llm import BaseCompletionOptions, CompletionOptions, RequestOptions from ...models.main import ContinueBaseModel @@ -58,7 +62,7 @@ class LLM(ContinueBaseModel): ) prompt_templates: dict = Field( - default={}, + default=None, 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.', ) @@ -103,6 +107,14 @@ class LLM(ContinueBaseModel): }, } + @validator("template_messages", pre=True, always=True) + def set_template_messages(cls, template_messages, values): + return template_messages or autodetect_template_function(values["model"]) + + @validator("prompt_templates", pre=True, always=True) + def set_prompt_templates(cls, prompt_templates, values): + return prompt_templates or autodetect_prompt_templates(values["model"]) + def dict(self, **kwargs): original_dict = super().dict(**kwargs) original_dict.pop("write_log") diff --git a/server/continuedev/libs/util/paths.py b/server/continuedev/libs/util/paths.py index 6fd38a675..8114f8061 100644 --- a/server/continuedev/libs/util/paths.py +++ b/server/continuedev/libs/util/paths.py @@ -1,6 +1,6 @@ import os import re -from typing import Awaitable, Callable, Optional +from typing import Any, Awaitable, Callable, Optional from ..constants.default_config import default_config from ..constants.main import ( @@ -44,6 +44,12 @@ async def migrate(migration_id: str, migrate_func: Callable[[], Awaitable]): markMigrated(migration_id) +def sync_migrate(migration_id: str, migrate_func: Callable[[], Any]): + if not hasMigrated(migration_id): + migrate_func() + markMigrated(migration_id) + + def getSessionsFolderPath(): path = os.path.join(getGlobalFolderPath(), CONTINUE_SESSIONS_FOLDER) os.makedirs(path, exist_ok=True) diff --git a/server/continuedev/plugins/context_providers/highlighted_code.py b/server/continuedev/plugins/context_providers/highlighted_code.py index 8f0bac9be..82d3b5f92 100644 --- a/server/continuedev/plugins/context_providers/highlighted_code.py +++ b/server/continuedev/plugins/context_providers/highlighted_code.py @@ -99,7 +99,7 @@ class HighlightedCodeContextProvider(ContextProvider): ) return ChatMessage( role="user", - content=f"Code in this file is highlighted ({item.description.name}):\n```\n{rif.contents}\n```", + content=f"```{item.description.name}\n{rif.contents}\n```", summary=f"Code in this file is highlighted: {item.description.name}", )