🔧 writing back to config.json

This commit is contained in:
Nate Sesti 2023-11-14 15:24:37 -08:00
parent d0cff2682a
commit 90fab6317f
12 changed files with 422 additions and 199 deletions

View file

@ -184,10 +184,105 @@
]
}
},
"required": [
"title",
"provider",
"model"
"required": ["title", "provider", "model"],
"allOf": [
{
"if": {
"properties": {
"provider": {
"enum": [
"openai",
"anthropic",
"google-palm",
"huggingface-inference-api",
"replicate",
"together"
]
}
}
},
"then": {
"required": ["api_key"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["huggingface-tgi"]
}
}
},
"then": {
"required": ["api_base"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["openai", "openai-aiohttp"]
}
}
},
"then": {
"properties": {
"engine": {
"type": "string"
},
"api_type": {
"type": "string"
},
"api_version": {
"type": "string"
}
}
}
},
{
"if": {
"properties": {
"api_type": {
"const": "azure"
}
}
},
"then": {
"required": ["engine", "api_version", "api_base"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["openai"]
}
}
},
"then": {
"properties": {
"use_legacy_completions_endpoint": {
"type": "boolean"
}
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["text-gen-webui"]
}
}
},
"then": {
"properties": {
"streaming_url": {
"type": "string"
}
}
}
}
]
},
"ModelRoles": {
@ -215,9 +310,7 @@
"type": "string"
}
},
"required": [
"default"
]
"required": ["default"]
},
"SlashCommand": {
"title": "SlashCommand",
@ -251,11 +344,7 @@
"type": "object"
}
},
"required": [
"name",
"description",
"step"
]
"required": ["name", "description", "step"]
},
"CustomCommand": {
"title": "CustomCommand",
@ -274,11 +363,7 @@
"type": "string"
}
},
"required": [
"name",
"prompt",
"description"
]
"required": ["name", "prompt", "description"]
},
"ContextProviderWithParams": {
"title": "ContextProviderWithParams",
@ -303,9 +388,7 @@
"type": "object"
}
},
"required": [
"name"
]
"required": ["name"]
},
"RetrievalSettings": {
"title": "RetrievalSettings",
@ -420,6 +503,11 @@
}
]
},
"system_message": {
"title": "System Message",
"description": "A system message that will always be followed by the LLM",
"type": "string"
},
"completion_options": {
"title": "Completion Options",
"description": "Default options for completion. These will be overriden by any options set for a specific model.",
@ -518,4 +606,4 @@
}
}
}
}
}

View file

@ -278,7 +278,7 @@
"jsonValidation": [
{
"fileMatch": "config.json",
"url": "./SerializedContinueConfig.json"
"url": "./config_schema.json"
}
]
},

View file

