feat: ✨ auto-reload for config.py

This commit is contained in:
Nate Sesti 2023-10-06 00:13:45 -07:00
parent cc98ad86d5
commit e652e90806
5 changed files with 79 additions and 32 deletions

View file

@ -1,4 +1,4 @@
import React, { useContext } from "react";
import React, { useContext, useEffect } from "react";
import { GUIClientContext } from "../App";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../redux/store";
@ -113,6 +113,13 @@ function Settings() {
navigate("/");
};
useEffect(() => {
if (!config) return;
formMethods.setValue("system_message", config.system_message);
formMethods.setValue("temperature", config.temperature);
}, [config]);
return (
<FormProvider {...formMethods}>
<div className="overflow-scroll">
@ -145,7 +152,6 @@ function Settings() {
<TextArea
placeholder="Enter a system message (e.g. 'Always respond in German')"
{...formMethods.register("system_message")}
defaultValue={config.system_message}
/>
<Hr />
@ -164,7 +170,6 @@ function Settings() {
min="0"
max="1"
step="0.01"
defaultValue={config.temperature}
{...formMethods.register("temperature")}
/>
<p>1</p>

View file

@ -100,10 +100,8 @@ class Autopilot(ContinueBaseModel):
started: bool = False
async def start(
self,
full_state: Optional[FullState] = None,
config: Optional[ContinueConfig] = None,
async def load(
self, config: Optional[ContinueConfig] = None, only_reloading: bool = False
):
self.continue_sdk = await ContinueSDK.create(self, config=config)
if override_policy := self.continue_sdk.config.policy_override:
@ -118,8 +116,16 @@ class Autopilot(ContinueBaseModel):
FileContextProvider(workspace_dir=self.ide.workspace_directory),
],
self.continue_sdk,
only_reloading=only_reloading,
)
async def start(
self,
full_state: Optional[FullState] = None,
config: Optional[ContinueConfig] = None,
):
await self.load(config=config, only_reloading=False)
if full_state is not None:
self.history = full_state.history
self.session_info = full_state.session_info
@ -141,6 +147,10 @@ class Autopilot(ContinueBaseModel):
self.started = True
async def reload_config(self):
await self.load(config=None, only_reloading=True)
await self.update_subscribers()
async def cleanup(self):
stop_meilisearch()

View file

@ -1,7 +1,7 @@
import asyncio
import time
from abc import abstractmethod
from typing import Awaitable, Callable, Dict, List
from typing import Awaitable, Callable, Dict, List, Optional
from meilisearch_python_async import Client
from pydantic import BaseModel, Field
@ -251,11 +251,21 @@ class ContextManager:
self.context_providers = {}
self.provider_titles = set()
async def start(self, context_providers: List[ContextProvider], sdk: ContinueSDK):
async def start(
self,
context_providers: List[ContextProvider],
sdk: ContinueSDK,
only_reloading: bool = False,
):
"""
Starts the context manager.
"""
# Use only non-meilisearch-dependent providers until it is loaded
new_context_providers = {
provider.title: provider
for provider in context_providers
if provider.title not in self.provider_titles
}
self.context_providers = {
provider.title: provider for provider in context_providers
}
@ -272,7 +282,7 @@ class ContextManager:
logger.warning(f"Error loading meilisearch index: {e}")
# Start MeiliSearch in the background without blocking
async def load_index(context_providers):
async def load_index(providers_to_load: List[ContextProvider]):
running = await check_meilisearch_running()
if not running:
await start_meilisearch()
@ -285,10 +295,15 @@ class ContextManager:
return
logger.debug("Loading Meilisearch index...")
await self.load_index(sdk.ide.workspace_directory)
await self.load_index(
sdk.ide.workspace_directory, providers_to_load=providers_to_load
)
logger.debug("Loaded Meilisearch index")
create_async_task(load_index(context_providers), on_err)
providers_to_load = (
new_context_providers if only_reloading else context_providers
)
create_async_task(load_index(providers_to_load), on_err)
@staticmethod
async def update_documents(context_items: List[ContextItem], workspace_dir: str):
@ -337,7 +352,12 @@ class ContextManager:
except Exception as e:
logger.warning(f"Error deleting document from meilisearch: {e}")
async def load_index(self, workspace_dir: str, should_retry: bool = True):
async def load_index(
self,
workspace_dir: str,
should_retry: bool = True,
providers_to_load: Optional[List[ContextProvider]] = None,
):
try:
async with Client(get_meilisearch_url()) as search_client:
# First, create the index if it doesn't exist
@ -396,7 +416,9 @@ class ContextManager:
tasks = [
safe_load(provider)
for _, provider in self.context_providers.items()
for _, provider in (
providers_to_load or self.context_providers
).items()
]
await asyncio.wait_for(asyncio.gather(*tasks), timeout=20)

View file

@ -64,25 +64,19 @@ class ContinueSDK(AbstractContinueSDK):
self.__autopilot = autopilot
self.context = autopilot.context
@classmethod
async def create(
cls, autopilot: Autopilot, config: Optional[ContinueConfig] = None
) -> "ContinueSDK":
sdk = ContinueSDK(autopilot)
autopilot.continue_sdk = sdk
async def load(self, config: Optional[ContinueConfig] = None):
# Create necessary directories
getDiffsFolderPath()
try:
sdk.config = config or sdk._load_config_dot_py()
self.config = config or self._load_config_dot_py()
except Exception as e:
logger.error(f"Failed to load config.py: {traceback.format_exception(e)}")
sdk.config = (
self.config = (
ContinueConfig()
if sdk._last_valid_config is None
else sdk._last_valid_config
if self._last_valid_config is None
else self._last_valid_config
)
formatted_err = "\n".join(traceback.format_exception(e))
@ -90,14 +84,14 @@ class ContinueSDK(AbstractContinueSDK):
name="Invalid Continue Config File", message=formatted_err
)
msg_step.description = f"Falling back to default config settings due to the following error in `~/.continue/config.py`.\n```\n{formatted_err}\n```\n\nIt's possible this was caused by an update to the Continue config format. If you'd like to see the new recommended default `config.py`, check [here](https://github.com/continuedev/continue/blob/main/continuedev/src/continuedev/libs/constants/default_config.py).\n\nIf the error is related to OpenAIServerInfo, see the updated way of using these parameters [here](https://continue.dev/docs/customization#azure-openai-service)."
sdk.history.add_node(
self.history.add_node(
HistoryNode(step=msg_step, observation=None, depth=0, active=False)
)
await sdk.ide.setFileOpen(getConfigFilePath())
await self.ide.setFileOpen(getConfigFilePath())
# Start models
sdk.models = sdk.config.models
await sdk.models.start(sdk)
self.models = self.config.models
await self.models.start(self)
# Start LSP
# async def start_lsp():
@ -116,9 +110,18 @@ class ContinueSDK(AbstractContinueSDK):
# When the config is loaded, setup posthog logger
posthog_logger.setup(
sdk.ide.unique_id, sdk.config.allow_anonymous_telemetry, sdk.ide.ide_info
self.ide.unique_id, self.config.allow_anonymous_telemetry, self.ide.ide_info
)
dev_data_logger.setup(sdk.config.user_token, sdk.config.data_server_url)
dev_data_logger.setup(self.config.user_token, self.config.data_server_url)
@classmethod
async def create(
cls, autopilot: Autopilot, config: Optional[ContinueConfig] = None
) -> "ContinueSDK":
sdk = ContinueSDK(autopilot)
autopilot.continue_sdk = sdk
await sdk.load(config=config)
return sdk

View file

@ -456,6 +456,13 @@ class IdeProtocolServer(AbstractIdeProtocolServer):
for callback in self._file_saved_callbacks:
self.call_callback(callback, filepath, contents)
# If ~/.continue/config.py was saved, auto-update the SDK
if filepath.endswith(".continue/config.py") or filepath.endswith(
".continue\\config.py"
):
if autopilot := self.__get_autopilot():
create_async_task(autopilot.reload_config(), self.on_error)
## END Subscriptions ##
def onMainUserInput(self, input: str):