@ -55,10 +55,11 @@ function FTCDialog() {
<Button
disabled={!apiKey}
onClick={() => {
client?.addModelForRole("*", "OpenAI", {
client?.addModelForRole("*", {
model: "gpt-4",
api_key: apiKey,
title: "GPT-4",
provider: "openai",
});
dispatch(setShowDialog(false));
}}

View file

@ -1,6 +1,7 @@
import { ContextItem } from "../schema/ContextItem";
import { ContextItemId } from "../schema/ContextItemId";
import { ContinueConfig } from "../schema/ContinueConfig";
import { ModelDescription } from "../schema/SerializedContinueConfig";
abstract class AbstractContinueGUIClientProtocol {
abstract sendMainInput(input: string): void;
@ -45,11 +46,7 @@ abstract class AbstractContinueGUIClientProtocol {
abstract setTemperature(temperature: number): void;
abstract addModelForRole(
role: string,
model_class: string,
model: string
): void;
abstract addModelForRole(role: string, model: ModelDescription): void;
abstract saveContextGroup(title: string, contextItems: ContextItem[]): void;

View file

@ -3,6 +3,7 @@ import { ContextItem } from "../schema/ContextItem";
import { ContextItemId } from "../schema/ContextItemId";
import { ContinueConfig } from "../schema/ContinueConfig";
import { PersistedSessionInfo } from "../schema/PersistedSessionInfo";
import { ModelDescription } from "../schema/SerializedContinueConfig";
import { SessionState, StepDescription } from "../schema/SessionState";
import { SessionUpdate } from "../schema/SessionUpdate";
import AbstractContinueGUIClientProtocol from "./AbstractContinueGUIClientProtocol";
@ -215,8 +216,8 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
this.messenger?.send("set_temperature", { temperature });
}
addModelForRole(role: string, model_class: string, model: any): void {
this.messenger?.send("add_model_for_role", { role, model, model_class });
addModelForRole(role: string, model: ModelDescription): void {
this.messenger?.send("add_model_for_role", { role, model });
}
setModelForRoleFromIndex(role: string, index: number): void {

View file

@ -223,7 +223,7 @@ function ModelConfig() {
: parseFloat(formMethods.watch(d.key));
}
client?.addModelForRole("*", modelInfo.class, {
client?.addModelForRole("*", {
...pkg.params,
...modelInfo.params,
..._.merge(
@ -255,7 +255,7 @@ function ModelConfig() {
: parseFloat(formMethods.watch(d.key));
}
client?.addModelForRole("*", modelInfo.class, {
client?.addModelForRole("*", {
...modelInfo.packages[0]?.params,
...modelInfo.params,
...formParams,

View file

@ -0,0 +1,194 @@
{
"title": "ModelDescription",
"$ref": "#/definitions/continuedev__core__config__serialized_config__ModelDescription",
"definitions": {
"BaseCompletionOptions": {
"title": "BaseCompletionOptions",
"type": "object",
"properties": {
"temperature": {
"title": "Temperature",
"description": "The temperature of the completion.",
"type": "number"
},
"top_p": {
"title": "Top P",
"description": "The top_p of the completion.",
"type": "number"
},
"top_k": {
"title": "Top K",
"description": "The top_k of the completion.",
"type": "integer"
},
"presence_penalty": {
"title": "Presence Penalty",
"description": "The presence penalty Aof the completion.",
"type": "number"
},
"frequency_penalty": {
"title": "Frequency Penalty",
"description": "The frequency penalty of the completion.",
"type": "number"
},
"stop": {
"title": "Stop",
"description": "The stop tokens of the completion.",
"type": "array",
"items": {
"type": "string"
}
},
"max_tokens": {
"title": "Max Tokens",
"description": "The maximum number of tokens to generate.",
"default": 600,
"type": "integer"
}
}
},
"RequestOptions": {
"title": "RequestOptions",
"type": "object",
"properties": {
"timeout": {
"title": "Timeout",
"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.",
"default": 300,
"type": "integer"
},
"verify_ssl": {
"title": "Verify Ssl",
"description": "Whether to verify SSL certificates for requests.",
"type": "boolean"
},
"ca_bundle_path": {
"title": "Ca Bundle Path",
"description": "Path to a custom CA bundle to use when making the HTTP request",
"type": "string"
},
"proxy": {
"title": "Proxy",
"description": "Proxy URL to use when making the HTTP request",
"type": "string"
},
"headers": {
"title": "Headers",
"description": "Headers to use when making the HTTP request",
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
},
"continuedev__core__config__serialized_config__ModelDescription": {
"title": "ModelDescription",
"type": "object",
"properties": {
"title": {
"title": "Title",
"description": "The title you wish to give your model.",
"type": "string"
},
"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"
],
"type": "string"
},
"model": {
"title": "Model",
"description": "The name of the model. Used to autodetect prompt template.",
"type": "string"
},
"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": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by count_tokens.",
"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"
],
"type": "string"
},
"completion_options": {
"title": "Completion Options",
"description": "Options for the completion endpoint. Read more about the completion options in the documentation.",
"default": {
"temperature": null,
"top_p": null,
"top_k": null,
"presence_penalty": null,
"frequency_penalty": null,
"stop": null,
"max_tokens": 600
},
"allOf": [
{
"$ref": "#/definitions/BaseCompletionOptions"
}
]
},
"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.",
"default": {
"timeout": 300,
"verify_ssl": null,
"ca_bundle_path": null,
"proxy": null,
"headers": null
},
"allOf": [
{
"$ref": "#/definitions/RequestOptions"
}
]
}
},
"required": [
"title",
"provider",
"model"
]
}
}
}

View file

@ -154,7 +154,8 @@ class ContinueConfig(BaseModel):
@staticmethod
def load_default() -> "ContinueConfig":
path = getConfigFilePath(json=True)
return ContinueConfig.from_filepath(path)
config = ContinueConfig.from_filepath(path)
return config
def get_slash_command_descriptions(self) -> List[SlashCommandDescription]:
custom_commands = (
@ -196,32 +197,3 @@ class ContinueConfig(BaseModel):
requires_query=False,
)
]
@staticmethod
def set_temperature(temperature: float):
edit_config_property(["temperature"], temperature)
posthog_logger.capture_event("set_temperature", {"temperature": temperature})
@staticmethod
def set_system_message(message: str):
edit_config_property(["system_message"], message)
posthog_logger.capture_event("set_system_message", {"message": message})
@staticmethod
def set_models(models: Models, role: str):
JOINER = ",\n\t\t"
models_args = {
"saved": f"[{JOINER.join([display_llm_class(llm) for llm in models.saved])}]",
("default" if role == "*" else role): display_llm_class(models.default),
}
edit_config_property(
["models"],
create_obj_node("Models", models_args),
)
@staticmethod
def set_telemetry_enabled(enabled: bool):
edit_config_property(
["allow_anonymous_telemetry"],
create_bool_node(enabled),
)

View file

@ -1,9 +1,12 @@
from typing import Any, Dict, List, Optional, Type
from contextlib import contextmanager
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
from ...libs.util.paths import getConfigFilePath
from ...libs.util.telemetry import posthog_logger
from ...models.llm import BaseCompletionOptions, RequestOptions
from ..main import SlashCommandDescription, Step
from ..main import SlashCommandDescription
from .context import ContextProviderName
from .shared import ModelProvider, StepName, TemplateType
@ -73,6 +76,9 @@ class RetrievalSettings(BaseModel):
class ModelDescription(BaseModel):
class Config:
extra = "allow"
title: str = Field(
default=...,
description="The title you wish to give your model.",
@ -133,6 +139,9 @@ class ModelRoles(BaseModel):
)
CONFIG_JSON_PATH = getConfigFilePath(json=True)
class SerializedContinueConfig(BaseModel):
disallowed_steps: Optional[List[str]] = Field(
default=[],
@ -201,3 +210,67 @@ class SerializedContinueConfig(BaseModel):
default=RetrievalSettings(),
description="Settings for the retrieval system. Read more about the retrieval system in the documentation.",
)
@staticmethod
@contextmanager
def edit_config():
config = SerializedContinueConfig.parse_file(CONFIG_JSON_PATH)
yield config
with open(CONFIG_JSON_PATH, "w") as f:
f.write(config.json(exclude_none=True, exclude_defaults=True, indent=2))
@staticmethod
def set_temperature(temperature: float):
with SerializedContinueConfig.edit_config() as config:
config.completion_options.temperature = temperature
posthog_logger.capture_event(
"set_temperature", {"temperature": temperature}
)
@staticmethod
def set_system_message(message: str):
with SerializedContinueConfig.edit_config() as config:
config.system_message = message
posthog_logger.capture_event("set_system_message", {"message": message})
@staticmethod
def set_model_for_role(title: str, role: str):
with SerializedContinueConfig.edit_config() as config:
if role == "*":
config.model_roles.default = title
if config.model_roles.chat is None:
config.model_roles.chat = title
if config.model_roles.edit is None:
config.model_roles.edit = title
if config.model_roles.summarize is None:
config.model_roles.summarize = title
else:
config.model_roles.__setattr__(role, title)
@staticmethod
def add_model(model: ModelDescription):
with SerializedContinueConfig.edit_config() as config:
config.models.append(model)
@staticmethod
def set_telemetry_enabled(enabled: bool):
with SerializedContinueConfig.edit_config() as config:
config.allow_anonymous_telemetry = enabled
@staticmethod
def delete_model(title: str):
with SerializedContinueConfig.edit_config() as config:
config.models = [model for model in config.models if model.title != title]
if config.model_roles.default == title:
config.model_roles.default = config.models[0].title
if config.model_roles.chat == title:
config.model_roles.chat = None
if config.model_roles.edit == title:
config.model_roles.edit = None
if config.model_roles.summarize == title:
config.model_roles.summarize = None

View file

@ -104,29 +104,32 @@ class Models(BaseModel):
edit = model_with_title(config.model_roles.edit, default)
summarize = model_with_title(config.model_roles.summarize, default)
saved = [
model_with_title(model.title, default)
for model in config.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 = config.completion_options.dict()
completion_options.update(model.completion_options.dict(exclude_none=True))
model_class.system_message = model.system_message
return model_class(
title=model.title,
api_key=model.api_key,
completion_options=cast(BaseCompletionOptions, completion_options),
request_options=model.request_options,
system_message=model.system_message,
api_base=model.api_base,
model=model.model,
template_messages=autodetect_template_function(model.model),
prompt_templates=autodetect_prompt_templates(model.model),
context_length=model.context_length,
) # TODO: This doesn't yet match up with all of the fields. Check individual model types. Update them. Update the docs.
# 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],
)
def dict(self, **kwargs):

View file

@ -3,7 +3,7 @@ import os
from pydantic import schema_json_of
from ..core.config.config import ContinueConfig
from ..core.config.serialized_config import SerializedContinueConfig
from ..core.config.serialized_config import ModelDescription, SerializedContinueConfig
from ..core.context import ContextItem, ContextItemId
from ..core.main import (
ContextProviderDescription,
@ -32,7 +32,7 @@ MODELS_TO_GENERATE = (
SlashCommandDescription,
ContextProviderDescription,
]
+ [SerializedContinueConfig]
+ [SerializedContinueConfig, ModelDescription]
+ [ContinueConfig]
+ [ContextItem, ContextItemId]
+ [Models]

View file

@ -1,26 +1,13 @@
import uuid
from typing import Any, Awaitable, Callable, Dict, List, Optional, TypeVar
from typing import Awaitable, Callable, Dict, List, Optional, TypeVar
import socketio
from pydantic import BaseModel
from ...core.autopilot import Autopilot
from ...core.config.config import ContinueConfig
from ...core.config.serialized_config import ModelDescription, SerializedContinueConfig
from ...core.main import ContextItem, SessionState, SessionUpdate, Step, StepDescription
from ...core.models import ALL_MODEL_ROLES, MODEL_CLASSES, MODEL_MODULE_NAMES
from ...libs.llm.prompts.chat import (
llama2_template_messages,
phind_template_messages,
sqlcoder_template_messages,
template_alpaca_messages,
)
from ...libs.llm.prompts.edit import alpaca_edit_prompt, codellama_edit_prompt
from ...libs.util.edit_config import (
add_config_import,
create_obj_node,
display_llm_class,
edit_config_property,
)
from ...libs.util.telemetry import posthog_logger
from ...libs.util.types import AsyncFunc
from ...models.websockets import WebsocketsMessage
@ -28,8 +15,6 @@ from ..websockets_messenger import SocketIOMessenger
T = TypeVar("T", bound=BaseModel)
# You should probably abstract away the websocket stuff into a separate class
class GUIProtocolServer:
window_id: str
@ -74,19 +59,19 @@ class GUIProtocolServer:
elif msg.message_type == "set_system_message":
sys_message = data["system_message"]
ContinueConfig.set_system_message(sys_message)
SerializedContinueConfig.set_system_message(sys_message)
posthog_logger.capture_event(
"set_system_message", {"system_message": sys_message}
)
await self.reload_config()
await self.send_config_update()
elif msg.message_type == "set_temperature":
ContinueConfig.set_temperature(float(data["temperature"]))
SerializedContinueConfig.set_temperature(float(data["temperature"]))
await self.reload_config()
await self.send_config_update()
elif msg.message_type == "add_model_for_role":
await self.add_model_for_role(
data["role"], data["model_class"], data["model"]
data["role"], ModelDescription(**data["model"])
)
elif msg.message_type == "set_model_for_role_from_index":
await self.set_model_for_role_from_index(data["role"], data["index"])
@ -95,110 +80,21 @@ class GUIProtocolServer:
async def set_model_for_role_from_index(self, role: str, index: int):
models = self.get_config().models
temp = models.default
models.default = models.saved[index]
models.saved[index] = temp
ContinueConfig.set_models(models, role)
await self.reload_config()
await self.send_config_update()
if title := models.saved[index].title:
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):
models = self.get_config().models
models.saved.pop(index)
ContinueConfig.set_models(models, "*")
await self.reload_config()
await self.send_config_update()
async def add_model_for_role(self, role: str, model_class: str, model: Any):
models = self.get_config().models
model_copy = model.copy()
if "api_key" in model_copy:
del model_copy["api_key"]
if "hf_token" in model_copy:
del model_copy["hf_token"]
posthog_logger.capture_event(
"select_model_for_role",
{"role": role, "model_class": model_class, "model": model_copy},
)
if role == "*":
# Remove all previous models in roles and place in saved
saved_models = models.saved
existing_saved_models = set(
[display_llm_class(llm) for llm in saved_models]
)
for role in ALL_MODEL_ROLES:
val = models.__getattribute__(role)
if (
val is not None
and display_llm_class(val) not in existing_saved_models
):
saved_models.append(val)
existing_saved_models.add(display_llm_class(val))
models.__setattr__(role, None)
# Add the requisite import to config.py
default_model_display_overrides = {}
add_config_import(
f"from continuedev.libs.llm.{MODEL_MODULE_NAMES[model_class]} import {model_class}"
)
if "template_messages" in model:
if model["template_messages"] != "None":
add_config_import(
f"from continuedev.libs.llm.prompts.chat import {model['template_messages']}"
)
sqtm = sqlcoder_template_messages("<MY_DATABASE_SCHEMA>")
sqtm.__name__ = 'sqlcoder_template_messages("<MY_DATABASE_SCHEMA>")'
model["template_messages"] = {
"llama2_template_messages": llama2_template_messages,
"template_alpaca_messages": template_alpaca_messages,
"phind_template_messages": phind_template_messages,
"sqlcoder_template_messages": sqtm,
"None": None,
}[model["template_messages"]]
if "prompt_templates" in model and "edit" in model["prompt_templates"]:
default_model_display_overrides[
"prompt_templates"
] = f"""{{"edit": {model["prompt_templates"]["edit"]}}}"""
add_config_import(
f"from continuedev.libs.llm.prompts.edit import {model['prompt_templates']['edit']}"
)
model["prompt_templates"]["edit"] = {
"codellama_edit_prompt": codellama_edit_prompt,
"alpaca_edit_prompt": alpaca_edit_prompt,
}[model["prompt_templates"]["edit"]]
# Set the new default model
new_model = MODEL_CLASSES[model_class](**model)
models.default = new_model
# Construct and set the new models object
JOINER = ",\n\t\t"
saved_model_strings = set([display_llm_class(llm) for llm in saved_models])
models_args = {
"default": display_llm_class(
models.default, True, default_model_display_overrides
),
"saved": f"[{JOINER.join(saved_model_strings)}]",
}
edit_config_property(
["models"],
create_obj_node("Models", models_args),
)
if title := models.saved[index].title:
SerializedContinueConfig.delete_model(title)
await self.reload_config()
await self.send_config_update()
else:
# TODO
pass
# region: Send data to GUI
async def add_model_for_role(self, role: str, model: ModelDescription):
SerializedContinueConfig.add_model(model)
SerializedContinueConfig.set_model_for_role(model.title, role)
_running_autopilots: Dict[str, Autopilot] = {}
@ -251,5 +147,3 @@ class GUIProtocolServer:
return await self.get_autopilot(
SessionState(history=history, context_items=[])
).get_session_title()
# endregion