🚚 move Python server to legacy-python-server repo

This commit is contained in:
Nate Sesti 2024-01-19 08:47:15 -08:00
parent 3a013818fa
commit 083b1d1263
202 changed files with 0 additions and 28121 deletions

View file

@ -1,23 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
## v0.1.104 - 2023-12-25
### Added
- Continuous and faster syncing of codebase index
### Removed
- No longer using Continue Python server
## v0.1.99 - 2023-11-19
### Changed
- migrated to .json config file format

1078
archive/server/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,31 +0,0 @@
# If you already have [package] information in `Cargo.toml`, you can ignore
# this section!
[package]
# `name` here is name of the package.
name = "continuedev"
# these are good defaults:
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"
[lib]
# The name of the native library. This is the name which will be used in Python to import the
# library (i.e. `import string_sum`). If you change this, you must also change the name of the
# `#[pymodule]` in `src/lib.rs`.
name = "continuedev"
# "cdylib" is necessary to produce a shared library for Python to import from.
crate-type = ["cdylib"]
[dependencies]
hex-literal = "0.4.1"
homedir = "0.2.1"
ignore = "0.4.20"
pyo3 = { version = "0.20.0", features = ["extension-module"] }
serde = { version = "1.0.192", features = ["derive"] }
serde_json = "1.0.108"
sha1 = "0.10.6"
tempfile = "3.8.1"
[dev-dependencies]
tempfile = "3.8.1"

View file

@ -1,88 +0,0 @@
# Continue PyPI Package
This package contains the [Continue](https://github.com/continuedev/continue) server and core classes needed to build your own recipes.
Continue is a Python library for automating repetitive sequences of software development tasks using language models. Using our VS Code extension, you can build, run, and refine these recipes as they natively interact with your codebase. Read the docs [here](https://continue.dev/docs) or download the VS Code extension [here](https://marketplace.visualstudio.com/items?itemName=Continue.continue).
## Continue Server
The Continue server acts as a bridge between the Continue React app and your IDE, running your recipes and acting on the codebase.
Start it by running the following commands:
1. `cd server`
2. Make sure packages are installed with `poetry install`
- If poetry is not installed, you can install with
```bash
curl -sSL https://install.python-poetry.org | python3 -
```
(official instructions [here](https://python-poetry.org/docs/#installing-with-the-official-installer))
3. `poetry shell` to activate the virtual environment
4. `python3 -m continuedev.server.main` to start the server
Once you've validated that this works, you'll often want to use a debugger, in which case we've provided a launch configuration for VS Code in `.vscode/launch.json`. To start the debugger in VS Code, ensure that the workspace directory is the root of the `continue` repo, then press F5.
> [!NOTE]
> To start the debugger, you'll have to select the poetry Python interpreter
> (`/path-to-poetry-venv/bin/python3`) in the bottom right of the VS Code window. If you
> don't see this, you may have to install the [Python
> extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python).
## Scripts
`poetry run typegen` to generate JSONSchema .json files from the Pydantic types defined in the `models` directory.
`poetry build` will output wheel and tarball files in `./dist`.
## Writing Steps
See the `continuedev/libs/steps` folder for examples of writing a Continue step. See our documentation for tutorials.
## How to contribute
Open a [new GitHub Issue](https://github.com/continuedev/continue/issues/new) or comment on [an existing one](https://github.com/continuedev/continue/issues). Let us know what you would like to contribute, and we will help you make it happen!
For more a more detailed contributing guide, see [CONTRIBUTING.md](../CONTRIBUTING.md).
## Install from source
#### 1. Clone this repo
Recommended: Run this command to use SSH
```bash
git clone git@github.com:continuedev/continue.git
```
Alternative: Run this command to use HTTPS
```bash
git clone https://github.com/continuedev/continue
```
#### 2. Install Continue
Run this command to use the install script
```bash
cd continue/extensions/vscode/scripts && python3 install_from_source.py
```
> [!IMPORTANT]
> Ensure you have a Java Runtime Environment (JRE) installed. Verify this by typing `java
-version` in your command prompt or terminal. If a version number appears, you're set.
> If not, download and install a JRE from Oracle's website or through a package manager,
> for example Homebrew.
>
> ```sh
> brew install openjdk@11
> ```
# Understanding the codebase
- [Continue Server README](./README.md): learn about the core of Continue, which can be downloaded as a [PyPI package](https://pypi.org/project/continuedev/)
- [VS Code Extension README](../extensions/vscode/README.md): learn about the capabilities of our extension—the first implementation of Continue's IDE Protocol—which makes it possible to use use Continue in VS Code and GitHub Codespaces
- [Continue GUI README](../gui/): learn about the React app that lets users interact with the server and is placed adjacent to the text editor in any supported IDE
- [Schema README](../schema/README.md): learn about the JSON Schema types generated from Pydantic models, which we use across the `server/` and `extensions/vscode/` directories
- [Continue Docs README](../docs/README.md): learn how our [docs](https://continue.dev/docs) are written and built
- [How to debug the VS Code Extension README](../extensions/vscode/src/README.md): learn how to set up the VS Code extension, so you can debug it

View file

@ -1,52 +0,0 @@
{
"models": [
{
"title": "GPT-4",
"provider": "free-trial",
"model": "gpt-4"
},
{
"title": "GPT-3.5-Turbo",
"provider": "free-trial",
"model": "gpt-3.5-turbo"
}
],
"model_roles": {
"default": "GPT-4",
"summarize": "GPT-3.5-Turbo"
},
"slash_commands": [
{
"name": "edit",
"description": "Edit highlighted code",
"step": "EditHighlightedCodeStep"
},
{
"name": "config",
"description": "Customize Continue",
"step": "OpenConfigStep"
},
{
"name": "comment",
"description": "Write comments for the highlighted code",
"step": "CommentCodeStep"
},
{
"name": "share",
"description": "Download and share this session",
"step": "ShareSessionStep"
},
{
"name": "cmd",
"description": "Generate a shell command",
"step": "GenerateShellCommandStep"
}
],
"custom_commands": [
{
"name": "test",
"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.",
"description": "Write unit tests for highlighted code"
}
]
}

View file

@ -1,13 +0,0 @@
"""
config.py allows you to modify Continue programmatically instead of just using config.json.
First, config.json is loaded. Then, if you have defined modify_config here, the function will be given the result of
loading config.json, and will return the final ContinueConfig to be used.
"""
from continuedev.core.config import ContinueConfig
def modify_config(config: ContinueConfig) -> ContinueConfig:
config.completion_options.temperature = 0.5
return config

View file

@ -1,22 +0,0 @@
import asyncio
from typing import Union
from .core.config import ContinueConfig
from .core.main import Step
# from .headless import start_headless_session
def run(step_or_config: Union[Step, ContinueConfig, str]):
if isinstance(step_or_config, ContinueConfig):
config = step_or_config
elif isinstance(step_or_config, str):
config = ContinueConfig.from_filepath(step_or_config)
else:
config = ContinueConfig()
config.steps_on_startup = [step_or_config]
loop = asyncio.get_event_loop()
# loop.run_until_complete(start_headless_session(config=config))
tasks = asyncio.all_tasks(loop)
loop.run_until_complete(asyncio.gather(*tasks))

View file

@ -1,176 +0,0 @@
import asyncio
import os
from typing import Optional
import typer
from dotenv import load_dotenv
from rich.console import Console
from rich.markdown import Markdown
from tqdm import tqdm
from . import run
from .core.config import ContinueConfig, RetrievalSettings
from .headless import get_headless_autopilot
from .headless.headless_ide import LocalIdeProtocol
from .libs.index.build_index import build_index
from .libs.index.chunkers.chunk import Chunk
from .libs.index.pipelines.main import main_retrieval_pipeline
from .libs.util.ext_to_lang import ext_to_lang
from .libs.util.paths import getConfigFilePath
from .server.main import run_server
load_dotenv()
app = typer.Typer(invoke_without_command=True)
console = Console()
CONTINUE_ASCII = r"""
_________ _____ _____
__ ____/______ _______ __ /____(_)_______ ____ _______
_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \
/ /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
\____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/
"""
def main_command(
port: int = typer.Option(65432, help="server port"),
host: str = typer.Option("127.0.0.1", help="server host"),
meilisearch_url: Optional[str] = typer.Option(
None, help="The URL of the MeiliSearch server if running manually"
),
disable_meilisearch: bool = typer.Option(
False, help="Disable the MeiliSearch server"
),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
headless: bool = typer.Option(False, help="Run in headless mode"),
):
if headless:
run(config or getConfigFilePath())
else:
print(CONTINUE_ASCII)
run_server(
port=port,
host=host,
meilisearch_url=meilisearch_url,
disable_meilisearch=disable_meilisearch,
)
@app.callback()
def main(
ctx: typer.Context,
port: int = typer.Option(65432, help="server port"),
host: str = typer.Option("127.0.0.1", help="server host"),
meilisearch_url: Optional[str] = typer.Option(
None, help="The URL of the MeiliSearch server if running manually"
),
disable_meilisearch: bool = typer.Option(
False, help="Disable the MeiliSearch server"
),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
headless: bool = typer.Option(False, help="Run in headless mode"),
):
if ctx.invoked_subcommand is None:
main_command(
port=port,
host=host,
meilisearch_url=meilisearch_url,
config=config,
headless=headless,
disable_meilisearch=disable_meilisearch,
)
def print_chunk(chunk: Chunk):
# A nice colored representation of the piece of the file
language = ext_to_lang(chunk.digest.split(".")[-1])
console.print(
Markdown(f"\n**{chunk.digest}**\n\n```{language}\n{chunk.content}\n```\n---\n")
)
@app.command()
def search(
query: str = typer.Argument(..., help="The query to search for"),
config: Optional[str] = typer.Option(
None, "--config", help="The path to the configuration file"
),
directory: str = typer.Option(None, "--directory", help="The directory to index"),
):
if directory is None:
directory = "."
print(f"Searching {directory}...")
# Make absolute
directory = os.path.abspath(directory)
async def run():
autopilot = await get_headless_autopilot(config=config, directory=directory)
results = await main_retrieval_pipeline(
query,
autopilot.sdk,
openai_api_key=None, # os.environ.get("OPENAI_API_KEY"),
)
console.print(Markdown(f"## Results for `{query}`"))
for result in results:
print_chunk(result)
asyncio.run(run())
@app.command()
def index(
directory: str = typer.Argument(None, help="The directory to index"),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
openai_api_key: Optional[str] = typer.Option(
None, help="The OpenAI API key to use for indexing"
),
):
if directory is None:
directory = "."
# Make absolute
directory = os.path.abspath(directory)
print(f"Indexing {directory}...")
async def run():
nonlocal config
config_obj = None
if config is None:
config_obj = ContinueConfig.load_default()
else:
config_obj = ContinueConfig.from_filepath(config)
if config_obj.retrieval_settings is None:
config_obj.retrieval_settings = RetrievalSettings()
config_obj.retrieval_settings.openai_api_key = openai_api_key
pbar = tqdm(total=100)
async for progress in build_index(
ide=LocalIdeProtocol(workspace_directory=directory), config=config_obj
):
pbar.update(int(progress * 100) - pbar.n)
pbar.close()
print("Indexing complete")
asyncio.run(run())
if __name__ == "__main__":
app()

View file

@ -1,20 +0,0 @@
import asyncio
from typing import Union
from .core.config import ContinueConfig
from .core.main import Step
# from .headless import start_headless_session
def run(step_or_config: Union[Step, ContinueConfig]):
if isinstance(step_or_config, ContinueConfig):
config = step_or_config
else:
config = ContinueConfig()
config.steps_on_startup = [step_or_config]
loop = asyncio.get_event_loop()
# loop.run_until_complete(start_headless_session(config=config))
tasks = asyncio.all_tasks(loop)
loop.run_until_complete(asyncio.gather(*tasks))

View file

@ -1,12 +0,0 @@
from typing import List, Tuple
def sync_results(
dir: str, branch: str
) -> Tuple[
List[Tuple[str, str]],
List[Tuple[str, str]],
List[Tuple[str, str]],
List[Tuple[str, str]],
]:
"""Returns lists of files that need (compute, delete, add label, remove label) with each item being a (path, hash) tuple"""
...

View file

@ -1,120 +0,0 @@
from abc import abstractmethod, abstractproperty
from typing import List, Optional, Union
from ..models.filesystem import RangeInFileWithContents
from ..models.filesystem_edit import FileSystemEdit
from ..models.main import Range
from ..server.protocols.gui_protocol import AbstractGUIProtocolServer
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from .config import ContinueConfig
from .lsp import ContinueLSPClient
from .main import ChatMessage, Context, ContextItem, Step, StepDescription
from .models import Models
class AbstractContinueSDK:
"""The SDK provided as parameters to a step"""
ide: AbstractIdeProtocolServer
gui: AbstractGUIProtocolServer
config: ContinueConfig
models: Models
lsp: Optional[ContinueLSPClient] = None
context: Context = Context()
@abstractproperty
def history(self) -> List[StepDescription]:
...
@abstractproperty
def context_items(self) -> List[ContextItem]:
...
@abstractmethod
async def _ensure_absolute_path(self, path: str) -> str:
...
@abstractmethod
async def run_step(self, step: Step):
...
@abstractmethod
async def apply_filesystem_edit(
self,
edit: FileSystemEdit,
name: str = "Filesystem Edit",
description: str = "Filesystem Edit",
):
...
@abstractmethod
async def run(
self,
commands: Union[List[str], str],
cwd: Optional[str] = None,
name: str = "Run Command",
description: str = "Run Command",
handle_error: bool = True,
) -> str:
...
@abstractmethod
async def edit_file(
self,
filename: str,
prompt: str,
name: str = "Edit File",
description: str = "",
range: Optional[Range] = None,
):
...
@abstractmethod
async def append_to_file(self, filename: str, content: str):
...
@abstractmethod
async def add_file(self, filename: str, content: Union[str, None]):
...
@abstractmethod
async def delete_file(self, filename: str):
...
@abstractmethod
async def add_directory(self, path: str):
...
@abstractmethod
async def delete_directory(self, path: str):
...
@abstractmethod
async def get_code_context(
self, only_editing: bool = False
) -> List[RangeInFileWithContents]:
...
@abstractmethod
async def add_context_item(self, item: ContextItem):
...
@abstractmethod
def set_loading_message(self, message: str):
...
@abstractmethod
def raise_exception(
self, message: str, title: str, with_step: Union[Step, None] = None
):
...
async def get_chat_context(self) -> List[ChatMessage]:
...
@abstractmethod
async def get_context_item_chat_messages(
self, exclude: Optional[str] = None
) -> List[ChatMessage]:
...

View file

@ -1,349 +0,0 @@
import inspect
import uuid
from typing import List, Optional, cast
from aiohttp import ClientPayloadError
from openai import (
APIConnectionError,
APIError,
BadRequestError,
RateLimitError,
Timeout,
)
from ..libs.llm.prompts.chat import template_alpaca_messages
from ..libs.util.devdata import dev_data_logger
from ..libs.util.errors import format_exc
from ..libs.util.logging import logger
from ..libs.util.strings import remove_quotes_and_escapes
from ..libs.util.telemetry import posthog_logger
from ..plugins.policies.default import DefaultPolicy
from ..server.protocols.gui_protocol import AbstractGUIProtocolServer
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from .config import ContinueConfig
from .context import ContextManager
from .main import (
AutopilotGenerator,
AutopilotGeneratorOutput,
Context,
ContextItem,
ContinueCustomException,
ContinueError,
DeltaStep,
Policy,
SessionState,
SessionUpdate,
SetStep,
Step,
StepDescription,
UpdateStep,
)
from .models import Models
from .observation import Observation
from .sdk import ContinueSDK
def get_error_title(e: Exception) -> str:
if isinstance(e, APIError):
return "OpenAI is overloaded with requests. Please try again."
elif isinstance(e, RateLimitError):
return "This OpenAI API key has been rate limited. Please try again."
elif isinstance(e, Timeout):
return "OpenAI timed out. Please try again."
elif isinstance(e, BadRequestError) and e.code == "context_length_exceeded":
return e.message or e.__str__()
elif isinstance(e, ClientPayloadError):
return "The request failed. Please try again."
elif isinstance(e, APIConnectionError):
return 'The request failed. Please check your internet connection and try again. If this issue persists, you can use our API key for free by going to VS Code settings and changing the value of continue.OPENAI_API_KEY to ""'
elif isinstance(e, BadRequestError):
return "Invalid request sent to OpenAI. Please try again."
elif "rate_limit_ip_middleware" in e.__str__():
return "You have reached your limit for free usage of our token. You can continue using Continue by entering your own OpenAI API key in VS Code settings."
elif e.__str__().startswith("Cannot connect to host"):
return (
"The request failed. Please check your internet connection and try again."
)
return e.__str__() or e.__repr__()
class Autopilot:
session_state: SessionState
ide: AbstractIdeProtocolServer
gui: AbstractGUIProtocolServer
config: ContinueConfig
context_manager: ContextManager
context: Context = Context()
def __init__(
self,
session_state: SessionState,
ide: AbstractIdeProtocolServer,
gui: AbstractGUIProtocolServer,
config: ContinueConfig,
context_manager: ContextManager,
models: Models,
):
self.session_state = session_state
self.ide = ide
self.gui = gui
self.config = config
self.context_manager = context_manager
self.models = models
@property
def policy(self) -> Policy:
return self.config.policy_override or DefaultPolicy()
@property
def sdk(self) -> ContinueSDK:
return ContinueSDK(self.config, self.ide, self.gui, self, self.models)
class Config:
arbitrary_types_allowed = True
def handle_error(self, e: Exception, step: Step) -> ContinueCustomException:
is_continue_custom_exception = (
issubclass(e.__class__, ContinueCustomException)
or e.__class__.__name__ == ContinueCustomException.__name__
)
if is_continue_custom_exception:
e = cast(ContinueCustomException, e)
error_string = e.message
error_title = e.title
else:
error_string = format_exc(e)
error_title = get_error_title(e)
# Attach an InternalErrorObservation to the step and unhide it.
logger.error(f"Error while running step: \n{error_string}\n{error_title}")
posthog_logger.capture_event(
"step error",
{
"error_message": error_string,
"error_title": error_title,
"step_name": step.name,
"params": step.dict(),
},
)
if is_continue_custom_exception:
return cast(ContinueCustomException, e)
else:
return ContinueCustomException(title=error_title, message=error_string)
def log_step(self, step: Step, context_used: List[ContextItem]):
posthog_logger.capture_event(
"step run",
{
"step_name": step.name,
"params": step.dict(),
"context": list(
map(
lambda item: item.dict(),
context_used,
)
),
},
)
step_id = uuid.uuid4().hex
dev_data_logger.capture(
"step_run",
{"step_name": step.name, "params": step.dict(), "step_id": step_id},
)
dev_data_logger.capture(
"context_used",
{
"context": list(
map(
lambda item: item.dict(),
context_used,
)
),
"step_id": step_id,
},
)
_step_depth: int = 0
stopped = False
async def _run_singular_step(self, step: "Step") -> AutopilotGenerator:
# Allow config to set disallowed steps
if (
self.sdk.config.disallowed_steps is not None
and step.__class__.__name__ in self.sdk.config.disallowed_steps
):
return
# Log the context and step to dev data
context_used = self.session_state.context_items
self.log_step(step, context_used)
# Update history - do this first so we get top-first tree ordering
self._step_depth += 1
index = len(self.session_state.history)
yield StepDescription(
step_type=step.__class__.__name__,
name=step.name,
description=step.description,
params=step.dict(),
hide=step.hide,
depth=self._step_depth,
)
def handle_step_update(
update: UpdateStep,
) -> Optional[AutopilotGeneratorOutput]:
if update.__class__.__name__ == "SessionUpdate":
return update # type: ignore
elif isinstance(update, str):
return SessionUpdate(index=index, update=DeltaStep(description=update))
elif update.__class__.__name__ == "Observation":
return SessionUpdate(
index=index,
update=DeltaStep(observations=[cast(Observation, update)]),
)
elif (
update.__class__.__name__ == "DeltaStep"
or update.__class__.__name__ == "SetStep"
):
return SessionUpdate(index=index, update=update)
elif update is None:
return None
else:
logger.warning(f"Unknown type yielded from Step: {update}")
# Try to run step and handle errors
try:
if inspect.iscoroutinefunction(step.run):
await step.run(self.sdk)
elif inspect.isasyncgenfunction(step.run):
async for update in step.run(self.sdk):
if self.stopped:
if on_stop_generator := step.on_stop(self.sdk):
for update in on_stop_generator: # type: ignore
if handled := handle_step_update(update):
yield handled
return
if handled := handle_step_update(update):
yield handled
else:
logger.warning(
f"{step.__class__.__name__}.run is not a coroutine function or async generator"
)
except Exception as e:
continue_custom_exception = self.handle_error(e, step)
yield SessionUpdate(index=index, update=SetStep(hide=False))
while self.session_state.history[index].name != step.name:
yield SessionUpdate(index=index, update=SetStep(hide=True))
index -= 1
# i is now the index of the step that we want to show/rerun
yield SessionUpdate(
index=index,
update=SetStep(
error=ContinueError(
title=continue_custom_exception.title or "Error",
message=continue_custom_exception.message or "Error",
),
hide=False,
),
)
# ContinueCustomException can optionally specify a step to run on the error
if after_err_step := continue_custom_exception.with_step:
await self.run_step(after_err_step)
self._step_depth -= 1
# NOTE: index here doesn't matter, awkward
yield SessionUpdate(index=index, stop=True, update=DeltaStep())
# # Update its description
# async def update_description():
# if (
# self.continue_sdk.config.disable_summaries
# or self.history.timeline[index_of_history_node].deleted
# ):
# return
# description = await step.describe(self.continue_sdk.models)
# if description is not None:
# step.description = description
# # Update subscribers with new description
# await self.update_subscribers()
# create_async_task(
# update_description(),
# on_error=lambda e: self.continue_sdk.run_step(
# DisplayErrorStep.from_exception(e)
# ),
# )
async def run_step(self, step: Step):
async for update in self._run_singular_step(step):
await self.handle_session_update(update)
async def handle_session_update(self, update: AutopilotGeneratorOutput):
if update is None:
return
if isinstance(update, StepDescription):
index = len(self.session_state.history)
self.session_state.history.append(update)
set_step = SetStep(**update.dict())
await self.sdk.gui.send_session_update(
SessionUpdate(index=index, update=set_step)
)
return
if update.index > len(self.session_state.history):
raise Exception(
f"History update index {update.index} is greater than history length {len(self.session_state.history)}"
)
elif update.index == len(self.session_state.history):
raise Exception(
f"History update index {update.index} is equal to history length {len(self.session_state.history)}. Must yield a StepDescription to add a new step."
)
self.session_state.history[update.index].update(update.update)
await self.sdk.gui.send_session_update(update)
async def run(self, step: Optional[Step] = None):
async def add_log(log: str):
await self.handle_session_update(
SessionUpdate(
index=len(self.session_state.history) - 1,
update=DeltaStep(logs=[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):
await self.run_step(next_step)
self.sdk.models.remove_logger(logger_id)
async def get_session_title(self) -> str:
if self.sdk.config.disable_summaries:
return "New Session"
else:
chat_history = await self.sdk.get_chat_context()
chat_history_str = template_alpaca_messages(chat_history)
if self.sdk.models.summarize is None:
return "New Session"
title = await self.sdk.models.summarize.complete(
f"{chat_history_str}\n\nGive a short title to describe the above chat session. Do not put quotes around the title. Do not use more than 6 words. The title is: ",
max_tokens=20,
log=False,
)
return remove_quotes_and_escapes(title)

View file

@ -1,711 +0,0 @@
import importlib.util
import json
import os
from contextlib import contextmanager
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast
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, 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,
STEP_NAMES,
ModelProvider,
StepName,
TemplateType,
autodetect_prompt_templates,
autodetect_template_function,
autodetect_template_type,
)
from .context import ContextProvider
from .main import ContextProviderDescription, Policy, SlashCommandDescription, Step
from .models import MODEL_CLASSES, Models
class StepWithParams(BaseModel):
name: StepName
params: Dict[str, Any] = {}
class ContextProviderWithParams(BaseModel):
name: ContextProviderName
params: Dict[str, Any] = {}
class SlashCommand(BaseModel):
name: str
description: str
step: Union[Type[Step], StepName, str]
params: Optional[Dict] = {}
# Allow step class for the migration
@validator("step", pre=True, always=True)
def step_is_string(cls, v):
if isinstance(v, str):
return v
elif (
isinstance(v, object)
and v.__class__.__name__ == "ModelMetaclass"
and v.__class__.__name__ in STEP_NAMES
):
return str(v).split(".")[-1].split("'")[0]
else:
return v
def dict(self, *args, **kwargs):
d = super().dict(*args, **kwargs)
if isinstance(d["step"], str):
d["step"] = d["step"].split(".")[-1]
else:
d["step"] = d["step"].__name__
return d
def slash_command_description(self) -> SlashCommandDescription:
return SlashCommandDescription(
name=self.name,
description=self.description,
)
class CustomCommand(BaseModel):
name: str
prompt: str
description: str
def slash_command_description(self) -> SlashCommandDescription:
return SlashCommandDescription(
name=self.name,
description=self.description,
)
class RetrievalSettings(BaseModel):
n_retrieve: Optional[int] = Field(
default=50,
description="Number of results to initially retrieve from vector database",
)
n_final: Optional[int] = Field(
default=10, description="Final number of results to use after re-ranking"
)
use_reranking: bool = Field(
default=True,
description="Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results",
)
rerank_group_size: int = Field(
default=5,
description="Number of results to group together when re-ranking. Each group will be processed in parallel.",
)
ignore_files: List[str] = Field(
default=[],
description="Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.",
)
openai_api_key: Optional[str] = Field(default=None, description="OpenAI API key")
api_base: Optional[str] = Field(default=None, description="OpenAI API base URL")
api_type: Optional[str] = Field(default=None, description="OpenAI API type")
api_version: Optional[str] = Field(default=None, description="OpenAI API version")
organization_id: Optional[str] = Field(
default=None, description="OpenAI organization ID"
)
class ModelDescription(BaseModel):
class Config:
extra = "allow"
title: str = Field(
default=...,
description="The title you wish to give your model.",
)
provider: ModelProvider = Field(
default=...,
description="The provider of the model. This is used to determine the type of model, and how to interact with it.",
)
model: str = Field(
default=...,
description="The name of the model. Used to autodetect prompt template.",
)
api_key: Optional[str] = Field(
default=None, description="OpenAI, Anthropic, Together, or other API key"
)
api_base: Optional[str] = Field(
default=None, description="The base URL of the LLM API."
)
context_length: int = Field(
default=2048,
description="The maximum context length of the LLM in tokens, as counted by count_tokens.",
)
template: Optional[TemplateType] = Field(
default=None,
description="The chat template used to format messages. This is auto-detected for most models, but can be overridden here.",
)
completion_options: BaseCompletionOptions = Field(
default=BaseCompletionOptions(),
description="Options for the completion endpoint. Read more about the completion options in the documentation.",
)
system_message: Optional[str] = Field(
default=None,
description="A system message that will always be followed by the LLM",
)
request_options: RequestOptions = Field(
default=RequestOptions(),
description="Options for the HTTP request to the LLM.",
)
class ModelRoles(BaseModel):
default: str = Field(
default=...,
description="The default model. If other model roles are not set, they will fall back to default.",
)
chat: Optional[str] = Field(
default=None,
description="The model to use for chat. If not set, will fall back to default.",
)
edit: Optional[str] = Field(
default=None,
description="The model to use for editing. If not set, will fall back to default.",
)
summarize: Optional[str] = Field(
default=None,
description="The model to use for summarization. If not set, will fall back to default.",
)
CONFIG_JSON_PATH = getConfigFilePath(json=True)
class SerializedContinueConfig(BaseModel):
disallowed_steps: Optional[List[str]] = Field(
default=[],
description="Steps that are not allowed to be run, and will be skipped if attempted",
)
allow_anonymous_telemetry: Optional[bool] = Field(
default=True,
description="If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to False, we will not collect any data.",
)
models: List[ModelDescription] = Field(
default=[
ModelDescription(
title="GPT-4 (trial)",
provider="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,
description="A system message that will always be followed by the LLM",
)
completion_options: BaseCompletionOptions = Field(
default=BaseCompletionOptions(),
description="Default options for completion. These will be overriden by any options set for a specific model.",
)
slash_commands: Optional[List[SlashCommand]] = Field(
default=[],
description="An array of slash commands that let you map custom Steps to a shortcut.",
)
custom_commands: Optional[List[CustomCommand]] = Field(
default=[
CustomCommand(
name="test",
description="This is an example custom command. Use /config to edit it and create more",
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.",
)
],
description="An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
)
context_providers: List[ContextProviderWithParams] = Field(
default=[],
description="A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
)
user_token: Optional[str] = Field(
default=None, description="An optional token to identify the user."
)
data_server_url: Optional[str] = Field(
default="https://us-west1-autodebug.cloudfunctions.net",
description="The URL of the server where development data is sent. No data is sent unless you have explicitly set the `user_token` property to a valid token that we have shared.",
)
disable_summaries: Optional[bool] = Field(
default=False,
description="If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.",
)
disable_indexing: Optional[bool] = Field(
default=False,
description="If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.",
)
retrieval_settings: Optional[RetrievalSettings] = Field(
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
config.model_roles.chat = title
config.model_roles.edit = title
config.model_roles.summarize = title
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:
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
class ContinueConfig(BaseModel):
"""
Continue can be deeply customized by editing the `ContinueConfig` object in `~/.continue/config.py` (`%userprofile%\\.continue\\config.py` for Windows) on your machine. This class is instantiated from the config file for every new session.
"""
steps_on_startup: List[Step] = Field(
default=[],
description="Steps that will be automatically run at the beginning of a new session",
)
disallowed_steps: Optional[List[str]] = Field(
default=[],
description="Steps that are not allowed to be run, and will be skipped if attempted",
)
allow_anonymous_telemetry: bool = Field(
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[LLM] = Field(
default=[
OpenAIFreeTrial(
title="GPT-4 (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,
description="A system message that will always be followed by the LLM",
)
completion_options: BaseCompletionOptions = Field(
default=BaseCompletionOptions(),
description="Options for the completion endpoint. Read more about the completion options in the documentation.",
)
custom_commands: Optional[List[CustomCommand]] = Field(
default=[
CustomCommand(
name="test",
description="This is an example custom command. Use /config to edit it and create more",
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.",
)
],
description="An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
)
slash_commands: Optional[List[SlashCommand]] = Field(
default=[],
description="An array of slash commands that let you map custom Steps to a shortcut.",
)
on_traceback: Optional[Step] = Field(
default=None,
description="The step that will be run when a traceback is detected (when you use the shortcut cmd+shift+R)",
)
policy_override: Optional[Policy] = Field(
default=None,
description="A Policy object that can be used to override the default behavior of Continue, for example in order to build custom agents that take multiple steps at a time.",
)
context_providers: List[ContextProvider] = Field(
default=[],
description="A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
)
user_token: Optional[str] = Field(
default=None, description="An optional token to identify the user."
)
data_server_url: Optional[str] = Field(
default="https://us-west1-autodebug.cloudfunctions.net",
description="The URL of the server where development data is sent. No data is sent unless you have explicitly set the `user_token` property to a valid token that we have shared.",
)
disable_summaries: Optional[bool] = Field(
default=False,
description="If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.",
)
disable_indexing: bool = Field(
default=False,
description="If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.",
)
retrieval_settings: Optional[RetrievalSettings] = Field(
default=RetrievalSettings(),
description="Settings for the retrieval system. Read more about the retrieval system in the documentation.",
)
llm_request_hook: Optional[Callable[[str, str], Any]] = Field(
default=None,
description="A function that will be called before every request to the LLM. It will be passed the model used (str) and the exact prompt that is sent to the LLM (str).",
)
def dict(self, *args, **kwargs):
original_dict = super().dict(*args, **kwargs)
if "llm_request_hook" in original_dict:
del original_dict["llm_request_hook"]
return original_dict
@staticmethod
def from_serialized_config(config: SerializedContinueConfig) -> "ContinueConfig":
context_providers = [
CONTEXT_PROVIDER_NAME_TO_CLASS[provider.name](**provider.params)
for provider in config.context_providers
]
return ContinueConfig(
disallowed_steps=config.disallowed_steps,
allow_anonymous_telemetry=config.allow_anonymous_telemetry
if config.allow_anonymous_telemetry is not None
else True,
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,
custom_commands=config.custom_commands,
slash_commands=config.slash_commands,
context_providers=context_providers,
user_token=config.user_token,
data_server_url=config.data_server_url,
disable_summaries=config.disable_summaries,
disable_indexing=config.disable_indexing or False,
retrieval_settings=config.retrieval_settings,
)
@staticmethod
def modifiers_from_filepath(
filepath: str,
) -> Tuple[Optional[Callable], Optional[Callable]]:
if not os.path.exists(filepath):
return None, None
try:
if spec := importlib.util.spec_from_file_location("config", filepath):
config = importlib.util.module_from_spec(spec)
if spec.loader:
spec.loader.exec_module(config)
modify_config = None
modify_json = None
if hasattr(config, "modify_config"):
modify_config = config.modify_config
if hasattr(config, "modify_json"):
modify_json = config.modify_json
return modify_config, modify_json
except Exception as e:
logger.warning(f"Failed to load config modifier from {filepath}: {e}")
return None, None
return None, None
@staticmethod
def from_filepath(filepath: str, retry: bool = True) -> "ContinueConfig":
if filepath.endswith(".json"):
try:
contents = open(filepath).read()
if contents.strip() == "":
raise ValueError("Empty config file")
serialized_config = json.loads(contents)
except json.JSONDecodeError as e:
raise e
except ValueError as e:
logger.warning(f"Found empty config.json at {filepath}: {e}")
with open(filepath, "w") as f:
f.write(default_config_json)
serialized_config = json.load(open(filepath))
serialized = SerializedContinueConfig(**serialized_config)
modify_config, modify_json = ContinueConfig.modifiers_from_filepath(
filepath[: -len(".json")] + ".py"
)
if modify_json:
try:
serialized = modify_json(serialized)
except Exception as e:
logger.warning(f"Failed to modify config: {e}")
final_config = ContinueConfig.from_serialized_config(serialized)
if modify_config:
try:
final_config = modify_config(final_config)
except Exception as e:
logger.warning(f"Failed to modify config: {e}")
return final_config
# Use importlib to load the config file config.py at the given path
if spec := importlib.util.spec_from_file_location("config", filepath):
config = importlib.util.module_from_spec(spec)
if spec.loader:
spec.loader.exec_module(config)
return config.config
raise Exception(f"Failed to load config from {filepath}")
@staticmethod
def load_default() -> "ContinueConfig":
json_path = os.path.join(getGlobalFolderPath(), "config.json")
if not os.path.exists(json_path):
# MIGRATE FROM OLD CONFIG FORMAT TO JSON
def move_config_to_old():
old_path = py_path.replace(".py", ".py.old")
if os.path.exists(old_path):
os.remove(old_path)
os.rename(py_path, old_path)
py_path = getConfigFilePath()
try:
# If they have pre-existing old config.py this will work
config = ContinueConfig.from_filepath(py_path)
if os.path.exists(json_path):
os.remove(json_path)
with open(json_path, "w") as f:
json.dump(
config.to_serialized_continue_config().dict(
exclude_none=True, exclude_defaults=True
),
f,
indent=2,
)
# Rename config.py to config.old.py
move_config_to_old()
return config
except Exception as e:
logger.warning(f"Failed to load config from {py_path}: {e}")
with open(json_path, "w") as f:
f.write(default_config_json)
# Rename config.py to config.old.py
move_config_to_old()
return ContinueConfig.load_default()
# The second time and thereafter, load from the json file
config = ContinueConfig.from_filepath(json_path)
return config
def get_slash_command_descriptions(self) -> List[SlashCommandDescription]:
custom_commands = (
list(
map(
lambda x: x.slash_command_description(),
self.custom_commands or [],
)
)
or []
)
slash_commands = (
list(
map(
lambda x: x.slash_command_description(),
self.slash_commands or [],
)
)
or []
)
cmds = custom_commands + slash_commands
cmds.sort(key=lambda x: x.name == "edit", reverse=True)
return cmds
def get_context_provider_descriptions(self) -> List[ContextProviderDescription]:
"""
Returns a list of ContextProviderDescriptions
"""
return [
provider.get_description()
for provider in self.context_providers
if provider.title != "code" # Code isn't used with '@'
] + [
ContextProviderDescription(
title="file",
display_title="Files",
description="Type to search the workspace",
dynamic=False,
requires_query=False,
)
]
def to_serialized_continue_config(self) -> SerializedContinueConfig:
# For migration purposes
slash_commands = []
for slash_command in self.slash_commands or []:
if not isinstance(slash_command.step, str):
slash_command.step = slash_command.step.__class__.__name__
slash_commands.append(slash_command)
return SerializedContinueConfig(
disallowed_steps=self.disallowed_steps,
allow_anonymous_telemetry=self.allow_anonymous_telemetry,
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,
custom_commands=self.custom_commands,
slash_commands=slash_commands,
context_providers=[
ContextProviderWithParams(
name=cast(ContextProviderName, provider.title),
params=provider.dict(exclude_none=True, exclude_defaults=True),
)
for provider in self.context_providers
if provider.title in CONTEXT_PROVIDER_NAME_TO_CLASS
],
user_token=self.user_token,
data_server_url=self.data_server_url,
disable_summaries=self.disable_summaries,
disable_indexing=self.disable_indexing,
retrieval_settings=self.retrieval_settings,
)
@staticmethod
def create_llm(
completion_options: BaseCompletionOptions, model: ModelDescription
) -> LLM:
model_class = MODEL_CLASSES[MODEL_PROVIDER_TO_MODEL_CLASS[model.provider]]
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 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"] = options
kwargs["template_messages"] = autodetect_template_function(
model.model, model.template
)
kwargs["prompt_templates"] = autodetect_prompt_templates(
model.model, model.template
)
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: LLM):
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]
]
return Models(
default=default,
chat=chat,
edit=edit,
summarize=summarize,
saved=saved,
)

View file

@ -1,43 +0,0 @@
from typing import Dict, Literal
from ...plugins.context_providers.diff import DiffContextProvider
from ...plugins.context_providers.filetree import FileTreeContextProvider
from ...plugins.context_providers.github import GitHubIssuesContextProvider
from ...plugins.context_providers.google import GoogleContextProvider
from ...plugins.context_providers.open_tabs import OpenTabsContextProvider
from ...plugins.context_providers.search import SearchContextProvider
from ...plugins.context_providers.terminal import TerminalContextProvider
from ...plugins.context_providers.url import URLContextProvider
ContextProviderName = Literal[
"diff",
"github",
"terminal",
"open",
"google",
"search",
"url",
"tree",
]
CONTEXT_PROVIDER_NAME_TO_CLASS = {
"diff": DiffContextProvider,
"github": GitHubIssuesContextProvider,
"terminal": TerminalContextProvider,
"open": OpenTabsContextProvider,
"google": GoogleContextProvider,
"search": SearchContextProvider,
"url": URLContextProvider,
"tree": FileTreeContextProvider,
}
CLASS_TO_CONTEXT_PROVIDER_NAME: Dict[str, ContextProviderName] = {
"DiffContextProvider": "diff",
"GitHubIssuesContextProvider": "github",
"TerminalContextProvider": "terminal",
"OpenTabsContextProvider": "open",
"GoogleContextProvider": "google",
"SearchContextProvider": "search",
"URLContextProvider": "url",
"FileTreeContextProvider": "tree",
}

View file

@ -1,241 +0,0 @@
from typing import Any, Dict, Literal, Optional
from ...libs.llm.prompts.chat import (
anthropic_template_messages,
chatml_template_messages,
deepseek_template_messages,
llama2_template_messages,
phind_template_messages,
template_alpaca_messages,
zephyr_template_messages,
neuralchat_template_messages,
)
from ...libs.llm.prompts.edit import (
alpaca_edit_prompt,
codellama_edit_prompt,
deepseek_edit_prompt,
phind_edit_prompt,
simplest_edit_prompt,
zephyr_edit_prompt,
neuralchat_edit_prompt,
)
STEP_NAMES = [
"AnswerQuestionChroma",
"GenerateShellCommandStep",
"EditHighlightedCodeStep",
"ShareSessionStep",
"CommentCodeStep",
"ClearHistoryStep",
"StackOverflowStep",
"OpenConfigStep",
"DraftIssueStep",
]
StepName = Literal[
"AnswerQuestionChroma",
"EditHighlightedCodeStep",
"ShareSessionStep",
"CommentCodeStep",
"ClearHistoryStep",
"StackOverflowStep",
"OpenConfigStep",
"GenerateShellCommandStep",
"DraftIssueStep",
]
TemplateType = Literal[
"llama2", "alpaca", "zephyr", "phind", "anthropic", "chatml", "deepseek", "neural-chat"
]
def autodetect_template_type(model: str) -> Optional[TemplateType]:
lower = model.lower()
if "gpt" in lower or "chat-bison" in lower or "pplx" in lower:
return None
if "phind" in lower:
return "phind"
if "llama" in lower:
return "llama2"
if "zephyr" in lower:
return "zephyr"
if "claude" in lower:
return "anthropic"
if "alpaca" in lower or "wizard" in lower:
return "alpaca"
if "mistral" in lower:
return "llama2"
if "deepseek" in lower:
return "deepseek"
if "neural-chat" in lower:
return "neural-chat"
return "chatml"
def autodetect_template_function(
model: str, explicit_template: Optional[TemplateType] = None
):
if template_type := explicit_template or autodetect_template_type(model):
mapping: Dict[TemplateType, Any] = {
"llama2": llama2_template_messages,
"alpaca": template_alpaca_messages,
"phind": phind_template_messages,
"zephyr": zephyr_template_messages,
"anthropic": anthropic_template_messages,
"chatml": chatml_template_messages,
"deepseek": deepseek_template_messages,
"neural-chat": neuralchat_template_messages
}
return mapping[template_type]
return None
def autodetect_prompt_templates(
model: str, explicit_template: Optional[TemplateType] = None
):
template_type = explicit_template or autodetect_template_type(model)
templates = {}
edit_template = None
if template_type == "phind":
edit_template = phind_edit_prompt
elif template_type == "zephyr":
edit_template = zephyr_edit_prompt
elif template_type == "llama2":
edit_template = codellama_edit_prompt
elif template_type == "alpaca":
edit_template = alpaca_edit_prompt
elif template_type == "deepseek":
edit_template = deepseek_edit_prompt
elif template_type == "neural-chat":
edit_template = neuralchat_edit_prompt
elif template_type is not None:
edit_template = simplest_edit_prompt
if edit_template is not None:
templates["edit"] = edit_template
return templates
ModelProvider = Literal[
"openai",
"free-trial",
"openai-aiohttp",
"anthropic",
"together",
"ollama",
"huggingface-tgi",
"huggingface-inference-api",
"llama.cpp",
"replicate",
"text-gen-webui",
"google-palm",
"lmstudio",
"llamafile",
]
MODEL_PROVIDER_TO_MODEL_CLASS = {
"openai": "OpenAI",
"free-trial": "OpenAIFreeTrial",
"openai-aiohttp": "GGML",
"anthropic": "AnthropicLLM",
"together": "TogetherLLM",
"ollama": "Ollama",
"huggingface-tgi": "HuggingFaceTGI",
"huggingface-inference-api": "HuggingFaceInferenceAPI",
"llama.cpp": "LlamaCpp",
"replicate": "ReplicateLLM",
"text-gen-webui": "TextGenWebUI",
"google-palm": "GooglePaLMAPI",
"lmstudio": "LMStudio",
"llamafile": "Llamafile",
}
MODEL_CLASS_TO_MODEL_PROVIDER: Dict[str, ModelProvider] = {
"OpenAI": "openai",
"OpenAIFreeTrial": "free-trial",
"AnthropicLLM": "anthropic",
"TogetherLLM": "together",
"Ollama": "ollama",
"HuggingFaceTGI": "huggingface-tgi",
"HuggingFaceInferenceAPI": "huggingface-inference-api",
"LlamaCpp": "llama.cpp",
"ReplicateLLM": "replicate",
"TextGenWebUI": "text-gen-webui",
"GooglePaLMAPI": "google-palm",
"LMStudio": "lmstudio",
"Llamafile": "llamafile",
}
MODELS = [
# OpenAI
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview",
# Open-Source
"mistral-7b",
"llama2-7b",
"llama2-13b",
"codellama-7b",
"codellama-13b",
"codellama-34b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
"wizardcoder-34b",
"zephyr-7b",
"codeup-13b",
"deepseek-1b",
"deepseek-7b",
"deepseek-33b",
"neural-chat-7b"
# Anthropic
"claude-2",
# Google PaLM
"chat-bison-001",
]
ModelName = Literal[
# OpenAI
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview",
# Open-Source
"mistral-7b",
"llama2-7b",
"llama2-13b",
"codellama-7b",
"codellama-13b",
"codellama-34b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
"wizardcoder-34b",
"zephyr-7b",
"codeup-13b",
"deepseek-1b",
"deepseek-7b",
"deepseek-33b",
"neural-chat-7b",
# Anthropic
"claude-2",
# Google PaLM
"chat-bison-001",
]

View file

@ -1,23 +0,0 @@
from ...plugins.steps.clear_history import ClearHistoryStep
from ...plugins.steps.cmd import GenerateShellCommandStep
from ...plugins.steps.codebase import AnswerQuestionChroma
from ...plugins.steps.comment_code import CommentCodeStep
from ...plugins.steps.draft_issue import DraftIssueStep
from ...plugins.steps.main import EditHighlightedCodeStep
from ...plugins.steps.on_traceback import DefaultOnTracebackStep
from ...plugins.steps.open_config import OpenConfigStep
from ...plugins.steps.share_session import ShareSessionStep
from ...plugins.steps.stack_overflow import StackOverflowStep
step_name_to_step_class = {
"EditHighlightedCodeStep": EditHighlightedCodeStep,
"CommentCodeStep": CommentCodeStep,
"DefaultOnTracebackStep": DefaultOnTracebackStep,
"ClearHistoryStep": ClearHistoryStep,
"OpenConfigStep": OpenConfigStep,
"AnswerQuestionChroma": AnswerQuestionChroma,
"GenerateShellCommandStep": GenerateShellCommandStep,
"ShareSessionStep": ShareSessionStep,
"StackOverflowStep": StackOverflowStep,
"DraftIssueStep": DraftIssueStep,
}

View file

@ -1,487 +0,0 @@
import asyncio
import time
from abc import abstractmethod
from typing import Any, Awaitable, Callable, List, Optional
from meilisearch_python_async import Client
from pydantic import BaseModel, Field
from ..libs.util.create_async_task import create_async_task
from ..libs.util.devdata import dev_data_logger
from ..libs.util.logging import logger
from ..libs.util.paths import migrate
from ..libs.util.telemetry import posthog_logger
from ..server.global_config import global_config
from ..server.meilisearch_server import (
check_meilisearch_running,
get_meilisearch_url,
poll_meilisearch_running,
remove_meilisearch_disallowed_chars,
restart_meilisearch,
start_meilisearch,
)
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from .main import (
ChatMessage,
ContextItem,
ContextItemDescription,
ContextItemId,
ContextProviderDescription,
)
class ContinueSDK(BaseModel):
"""To avoid circular imports"""
...
SEARCH_INDEX_NAME = "continue_context_items"
class ContextProvider(BaseModel):
"""
The ContextProvider class is a plugin that lets you provide new information to the LLM by typing '@'.
When you type '@', the context provider will be asked to populate a list of options.
These options will be updated on each keystroke.
When you hit enter on an option, the context provider will add that item to the autopilot's list of context (which is all stored in the ContextManager object).
"""
title: str = Field(
...,
description="The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.",
)
ide: Any = None
delete_documents: Callable[[List[str]], Awaitable] | None = Field(
None, description="Function to delete documents"
)
update_documents: Callable[[List[ContextItem], str], Awaitable] | None = Field(
None, description="Function to update documents"
)
display_title: str = Field(
...,
description="The display title of the ContextProvider shown in the dropdown menu",
)
description: str = Field(
...,
description="A description of the ContextProvider displayed in the dropdown menu",
)
dynamic: bool = Field(
..., description="Indicates whether the ContextProvider is dynamic"
)
requires_query: bool = Field(
False,
description="Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.",
)
selected_items: List[ContextItem] = Field(
[], description="List of selected items in the ContextProvider"
)
class Config:
arbitrary_types_allowed = True
exclude = {"ide", "delete_documents", "update_documents"}
def get_description(self) -> ContextProviderDescription:
return ContextProviderDescription(
title=self.title,
display_title=self.display_title,
description=self.description,
dynamic=self.dynamic,
requires_query=self.requires_query,
)
def dict(self, *args, **kwargs):
original_dict = super().dict(*args, **kwargs)
original_dict.pop("ide", None)
original_dict.pop("delete_documents", None)
original_dict.pop("update_documents", None)
return original_dict
async def start(
self, ide: AbstractIdeProtocolServer, delete_documents, update_documents
):
"""
Starts the context provider.
Default implementation sets the sdk.
"""
self.ide = ide
self.delete_documents = delete_documents
self.update_documents = update_documents
async def get_selected_items(self) -> List[ContextItem]:
"""
Returns all of the selected ContextItems.
Default implementation simply returns self.selected_items.
Other implementations may add an async processing step.
"""
return self.selected_items
@abstractmethod
async def provide_context_items(self, workspace_dir: str) -> List[ContextItem]:
"""
Provide documents for search index. This is run on startup.
This is the only method that must be implemented.
"""
async def get_chat_message(self, item: ContextItem) -> ChatMessage:
"""Returns the ChatMessage for the given ContextItem."""
return ChatMessage(
role="user",
content=f"{item.description.name}: {item.description.description}\n\n{item.content}",
summary=item.description.description,
)
async def get_item(self, id: ContextItemId, query: str) -> Optional[ContextItem]:
"""
Returns the ContextItem with the given id.
Default implementation uses the search index to get the item.
"""
async with Client(get_meilisearch_url()) as search_client:
try:
result = await search_client.index(SEARCH_INDEX_NAME).get_document(
id.to_string()
)
return ContextItem(
description=ContextItemDescription(
name=result["name"], description=result["description"], id=id
),
content=result["content"],
)
except Exception as e:
logger.warning(f"Error while retrieving document from meilisearch: {e}")
return None
async def clear_context(self):
"""
Clears all context.
Default implementation simply clears the selected items.
"""
self.selected_items = []
async def add_context_item(self, id: ContextItemId, query: str):
"""
Adds the given ContextItem to the list of ContextItems.
Default implementation simply appends the item, not allowing duplicates.
This method also allows you not to have to load all of the information until an item is selected.
"""
# Don't add duplicate context
for item in self.selected_items:
if item.description.id.item_id == id.item_id:
return
if new_item := await self.get_item(id, query):
self.selected_items.append(new_item)
async def preview_contents(self, id: ContextItemId):
"""
Open a virtual file or otherwise preview the contents of the context provider in the IDE
"""
if item := next(
filter(lambda x: x.description.id == id, self.selected_items), None
):
await self.ide.showVirtualFile(item.description.name, item.content)
class ContextManager:
"""
The context manager is responsible for storing the context to be passed to the LLM, including
- ContextItems (highlighted code, GitHub Issues, etc.)
- ChatMessages in the history
- System Message
- Functions
It is responsible for compiling all of this information into a single prompt without exceeding the token limit.
"""
async def get_chat_messages(self, items: List[ContextItem]) -> List[ChatMessage]:
"""
Returns chat messages from each provider.
"""
tasks = []
msgs = []
for item in items:
if item.description.id.provider_title in self.context_providers:
tasks.append(
self.context_providers[
item.description.id.provider_title
].get_chat_message(item)
)
else:
msgs.append(
ChatMessage(
role="user",
content=item.content,
summary=item.description.description,
)
)
return (await asyncio.gather(*tasks)) + msgs
def __init__(self):
self.context_providers = {}
self.provider_titles = set()
async def start(
self,
context_providers: List[ContextProvider],
ide: AbstractIdeProtocolServer,
only_reloading: bool = False,
disable_indexing: bool = False,
):
"""
Starts the context manager.
"""
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
}
self.provider_titles = {provider.title for provider in context_providers}
for provider in context_providers:
await provider.start(
ide,
ContextManager.delete_documents,
ContextManager.update_documents,
)
async def on_err(e):
logger.warning(f"Error loading meilisearch index: {e}")
# Start MeiliSearch in the background without blocking
async def load_index(providers_to_load: List[ContextProvider]):
running = await check_meilisearch_running()
if not running:
await start_meilisearch(global_config.meilisearch_url)
try:
await asyncio.wait_for(poll_meilisearch_running(), timeout=20)
except asyncio.TimeoutError:
logger.warning(
"Meilisearch did not start in less than 20 seconds. Stopping polling."
)
return
ti = time.time()
await self.load_index(
ide.workspace_directory, providers_to_load=providers_to_load
)
logger.info(f"Loaded Meilisearch index in {time.time() - ti:.3f} seconds")
providers_to_load = (
list(new_context_providers.values())
if only_reloading
else context_providers
)
if not disable_indexing:
create_async_task(load_index(providers_to_load), on_err)
@staticmethod
async def update_documents(context_items: List[ContextItem], workspace_dir: str):
"""
Updates the documents in the search index.
"""
documents = [
{
"id": item.description.id.to_string(),
"name": item.description.name,
"description": item.description.description,
"content": item.content,
"workspace_dir": workspace_dir,
"provider_name": item.description.id.provider_title,
}
for item in context_items
]
async with Client(get_meilisearch_url()) as search_client:
async def add_docs():
index = await search_client.get_index(SEARCH_INDEX_NAME)
await index.add_documents(documents or [])
try:
await asyncio.wait_for(add_docs(), timeout=20)
except asyncio.TimeoutError:
logger.warning("Failed to add document to meilisearch in 20 seconds")
except Exception as e:
logger.warning(f"Error adding document to meilisearch: {e}")
@staticmethod
async def delete_documents(ids):
"""
Deletes the documents in the search index.
"""
async with Client(get_meilisearch_url()) as search_client:
try:
await asyncio.wait_for(
search_client.index(SEARCH_INDEX_NAME).delete_documents(ids),
timeout=20,
)
except asyncio.TimeoutError:
logger.warning(
"Failed to delete document from meilisearch in 20 seconds"
)
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,
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
# The index is currently shared by all workspaces
# Check if need to migrate to new id format
# If so, delete the index before recreating
async def migrate_fn():
await search_client.delete_index_if_exists(SEARCH_INDEX_NAME)
await migrate(
"meilisearch_context_items_001",
migrate_fn,
)
await search_client.create_index(SEARCH_INDEX_NAME)
globalSearchIndex = await search_client.get_index(SEARCH_INDEX_NAME)
await globalSearchIndex.update_ranking_rules(
["attribute", "words", "typo", "proximity", "sort", "exactness"]
)
await globalSearchIndex.update_searchable_attributes(
["name", "description"]
)
await globalSearchIndex.update_filterable_attributes(
["workspace_dir", "provider_name"]
)
async def load_context_provider(provider: ContextProvider):
context_items = await provider.provide_context_items(workspace_dir)
documents = [
{
"id": item.description.id.to_string()
+ remove_meilisearch_disallowed_chars(workspace_dir),
"name": item.description.name,
"description": item.description.description,
"content": item.content,
"workspace_dir": workspace_dir,
"provider_name": provider.title,
}
for item in context_items
]
if len(documents) > 0:
await globalSearchIndex.add_documents(documents)
return len(documents)
async def safe_load(provider: ContextProvider):
try:
await asyncio.wait_for(
load_context_provider(provider), timeout=20
)
except asyncio.TimeoutError:
logger.warning(
f"Failed to add documents to meilisearch for context provider {provider.__class__.__name__} in 20 seconds"
)
return
except Exception as e:
logger.warning(
f"Error adding documents to meilisearch for context provider {provider.__class__.__name__}: {e}"
)
return
# logger.info(
# f"Loaded {num_documents} documents into meilisearch in {tf - ti} seconds for context provider {provider.title}"
# )
tasks = [
safe_load(provider)
for _, provider in (
{provider.title: provider for provider in providers_to_load}
if providers_to_load
else self.context_providers
).items()
]
await asyncio.wait_for(asyncio.gather(*tasks), timeout=20)
except Exception as e:
logger.debug(f"Error loading meilisearch index: {e}")
if should_retry:
try:
await restart_meilisearch()
await asyncio.wait_for(poll_meilisearch_running(), timeout=20)
except asyncio.TimeoutError:
logger.warning(
"Meilisearch did not restart in less than 20 seconds. Stopping polling."
)
except Exception as e:
logger.warning(f"Error restarting meilisearch: {e}")
await self.load_index(workspace_dir, False)
async def get_context_item(self, id: str, query: str) -> Optional[ContextItem]:
"""
Returns the ContextItem with the given id.
"""
item_id: ContextItemId = ContextItemId.from_string(id)
if item_id.provider_title not in self.provider_titles:
raise ValueError(
f"Context provider with title {item_id.provider_title} not found"
)
posthog_logger.capture_event(
"select_context_item",
{
"provider_title": item_id.provider_title,
"item_id": item_id.item_id,
"query": query,
},
)
dev_data_logger.capture(
"select_context_item",
{
"provider_title": item_id.provider_title,
"item_id": item_id.item_id,
"query": query,
},
)
return await self.context_providers[item_id.provider_title].get_item(
item_id, query
)
async def preview_context_item(self, id: str):
"""
Opens a virtual file or otherwise previews the contents of the context provider in the IDE.
"""
item_id: ContextItemId = ContextItemId.from_string(id)
if item_id.provider_title not in self.provider_titles:
raise ValueError(
f"Context provider with title {item_id.provider_title} not found"
)
await self.context_providers[item_id.provider_title].preview_contents(item_id)
"""
Should define "ArgsTransformer" and "PromptTransformer" classes for the different LLMs. A standard way for them to ingest the
same format of prompts so you don't have to redo all of this logic.
"""

View file

@ -1,31 +0,0 @@
import os
from dotenv import load_dotenv
def get_env_var(var_name: str):
load_dotenv()
return os.getenv(var_name)
def make_sure_env_exists():
if not os.path.exists(".env"):
with open(".env", "w") as f:
f.write("")
def save_env_var(var_name: str, var_value: str):
make_sure_env_exists()
with open(".env", "r") as f:
lines = f.readlines()
with open(".env", "w") as f:
values = {}
for line in lines:
key, value = line.split("=")
value = value.replace('"', "")
values[key] = value
values[var_name] = var_value
for key, value in values.items():
f.write(f'{key}="{value}"\n')

View file

@ -1,416 +0,0 @@
import asyncio
import threading
from typing import List, Literal, Optional
import aiohttp
from pydantic import BaseModel
from ..models.filesystem import RangeInFile
from ..models.main import Position, Range
def filepath_to_uri(filename: str) -> str:
return f"file://{filename}"
def uri_to_filepath(uri: str) -> str:
if uri.startswith("file://"):
return uri[7:]
else:
return uri
PORT = 8099
class LSPClient:
ready: bool = False
lock: asyncio.Lock = asyncio.Lock()
def __init__(self, host: str, port: int, workspace_paths: List[str]):
self.host = host
self.port = port
self.session = aiohttp.ClientSession()
self.next_id = 0
self.workspace_paths = workspace_paths
async def connect(self):
print("Connecting")
self.ws = await self.session.ws_connect(f"ws://{self.host}:{self.port}/")
print("Connected")
self.ready = True
async def send(self, data):
await self.ws.send_json(data)
async def recv(self):
await self.lock.acquire()
try:
return await self.ws.receive_json()
finally:
self.lock.release()
async def close(self):
await self.ws.close()
await self.session.close()
async def call_method(self, method_name, **kwargs):
body = {
"jsonrpc": "2.0",
"id": self.next_id,
"method": method_name,
"params": kwargs,
}
self.next_id += 1
await self.send(body)
response = await self.recv()
return response
async def initialize(self):
initialization_args = {
"capabilities": {
"textDocument": {
"codeAction": {"dynamicRegistration": True},
"codeLens": {"dynamicRegistration": True},
"colorProvider": {"dynamicRegistration": True},
"completion": {
"completionItem": {
"commitCharactersSupport": True,
"documentationFormat": ["markdown", "plaintext"],
"snippetSupport": True,
},
"completionItemKind": {
"valueSet": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
]
},
"contextSupport": True,
"dynamicRegistration": True,
},
"definition": {"dynamicRegistration": True},
"documentHighlight": {"dynamicRegistration": True},
"documentLink": {"dynamicRegistration": True},
"documentSymbol": {
"dynamicRegistration": True,
"symbolKind": {
"valueSet": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
]
},
},
"formatting": {"dynamicRegistration": True},
"hover": {
"contentFormat": ["markdown", "plaintext"],
"dynamicRegistration": True,
},
"implementation": {"dynamicRegistration": True},
"onTypeFormatting": {"dynamicRegistration": True},
"publishDiagnostics": {"relatedInformation": True},
"rangeFormatting": {"dynamicRegistration": True},
"references": {"dynamicRegistration": True},
"rename": {"dynamicRegistration": True},
"signatureHelp": {
"dynamicRegistration": True,
"signatureInformation": {
"documentationFormat": ["markdown", "plaintext"]
},
},
"synchronization": {
"didSave": True,
"dynamicRegistration": True,
"willSave": True,
"willSaveWaitUntil": True,
},
"typeDefinition": {"dynamicRegistration": True},
},
"workspace": {
"applyEdit": True,
"configuration": True,
"didChangeConfiguration": {"dynamicRegistration": True},
"didChangeWatchedFiles": {"dynamicRegistration": True},
"executeCommand": {"dynamicRegistration": True},
"symbol": {
"dynamicRegistration": True,
"symbolKind": {
"valueSet": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
]
},
},
"workspaceEdit": {"documentChanges": True},
"workspaceFolders": True,
},
},
"processId": 1234,
"rootPath": None,
"rootUri": filepath_to_uri(self.workspace_paths[0]),
"initializationOptions": {},
"trace": "off",
"workspaceFolders": [
{
"uri": filepath_to_uri(workspacePath),
"name": workspacePath.split("/")[-1],
}
for workspacePath in self.workspace_paths
],
}
return await self.call_method("initialize", **initialization_args)
async def goto_definition(self, filepath: str, position: Position):
return await self.call_method(
"textDocument/definition",
textDocument={"uri": filepath_to_uri(filepath)},
position=position.dict(),
)
async def document_symbol(self, filepath: str):
return await self.call_method(
"textDocument/documentSymbol",
textDocument={"uri": filepath_to_uri(filepath)},
)
async def find_references(
self, filepath: str, position: Position, include_declaration: bool = False
):
return await self.call_method(
"textDocument/references",
textDocument={"uri": filepath_to_uri(filepath)},
position=position.dict(),
context={"includeDeclaration": include_declaration},
)
async def folding_range(self, filepath: str):
response = await self.call_method(
"textDocument/foldingRange",
textDocument={"uri": filepath_to_uri(filepath)},
)
return response["result"]
async def start_language_server() -> threading.Thread:
"""Manually start the python language server. Not used currently."""
raise NotImplementedError()
# try:
# kill_proc(PORT)
# thread = threading.Thread(
# target=start_ws_lang_server,
# args=(PORT, False, PythonLSPServer),
# )
# thread.daemon = True
# thread.start()
# except Exception as e:
# logger.warning("Could not start TCP server: %s", e)
# await asyncio.sleep(2)
# return thread
class DocumentSymbol(BaseModel):
name: str
containerName: Optional[str] = None
kind: int
location: RangeInFile
class FoldingRange(BaseModel):
range: Range
kind: Optional[Literal["comment", "imports", "region"]] = None
class ContinueLSPClient(BaseModel):
workspace_dir: str
lsp_client: LSPClient
lsp_thread: Optional[threading.Thread] = None
@property
def ready(self):
if self.lsp_client is None:
return False
return self.lsp_client.ready
class Config:
arbitrary_types_allowed = True
def dict(self, **kwargs):
original_dict = super().dict(**kwargs)
original_dict.pop("lsp_client", None)
return original_dict
async def start(self):
self.lsp_thread = await start_language_server()
self.lsp_client = LSPClient("localhost", PORT, [self.workspace_dir])
await self.lsp_client.connect()
await self.lsp_client.initialize()
async def stop(self):
await self.lsp_client.close()
if self.lsp_thread:
self.lsp_thread.join()
def location_to_range_in_file(self, location):
return RangeInFile(
filepath=uri_to_filepath(location["uri"]),
range=Range.from_shorthand(
location["range"]["start"]["line"],
location["range"]["start"]["character"],
location["range"]["end"]["line"],
location["range"]["end"]["character"],
),
)
async def goto_definition(
self, position: Position, filename: str
) -> List[RangeInFile]:
response = await self.lsp_client.goto_definition(
filename,
position,
)
return [self.location_to_range_in_file(x) for x in response]
async def find_references(
self, position: Position, filename: str, include_declaration: bool = False
) -> List[RangeInFile]:
response = await self.lsp_client.find_references(
filename,
position,
include_declaration=include_declaration,
)
return [self.location_to_range_in_file(x) for x in response["result"]]
async def document_symbol(self, filepath: str) -> List:
response = await self.lsp_client.document_symbol(filepath)
return [
DocumentSymbol(
name=x["name"],
containerName=x["containerName"],
kind=x["kind"],
location=self.location_to_range_in_file(x["location"]),
)
for x in response["result"]
]
async def folding_range(self, filepath: str) -> List[FoldingRange]:
response = await self.lsp_client.folding_range(filepath)
return [
FoldingRange(
range=Range.from_shorthand(
x["startLine"],
x.get("startCharacter", 0),
x["endLine"] if "endCharacter" in x else x["endLine"] + 1,
x.get("endCharacter", 0),
),
kind=x.get("kind"),
)
for x in response
]
async def get_enclosing_folding_range_of_position(
self, position: Position, filepath: str
) -> Optional[FoldingRange]:
ranges = await self.folding_range(filepath)
max_start_position = Position(line=0, character=0)
max_range = None
for r in ranges:
if r.range.contains(position):
if r.range.start > max_start_position:
max_start_position = r.range.start
max_range = r
return max_range
async def get_enclosing_folding_range(
self, range_in_file: RangeInFile
) -> Optional[FoldingRange]:
ranges = await self.folding_range(range_in_file.filepath)
max_start_position = Position(line=0, character=0)
max_range = None
for r in ranges:
if r.range.contains(range_in_file.range.start) and r.range.contains(
range_in_file.range.end
):
if r.range.start > max_start_position:
max_start_position = r.range.start
max_range = r
return max_range

View file

@ -1,447 +0,0 @@
import json
from typing import Any, AsyncGenerator, Dict, List, Literal, Optional, Union, cast
from pydantic import BaseModel, Field, validator
from pydantic.schema import schema
from ..models.main import ContinueBaseModel
from .observation import Observation
ChatMessageRole = Literal["assistant", "user", "system", "function"]
class FunctionCall(ContinueBaseModel):
name: str
arguments: str
class ChatMessage(ContinueBaseModel):
role: ChatMessageRole
content: str = ""
name: Optional[str] = None
# A summary for pruning chat context to fit context window. Often the Step name.
summary: str = Field(default=None, title="Summary")
function_call: Optional[FunctionCall] = None
@validator("summary", pre=True, always=True)
def summary_is_content(cls, summary, values):
if summary is None:
return values.get("content", "")
return summary
def to_dict(self, with_functions: bool = False) -> Dict[str, str]:
d = self.dict()
del d["summary"]
if d["function_call"] is not None:
d["function_call"]["name"] = d["function_call"]["name"].replace(" ", "")
if d["content"] is None:
d["content"] = ""
for key, value in list(d.items()):
if value is None:
del d[key]
if not with_functions:
if d["role"] == "function":
d["role"] = "assistant"
if "name" in d:
del d["name"]
if "function_call" in d:
del d["function_call"]
return d
def resolve_refs(schema_data):
def traverse(obj):
if isinstance(obj, dict):
if "$ref" in obj:
ref = obj["$ref"]
parts = ref.split("/")
ref_obj = schema_data
for part in parts[1:]:
ref_obj = ref_obj[part]
return traverse(ref_obj)
else:
for key, value in obj.items():
obj[key] = traverse(value)
elif isinstance(obj, list):
for i in range(len(obj)):
obj[i] = traverse(obj[i])
return obj
return traverse(schema_data)
unincluded_parameters = [
"system_message",
"chat_context",
"manage_own_chat_context",
"hide",
"name",
"description",
]
def step_to_json_schema(step) -> Dict[str, Any]:
pydantic_class = step.__class__
schema_data = schema([pydantic_class])
resolved_schema = cast(Dict[str, Any], resolve_refs(schema_data))
parameters = resolved_schema["definitions"][pydantic_class.__name__]
for parameter in unincluded_parameters:
if parameter in parameters["properties"]:
del parameters["properties"][parameter]
return {
"name": step.name.replace(" ", ""),
"description": step.description or "",
"parameters": parameters,
}
def step_to_fn_call_arguments(step: "Step") -> str:
args = step.dict()
for parameter in unincluded_parameters:
if parameter in args:
del args[parameter]
return json.dumps(args)
class ContinueError(BaseModel):
title: str
message: str
class SetStep(BaseModel):
step_type: Optional[str] = None
name: Optional[str] = None
description: Optional[str] = None
params: Optional[Dict[str, Any]] = None
hide: Optional[bool] = None
depth: Optional[int] = None
error: Optional[ContinueError] = None
observations: Optional[List[Observation]] = None
logs: Optional[List[str]] = None
def dict(self, *args, **kwargs):
kwargs["exclude_none"] = True
return super().dict(*args, **kwargs)
class DeltaStep(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
observations: Optional[List[Observation]] = None
logs: Optional[List[str]] = None
def dict(self, *args, **kwargs):
kwargs["exclude_none"] = True
return super().dict(*args, **kwargs)
class StepDescription(BaseModel):
step_type: str
name: str
description: str
params: Dict[str, Any]
hide: bool
depth: int
error: Optional[ContinueError] = None
observations: List[Observation] = []
logs: List[str] = []
def update(self, update: "UpdateStep"):
if isinstance(update, DeltaStep):
for key, value in update.dict(exclude_none=True).items():
setattr(self, key, getattr(self, key) + value)
elif isinstance(update, SetStep):
for key, value in update.dict(exclude_none=True).items():
setattr(self, key, value)
@staticmethod
def from_empty() -> "StepDescription":
return StepDescription(
step_type="EmptyStep",
name="",
description="",
params={},
hide=True,
depth=0,
error=None,
observations=[],
logs=[],
)
class SessionUpdate(BaseModel):
index: int
update: "UpdateStep"
stop: Optional[bool] = None
class Config:
smart_union = True
def dict(self, *args, **kwargs):
d = super().dict(*args, **kwargs)
# Because the front-end doesn't see the Model type
d["delta"] = isinstance(self.update, DeltaStep)
return d
UpdateStep = Union[DeltaStep, SetStep, SessionUpdate]
SessionUpdate.update_forward_refs()
StepGenerator = AsyncGenerator[Union[str, UpdateStep, Observation], None]
AutopilotGeneratorOutput = Union[SessionUpdate, StepDescription]
AutopilotGenerator = AsyncGenerator[AutopilotGeneratorOutput, None]
class SlashCommandDescription(ContinueBaseModel):
name: str
description: str
class ContextItemId(BaseModel):
"""
A ContextItemId is a unique identifier for a ContextItem.
"""
provider_title: str
item_id: str
@validator("provider_title", "item_id")
def must_be_valid_id(cls, v):
import re
if not re.match(r"^[0-9a-zA-Z_-]*$", v):
raise ValueError(
"Both provider_title and item_id can only include characters 0-9, a-z, A-Z, -, and _"
)
return v
def to_string(self) -> str:
return f"{self.provider_title}-{self.item_id}"
def __eq__(self, other):
return (
self.provider_title == other.provider_title
and self.item_id == other.item_id
)
@staticmethod
def from_string(string: str) -> "ContextItemId":
provider_title, *rest = string.split("-")
item_id = "-".join(rest)
return ContextItemId(provider_title=provider_title, item_id=item_id)
class ContextItemDescription(BaseModel):
"""
A ContextItemDescription is a description of a ContextItem that is displayed to the user when they type '@'.
The id can be used to retrieve the ContextItem from the ContextManager.
"""
name: str
description: str
id: ContextItemId
class ContextItem(BaseModel):
"""
A ContextItem is a single item that is stored in the ContextManager.
"""
description: ContextItemDescription
content: str
@validator("content", pre=True)
def content_must_be_string(cls, v):
if v is None:
return ""
return v
editing: bool = False
editable: bool = False
class SessionInfo(ContinueBaseModel):
session_id: str
title: str
date_created: str
workspace_directory: Optional[str] = None
class ContinueConfig(ContinueBaseModel):
system_message: Optional[str]
temperature: Optional[float]
class Config:
extra = "allow"
def dict(self, **kwargs):
original_dict = super().dict(**kwargs)
original_dict.pop("policy", None)
return original_dict
class ContextProviderDescription(BaseModel):
title: str
display_title: str
description: str
dynamic: bool
requires_query: bool
class SessionState(ContinueBaseModel):
"""Full session history and important state needed for autopilot to Continue"""
history: List[StepDescription]
context_items: List[ContextItem]
# future: List = []
@staticmethod
def from_empty():
return SessionState(history=[], context_items=[])
@classmethod
def parse_obj(cls, obj: Any):
# Safety net against the client sending malformed data
valid_steps = []
for step in obj["history"]:
try:
StepDescription.parse_obj(step)
valid_steps.append(step)
except Exception:
valid_steps.append(StepDescription.from_empty())
obj["history"] = valid_steps
return super().parse_obj(obj)
class ContinueSDK:
async def run_step(self, step: "Step"):
...
class Models:
...
class Policy(ContinueBaseModel):
"""A rule that determines which step to take next"""
# Note that history is mutable, kinda sus
def next(
self, config: ContinueConfig, session_state: SessionState
) -> Optional["Step"]:
raise NotImplementedError
class Step(ContinueBaseModel):
name: str = Field(default=None, title="Name")
hide: bool = False
description: str = ""
class_name: str = "Step"
@validator("class_name", pre=True, always=True)
def class_name_is_class_name(cls, class_name):
return cls.__name__
system_message: Union[str, None] = None
chat_context: List[ChatMessage] = []
manage_own_chat_context: bool = False
class Config:
copy_on_model_validation = False
async def describe(self, models: Models) -> str:
if self.description is not None:
return self.description
return "Running step: " + self.name
def on_stop(self, sdk: ContinueSDK) -> Optional[StepGenerator]:
return None
def dict(self, *args, **kwargs):
d = super().dict(*args, **kwargs)
# Make sure description is always a string
d["description"] = self.description or ""
return d
@validator("name", pre=True, always=True)
def name_is_class_name(cls, name):
if name is None:
return cls.__name__
return name
async def run(self, sdk: ContinueSDK) -> StepGenerator:
raise NotImplementedError
async def __call__(self, sdk: ContinueSDK) -> StepGenerator:
return await self.run(sdk)
def __rshift__(self, other: "Step"):
steps = []
if isinstance(self, SequentialStep):
steps = self.steps
else:
steps.append(self)
if isinstance(other, SequentialStep):
steps += other.steps
else:
steps.append(other)
return SequentialStep(steps=steps)
class SequentialStep(Step):
steps: List[Step]
hide: bool = True
async def run(self, sdk: ContinueSDK):
for step in self.steps:
await sdk.run_step(step)
class ValidatorObservation(Observation):
passed: bool
observation: Observation
class Validator(Step):
def run(self, sdk: ContinueSDK) -> ValidatorObservation:
raise NotImplementedError
class Context:
key_value: Dict[str, Any] = {}
def set(self, key: str, value: Any):
self.key_value[key] = value
def get(self, key: str) -> Any:
return self.key_value.get(key, None)
class ContinueCustomException(Exception):
title: str
message: str
with_step: Union[Step, None]
def __init__(
self,
message: str,
title: str = "Error while running step:",
with_step: Union[Step, None] = None,
):
self.message = message
self.title = title
self.with_step = with_step

View file

@ -1,147 +0,0 @@
import uuid
from typing import Any, Callable, Dict, List, Optional, Type, Union
from pydantic import BaseModel, validator
from ..libs.llm.anthropic import AnthropicLLM
from ..libs.llm.base import LLM
from ..libs.llm.ggml import GGML
from ..libs.llm.google_palm_api import GooglePaLMAPI
from ..libs.llm.hf_inference_api import HuggingFaceInferenceAPI
from ..libs.llm.hf_tgi import HuggingFaceTGI
from ..libs.llm.llamacpp import LlamaCpp
from ..libs.llm.llamafile import Llamafile
from ..libs.llm.lmstudio import LMStudio
from ..libs.llm.ollama import Ollama
from ..libs.llm.openai import OpenAI
from ..libs.llm.openai_free_trial import OpenAIFreeTrial
from ..libs.llm.replicate import ReplicateLLM
from ..libs.llm.text_gen_webui import TextGenWebUI
from ..libs.llm.together import TogetherLLM
class ContinueSDK(BaseModel):
pass
ALL_MODEL_ROLES = [
"default",
"summarize",
"edit",
"chat",
]
MODEL_CLASSES: Dict[str, Type[LLM]] = {
cls.__name__: cls
for cls in [
OpenAI,
OpenAIFreeTrial,
GGML,
TogetherLLM,
AnthropicLLM,
ReplicateLLM,
Ollama,
LlamaCpp,
HuggingFaceInferenceAPI,
HuggingFaceTGI,
GooglePaLMAPI,
TextGenWebUI,
LMStudio,
Llamafile,
]
}
MODEL_MODULE_NAMES = {
"OpenAI": "openai",
"OpenAIFreeTrial": "openai_free_trial",
"GGML": "ggml",
"TogetherLLM": "together",
"AnthropicLLM": "anthropic",
"ReplicateLLM": "replicate",
"Ollama": "ollama",
"LlamaCpp": "llamacpp",
"HuggingFaceInferenceAPI": "hf_inference_api",
"HuggingFaceTGI": "hf_tgi",
"GooglePaLMAPI": "google_palm_api",
"TextGenWebUI": "text_gen_webui",
"LMStudio": "lmstudio",
"Llamafile": "llamafile",
}
class Models(BaseModel):
"""Main class that holds the current model configuration"""
default: Union[Any, LLM]
summarize: Union[Any, LLM]
edit: Union[Any, LLM]
chat: Union[Any, LLM]
saved: List[Union[Any, LLM]] = []
temperature: Optional[float] = None
system_message: Optional[str] = None
@validator(
"summarize",
"edit",
"chat",
pre=True,
always=True,
)
def roles_not_none(cls, v, values):
if v is None:
return values["default"]
return v
def dict(self, **kwargs):
original_dict = super().dict(**kwargs)
return original_dict
@property
def all_models(self) -> List[LLM]:
models = [getattr(self, role) for role in ALL_MODEL_ROLES]
return [model for model in models if model is not None]
def set_main_config_params(
self, system_msg: Optional[str], temperature: Optional[float]
):
self.system_message = system_msg
self.temperature = temperature
for model in self.all_models:
model.set_main_config_params(system_msg, temperature)
def start(
self,
unique_id: str,
system_message: Optional[str],
temperature: Optional[float],
llm_request_hook: Optional[Callable[[str, str], Any]] = None,
):
"""Start each of the LLMs, or fall back to default"""
for model in self.saved + self.all_models:
model.start(unique_id)
model.write_log = self.write_log
model.llm_request_hook = llm_request_hook
self.set_main_config_params(system_message, temperature)
async def stop(self):
"""Stop each LLM (if it's not the default, which is shared)"""
for model in self.all_models:
await model.stop()
_loggers = {}
async def write_log(self, msg):
for logger in self._loggers.values():
await logger(msg)
def add_logger(self, logger: Callable[[str], Any]) -> str:
logger_id = uuid.uuid4().hex
self._loggers[logger_id] = logger
return logger_id
def remove_logger(self, logger_id: str):
if logger_id in self._loggers:
del self._loggers[logger_id]

View file

@ -1,41 +0,0 @@
from pydantic import BaseModel, validator
from ..models.main import Traceback
class Observation(BaseModel):
pass
class TracebackObservation(Observation):
traceback: Traceback
class ValidatorObservation(Observation):
passed: bool
class UserInputObservation(Observation):
user_input: str
class DictObservation(Observation):
values: dict
def __getitem__(self, key):
return self.values[key]
class TextObservation(Observation):
text: str
@validator("text", pre=True, always=True)
def text_not_none(cls, v):
if v is None:
return ""
return v
class InternalErrorObservation(Observation):
title: str
error: str

View file

@ -1,277 +0,0 @@
import asyncio
import os
from abc import ABC
from typing import List, Optional, Union
from ..models.filesystem import RangeInFile
from ..models.filesystem_edit import (
AddDirectory,
AddFile,
DeleteDirectory,
DeleteFile,
FileEdit,
FileSystemEdit,
)
from ..models.main import Range
from ..plugins.context_providers.highlighted_code import HighlightedCodeContextProvider
from ..server.protocols.gui_protocol import AbstractGUIProtocolServer
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from .abstract_sdk import AbstractContinueSDK
from .config import ContinueConfig
from .context import ContextManager
from .lsp import ContinueLSPClient
from .main import (
ChatMessage,
Context,
ContextItem,
ContinueCustomException,
SessionState,
Step,
StepDescription,
)
from .models import Models
from .steps import (
DefaultModelEditCodeStep,
FileSystemEditStep,
RangeInFileWithContents,
ShellCommandsStep,
)
class Autopilot(ABC):
session_state: SessionState
ide: AbstractIdeProtocolServer
gui: AbstractGUIProtocolServer
config: ContinueConfig
context_manager: ContextManager
context: Context = Context()
async def run_step(self, step: Step):
...
class ContinueSDK(AbstractContinueSDK):
"""The SDK provided as parameters to a step"""
ide: AbstractIdeProtocolServer
gui: AbstractGUIProtocolServer
config: ContinueConfig
models: Models
lsp: Optional[ContinueLSPClient] = None
context: Context = Context()
__autopilot: Autopilot
def __init__(
self,
config: ContinueConfig,
ide: AbstractIdeProtocolServer,
gui: AbstractGUIProtocolServer,
autopilot: Autopilot,
models: Models,
):
self.ide = ide
self.gui = gui
self.config = config
self.models = models
self.__autopilot = autopilot
@property
def history(self) -> List[StepDescription]:
return self.__autopilot.session_state.history
@property
def context_items(self) -> List[ContextItem]:
return self.__autopilot.session_state.context_items
async def _ensure_absolute_path(self, path: str) -> str:
if os.path.isabs(path):
return path
# Else if in workspace
workspace_path = os.path.join(self.ide.workspace_directory, path)
if os.path.exists(workspace_path):
return workspace_path
else:
# Check if it matches any of the open files, then use that absolute path
open_files = await self.ide.getOpenFiles()
for open_file in open_files:
if os.path.basename(open_file) == os.path.basename(path):
return open_file
raise Exception(f"Path {path} does not exist")
async def run_step(self, step: Step):
await self.__autopilot.run_step(step)
async def apply_filesystem_edit(
self,
edit: FileSystemEdit,
name: str = "Filesystem Edit",
description: str = "Filesystem Edit",
):
return await self.run_step(
FileSystemEditStep(edit=edit, description=description, name=name)
)
async def run(
self,
commands: Union[List[str], str],
cwd: Optional[str] = None,
name: str = "Run Command",
description: str = "Run Command",
handle_error: bool = True,
):
commands = commands if isinstance(commands, List) else [commands]
await self.run_step(
ShellCommandsStep(
cmds=commands,
cwd=cwd,
description=description,
handle_error=handle_error,
name=name,
)
) # TODO: Return the output
async def edit_file(
self,
filename: str,
prompt: str,
name: str = "Edit File",
description: str = "",
range: Optional[Range] = None,
):
filepath = await self._ensure_absolute_path(filename)
await self.ide.setFileOpen(filepath)
contents = await self.ide.readFile(filepath)
await self.run_step(
DefaultModelEditCodeStep(
range_in_files=[
RangeInFile(filepath=filepath, range=range)
if range is not None
else RangeInFile.from_entire_file(filepath, contents)
],
user_input=prompt,
description=description,
name=name,
)
)
async def append_to_file(self, filename: str, content: str):
filepath = await self._ensure_absolute_path(filename)
previous_content = await self.ide.readFile(filepath)
file_edit = FileEdit.from_append(filepath, previous_content, content)
await self.ide.applyFileSystemEdit(file_edit)
async def add_file(self, filename: str, content: Union[str, None]):
filepath = await self._ensure_absolute_path(filename)
dir_name = os.path.dirname(filepath)
os.makedirs(dir_name, exist_ok=True)
return await self.run_step(
FileSystemEditStep(edit=AddFile(filepath=filepath, content=content or ""))
)
async def delete_file(self, filename: str):
filename = await self._ensure_absolute_path(filename)
return await self.run_step(
FileSystemEditStep(edit=DeleteFile(filepath=filename))
)
async def add_directory(self, path: str):
path = await self._ensure_absolute_path(path)
return await self.run_step(FileSystemEditStep(edit=AddDirectory(path=path)))
async def delete_directory(self, path: str):
path = await self._ensure_absolute_path(path)
return await self.run_step(FileSystemEditStep(edit=DeleteDirectory(path=path)))
async def get_code_context(
self, only_editing: bool = False
) -> List[RangeInFileWithContents]:
editing = filter(
lambda x: x.editable and (x.editing or not only_editing), self.context_items
)
return await asyncio.gather(
*[
HighlightedCodeContextProvider.get_range_in_file_with_contents(
self.ide, item
)
for item in editing
]
)
async def add_context_item(self, item: ContextItem):
index = len(self.__autopilot.session_state.history) - 1
while index > 0:
if (
self.__autopilot.session_state.history[index].step_type
== "UserInputStep"
):
break
index -= 1
await self.add_context_item_at_index(item, index)
async def add_context_item_at_index(self, item: ContextItem, index: int):
context_items = self.__autopilot.session_state.history[index].params.get(
"context_items", []
)
context_items.append(item.dict())
self.__autopilot.session_state.history[index].params[
"context_items"
] = context_items
await self.gui.add_context_item_at_index(item, index)
def set_loading_message(self, message: str):
# self.__autopilot.set_loading_message(message)
raise NotImplementedError()
def raise_exception(
self, message: str, title: str, with_step: Union[Step, None] = None
):
raise ContinueCustomException(message, title, with_step)
async def get_chat_context(self) -> List[ChatMessage]:
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}",
)
)
ctx_msgs = await self.__autopilot.context_manager.get_chat_messages(
self.context_items
)
for ctx_msg in ctx_msgs:
# Add as second-to-last message
msgs.insert(-1, ctx_msg)
return msgs
async def get_context_item_chat_messages(
self, exclude: Optional[str] = None
) -> List[ChatMessage]:
return await self.__autopilot.context_manager.get_chat_messages(
# list(
# filter(
# lambda x: x.description,
self.context_items
# )
# )
)

View file

@ -1,873 +0,0 @@
# These steps are depended upon by ContinueSDK
import difflib
import subprocess
import time
from textwrap import dedent
from typing import Any, AsyncGenerator, Dict, List, Optional, Union
from pydantic import Field
from ..libs.llm.base import LLM
from ..libs.llm.openai_free_trial import OpenAIFreeTrial
from ..libs.util.count_tokens import DEFAULT_MAX_TOKENS
from ..libs.util.devdata import dev_data_logger
from ..libs.util.strings import (
dedent_and_get_common_whitespace,
remove_quotes_and_escapes,
)
from ..libs.util.telemetry import posthog_logger
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,
ContextItem,
ContinueCustomException,
DeltaStep,
SessionUpdate,
SetStep,
Step,
)
from .observation import TextObservation, UserInputObservation
class Models:
default: LLM
summarize: LLM = Field(default=None)
edit: LLM = Field(default=None)
chat: LLM = Field(default=None)
class ReversibleStep(Step):
async def reverse(self, sdk: AbstractContinueSDK):
raise NotImplementedError
class MessageStep(Step):
name: str = "Message"
message: str
async def describe(self, models: Models):
return self.message
async def run(self, sdk: AbstractContinueSDK):
yield TextObservation(text=self.message)
class DisplayErrorStep(Step):
name: str = "Error in the Continue server"
title: str = "Error in the Continue server"
message: str = "There was an error in the Continue server."
@staticmethod
def from_exception(e: Exception) -> "DisplayErrorStep":
if isinstance(e, ContinueCustomException):
return DisplayErrorStep(title=e.title, message=e.message, name=e.title)
return DisplayErrorStep(message=str(e))
class Config:
arbitrary_types_allowed = True
async def describe(self, models: Models):
return self.message
async def run(self, sdk: AbstractContinueSDK):
raise ContinueCustomException(message=self.message, title=self.title)
class FileSystemEditStep(ReversibleStep):
edit: FileSystemEdit
_diff: Union[EditDiff, None] = None
hide: bool = True
async def run(self, sdk: "AbstractContinueSDK"):
self._diff = await sdk.ide.applyFileSystemEdit(self.edit)
async def reverse(self, sdk: "AbstractContinueSDK"):
if self._diff:
await sdk.ide.applyFileSystemEdit(self._diff.backward)
def output_contains_error(output: str) -> bool:
return "Traceback" in output or "SyntaxError" in output
AI_ASSISTED_STRING = "(✨ AI-Assisted ✨)"
class ShellCommandsStep(Step):
cmds: List[str]
cwd: Union[str, None] = None
name: str = "Run Shell Commands"
handle_error: bool = True
_err_text: Union[str, None] = None
async def describe(self, models: Models) -> str:
if self._err_text is not None:
return f"Error when running shell commands:\n```\n{self._err_text}\n```"
cmds_str = "\n".join(self.cmds)
return await models.summarize.complete(
f"{cmds_str}\n\nSummarize what was done in these shell commands, using markdown bullet points:"
)
async def run(self, sdk: AbstractContinueSDK):
process = subprocess.Popen(
"/bin/bash",
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
cwd=self.cwd or sdk.ide.workspace_directory,
)
stdin_input = "\n".join(self.cmds)
out, err_bytes = process.communicate(stdin_input.encode())
err = err_bytes.decode()
# If it fails, return the error
if err is not None and err != "":
self._err_text = err
return TextObservation(text=err)
class DefaultModelEditCodeStep(Step):
user_input: str
model: Optional[LLM] = None
range_in_files: List[RangeInFile]
name: str = "Editing Code"
hide = False
description: str = ""
_prompt: str = dedent(
"""\
Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The </modified_code_to_edit> tag should be written to indicate the end of the modified code section. Do not ever use nested tags.
Example:
<file_prefix>
class Database:
def __init__(self):
self._data = {{}}
def get(self, key):
return self._data[key]
</file_prefix>
<code_to_edit>
def set(self, key, value):
self._data[key] = value
</code_to_edit>
<file_suffix>
def clear_all():
self._data = {{}}
</file_suffix>
<user_request>
Raise an error if the key already exists.
</user_request>
<modified_code_to_edit>
def set(self, key, value):
if key in self._data:
raise KeyError(f"Key {{key}} already exists")
self._data[key] = value
</modified_code_to_edit>
Main task:
"""
)
_previous_contents: str = ""
_new_contents: str = ""
_prompt_and_completion: str = ""
summary_prompt: str = "Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:"
async def get_prompt_parts(
self,
rif: RangeInFileWithContents,
sdk: AbstractContinueSDK,
full_file_contents: str,
):
# We don't know here all of the functions being passed in.
# We care because if this prompt itself goes over the limit, then the entire message will have to be cut from the completion.
# Overflow won't happen, but prune_chat_messages in count_tokens.py will cut out this whole thing, instead of us cutting out only as many lines as we need.
model_to_use = self.model or sdk.models.edit
max_tokens = int(model_to_use.context_length / 2)
TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = 1200
if (
model_to_use.count_tokens(rif.contents)
> TOKENS_TO_BE_CONSIDERED_LARGE_RANGE
):
self.description += "\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**"
# At this point, we also increase the max_tokens parameter so it doesn't stop in the middle of generation
# Increase max_tokens to be double the size of the range
# But don't exceed twice default max tokens
max_tokens = int(
min(model_to_use.count_tokens(rif.contents), DEFAULT_MAX_TOKENS) * 2.5
)
BUFFER_FOR_FUNCTIONS = 400
total_tokens = (
model_to_use.count_tokens(
full_file_contents + self._prompt + self.user_input
)
+ BUFFER_FOR_FUNCTIONS
+ max_tokens
)
# If using 3.5 and overflows, upgrade to 3.5.16k
if (
model_to_use.model == "gpt-3.5-turbo"
and model_to_use.__class__.__name__ == "OpenAI"
):
if total_tokens > model_to_use.context_length:
model_to_use = OpenAIFreeTrial(model="gpt-3.5-turbo-0613")
# Remove tokens from the end first, and then the start to clear space
# This part finds the start and end lines
full_file_contents_lst = full_file_contents.split("\n")
max_start_line = rif.range.start.line
min_end_line = rif.range.end.line
cur_start_line = 0
cur_end_line = len(full_file_contents_lst) - 1
if total_tokens > model_to_use.context_length:
while cur_end_line > min_end_line:
total_tokens -= model_to_use.count_tokens(
full_file_contents_lst[cur_end_line]
)
cur_end_line -= 1
if total_tokens < model_to_use.context_length:
break
if total_tokens > model_to_use.context_length:
while cur_start_line < max_start_line:
cur_start_line += 1
total_tokens -= model_to_use.count_tokens(
full_file_contents_lst[cur_start_line]
)
if total_tokens < model_to_use.context_length:
break
# Now use the found start/end lines to get the prefix and suffix strings
file_prefix = "\n".join(full_file_contents_lst[cur_start_line:max_start_line])
file_suffix = "\n".join(full_file_contents_lst[min_end_line : cur_end_line - 1])
# Move any surrounding blank line in rif.contents to the prefix/suffix
# TODO: Keep track of start line of the range, because it's needed below for offset stuff
if len(rif.contents) > 0:
lines = rif.contents.splitlines(keepends=True)
first_line = lines[0] if lines else None
while first_line and first_line.strip() == "":
file_prefix += first_line
rif.contents = rif.contents[len(first_line) :]
lines = rif.contents.splitlines(keepends=True)
first_line = lines[0] if lines else None
last_line = lines[-1] if lines else None
while last_line and last_line.strip() == "":
file_suffix = last_line + file_suffix
rif.contents = rif.contents[: len(rif.contents) - len(last_line)]
lines = rif.contents.splitlines(keepends=True)
last_line = lines[-1] if lines else None
while rif.contents.startswith("\n"):
file_prefix += "\n"
rif.contents = rif.contents[1:]
while rif.contents.endswith("\n"):
file_suffix = "\n" + file_suffix
rif.contents = rif.contents[:-1]
return file_prefix, rif.contents, file_suffix, model_to_use, max_tokens
def compile_prompt(
self,
file_prefix: str,
contents: str,
file_suffix: str,
sdk: AbstractContinueSDK,
) -> str:
if contents.strip() == "":
# Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file
prompt = dedent(
f"""\
<file_prefix>
{file_prefix}
</file_prefix>
<insertion_code_here>
<file_suffix>
{file_suffix}
</file_suffix>
<user_request>
{self.user_input}
</user_request>
Please output the code to be inserted at the cursor in order to fulfill the user_request. Do NOT preface your answer or write anything other than code. You should not write any tags, just the code. Make sure to correctly indent the code:"""
)
return prompt
prompt = self._prompt
if file_prefix.strip() != "":
prompt += dedent(
f"""
<file_prefix>
{file_prefix}
</file_prefix>"""
)
prompt += dedent(
f"""
<code_to_edit>
{contents}
</code_to_edit>"""
)
if file_suffix.strip() != "":
prompt += dedent(
f"""
<file_suffix>
{file_suffix}
</file_suffix>"""
)
prompt += dedent(
f"""
<user_request>
{self.user_input}
</user_request>
<modified_code_to_edit>
"""
)
return prompt
def is_end_line(self, line: str) -> bool:
return (
"</modified_code_to_edit>" in line
or "</code_to_edit>" in line
or "[/CODE]" in line
)
def line_to_be_ignored(self, line: str, is_first_line: bool = False) -> bool:
return (
"```" in line
or "<modified_code_to_edit>" in line
or "<file_prefix>" in line
or "</file_prefix>" in line
or "<file_suffix>" in line
or "</file_suffix>" in line
or "<user_request>" in line
or "</user_request>" in line
or "<code_to_edit>" in line
)
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)
(
file_prefix,
contents,
file_suffix,
model_to_use,
max_tokens,
) = await self.get_prompt_parts(rif, sdk, full_file_contents)
contents, common_whitespace = dedent_and_get_common_whitespace(contents)
prompt = self.compile_prompt(file_prefix, contents, file_suffix, sdk)
full_file_contents_lines = full_file_contents.split("\n")
lines_to_display = []
async def sendDiffUpdate(
lines: List[str], sdk: AbstractContinueSDK, final: bool = False
):
nonlocal full_file_contents_lines, rif, lines_to_display
completion = "\n".join(lines)
full_prefix_lines = full_file_contents_lines[: rif.range.start.line]
full_suffix_lines = full_file_contents_lines[rif.range.end.line :]
# Don't do this at the very end, just show the inserted code
if final:
lines_to_display = []
# Only recalculate at every new-line, because this is sort of expensive
elif completion.endswith("\n"):
contents_lines = rif.contents.split("\n")
rewritten_lines = 0
for line in lines:
for i in range(rewritten_lines, len(contents_lines)):
if (
difflib.SequenceMatcher(
None, line, contents_lines[i]
).ratio()
> 0.7
and contents_lines[i].strip() != ""
):
rewritten_lines = i + 1
break
lines_to_display = contents_lines[rewritten_lines:]
new_file_contents = (
"\n".join(full_prefix_lines)
+ "\n"
+ completion
+ "\n"
+ (
"\n".join(lines_to_display) + "\n"
if len(lines_to_display) > 0
else ""
)
+ "\n".join(full_suffix_lines)
)
step_index = len(sdk.history) - 1
await sdk.ide.showDiff(rif.filepath, new_file_contents, step_index)
# Important state variables
# -------------------------
original_lines = [] if rif.contents == "" else rif.contents.split("\n")
# In the actual file, taking into account block offset
current_line_in_file = rif.range.start.line
current_block_lines = []
original_lines_below_previous_blocks = original_lines
# The start of the current block in file, taking into account block offset
current_block_start = -1
offset_from_blocks = 0
# Don't end the block until you've matched N simultaneous lines
# This helps avoid many tiny blocks
LINES_TO_MATCH_BEFORE_ENDING_BLOCK = 2
# If a line has been matched at the end of the block, this is its index within original_lines_below_previous_blocks
# Except we are keeping track of multiple potentialities, so it's a list
# We always check the lines following each of these leads, but if multiple make it out at the end, we use the first one
# This is a tuple of (index_of_last_matched_line, number_of_lines_matched)
indices_of_last_matched_lines = []
async def handle_generated_line(line: str):
nonlocal current_block_start, current_line_in_file, original_lines, original_lines_below_previous_blocks, current_block_lines, indices_of_last_matched_lines, LINES_TO_MATCH_BEFORE_ENDING_BLOCK, offset_from_blocks
if len(current_block_lines) == 0:
# Set this as the start of the next block
current_block_start = (
rif.range.start.line
+ len(original_lines)
- len(original_lines_below_previous_blocks)
+ offset_from_blocks
)
if (
len(original_lines_below_previous_blocks) > 0
and line == original_lines_below_previous_blocks[0]
):
# Line is equal to the next line in file, move past this line
original_lines_below_previous_blocks = (
original_lines_below_previous_blocks[1:]
)
return
# In a block, and have already matched at least one line
# Check if the next line matches, for each of the candidates
matches_found = []
first_valid_match = None
for (
index_of_last_matched_line,
num_lines_matched,
) in indices_of_last_matched_lines:
if (
index_of_last_matched_line + 1
< len(original_lines_below_previous_blocks)
and line
== original_lines_below_previous_blocks[
index_of_last_matched_line + 1
]
):
matches_found.append(
(index_of_last_matched_line + 1, num_lines_matched + 1)
)
if (
first_valid_match is None
and num_lines_matched + 1 >= LINES_TO_MATCH_BEFORE_ENDING_BLOCK
):
first_valid_match = (
index_of_last_matched_line + 1,
num_lines_matched + 1,
)
indices_of_last_matched_lines = matches_found
if first_valid_match is not None:
# We've matched the required number of lines, insert suggestion!
# We added some lines to the block that were matched (including maybe some blank lines)
# So here we will strip all matching lines from the end of current_block_lines
lines_stripped = []
index_of_last_line_in_block = first_valid_match[0]
while (
len(current_block_lines) > 0
and current_block_lines[-1]
== original_lines_below_previous_blocks[
index_of_last_line_in_block - 1
]
):
lines_stripped.append(current_block_lines.pop())
index_of_last_line_in_block -= 1
# Reset current block / update variables
current_line_in_file += 1
offset_from_blocks += len(current_block_lines)
original_lines_below_previous_blocks = (
original_lines_below_previous_blocks[
index_of_last_line_in_block + 1 :
]
)
current_block_lines = []
current_block_start = -1
indices_of_last_matched_lines = []
return
# Always look for new matching candidates
new_matches = []
for i in range(len(original_lines_below_previous_blocks)):
og_line = original_lines_below_previous_blocks[i]
# TODO: It's a bit sus to be disqualifying empty lines.
# What you ideally do is find ALL matches, and then throw them out as you check the following lines
if og_line == line: # and og_line.strip() != "":
new_matches.append((i, 1))
indices_of_last_matched_lines += new_matches
# Make sure they are sorted by index
indices_of_last_matched_lines = sorted(
indices_of_last_matched_lines, key=lambda x: x[0]
)
current_block_lines.append(line)
messages = await sdk.get_chat_context()
# Delete the last user and assistant messages
i = len(messages) - 1
deleted = 0
while i >= 0 and deleted < 2:
if messages[i].role == "user" or messages[i].role == "assistant":
messages.pop(i)
deleted += 1
i -= 1
messages.append(
ChatMessage(role="user", content=prompt, summary=self.user_input)
)
lines_of_prefix_copied = 0
lines = []
unfinished_line = ""
completion_lines_covered = 0
repeating_file_suffix = False
line_below_highlighted_range = file_suffix.lstrip().split("\n")[0]
# Use custom templates defined by the model
if template := model_to_use.prompt_templates.get("edit"):
rendered = render_prompt_template(
template if isinstance(template, str) else template.prompt,
messages[:-1],
{
"code_to_edit": rif.contents,
"user_input": self.user_input,
"file_prefix": file_prefix,
"file_suffix": file_suffix,
"system_message": model_to_use.system_message
or sdk.config.system_message
or "",
"context_items": "\n\n".join(
list(
map(
lambda x: x.content or "",
await sdk.get_context_item_chat_messages(),
)
)
),
},
)
if isinstance(rendered, str):
messages = [
ChatMessage(
role="user",
content=rendered,
summary=self.user_input,
)
]
else:
messages = rendered
params: Dict[str, Any] = {"prompt": rendered}
if template.__class__.__name__ == "PromptTemplate":
params.update(template.dict(exclude={"prompt"}))
params.update(
{"max_tokens": min(max_tokens, model_to_use.context_length // 2, 4096)}
)
generator = model_to_use.stream_complete(**params)
else:
async def gen():
async for chunk in model_to_use.stream_chat(
messages,
temperature=sdk.config.completion_options.temperature,
max_tokens=min(max_tokens, model_to_use.context_length // 2, 4096),
):
yield chunk.content
generator = gen()
posthog_logger.capture_event(
"model_use",
{"model": model_to_use.model, "provider": model_to_use.__class__.__name__},
)
dev_data_logger.capture(
"model_use",
{"model": model_to_use.model, "provider": model_to_use.__class__.__name__},
)
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
# Accumulate lines
chunk_lines = chunk.split("\n")
chunk_lines[0] = unfinished_line + chunk_lines[0]
if chunk.endswith("\n"):
unfinished_line = ""
chunk_lines.pop() # because this will be an empty string
else:
unfinished_line = chunk_lines.pop()
# Deal with newly accumulated lines
for i in range(len(chunk_lines)):
# Trailing whitespace doesn't matter
chunk_lines[i] = chunk_lines[i].rstrip()
chunk_lines[i] = common_whitespace + chunk_lines[i]
# Lines that should signify the end of generation
if self.is_end_line(chunk_lines[i]):
break
# Lines that should be ignored, like the <> tags
elif self.line_to_be_ignored(
chunk_lines[i], completion_lines_covered == 0
):
continue # noice
# Check if we are currently just copying the prefix
elif (
(lines_of_prefix_copied > 0 or completion_lines_covered == 0)
and lines_of_prefix_copied < len(file_prefix.splitlines())
and chunk_lines[i]
== full_file_contents_lines[lines_of_prefix_copied]
):
# This is a sketchy way of stopping it from repeating the file_prefix. Is a bug if output happens to have a matching line
lines_of_prefix_copied += 1
continue # also nice
# Because really short lines might be expected to be repeated, this is only a !heuristic!
# Stop when it starts copying the file_suffix
elif (
chunk_lines[i].strip() == line_below_highlighted_range.strip()
and len(chunk_lines[i].strip()) > 4
and not (
len(original_lines_below_previous_blocks) > 0
and chunk_lines[i].strip()
== original_lines_below_previous_blocks[0].strip()
)
):
repeating_file_suffix = True
break
lines.append(chunk_lines[i])
completion_lines_covered += 1
current_line_in_file += 1
# Debounce the diff updates, last in only out for each period
if last_task_time is None or time.time() - last_task_time > 0.15:
last_task_time = time.time()
await sendDiffUpdate(
lines
+ [
common_whitespace
if unfinished_line.startswith("<")
else (common_whitespace + unfinished_line)
],
sdk,
)
finally:
await generator.aclose()
# Add the unfinished line
if (
unfinished_line != ""
and not self.line_to_be_ignored(
unfinished_line, completion_lines_covered == 0
)
and not self.is_end_line(unfinished_line)
):
unfinished_line = common_whitespace + unfinished_line
lines.append(unfinished_line)
await handle_generated_line(unfinished_line)
completion_lines_covered += 1
current_line_in_file += 1
await sendDiffUpdate(lines, sdk, final=True)
# Record the completion
completion = "\n".join(lines)
self._previous_contents = "\n".join(original_lines)
self._new_contents = completion
self._prompt_and_completion += prompt + completion
async def run(self, sdk: AbstractContinueSDK):
rif_with_contents = []
for range_in_file in map(
lambda x: RangeInFile(
filepath=x.filepath,
# Only consider the range line-by-line. Maybe later don't if it's only a single line.
range=x.range.to_full_lines(),
),
self.range_in_files,
):
file_contents = await sdk.ide.readRangeInFile(range_in_file)
rif_with_contents.append(
RangeInFileWithContents.from_range_in_file(range_in_file, file_contents)
)
rif_dict = {}
for rif in rif_with_contents:
rif_dict[rif.filepath] = rif.contents
for rif in rif_with_contents:
await sdk.ide.setSuggestionsLocked(rif.filepath, True)
async for update in self.stream_rif(rif, sdk):
yield update
await sdk.ide.setSuggestionsLocked(rif.filepath, False)
changes = "\n".join(
difflib.ndiff(
self._previous_contents.splitlines(),
self._new_contents.splitlines(),
)
)
if sdk.config.disable_summaries:
yield SetStep(
name="",
description=f"Edited {len(self.range_in_files)} files",
)
else:
yield SetStep(
name="Generating summary",
description="",
)
async for chunk in sdk.models.summarize.stream_complete(
dedent(
f"""\
Diff summary: "{self.user_input}"
```diff
{changes}
```
{self.summary_prompt}"""
)
):
yield chunk
# TODO: Follow-up edits might die with this update???
sdk.context.set("last_edit_user_input", self.user_input)
sdk.context.set("last_edit_diff", changes)
sdk.context.set("last_edit_range", self.range_in_files[-1].range)
class EditFileStep(Step):
filepath: str
prompt: str
hide: bool = True
model: Optional[LLM] = None
async def describe(self, models: Models):
return "Editing file: " + self.filepath
async def run(self, sdk: AbstractContinueSDK):
file_contents = await sdk.ide.readFile(self.filepath)
await sdk.run_step(
DefaultModelEditCodeStep(
range_in_files=[
RangeInFile.from_entire_file(self.filepath, file_contents)
],
user_input=self.prompt,
model=self.model,
)
)
class ManualEditStep(ReversibleStep):
edit_diff: EditDiff
hide: bool = True
hide: bool = True
async def describe(self, models: Models):
return "Manual edit step"
# TODO - only handling FileEdit here, but need all other types of FileSystemEdits
# Also requires the merge_file_edit function
# return llm.complete(dedent(f"""This code was replaced:
# {self.edit_diff.backward.replacement}
# With this code:
# {self.edit_diff.forward.replacement}
# Maximally concise summary of changes in bullet points (can use markdown):
# """))
@classmethod
def from_sequence(cls, edits: List[FileEditWithFullContents]) -> "ManualEditStep":
diffs = []
for edit in edits:
_, diff = FileSystem.apply_edit_to_str(edit.fileContents, edit.fileEdit)
diffs.append(diff)
return cls(edit_diff=EditDiff.from_sequence(diffs))
async def run(self, sdk: AbstractContinueSDK):
...
async def reverse(self, sdk: AbstractContinueSDK):
await sdk.ide.applyFileSystemEdit(self.edit_diff.backward)
class UserInputStep(Step):
user_input: str
context_items: List[ContextItem] = []
name: str = "User Input"
hide: bool = False
manage_own_chat_context: bool = True
async def describe(self, models: Models):
if self.description is not None:
return self.description
return self.user_input
async def run(self, sdk: AbstractContinueSDK):
self.chat_context.append(
ChatMessage(role="user", content=self.user_input, summary=self.user_input)
)
self.description = self.user_input
yield UserInputObservation(user_input=self.user_input)

View file

@ -1,634 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/natesesti/Desktop/continue/server/.venv/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n",
"[2023-10-24 23:31:12,190] [DEBUG] New session: None\n",
"[2023-10-24 23:31:12,195] [DEBUG] Loaded Continue config file from /Users/natesesti/.continue/config.py\n",
"Unclosed client session\n",
"client_session: <aiohttp.client.ClientSession object at 0x127737d10>\n",
"[2023-10-24 23:31:12,266] [DEBUG] Starting context manager\n"
]
}
],
"source": [
"import json\n",
"import os\n",
"from typing import List\n",
"import asyncio\n",
"\n",
"from continuedev.core.sdk import ContinueSDK\n",
"from continuedev.libs.index.chunkers import Chunk\n",
"from continuedev.headless import start_headless_session\n",
"from continuedev.libs.index.pipelines.main import main_retrieval_pipeline, retrieval_step\n",
"from continuedev.libs.index.hyde import code_hyde\n",
"from continuedev.libs.index.rerankers.single_token import single_token_reranker_parallel\n",
"\n",
"session = await start_headless_session(directory=\"/Users/natesesti/Desktop/continue/server/continuedev\")\n",
"sdk: ContinueSDK = session.autopilot.continue_sdk"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"async def f(q: str):\n",
" return await main_retrieval_pipeline(q, sdk)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'basePath': '/Users/natesesti/Desktop/continue/server/continuedev', 'questions': [{'q': 'How does the Continue FastAPI server work?', 'files': ['server/main.py', 'server/gui.py', 'server/ide.py']}, {'q': 'Where is logic for pruning the prompt tokens?', 'files': ['libs/util/count_tokens.py', 'libs/llm/base.py']}, {'q': 'Where does codebase indexing happen?', 'files': ['plugins/steps/chroma.py', 'libs/index/indices/chroma_index.py', 'libs/index/indices/meilisearch_index.py', 'libs/index/indices/base.py', 'core/context.py']}, {'q': 'How is meilisearch used?', 'files': ['plugins/steps/chroma.py', 'libs/index/indices/meilisearch_index.py', 'libs/index/indices/base.py', 'core/context.py', 'server/meilisearch_server.py']}, {'q': 'I want to update Ollama integration', 'files': ['libs/llm/ollama.py']}, {'q': 'How does Continue chunk code?', 'files': ['libs/index/chunkers/basic.py', 'libs/index/chunkers/chunk_directory.py', 'libs/index/chunkers/chunk.py', 'libs/index/chunkers/code.py']}]}\n"
]
}
],
"source": [
"with open(\"y.json\", \"r\") as file:\n",
" data = json.load(file)\n",
"\n",
"print(data)\n",
"questions = data[\"questions\"]\n",
"base_path = data[\"basePath\"]\n",
"\n",
"def abs_paths(question):\n",
" return list(map(\n",
" lambda x: os.path.join(base_path, x),\n",
" question[\"files\"]\n",
" ))\n",
"\n",
"def in_y(chunk: Chunk, question):\n",
" return chunk.document_id in abs_paths(question)\n",
"\n",
"def f1_score(chunks: List[Chunk], question) -> float:\n",
" chosen_files = list(set(map(lambda c: c.document_id, chunks)))\n",
" actual_files = abs_paths(question)\n",
" tp = len(list(filter(lambda x: x in actual_files, chosen_files)))\n",
" fp = len(chosen_files) - tp\n",
" fn = len(actual_files) - tp\n",
" if tp == 0:\n",
" return 0\n",
"\n",
" return 2 * tp / (2 * tp + fp + fn)\n",
"\n",
"def get_recall(chunks: List[Chunk], question) -> float:\n",
" chosen_files = list(set(map(lambda c: c.document_id, chunks)))\n",
" actual_files = abs_paths(question)\n",
" tp = len(list(filter(lambda x: x in actual_files, chosen_files)))\n",
" fn = len(actual_files) - tp\n",
" if tp == 0:\n",
" return 0\n",
"\n",
" return tp / (tp + fn)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# scores = []\n",
"# for question in questions:\n",
"# chunks = await f(question[\"q\"])\n",
"# score = f1_score(chunks, question)\n",
"# print(score)\n",
"# scores.append(score)\n",
"\n",
"# print(scores)\n",
"# print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[2023-10-24 23:31:12,418] [DEBUG] Loading Meilisearch index...\n",
"[2023-10-24 23:31:12,639] [DEBUG] Loaded 0 documents into meilisearch in 0.018690824508666992 seconds for context provider code\n",
"[2023-10-24 23:31:12,645] [DEBUG] Loaded 1 documents into meilisearch in 0.02457594871520996 seconds for context provider search\n",
"[2023-10-24 23:31:12,661] [DEBUG] Loaded 1 documents into meilisearch in 0.040534019470214844 seconds for context provider terminal\n",
"[2023-10-24 23:31:12,662] [DEBUG] Loaded 1 documents into meilisearch in 0.041803836822509766 seconds for context provider url\n",
"[2023-10-24 23:31:12,663] [DEBUG] Loaded 1 documents into meilisearch in 0.042099952697753906 seconds for context provider diff\n",
"[2023-10-24 23:31:12,664] [DEBUG] Loaded 152 documents into meilisearch in 0.04308819770812988 seconds for context provider file\n",
"[2023-10-24 23:31:12,664] [DEBUG] Loaded Meilisearch index\n"
]
}
],
"source": [
"hyde_mapping = {}\n",
"hydes = await asyncio.gather(*[code_hyde(question[\"q\"], \"python\", sdk) for question in questions])\n",
"for i, hyde in enumerate(hydes):\n",
" hyde_mapping[questions[i][\"q\"]] = hyde"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Unclosed client session\n",
"client_session: <aiohttp.client.ClientSession object at 0x147c077d0>\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"1.0\n",
"1.0\n",
"1.0\n",
"0.6\n",
"1.0\n",
"0.8\n",
"[1.0, 1.0, 0.6, 0.8, 1.0, 1.0]\n",
"0.9\n"
]
}
],
"source": [
"async def get_score(question):\n",
" chunks = await retrieval_step(hyde_mapping[question[\"q\"]], sdk, n_retrieve=50)\n",
" score = get_recall(chunks, question)\n",
" print(score)\n",
" return score\n",
"\n",
"scores = await asyncio.gather(*map(get_score, questions))\n",
"\n",
"print(scores)\n",
"print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"25\n",
"25\n",
"25\n",
"25\n",
"25\n",
"25\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"10\n",
"0.7499999999999999\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class AnswerQuestionChroma(Step):\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory, openai_api_key=self.openai_api_key\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" self.hide = False\n",
" self.description = f\"Scanning {self.n_retrieve} files...\"\n",
" await sdk.update_ui()\n",
"\n",
" # Get top chunks from index\n",
" to_retrieve_from_each = (\n",
" self.n_retrieve if self.use_reranking else self.n_final\n",
" ) // 2\n",
" chroma_chunks = await chroma_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" meilisearch_chunks = await meilisearch_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" chunk_ids = set()\n",
" chunks = []\n",
" for chunk in chroma_chunks + meilisearch_chunks:\n",
" if chunk.id not in chunk_ids:\n",
" chunk_ids.add(chunk.id)\n",
" chunks.append(chunk)\n",
"\n",
" # Rerank to select top results\n",
" self.description = f\"Selecting most important files...\"\n",
" await sdk.update_ui()\n",
"\n",
" if self.use_reranking:\n",
" chunks = await default_reranker_parallel(\n",
" chunks,\n",
" self.user_input,\n",
" self.n_final,\n",
" sdk,\n",
" group_size=self.rerank_group_size,\n",
" )\n",
"\n",
" # Add context items\n",
" context_items: List[ContextItem] = []\n",
" for chunk in chunks:\n",
" # Can we select the context item through the normal means so that the name is disambiguated?\n",
" # Also so you don't have to understand the internals of the context provider\n",
" # OR have a chunk context provider??? Nice short-term, but I don't like it for long-term\n",
" ctx_item = ContextItem(\n",
" content=chunk.content,\n",
" description=ContextItemDescription(\n",
" name=f\"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})\",\n",
" description=chunk.document_id,\n",
" id=ContextItemId(\n",
" provider_title=\"file\",\n",
" item_id=remove_meilisearch_disallowed_chars(chunk.document_id),\n",
" ),\n",
" ),\n",
" ) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!\n",
"\n",
" context_items.append(ctx_item)\n",
" await sdk.add_context_item(ctx_item)\n",
"\n",
" self.hide = True\n",
" model = sdk.models.chat.model\n",
" # if model == \"gpt-4\":\n",
" # model = \"gpt-4-32k\" # Not publicly available yet?\n",
" if model == \"gpt-3.5-turbo\":\n",
" model = \"gpt-3.5-turbo-16k\"\n",
"\n",
" await sdk.run_step(\n",
" SimpleChatStep(\n",
" name=\"Answer Question\",\n",
" description=f\"Reading from {len(context_items)} files...\",\n",
" completion_options=CompletionOptions(model=model),\n",
" )\n",
" )\n",
"\n",
" # for ctx_item in context_items:\n",
" # await sdk.delete_context_item(ctx_item.description.id)\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory,\n",
" openai_api_key=self.openai_api_key,\n",
" api_base=self.api_base,\n",
" api_type=self.api_type,\n",
" api_version=self.api_version,\n",
" organization_id=self.organization_id,\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" indices_to_build = 0\n",
" chroma_exists = await chroma_index.exists()\n",
" meilisearch_exists = await meilisearch_index.exists()\n",
" if not chroma_exists:\n",
" indices_to_build += 1\n",
" if not meilisearch_exists:\n",
" indices_to_build += 1\n",
"\n",
" if indices_to_build == 0:\n",
" return\n",
"\n",
" self.hide = False\n",
"\n",
" chunks = await chunk_directory(sdk, MAX_CHUNK_SIZE)\n",
"\n",
" total_progress = 0\n",
" if not chroma_exists:\n",
" async for progress in chroma_index.build(\n",
" sdk, ignore_files=self.ignore_files, chunks=chunks\n",
" ):\n",
" self.description = f\"Generating codebase embeddings... {int(progress*100 / indices_to_build)}%\"\n",
" print(self.description, flush=True)\n",
" await sdk.update_ui()\n",
"\n",
" total_progress += 50\n",
"\n",
" if not meilisearch_exists:\n",
" async for progress in meilisearch_index.build(\n",
" sdk, ignore_files=self.ignore_files, chunks=chunks\n",
" ):\n",
" self.description = f\"Generating codebase embeddings... {int(progress*100 / indices_to_build + total_progress)}%\"\n",
" print(self.description, flush=True)\n",
" await sdk.update_ui()\n",
"\n",
" await asyncio.sleep(1)\n",
" self.hide = True\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"10\n",
"0.6666666666666667\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class CreateCodebaseIndexChroma(Step):\n",
" name: str = \"Create Codebase Index\"\n",
" hide: bool = True\n",
" description: str = \"Generating codebase embeddings... 1%\"\n",
" openai_api_key: Optional[str] = Field(None, description=\"OpenAI API key\")\n",
" api_base: Optional[str] = Field(None, description=\"OpenAI API base URL\")\n",
" api_type: Optional[str] = Field(None, description=\"OpenAI API type\")\n",
" api_version: Optional[str] = Field(None, description=\"OpenAI API version\")\n",
" organization_id: Optional[str] = Field(None, description=\"OpenAI organization ID\")\n",
"\n",
" ignore_files: List[str] = Field(\n",
" [],\n",
" description=\"Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.\",\n",
" )\n",
"\n",
" async def describe(self, models) -> Coroutine[str, None, None]:\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" ...\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n"
]
}
],
"source": [
"async def get_rerank_score(question):\n",
" initial_chunks = await retrieval_step(hyde_mapping[question[\"q\"]], sdk, n_retrieve=50)\n",
" initial_recall = get_recall(initial_chunks, question)\n",
" print(len(initial_chunks))\n",
" chunks = await single_token_reranker_parallel(initial_chunks, question[\"q\"], 10, sdk)\n",
" print(len(chunks))\n",
" score = get_recall(chunks, question) / initial_recall\n",
" print(score)\n",
"\n",
" missed_by_rerank = [chunk for chunk in initial_chunks if in_y(chunk, question) and chunk.document_id not in [c.document_id for c in chunks]]\n",
" print(\"MISSED BY RERANK: \\n\\n\")\n",
" for chunk in missed_by_rerank:\n",
" print(chunk.document_id)\n",
" print(chunk.content)\n",
" print(\"\\n\\n-----------------------------\\n\\n\")\n",
"\n",
" return score\n",
"\n",
"scores = await asyncio.gather(*map(get_rerank_score, questions))\n",
"\n",
"print(scores)\n",
"print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"PROMPT = \"\"\"\n",
"You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: \"Yes\" or \"No\" indicating the retrieved snippet is relevant to the query.\n",
"\n",
"Query: Where is the FastAPI server?\n",
"Snippet:\n",
"```/Users/andrew/Desktop/server/main.py\n",
"from fastapi import FastAPI\n",
"app = FastAPI()\n",
"@app.get(\"/\")\n",
"def read_root():\n",
" return {\"Hello\": \"World\"}\n",
"```\n",
"Relevant: Yes\n",
"\n",
"Query: Where in the documentation does it talk about the UI?\n",
"Snippet:\n",
"```/Users/andrew/Projects/bubble_sort/src/lib.rs\n",
"fn bubble_sort<T: Ord>(arr: &mut [T]) {\n",
" for i in 0..arr.len() {\n",
" for j in 1..arr.len() - i {\n",
" if arr[j - 1] > arr[j] {\n",
" arr.swap(j - 1, j);\n",
" }\n",
" }\n",
" }\n",
"}\n",
"```\n",
"Relevant: No\n",
"\n",
"Query: Where does codebase indexing happen?\n",
"Snippet:\n",
"```/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class AnswerQuestionChroma(Step):\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory, openai_api_key=self.openai_api_key\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" self.hide = False\n",
" self.description = f\"Scanning {self.n_retrieve} files...\"\n",
" await sdk.update_ui()\n",
"\n",
" # Get top chunks from index\n",
" to_retrieve_from_each = (\n",
" self.n_retrieve if self.use_reranking else self.n_final\n",
" ) // 2\n",
" chroma_chunks = await chroma_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" meilisearch_chunks = await meilisearch_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" chunk_ids = set()\n",
" chunks = []\n",
" for chunk in chroma_chunks + meilisearch_chunks:\n",
" if chunk.id not in chunk_ids:\n",
" chunk_ids.add(chunk.id)\n",
" chunks.append(chunk)\n",
"\n",
" # Rerank to select top results\n",
" self.description = f\"Selecting most important files...\"\n",
" await sdk.update_ui()\n",
"\n",
" if self.use_reranking:\n",
" chunks = await default_reranker_parallel(\n",
" chunks,\n",
" self.user_input,\n",
" self.n_final,\n",
" sdk,\n",
" group_size=self.rerank_group_size,\n",
" )\n",
"\n",
" # Add context items\n",
" context_items: List[ContextItem] = []\n",
" for chunk in chunks:\n",
" # Can we select the context item through the normal means so that the name is disambiguated?\n",
" # Also so you don't have to understand the internals of the context provider\n",
" # OR have a chunk context provider??? Nice short-term, but I don't like it for long-term\n",
" ctx_item = ContextItem(\n",
" content=chunk.content,\n",
" description=ContextItemDescription(\n",
" name=f\"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})\",\n",
" description=chunk.document_id,\n",
" id=ContextItemId(\n",
" provider_title=\"file\",\n",
" item_id=remove_meilisearch_disallowed_chars(chunk.document_id),\n",
" ),\n",
" ),\n",
" ) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!\n",
"\n",
" context_items.append(ctx_item)\n",
" await sdk.add_context_item(ctx_item)\n",
"\n",
" self.hide = True\n",
" model = sdk.models.chat.model\n",
" # if model == \"gpt-4\":\n",
" # model = \"gpt-4-32k\" # Not publicly available yet?\n",
" if model == \"gpt-3.5-turbo\":\n",
" model = \"gpt-3.5-turbo-16k\"\n",
"\n",
" await sdk.run_step(\n",
" SimpleChatStep(\n",
" name=\"Answer Question\",\n",
" description=f\"Reading from {len(context_items)} files...\",\n",
" completion_options=CompletionOptions(model=model),\n",
" )\n",
" )\n",
"\n",
" # for ctx_item in context_items:\n",
" # await sdk.delete_context_item(ctx_item.description.id)\n",
"```\n",
"Relevant: \"\"\""
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<OpenAIObject at 0x11377c6b0> JSON: {\n",
" \"tokens\": [\n",
" \" No\"\n",
" ],\n",
" \"token_logprobs\": [\n",
" -0.0012104723\n",
" ],\n",
" \"top_logprobs\": [\n",
" {\n",
" \" No\": -0.0012104723,\n",
" \"\\n\": -6.8743377,\n",
" \"No\": -8.752341,\n",
" \"\\u00a0\": -11.196322,\n",
" \"<|endoftext|>\": -13.671831\n",
" }\n",
" ],\n",
" \"text_offset\": [\n",
" 4147\n",
" ]\n",
"}"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import openai\n",
"openai.api_key = \"\"\n",
"response = openai.Completion.create(\n",
" model=\"text-davinci-003\",\n",
" prompt=PROMPT,\n",
" max_tokens=1,\n",
" temperature=0.0,\n",
" stop=[\"```\"],\n",
" logit_bias={3363: 1, 1400: 1},\n",
" logprobs=10,\n",
")\n",
"response[\"choices\"][0][\"logprobs\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View file

@ -1,46 +0,0 @@
{
"basePath": "/Users/natesesti/Desktop/continue/server/continuedev",
"questions": [
{
"q": "How does the Continue FastAPI server work?",
"files": ["server/main.py", "server/gui.py", "server/ide.py"]
},
{
"q": "Where is logic for pruning the prompt tokens?",
"files": ["libs/util/count_tokens.py", "libs/llm/base.py"]
},
{
"q": "Where does codebase indexing happen?",
"files": [
"plugins/steps/chroma.py",
"libs/index/indices/chroma_index.py",
"libs/index/indices/meilisearch_index.py",
"libs/index/indices/base.py",
"core/context.py"
]
},
{
"q": "How is meilisearch used?",
"files": [
"plugins/steps/chroma.py",
"libs/index/indices/meilisearch_index.py",
"libs/index/indices/base.py",
"core/context.py",
"server/meilisearch_server.py"
]
},
{
"q": "I want to update Ollama integration",
"files": ["libs/llm/ollama.py"]
},
{
"q": "How does Continue chunk code?",
"files": [
"libs/index/chunkers/basic.py",
"libs/index/chunkers/chunk_directory.py",
"libs/index/chunkers/chunk.py",
"libs/index/chunkers/code.py"
]
}
]
}

View file

@ -1,47 +0,0 @@
from typing import List, Optional, Union
from ..core.autopilot import Autopilot
from ..core.config import ContinueConfig
from ..core.context import ContextManager, ContextProvider
from ..core.main import SessionState
from ..server.protocols.cli_gui import CommandLineGUI
from .headless_ide import LocalIdeProtocol
async def get_headless_autopilot(
directory: Optional[str] = ".",
state: Optional[SessionState] = None,
config: Optional[Union[str, ContinueConfig]] = None,
context_providers: List[ContextProvider] = [],
) -> Autopilot:
if config is not None:
if isinstance(config, str):
_config: ContinueConfig = ContinueConfig.from_filepath(config)
else:
_config = config
else:
_config = ContinueConfig.load_default()
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
# )
models = _config.construct_models()
models.start(
ide.window_info.unique_id,
_config.system_message,
_config.completion_options.temperature,
_config.llm_request_hook,
)
return Autopilot(
session_state=state or SessionState.from_empty(),
ide=ide,
gui=CommandLineGUI(),
config=_config,
context_manager=context_manager,
models=models,
)

View file

@ -1,202 +0,0 @@
import os
import subprocess
import uuid
from typing import Any, Callable, List, Optional
from dotenv import load_dotenv
from fastapi import WebSocket
from ..models.filesystem import (
FileSystem,
RangeInFile,
RangeInFileWithContents,
RealFileSystem,
)
from ..models.filesystem_edit import EditDiff, FileEdit, FileSystemEdit
from ..models.main import Position
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
load_dotenv()
def get_mac_address():
mac_num = hex(uuid.getnode()).replace("0x", "").upper()
mac = "-".join(mac_num[i : i + 2] for i in range(0, 11, 2))
return mac
class LocalIdeProtocol(AbstractIdeProtocolServer):
websocket: WebSocket
session_id: Optional[str]
workspace_directory: str = os.getcwd()
unique_id: str = get_mac_address()
filesystem: FileSystem = RealFileSystem()
def __init__(self, workspace_directory: Optional[str] = None):
if workspace_directory:
self.workspace_directory = workspace_directory
async def handle_json(self, data: Any):
"""Handle a json message"""
pass
def showSuggestion(self, file_edit: FileEdit):
"""Show a suggestion to the user"""
pass
async def setFileOpen(self, filepath: str, open: bool = True):
"""Set whether a file is open"""
pass
async def showMessage(self, message: str):
"""Show a message to the user"""
print(message)
async def showVirtualFile(self, name: str, contents: str):
"""Show a virtual file"""
pass
async def setSuggestionsLocked(self, filepath: str, locked: bool = True):
"""Set whether suggestions are locked"""
pass
async def getSessionId(self):
"""Get a new session ID"""
pass
def onAcceptRejectSuggestion(self, accepted: bool):
"""Called when the user accepts or rejects a suggestion"""
pass
def onFileSystemUpdate(self, update: FileSystemEdit):
"""Called when a file system update is received"""
pass
def onCloseGUI(self, session_id: str):
"""Called when a GUI is closed"""
pass
def onOpenGUIRequest(self):
"""Called when a GUI is requested to be opened"""
pass
async def getOpenFiles(self) -> List[str]:
"""Get a list of open files"""
return []
async def getVisibleFiles(self) -> List[str]:
"""Get a list of visible files"""
return []
async def getHighlightedCode(self) -> List[RangeInFile]:
"""Get a list of highlighted code"""
return []
async def readFile(self, filepath: str) -> str:
"""Read a file"""
try:
return self.filesystem.read(filepath)
except UnicodeDecodeError:
return ""
async def readRangeInFile(self, range_in_file: RangeInFile) -> str:
"""Read a range in a file"""
return self.filesystem.read_range_in_file(range_in_file)
async def editFile(self, edit: FileEdit):
"""Edit a file"""
self.filesystem.apply_file_edit(edit)
async def applyFileSystemEdit(self, edit: FileSystemEdit) -> EditDiff:
"""Apply a file edit"""
return self.filesystem.apply_edit(edit)
async def saveFile(self, filepath: str):
"""Save a file"""
pass
async def getUserSecret(self, key: str):
"""Get a user secret"""
return os.environ.get(key)
async def highlightCode(self, range_in_file: RangeInFile, color: str):
"""Highlight code"""
pass
async def runCommand(self, command: str) -> str:
"""Run a command using subprocess (don't pass, actually implement)"""
return subprocess.check_output(command, shell=True).decode("utf-8")
def onHighlightedCodeUpdate(self, range_in_files: List[RangeInFileWithContents]):
"""Called when highlighted code is updated"""
pass
def onDeleteAtIndex(self, index: int):
"""Called when a step is deleted at a given index"""
pass
async def showDiff(self, filepath: str, replacement: str, step_index: int):
"""Show a diff"""
pass
def subscribeToFilesCreated(self, callback: Callable[[List[str]], None]):
"""Subscribe to files created event"""
pass
def subscribeToFilesDeleted(self, callback: Callable[[List[str]], None]):
"""Subscribe to files deleted event"""
pass
def subscribeToFilesRenamed(self, callback: Callable[[List[str], List[str]], None]):
"""Subscribe to files renamed event"""
pass
def subscribeToFileSaved(self, callback: Callable[[str, str], None]):
"""Subscribe to file saved event"""
pass
def onFilesCreated(self, filepaths: List[str]):
"""Called when files are created"""
pass
def onFilesDeleted(self, filepaths: List[str]):
"""Called when files are deleted"""
pass
def onFilesRenamed(self, old_filepaths: List[str], new_filepaths: List[str]):
"""Called when files are renamed"""
pass
def onFileSaved(self, filepath: str, contents: str):
"""Called when a file is saved"""
pass
async def fileExists(self, filepath: str) -> bool:
"""Check if a file exists"""
return self.filesystem.exists(filepath)
async def getTerminalContents(self) -> str:
return ""
async def listDirectoryContents(
self, directory: str, recursive: bool = False
) -> List[str]:
return self.filesystem.list_directory_contents(directory, recursive=recursive)
async def goto_definition(self, filepath: str, position: Position):
raise NotImplementedError()
async def document_symbol(self, filepath: str):
raise NotImplementedError()
async def find_references(
self, filepath: str, position: Position, include_declaration: bool = False
):
raise NotImplementedError()
async def folding_range(self, filepath: str):
raise NotImplementedError()
async def get_enclosing_folding_range(self, position: Position, filepath: str):
raise NotImplementedError()

View file

@ -1 +0,0 @@
data

View file

@ -1,53 +0,0 @@
# import faiss
import os
import subprocess
from typing import List
from dotenv import load_dotenv
load_dotenv()
FILE_TYPES_TO_IGNORE = [".pyc", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico"]
def filter_ignored_files(files: List[str], root_dir: str):
"""Further filter files before indexing."""
for file in files:
if (
file.endswith(tuple(FILE_TYPES_TO_IGNORE))
or file.startswith(".git")
or file.startswith("archive")
):
continue # nice
yield root_dir + "/" + file
def get_git_ignored_files(root_dir: str):
"""Get the list of ignored files in a Git repository."""
try:
output = (
subprocess.check_output(
["git", "ls-files", "--ignored", "--others", "--exclude-standard"],
cwd=root_dir,
)
.strip()
.decode()
)
return output.split("\n")
except subprocess.CalledProcessError:
return []
def get_all_files(root_dir: str):
"""Get a list of all files in a directory."""
for dir_path, _, file_names in os.walk(root_dir):
for file_name in file_names:
yield os.path.join(os.path.relpath(dir_path, root_dir), file_name)
def get_input_files(root_dir: str):
"""Get a list of all files in a Git repository that are not ignored."""
ignored_files = set(get_git_ignored_files(root_dir))
all_files = set(get_all_files(root_dir))
nonignored_files = all_files - ignored_files
return filter_ignored_files(nonignored_files, root_dir)

View file

@ -1,64 +0,0 @@
default_config = """\
\"\"\"
config.py allows you to modify Continue programmatically instead of just using config.json.
First, config.json is loaded. Then, if you have defined modify_config here, the function will be given the result of
loading config.json, and will return the final ContinueConfig to be used.
\"\"\"
from continuedev.core.config import ContinueConfig
def modify_config(config: ContinueConfig) -> ContinueConfig:
# config.completion_options.temperature = 0.5
return config
"""
default_config_json = """\
{
"models": [
{
"title": "GPT-4",
"provider": "free-trial",
"model": "gpt-4"
},
{
"title": "GPT-3.5-Turbo",
"provider": "free-trial",
"model": "gpt-3.5-turbo"
}
],
"model_roles": {
"default": "GPT-4"
},
"slash_commands": [
{
"name": "edit",
"description": "Edit highlighted code",
"step": "EditHighlightedCodeStep"
},
{
"name": "comment",
"description": "Write comments for the highlighted code",
"step": "CommentCodeStep"
},
{
"name": "share",
"description": "Download and share this session",
"step": "ShareSessionStep"
},
{
"name": "cmd",
"description": "Generate a shell command",
"step": "GenerateShellCommandStep"
}
],
"custom_commands": [
{
"name": "test",
"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.",
"description": "Write unit tests for highlighted code"
}
]
}
"""

View file

@ -1,6 +0,0 @@
## PATHS ##
CONTINUE_GLOBAL_FOLDER = ".continue"
CONTINUE_SESSIONS_FOLDER = "sessions"
CONTINUE_SERVER_FOLDER = "server"
CONTINUE_SERVER_VERSION_FILE = "server_version.txt"

View file

@ -1 +0,0 @@
data

View file

@ -1,79 +0,0 @@
import asyncio
from typing import AsyncGenerator
from ...core.config import ContinueConfig
from ...libs.index.indices.chroma_index import MAX_CHUNK_SIZE, ChromaCodebaseIndex
from ...libs.index.indices.meilisearch_index import MeilisearchCodebaseIndex
from ...server.protocols.ide_protocol import AbstractIdeProtocolServer
from .chunkers.chunk_directory import (
local_stream_chunk_directory,
stream_chunk_directory,
)
async def build_index(
ide: AbstractIdeProtocolServer, config: ContinueConfig
) -> AsyncGenerator[float, None]:
tag = await ide.getTag()
branch = await ide.getBranch()
settings = config.retrieval_settings
chroma_index = ChromaCodebaseIndex(
tag,
openai_api_key=settings.openai_api_key,
api_base=settings.api_base,
api_type=settings.api_type,
api_version=settings.api_version,
organization_id=settings.organization_id,
)
meilisearch_index = MeilisearchCodebaseIndex(tag)
n = 2
done = False
buffers = [[] for _ in range(n)]
async def generator_for_chroma():
nonlocal buffers
while not done or len(buffers[0]) > 0:
if len(buffers[0]) > 0:
yield buffers[0].pop(0)
else:
await asyncio.sleep(0.1)
async def generator_for_meilisearch():
nonlocal buffers
while not done or len(buffers[1]) > 0:
if len(buffers[1]) > 0:
yield buffers[1].pop(0)
else:
await asyncio.sleep(0.1)
chroma_task = asyncio.create_task(chroma_index.build(generator_for_chroma()))
meilisearch_task = asyncio.create_task(
meilisearch_index.build(generator_for_meilisearch())
)
server_url = ide.window_info.ide_info.get("server_url", "http://localhost:65432")
if ide.window_info.ide_info.get("remote_name", None) in ["ssh-remote", "wsl"] or (
"localhost" not in server_url and "127.0.0.1" not in server_url
):
# Use the old method if workspace is remote OR if Continue server is not running on the same machine as the IDE
async for chunk, progress in stream_chunk_directory(ide, MAX_CHUNK_SIZE):
if chunk is not None:
buffers[0].append(("compute", chunk))
buffers[1].append(("compute", chunk))
yield progress
else:
# If on same machine, can access files directly
for action, chunk, progress in local_stream_chunk_directory(
ide.workspace_directory, MAX_CHUNK_SIZE, branch
):
buffers[0].append((action, chunk))
buffers[1].append((action, chunk))
yield progress
done = True
while not chroma_task.done() or not meilisearch_task.done():
await asyncio.sleep(0.1)
yield 1

View file

@ -1,11 +0,0 @@
import os
from typing import Dict
def chunk_metadata(filepath: str, chunk: str) -> Dict[str, str]:
# TODO: Try adding c-tags to the top of each chunk
return {}
def format_chunk_with_metadata(filepath: str, chunk: str) -> str:
return f"```title={os.path.basename(filepath)}\n{chunk}```"

View file

@ -1,26 +0,0 @@
from typing import List, Optional
from .basic import basic_chunker
from .chunk import Chunk, ChunkWithoutID
from .code import code_chunker, file_extension_to_language
def _chunk_document_without_id(
filepath: str, contents: Optional[str], max_chunk_size: int
) -> List[ChunkWithoutID]:
"""Chunk a document into smaller pieces."""
if contents is None:
return []
ext = filepath.split(".")[-1]
if ext in file_extension_to_language:
return code_chunker(filepath, contents, max_chunk_size)
return basic_chunker(contents, max_chunk_size)
def chunk_document(
filepath: str, contents: Optional[str], max_chunk_size: int, digest: str
) -> List[Chunk]:
chunks = _chunk_document_without_id(filepath, contents, max_chunk_size)
return [chunk.with_id(digest, i, filepath) for i, chunk in enumerate(chunks)]

View file

@ -1,42 +0,0 @@
from typing import List
from .chunk import ChunkWithoutID
from ...util.count_tokens import count_tokens
def basic_chunker(contents: str, max_chunk_size: int) -> List[ChunkWithoutID]:
"""Chunk a document into smaller pieces."""
chunks = []
chunk_content = ""
chunk_tokens = 0
start_line = 0
curr_line = 0
for line in contents.split("\n"):
line_tokens = count_tokens(line)
if chunk_tokens + line_tokens > max_chunk_size:
chunks.append(
ChunkWithoutID(
content=chunk_content,
start_line=start_line,
end_line=curr_line - 1,
)
)
chunk_content = ""
chunk_tokens = 0
start_line = curr_line
chunk_content += line + "\n"
chunk_tokens += line_tokens
curr_line += 1
chunks.append(
ChunkWithoutID(
content=chunk_content,
start_line=start_line,
end_line=curr_line - 1,
index=len(chunks),
)
)
return chunks

View file

@ -1,43 +0,0 @@
from chromadb.types import Metadata
from ....models.main import ContinueBaseModel
class ChunkWithoutID(ContinueBaseModel):
content: str
start_line: int
end_line: int
other_metadata: Metadata = {}
def with_id(self, digest: str, index: int, filepath: str):
return Chunk(
content=self.content,
start_line=self.start_line,
end_line=self.end_line,
other_metadata=self.other_metadata,
digest=digest,
index=index,
filepath=filepath,
)
class Chunk(ChunkWithoutID):
digest: str
index: int # The index of the chunk in the document
filepath: str
@property
def id(self):
return f"{self.digest}::{self.index}"
@property
def metadata(self):
# Nested dicts not allowed by chromadb
other_metadata = self.other_metadata.copy()
d = self.dict()
del d["content"]
del d["other_metadata"]
return {
**other_metadata,
**d,
}

View file

@ -1,140 +0,0 @@
import asyncio
import hashlib
import os
from typing import (
AsyncGenerator,
Callable,
Generator,
List,
Literal,
Optional,
Tuple,
Union,
)
from continuedev.continuedev import sync_results
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from . import chunk_document
from .chunk import Chunk
from .ignore import should_ignore_file_factory
MAX_SIZE_IN_CHARS = 50_000
async def get_file_contents(filepath: str, ide: AbstractIdeProtocolServer) -> str:
try:
return (await ide.readFile(filepath))[:MAX_SIZE_IN_CHARS]
except Exception as _:
return None
async def get_contents_of_files(
files: List[str], ide: AbstractIdeProtocolServer, ignore_files: List[str] = []
) -> List[str]:
# Get file contents for all at once
return await asyncio.gather(*[ide.readFile(file) for file in files])
async def get_all_filepaths(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = []
) -> Tuple[List[str], Callable[[str], bool]]:
files = await ide.listDirectoryContents(ide.workspace_directory, True)
# Get all .gitignores first
gitignore_paths = list(
filter(
lambda file: file.endswith(".gitignore")
or file.endswith(".continueignore"),
files,
)
)
gitignore_contents = await get_contents_of_files(gitignore_paths, ide)
gitignores = {
path: content for path, content in zip(gitignore_paths, gitignore_contents)
}
should_ignore_file = should_ignore_file_factory(ignore_files, gitignores)
return files, should_ignore_file
async def stream_file_contents(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = [], group_size: int = 100
) -> AsyncGenerator[Tuple[str, Optional[str], float], None]:
# Get list of filenames to index
# TODO: Don't get all at once, walk the tree, or break up
files, should_ignore = await get_all_filepaths(ide, ignore_files)
# Don't want to flood with too many requests
i = 0
total = len(files)
for file in files:
if should_ignore(file):
total = max(1, total - 1)
yield (file, None, i / total)
continue
contents = await get_file_contents(file, ide)
yield (file, contents, i / total)
i += 1
async def stream_chunk_directory(
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, ignore_files=ignore_files
):
if contents is None:
yield (None, progress)
continue
for chunk in chunk_document(
file, contents, max_chunk_size, hashlib.sha1(contents.encode()).hexdigest()
):
yield (chunk, progress)
IndexAction = Literal["compute", "delete", "add_label", "remove_label"]
def local_stream_chunk_directory(
workspace_dir: str, max_chunk_size: int, branch: str
) -> Generator[Tuple[IndexAction, Union[str, Chunk], float], None, None]:
"""Stream Tuples of (action, chunk, progress). the chunk is a Chunk if 'compute' action, otherwise it is the digest string. the assumption in this case is to delete/update all chunks for the document id (digest)."""
(compute, delete, add_label, remove_label) = sync_results(workspace_dir, branch)
progress = 1
total = len(compute) + len(delete) + len(add_label) + len(remove_label) + 1
for filepath, digest in compute:
# Ignore if the file is too large (cutoff is 10MB)
if os.path.getsize(filepath) > 10_000_000:
continue
try:
contents = open(filepath, "r").read()
except Exception as e:
print(e, filepath)
continue
if contents.strip() == "":
continue
for chunk in chunk_document(filepath, contents, max_chunk_size, digest):
yield ("compute", chunk, progress / total)
progress += 1
for filepath, digest in delete:
yield ("delete", digest, progress / total)
progress += 1
for filepath, digest in add_label:
yield ("add_label", digest, progress / total)
progress += 1
for filepath, digest in remove_label:
yield ("remove_label", digest, progress / total)
progress += 1

View file

@ -1,169 +0,0 @@
from typing import List, Union
from .chunk import ChunkWithoutID
from tree_sitter_languages import get_parser
from tree_sitter import Node
from ...util.count_tokens import count_tokens
file_extension_to_language = {
"py": "python",
"js": "javascript",
"ts": "typescript",
"java": "java",
"go": "go",
"rb": "ruby",
"rs": "rust",
"c": "c",
"cpp": "cpp",
"cs": "c_sharp",
"php": "php",
"scala": "scala",
"swift": "swift",
"kt": "kotlin",
}
def get_parser_for_file(filepath: str):
ext = filepath.split(".")[-1]
if lang := file_extension_to_language.get(ext):
return get_parser(lang)
raise Exception(f"Could not find language for file {filepath}")
def get_all_nodes(node: Node):
yield node
for child in node.children:
yield from get_all_nodes(child)
def first_child(node: Node, grammar_name: Union[str, List[str]]):
if isinstance(grammar_name, list):
return next(
filter(lambda x: x.grammar_name in grammar_name, node.children), None
)
return next(filter(lambda x: x.grammar_name == grammar_name, node.children), None)
# TODO: This should actually happen a level up. Given the whole function, return `def f():\n\t...` for example
def collapsed_replacement(node: Node):
if node.grammar_name == "statement_block":
return "{ ... }"
else:
return "..."
def collapse_children(
node: Node,
code: str,
block_types: List[str],
collapse_types: List[str],
collapse_block_types: List[str],
) -> str:
code = code[: node.end_byte]
if block := first_child(node, block_types):
for child in reversed(
list(
filter(
lambda x: x.grammar_name in collapse_types,
block.children,
)
)
):
if grand_child := first_child(child, collapse_block_types):
start = grand_child.start_byte
end = grand_child.end_byte
code = code[:start] + collapsed_replacement(grand_child) + code[end:]
return code[node.start_byte :]
def construct_class_definition_chunk(node: Node, code):
return collapse_children(
node,
code,
["block", "class_body", "declaration_list"],
["method_definition", "function_definition", "function_item"],
["block", "statement_block"],
)
def construct_function_definition_chunk(node: Node, code) -> str:
func_text = node.text.decode("utf8")
if (
node.parent
and node.parent.grammar_name in ["block", "declaration_list"]
and node.parent.parent
and node.parent.parent.grammar_name in ["class_definition", "impl_item"]
):
# If inside a class, include the class header
class_node = node.parent.parent
class_block = node.parent
return (
code[class_node.start_byte : class_block.start_byte]
+ "...\n\n"
+ (" " * node.start_point[1])
+ func_text
)
return func_text
collapsed_node_constructors = {
# Classes, structs, etc
"class_definition": construct_class_definition_chunk,
"class_declaration": construct_class_definition_chunk,
"impl_item": construct_class_definition_chunk,
# Functions
"function_definition": construct_function_definition_chunk,
"function_declaration": construct_function_definition_chunk,
"function_item": construct_function_definition_chunk,
}
def get_smart_collapsed_chunks(
node: Node, code: str, max_chunk_size: int, root: bool = True
) -> List[ChunkWithoutID]:
# Keep entire text if not over size
if (root or node.grammar_name in collapsed_node_constructors) and count_tokens(
node.text.decode("utf8")
) < max_chunk_size:
yield ChunkWithoutID(
content=node.text.decode("utf8"),
start_line=node.start_point[0],
end_line=node.end_point[0],
)
return
# If a collapsed form is defined, use that
if node.grammar_name in collapsed_node_constructors:
yield ChunkWithoutID(
content=collapsed_node_constructors[node.grammar_name](node, code),
start_line=node.start_point[0],
end_line=node.end_point[0],
)
# TODO - if this is still too large, what can you do?
# TODO: Should try to group elements together from the top. If you can fit together multiple functions, that is prob ideal
# But how to avoid separating a docstring from it's function for example?
# Also find a metric to test against please!
# Recurse (because even if collapsed version was shown, want to show the children in full somewhere)
for child in node.children:
yield from get_smart_collapsed_chunks(child, code, max_chunk_size, root=False)
def code_chunker(
filepath: str, contents: str, max_chunk_size: int
) -> List[ChunkWithoutID]:
if contents is None or len(contents.strip()) == 0:
return []
try:
parser = get_parser_for_file(filepath)
except Exception:
return []
tree = parser.parse(bytes(contents, "utf8"))
return list(get_smart_collapsed_chunks(tree.root_node, contents, max_chunk_size))

View file

@ -1,140 +0,0 @@
# TODO:
"""
- Follow .continueignore
- How do we know to remove embeddings?
On window load, check the list of branches against
those you have indexed. Then purge any that don't exist.
"""
from contextlib import contextmanager
import os
from typing import Callable, Generator, List, Tuple
from ...util.paths import getGlobalFolderPath
from .ignore import should_ignore_file_factory, local_find_gitignores
import pygit2
INDEX_CACHE_PATH = os.path.join(getGlobalFolderPath(), ".index_cache")
INDEX_BRANCHES_PATH = os.path.join(getGlobalFolderPath(), ".index_branches")
class DiskSet:
"""
An on-disk set.
- On disk
- Set operations
- False positives not okay
- False negatives okay
"""
def __init__(self, path: str):
if not os.path.exists(path):
with open(path, "w") as f:
f.write("")
self.file = open(path, "a+")
def __contains__(self, item: str) -> bool:
self.file.seek(0)
for line in self.file.readlines():
if line.strip() == item:
return True
return False
def add(self, item: str) -> None:
if item in self:
return
self.file.write(item + "\n")
self.file.flush()
def remove(self, item: str) -> None:
self.file.seek(0)
lines = self.file.readlines()
self.file.seek(0)
self.file.truncate(0)
for line in lines:
if line.strip() != item:
self.file.write(line)
def close(self) -> None:
self.file.close()
@contextmanager
def disk_set(path: str) -> Generator[DiskSet, None, None]:
set = DiskSet(path)
try:
yield set
finally:
set.close()
FileAndHash = Tuple[str, str]
def stream_files_to_update(
workspace_dir: str,
) -> Generator[FileAndHash, None, None]:
"""Yield (file, hash) pairs"""
repo = pygit2.Repository(workspace_dir)
commit = repo.head.peel(pygit2.Commit)
gitignores = local_find_gitignores(workspace_dir)
should_ignore = should_ignore_file_factory([], gitignores)
with disk_set(INDEX_CACHE_PATH) as already_indexed:
yield from files_to_update_in(
commit, already_indexed, repo.workdir, should_ignore
)
# Yield from files changed in the working tree
should_yield = set(
[
pygit2.GIT_STATUS_INDEX_NEW,
pygit2.GIT_STATUS_INDEX_MODIFIED,
pygit2.GIT_STATUS_WT_MODIFIED,
pygit2.GIT_STATUS_WT_NEW,
]
)
for filepath, status in repo.status().items():
if status in should_yield and not should_ignore(filepath):
digest = repo.revparse_single("HEAD:" + filepath).hex
yield filepath, digest
def files_to_update_in(
obj: pygit2.Object,
already_indexed: DiskSet,
path: str,
should_ignore: Callable[[str], bool],
) -> Generator[FileAndHash, None, None]:
"""Given an object, yield all files to update"""
if obj.hex in already_indexed or should_ignore(path):
return
if obj.type == pygit2.GIT_OBJ_BLOB:
yield path, obj.hex
elif obj.type == pygit2.GIT_OBJ_TREE:
for entry in obj:
yield from files_to_update_in(
entry, already_indexed, os.path.join(path, entry.name), should_ignore
)
elif obj.type == pygit2.GIT_OBJ_COMMIT:
yield from files_to_update_in(obj.tree, already_indexed, path, should_ignore)
else:
raise Exception("Unknown type: " + str(obj.type))
already_indexed.add(obj.hex)
def get_all_branches(workspace_dir: str) -> List[str]:
repo = pygit2.Repository(workspace_dir)
return [ref for ref in repo.branches.local]
def clean_deleted_branches(current_branches: str):
with disk_set(INDEX_BRANCHES_PATH) as indexed_branches:
for branch in indexed_branches:
if branch not in current_branches:
indexed_branches.remove(branch)

View file

@ -1,105 +0,0 @@
import os
from typing import Callable, Dict, List
from ...util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path
FILE_IGNORE_PATTERNS = [
# File Names
"**/.DS_Store",
"**/package-lock.json",
"**/yarn.lock",
# File Types
"*.log",
"*.ttf",
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.mp4",
"*.svg",
"*.ico",
"*.pdf",
"*.zip",
"*.gz",
"*.tar",
"*.tgz",
"*.rar",
"*.7z",
"*.exe",
"*.dll",
"*.obj",
"*.o",
"*.a",
"*.lib",
"*.so",
"*.dylib",
"*.ncb",
"*.sdf",
"*.woff",
"*.woff2",
"*.eot",
"*.cur",
"*.avi",
"*.mpg",
"*.mpeg",
"*.mov",
"*.mp3",
"*.mp4",
"*.mkv",
"*.mkv",
"*.webm",
"*.jar",
]
def gi_basename(path: str) -> str:
if ".gitignore" in path:
return path[: path.index(".gitignore")]
elif ".continueignore" in path:
return path[: path.index(".continueignore")]
else:
return path
def local_find_gitignores(workspace_dir: str) -> Dict[str, str]:
gitignores = {}
for root, dirs, files in os.walk(workspace_dir):
for file in files:
if file.endswith(".gitignore") or file.endswith(".continueignore"):
path = os.path.join(root, file)
with open(path, "r") as f:
gitignores[path] = f.read()
return gitignores
def should_ignore_file_factory(
ignore_files: List[str], gitignores: Dict[str, str]
) -> Callable[[str], bool]:
gitignore_paths = list(gitignores.keys())
def gitignore_patterns_for_file(filepath: str) -> List[str]:
paths = list(
filter(
lambda gitignore_path: filepath.startswith(gi_basename(gitignore_path)),
gitignore_paths,
)
)
patterns = []
for path in paths:
base = gi_basename(path)
for pattern in gitignores[path].split("\n"):
if pattern.strip() != "":
patterns.append(os.path.join(base, pattern.strip()))
return patterns
def should_ignore_file(filepath: str) -> bool:
return should_filter_path(
filepath,
ignore_files
+ DEFAULT_IGNORE_PATTERNS
+ FILE_IGNORE_PATTERNS
+ gitignore_patterns_for_file(filepath),
)
return should_ignore_file

View file

@ -1,89 +0,0 @@
from functools import cached_property
import os
import subprocess
from typing import List, Tuple
from .update import filter_ignored_files
class GitProject:
directory: str
def __init__(self, directory: str):
self.directory = directory
@cached_property
def current_commit(self) -> str:
"""Get the current commit."""
try:
return (
subprocess.check_output(
["git", "rev-parse", "HEAD"], cwd=self.directory
)
.decode("utf-8")
.strip()
)
except Exception:
return "NONE"
@cached_property
def current_branch(self) -> str:
"""Get the current branch."""
try:
return (
subprocess.check_output(
["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=self.directory
)
.decode("utf-8")
.strip()
)
except Exception:
return "NONE"
@cached_property
def git_root_dir(self):
"""Get the root directory of a Git repository."""
try:
return (
subprocess.check_output(
["git", "rev-parse", "--show-toplevel"], cwd=self.directory
)
.strip()
.decode()
)
except Exception:
return None
def get_modified_deleted_files(
self, since_commit: str
) -> Tuple[List[str], List[str]]:
"""Get a list of all files that have been modified since the last commit."""
try:
modified_deleted_files = (
subprocess.check_output(
["git", "diff", "--name-only", since_commit, self.current_commit]
)
.decode("utf-8")
.strip()
)
except Exception:
return [], []
modified_deleted_files = modified_deleted_files.split("\n")
modified_deleted_files = [f for f in modified_deleted_files if f]
deleted_files = [
f
for f in modified_deleted_files
if not os.path.exists(os.path.join(self.directory, f))
]
modified_files = [
f
for f in modified_deleted_files
if os.path.exists(os.path.join(self.directory, f))
]
return filter_ignored_files(
modified_files, self.index_dir
), filter_ignored_files(deleted_files, self.index_dir)

View file

@ -1,50 +0,0 @@
# Hypothetical Document Embeddings (HyDE) - Prompts
from ..llm.base import LLM
CODE_PROMPT = """\
Generate a hypothetical snippet of code that would be relevant in answering the user's question.
It can be either a function, a class, or more than one of these. It should be roughly 10-20 lines of code and must be valid {language} code.
User question: {user_input}
Write your code in the block below:
```{language}
"""
async def code_hyde(user_input, language: str, model: LLM):
prompt = CODE_PROMPT.format(user_input=user_input, language=language)
completion = await model.complete(
prompt, log=False, max_tokens=100, temperature=0.0, stop=["```"]
)
return completion
KEYWORDS_PROMPT = """\
For each user question, generate keywords or file names that would be useful to search for in the codebase. Don't repeat or include similar keywords more than once. Try to include specific keywords or snippets of code that might exist in a codebase, not just general terms. Separate the keywords with a comma.
User question: Where should I add unit tests for this Python project?
Keywords: import pytest, test, import unittest, pytest-cov, coverage, coverage.py, assert, fixture, pytest.mark.parametrize
User: How to add a new command to this VS Code extension?
Keywords: vscode, command, package.json, vscode.commands.registerCommand
User: How to add a new endpoint to this Spring Boot application?
Keywords: spring, boot, endpoint, controller, request mapping, mapping, requestbody, requestparam, pathvariable, req
User question: {user_input}
Keywords:
"""
async def generate_keywords(user_input, model: LLM):
completion = await model.complete(
KEYWORDS_PROMPT.format(user_input=user_input),
log=False,
max_tokens=80,
temperature=0.0,
stop=["\n"],
)
return completion.strip().replace("'", "").replace('"', "").split(", ")

View file

@ -1,19 +0,0 @@
from abc import ABC, abstractmethod
from typing import AsyncGenerator, List, Tuple, Union
from ..chunkers import Chunk
from ..chunkers.chunk_directory import IndexAction
class CodebaseIndex(ABC):
@abstractmethod
async def build(
self, chunks: AsyncGenerator[Tuple[IndexAction, Union[str, Chunk]], None]
):
"""Builds the index, yielding progress as a float between 0 and 1. Chunks are yielded from the given generator."""
raise NotImplementedError()
@abstractmethod
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Queries the index, returning the top n results"""
raise NotImplementedError()

View file

@ -1,273 +0,0 @@
import asyncio
import os
import re
import sqlite3
from functools import cached_property
from typing import Any, AsyncGenerator, Dict, List, Literal, Optional, Tuple, Union
import chromadb
# from chromadb.api import ClientAPI
from chromadb.config import Settings
from chromadb.utils import embedding_functions
from dotenv import load_dotenv
from openai import RateLimitError
from pydantic import BaseModel
from ...util.logging import logger
from ...util.paths import getIndexFolderPath
from ..chunkers.chunk import Chunk
from ..chunkers.chunk_directory import IndexAction
from ..git import GitProject
from .base import CodebaseIndex
load_dotenv()
EmbeddingsType = Literal["default", "openai"]
MAX_CHUNK_SIZE = 512
collection: chromadb.Collection = None
class CodebaseIndexMetadata(BaseModel):
commit: str
chunks: Dict[str, int]
GROUP_SIZE = 5
class ChromaCodebaseIndex(CodebaseIndex):
tag: str
client: Any
openai_api_key: Optional[str] = None
api_base: Optional[str] = None
api_version: Optional[str] = None
api_type: Optional[str] = None
organization_id: Optional[str] = None
git_project: GitProject
def __init__(
self,
tag: str,
openai_api_key: Optional[str] = None,
api_base: Optional[str] = None,
api_version: Optional[str] = None,
api_type: Optional[str] = None,
organization_id: Optional[str] = None,
):
self.tag = tag
self.openai_api_key = openai_api_key
self.api_base = api_base
self.api_version = api_version
self.api_type = api_type
self.organization_id = organization_id
self.client = chromadb.PersistentClient(
path=self.chroma_dir,
settings=Settings(anonymized_telemetry=False),
)
os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
@property
def chroma_dir(self):
return os.path.join(self.index_dir, "chroma")
@property
def embeddings_type(self) -> EmbeddingsType:
return "default" if self.openai_api_key is None else "openai"
@cached_property
def index_dir(self) -> str:
directory = os.path.join(
getIndexFolderPath(),
"chroma",
self.embeddings_type,
)
os.makedirs(directory, exist_ok=True)
return directory
@property
def index_name(self) -> str:
return self.embeddings_type
def exists(self):
"""Check whether the codebase index has already been built and saved on disk"""
return os.path.exists(self.chroma_dir)
def convert_to_valid_chroma_collection(self, name: str) -> str:
# https://docs.trychroma.com/usage-guide#creating-inspecting-and-deleting-collections
# Truncate or pad name to correct length
if len(name) < 3:
name = name.ljust(3, "a")
elif len(name) > 63:
name = name[:63]
# Ensure name starts and ends with a lowercase letter or digit
if not re.match("^[a-z0-9]", name[0]):
name = "a" + name[1:]
if not re.match("[a-z0-9]$", name[-1]):
name = name[:-1] + "a"
# Replace invalid characters with 'a'
name = re.sub("[^a-z0-9._-]", "a", name)
# Replace consecutive dots with a single dot
name = re.sub("\\.\\.+", ".", name)
return name
@property
def collection(self):
global collection
if os.path.exists(self.chroma_dir) and collection is not None:
return collection
kwargs: Dict[str, Any] = {
"name": self.convert_to_valid_chroma_collection(
f"chroma-{self.embeddings_type}"
),
}
if self.openai_api_key is not None:
kwargs["embedding_function"] = embedding_functions.OpenAIEmbeddingFunction(
api_key=self.openai_api_key,
model_name="text-embedding-ada-002",
api_base=self.api_base,
api_version=self.api_version,
api_type=self.api_type,
organization_id=self.organization_id,
)
collection = self.client.get_or_create_collection(**kwargs)
return collection
async def add_chunks(self, chunks: List[Chunk]):
global collection
# Flatten chunks, metadata, and ids for insertion to Chroma
documents = []
metadatas = []
ids = []
for chunk in chunks:
documents.append(chunk.content)
metadata = {**chunk.metadata}
metadata["filepath"] = chunk.filepath
metadata[
"document_id"
] = chunk.digest # Need to be able to filter by document_id (hash)
metadata[self.tag] = 1 # This is how we filter by tag
metadatas.append(metadata)
ids.append(chunk.id)
# Embed the chunks and place into vector database
# Attempt to avoid rate-limiting
i = 0
wait_time = 4.0
while i < len(ids):
try:
await asyncio.sleep(0.05)
self.collection.upsert(
documents=documents[i : i + GROUP_SIZE],
metadatas=metadatas[i : i + GROUP_SIZE],
ids=ids[i : i + GROUP_SIZE],
)
i += GROUP_SIZE
except RateLimitError as e:
logger.debug(f"Rate limit exceeded, waiting {wait_time} seconds")
await asyncio.sleep(wait_time)
wait_time *= 2
if wait_time > 2**10:
raise e
except sqlite3.OperationalError as e:
logger.debug(f"SQL error: {e}")
collection = None
def delete_chunks(self, digest: str):
# Delete the chunks from the vector database
result = self.collection.get(where={"document_id": digest})
ids = result["ids"]
if len(ids) > 0:
self.collection.delete(ids=ids)
def add_label(self, digest: str):
ids = self.collection.get(where={"document_id": digest})["ids"]
self.collection.update(ids=ids, metadatas=[{self.tag: 1}] * len(ids))
def remove_label(self, digest: str):
ids = self.collection.get(where={"document_id": digest})["ids"]
self.collection.update(ids=ids, metadatas=[{self.tag: 0}] * len(ids))
async def build(
self,
chunks: AsyncGenerator[Tuple[IndexAction, Union[str, Chunk]], None],
):
"""Create a new index for the current branch."""
group = []
async for action, chunk in chunks:
if action == "compute":
if chunk.content.strip() == "":
continue
group.append(chunk)
if len(group) < GROUP_SIZE:
continue
await self.add_chunks(group)
group = []
elif action == "delete":
self.delete_chunks(chunk)
elif action == "add_label":
self.add_label(chunk)
elif action == "remove_label":
self.remove_label(chunk)
if len(group) > 0:
await self.add_chunks(group)
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Query the codebase index for top n results"""
if not self.exists():
logger.warning(f"No index found for the codebase at {self.index_dir}")
return []
results = self.collection.query(
query_texts=[query], n_results=n, where={self.tag: {"$ne": 0}}
)
chunks = []
ids = results["ids"][0]
metadatas = results["metadatas"][0]
documents = results["documents"][0]
for i in range(len(ids)):
# Probably better to define some wrapper on Chroma or other VectorDB in general that is "Chunk in, Chunk out"
other_metadata = metadatas[i]
start_line = other_metadata.pop("start_line")
end_line = other_metadata.pop("end_line")
index = other_metadata.pop("index")
document_id = other_metadata.pop("document_id")
filepath = other_metadata.pop("filepath")
chunks.append(
Chunk(
content=documents[i],
start_line=start_line,
end_line=end_line,
other_metadata=other_metadata,
digest=document_id,
index=index,
filepath=filepath,
)
)
return chunks
async def delete_branch(self):
self.collection.copy
self.collection.delete()

View file

@ -1,198 +0,0 @@
import asyncio
from functools import cached_property
from typing import Any, AsyncGenerator, Dict, List, Tuple, Union
from meilisearch_python_async import Client
from meilisearch_python_async.index import Index
from ....server.meilisearch_server import (
get_meilisearch_url,
remove_meilisearch_disallowed_chars,
)
from ...util.logging import logger
from ..chunkers import Chunk
from ..chunkers.chunk_directory import IndexAction
from .base import CodebaseIndex
class MeilisearchCodebaseIndex(CodebaseIndex):
"""
The documents have the following structure:
- document_id field is the hash of the document
- actual id is document_id + :: + chunk index
- tags is a list of each (directory + branch) the chunk is indexed for, then we can query for all chunks with a given label
There is only a single index because it allows us to share between sub-directories
"""
tag: str
def __init__(self, tag: str):
self.tag = tag
@cached_property
def index_name(self) -> str:
return remove_meilisearch_disallowed_chars("continue_codebase_index")
def chunk_to_meilisearch_document(
self, chunk: Chunk, index: int, tags: List[str]
) -> Dict[str, Any]:
return {
"id": str(index),
"content": chunk.content,
"document_id": chunk.digest,
"tags": [],
**chunk.other_metadata,
"metadata": {
"start_line": chunk.start_line,
"end_line": chunk.end_line,
"index": chunk.index,
},
}
def meilisearch_document_to_chunk(self, document: Dict[str, Any]) -> Chunk:
other_metadata = document.copy()
del other_metadata["content"]
del other_metadata["metadata"]
del other_metadata["document_id"]
del other_metadata["id"]
del other_metadata["tags"]
del other_metadata["filepath"]
return Chunk(
content=document["content"],
start_line=document["metadata"]["start_line"],
end_line=document["metadata"]["end_line"],
index=document["metadata"]["index"],
digest=document["document_id"],
filepath=document["filepath"],
other_metadata=other_metadata,
)
async def add_chunks(self, chunks: List[Chunk], index: Index, offset: int):
await index.add_documents(
[
self.chunk_to_meilisearch_document(
chunk, int(chunk.digest, 16), [self.tag]
)
for chunk in chunks
],
primary_key="id",
)
async def delete_chunks(self, document_ids: List[str], index: Index):
documents = (
await index.get_documents(
filter=f'document_id IN [{",".join(document_ids)}]'
)
).results
ids = [document["id"] for document in documents]
await index.delete_documents(ids)
async def get_docs_for_digest(self, digest: str, index: Index):
"""Given the hash of a document, give all of the ids of the chunks stored in the index"""
return await index.get_documents(filter=f'document_id="{digest}"')
async def remove_label(self, digest: str, label: str, index: Index):
documents = (await self.get_docs_for_digest(digest, index)).results
for document in documents:
document["tags"].remove(label)
await index.update_documents(documents, primary_key="id")
async def add_label(self, digest: str, label: str, index: Index):
documents = (await self.get_docs_for_digest(digest, index)).results
for document in documents:
document["tags"].append(label)
await index.update_documents(documents, primary_key="id")
async def build(
self, chunks: AsyncGenerator[Tuple[IndexAction, Union[str, Chunk]], None]
):
"""Builds the index, yielding progress as a float between 0 and 1"""
async with Client(get_meilisearch_url()) as search_client:
try:
await search_client.create_index(self.index_name, primary_key="id")
index = await search_client.get_index(self.index_name)
# await index.update_ranking_rules(
# ["attribute", "words", "typo", "proximity", "sort", "exactness"]
# )
await index.update_searchable_attributes(["content", "document_id"])
await index.update_filterable_attributes(["tags", "document_id"])
i = 0
GROUP_SIZE = 100
group = []
async for action, chunk in chunks:
if action == "compute":
if len(group) < GROUP_SIZE:
group.append(chunk)
continue
await self.add_chunks(
group,
index,
i,
)
i += GROUP_SIZE
group = []
await asyncio.sleep(0.1)
elif action == "delete":
await self.delete_chunks([chunk], index)
elif action == "add_label":
await self.add_label(chunk, self.tag, index)
elif action == "remove_label":
await self.remove_label(chunk, self.tag, index)
if len(group) > 0:
await self.add_chunks(group, index, i)
except Exception as e:
logger.warning(f"Error while building meilisearch index: {e}")
async def _query(self, query: str, n: int = 4) -> List[Chunk]:
async with Client(get_meilisearch_url()) as search_client:
try:
results = await search_client.index(self.index_name).search(
query, limit=n, filter=f'tags IN ["{self.tag}"]'
)
return [
self.meilisearch_document_to_chunk(result)
for result in results.hits
]
except Exception as e:
logger.warning(f"Error while retrieving document from meilisearch: {e}")
return []
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Queries the index, returning the top n results"""
return await self._query(query, n=n)
async def query_keywords(self, keywords: List[str], n: int = 4) -> List[Chunk]:
count_per_chunk = {}
id_to_chunk = {}
for keyword in keywords:
chunks = await self._query(keyword, n=n)
for chunk in chunks:
if chunk.id not in count_per_chunk:
count_per_chunk[chunk.id] = 0
id_to_chunk[chunk.id] = chunk
count_per_chunk[chunk.id] += 1
# Sort by count
sorted_chunks = sorted(
count_per_chunk.items(), key=lambda item: item[1], reverse=True
)
# Get top n
chunks = []
for chunk_id, count in sorted_chunks[:n]:
chunks.append(id_to_chunk[chunk_id])
return chunks

View file

@ -1,56 +0,0 @@
from meilisearch_python_async import Client
async def add_docs():
async with Client("http://localhost:7700") as search_client:
index = await search_client.create_index("UsersnatesestiDesktopcontinueguisrc")
await index.delete_all_documents()
return
await index.add_documents(
[
{
"id": 0,
"content": 'import GUI from "./pages/gui";\nimport History from "./pages/history";\nimport Help from "./pages/help";\nimport Layout from "./components/Layout";\nimport { createContext, useEffect } from "react";\nimport useContinueGUIProtocol from "./hooks/useWebsocket";\nimport ContinueGUIClientProtocol from "./hooks/ContinueGUIClientProtocol";\nimport { useDispatch } from "react-redux";\nimport {\n setApiUrl,\n setVscMachineId,\n setSessionId,\n setVscMediaUrl,\n setDataSwitchOn,\n setWorkspacePaths,\n} from "./redux/slices/configSlice";\nimport {\n setHighlightedCode,\n setServerStatusMessage,\n} from "./redux/slices/miscSlice";\nimport { postVscMessage } from "./vscode";\nimport { RouterProvider, createMemoryRouter } from "react-router-dom";\nimport ErrorPage from "./pages/error";\nimport SettingsPage from "./pages/settings";\nimport Models from "./pages/models";\nimport HelpPage from "./pages/help";\nimport ModelConfig from "./pages/modelconfig";\nimport { usePostHog } from "posthog-js/react";\n\nconst router = createMemoryRouter([\n {\n path: "/",\n element: <Layout />,\n errorElement: <ErrorPage />,\n children: [\n {\n path: "/index.html",\n element: <GUI />,\n },\n {\n path: "/",\n element: <GUI />,\n },\n {\n path: "/history",\n element: <History />,\n },\n {\n path: "/help",\n element: <Help />,\n },\n {\n path: "/settings",\n element: <SettingsPage />,\n },\n {\n path: "/models",\n element: <Models />,\n },\n {\n path: "/help",\n element: <HelpPage />,\n },\n {\n path: "/modelconfig/:modelName",\n element: <ModelConfig />,\n },\n ],\n },\n]);\n\nexport const GUIClientContext = createContext<\n ContinueGUIClientProtocol | undefined\n>(undefined);\n\nfunction App() {\n const client = useContinueGUIProtocol(false);\n const posthog = usePostHog();\n\n const dispatch = useDispatch();\n useEffect(() => {\n const eventListener = (event: any) => {\n switch (event.data.type) {\n case "onLoad":\n dispatch(setApiUrl(event.data.apiUrl));\n dispatch(setVscMachineId(event.data.vscMachineId));\n dispatch(setSessionId(event.data.sessionId));\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/App.tsx",
"metadata": {"start_pos": 0, "end_pos": 10, "index": 0},
},
{
"id": 1,
"content": ' dispatch(setVscMediaUrl(event.data.vscMediaUrl));\n dispatch(setDataSwitchOn(event.data.dataSwitchOn));\n if (event.data.uniqueId) {\n posthog?.identify(event.data.vscMachineId);\n }\n dispatch(setWorkspacePaths(event.data.workspacePaths));\n break;\n case "highlightedCode":\n dispatch(setHighlightedCode(event.data.rangeInFile));\n break;\n case "serverStatus":\n dispatch(setServerStatusMessage(event.data.message));\n break;\n }\n };\n window.addEventListener("message", eventListener);\n postVscMessage("onLoad", {});\n return () => window.removeEventListener("message", eventListener);\n }, []);\n\n useEffect(() => {\n if (document.body.style.getPropertyValue("--vscode-editor-foreground")) {\n localStorage.setItem(\n "--vscode-editor-foreground",\n document.body.style.getPropertyValue("--vscode-editor-foreground")\n );\n }\n if (document.body.style.getPropertyValue("--vscode-editor-background")) {\n localStorage.setItem(\n "--vscode-editor-background",\n document.body.style.getPropertyValue("--vscode-editor-background")\n );\n }\n if (document.body.style.getPropertyValue("--vscode-list-hoverBackground")) {\n localStorage.setItem(\n "--vscode-list-hoverBackground",\n document.body.style.getPropertyValue("--vscode-list-hoverBackground")\n );\n }\n }, []);\n\n return (\n <GUIClientContext.Provider value={client}>\n <RouterProvider router={router} />\n </GUIClientContext.Provider>\n );\n}\n\nexport default App;\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/App.tsx",
# "metadata": {...},
},
{
"id": 2,
"content": '@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n:root {\n --secondary-dark: rgb(37, 37, 38);\n --vsc-background: rgb(30, 30, 30);\n --button-color: rgb(113, 28, 59);\n --button-color-hover: rgba(113, 28, 59, 0.667);\n --def-border-radius: 5px;\n\n --vscode-editor-background: rgb(30, 30, 30);\n --vscode-editor-foreground: rgb(197, 200, 198);\n --vscode-textBlockQuote-background: rgba(255, 255, 255, 1);\n}\n\nhtml,\nbody,\n#root {\n height: 100%;\n background-color: var(--vscode-editor-background);\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,\n Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;\n}\n\nbody {\n padding: 0;\n color: var(--vscode-editor-foreground);\n padding: 0px;\n margin: 0px;\n height: 100%;\n}\n\n.press-start-2p {\n font-family: "Press Start 2P", sans-serif;\n}\n\na:focus {\n outline: none;\n}\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/index.css",
# "metadata": {...},
},
{
"id": 3,
"content": 'import React from "react";\nimport ReactDOM from "react-dom/client";\nimport App from "./App";\nimport { Provider } from "react-redux";\nimport store from "./redux/store";\nimport "./index.css";\n\nimport CustomPostHogProvider from "./hooks/CustomPostHogProvider";\n\nReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(\n <React.StrictMode>\n <Provider store={store}>\n <CustomPostHogProvider>\n <App />\n </CustomPostHogProvider>\n </Provider>\n </React.StrictMode>\n);\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/main.tsx",
# "metadata": {...},
},
]
)
async def query(query: str):
async with Client("http://localhost:7700") as search_client:
results = await search_client.index(
"UsersnatesestiDesktopcontinueguisrc"
).search(query, limit=4)
return results
async def main():
await add_docs()
results = await query("import")
print(results)
if __name__ == "__main__":
import asyncio
asyncio.run(main())

View file

@ -1,70 +0,0 @@
from typing import List, Optional
from ....core.sdk import ContinueSDK
from ..chunkers.chunk import Chunk
from ..hyde import code_hyde
from ..indices.chroma_index import ChromaCodebaseIndex
from ..indices.meilisearch_index import MeilisearchCodebaseIndex
from ..rerankers.default import default_reranker_parallel
from ..rerankers.single_token import single_token_reranker_parallel
async def retrieval_step(
query: str,
sdk: ContinueSDK,
n_retrieve: int = 50,
n_final: int = 10,
use_reranking: bool = True,
openai_api_key: Optional[str] = None,
) -> List[Chunk]:
tag = await sdk.ide.getTag()
chroma_index = ChromaCodebaseIndex(tag, openai_api_key=openai_api_key)
meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)
print(f"Scanning {n_retrieve} files...")
# Get top chunks from index
to_retrieve_from_each = (n_retrieve if use_reranking else n_final) // 2
hyde = await code_hyde(query, "", sdk)
chroma_chunks = await chroma_index.query(hyde, n=to_retrieve_from_each)
meilisearch_chunks = await meilisearch_index.query(query, n=to_retrieve_from_each)
# De-duplicate
chunk_ids = set()
chunks = []
for chunk in chroma_chunks + meilisearch_chunks:
if chunk.id not in chunk_ids:
chunk_ids.add(chunk.id)
chunks.append(chunk)
return chunks
async def main_retrieval_pipeline(
query: str,
sdk: ContinueSDK,
openai_api_key: Optional[str] = None,
n_retrieve: int = 50,
use_reranking: bool = True,
n_final: int = 10,
rerank_group_size: int = 5,
) -> List[Chunk]:
chunks = await retrieval_step(
query,
sdk,
n_retrieve=n_retrieve,
use_reranking=use_reranking,
openai_api_key=openai_api_key,
n_final=n_final,
)
# Rerank to select top results
if use_reranking:
print(f"Selecting most important files...")
chunks = await single_token_reranker_parallel(
chunks,
query,
n_final,
sdk,
)
return chunks

View file

@ -1,167 +0,0 @@
import asyncio
import os
from typing import Dict, List
from ...llm.base import LLM
from ..chunkers.chunk import Chunk
async def decide_include_remove(
chunks: List[Chunk], user_input: str, n: int, model: LLM
) -> Dict[str, str]:
"""
Reranks the results from the codebase index based on the user input.
Returns a tuple of (include, remove) where both are lists of chunk ids
"""
# TODO: Go back to using disambiguated names instead of just basename
results_prompt = "\n\n".join(
map(
lambda chunk: f"{os.path.basename(chunk.id)}\n```\n{chunk.content[:500]}\n```",
chunks,
)
)
include_prompt = f"""\
You will be asked to select the most relevant results from a list. You should choose the results that will be most useful in answering the user's request. For each result that you think is important, you should simply say its title on a new line. Here is an example input:
\"\"\"
add.py::0
```
def add(a, b):
return a + b
```
multiply.py::0
```
def multiply(a, b):
return a * b
```
subtract.py::0
```
def subtract(a, b):
return a - b
```
\"\"\"
And here is the output you would give if you thought that add.py and subtract.py were the most relevant results:
\"\"\"
add.py::0
subtract.py::0
\"\"\"
Now for the real task, here are the top {len(chunks)} results from the codebase for the user request, "{user_input}":
{results_prompt}
Here are the {n} most relevant results listed in the same format from the example:"""
remove_prompt = f"""\
You will be asked to select items from a list that are irrelevant to the given request. For each result that is unrelated, you should simply say its title on a new line. Here is an example input:
\"\"\"
add.py::0
```
def add(a, b):
return a + b
```
multiply.py::0
```
def multiply(a, b):
return a * b
```
subtract.py::0
```
def subtract(a, b):
return a - b
```
\"\"\"
And here is the output you would give if you thought that add.py and subtract.py were not useful to answer the given request:
\"\"\"
add.py::0
subtract.py::0
\"\"\"
Now for the real task, here are the top {len(chunks)} results from the codebase for the user request, "{user_input}":
{results_prompt}
List the results that are not useful in answering the request, using in the same format from the example. Only choose those that are completely unrelated, and no more than {n // 2}:"""
include = model.complete(include_prompt, log=False)
remove = model.complete(remove_prompt, log=False)
include_completion, remove_completion = await asyncio.gather(include, remove)
return include_completion.split("\n"), remove_completion.split("\n")
async def default_reranker_parallel(
chunks: List[Chunk], user_input: str, n: int, model: LLM, group_size: int = 10
) -> List[Chunk]:
"""
A reranker, given a mapping from id to contents, returns the subset of the mapping that is most relevant to the user_input
"""
# Split the results into groups of max size 10
groups = []
group = []
for chunk in chunks:
group.append(chunk)
if len(group) == group_size:
groups.append(group)
group = []
if len(group) > 0:
groups.append(group)
# Gather the ids of chunks that should be removed and included
include = set([])
remove = set([])
tasks = []
for group in groups:
tasks.append(decide_include_remove(group, user_input, n, model))
reranking_results = await asyncio.gather(*tasks)
for rr in reranking_results:
include.update(rr[0])
remove.update(rr[1])
# Determine which documents were repeated, these are probably important
counts_per_document = {}
for chunk in chunks:
if chunk.digest not in counts_per_document:
counts_per_document[chunk.digest] = 0
counts_per_document[chunk.digest] += 1
repeated_documents = set(
filter(lambda x: counts_per_document[x] > 1, counts_per_document)
)
not_disqualified = set(
[
chunk.id
for chunk in chunks
if chunk.id not in remove or chunk.digest in repeated_documents
]
)
included = set([id for id in not_disqualified if chunk.id in include])
additional = n - len(included)
for i in range(additional):
if len(not_disqualified) == 0:
break
# Get an item from not_disqualified
included.add(not_disqualified.pop())
if additional < 0:
# We need to remove some items
additional = -additional
for i in range(additional):
if len(included) == 0:
break
# Remove one
included.pop()
return [chunk for chunk in chunks if chunk.id in included]

View file

@ -1,91 +0,0 @@
import asyncio
from typing import List
from ...llm.base import LLM
from ...util.logging import logger
from ..chunkers.chunk import Chunk
PROMPT = """
You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query.
Query: Where is the FastAPI server?
Snippet:
```/Users/andrew/Desktop/server/main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {{"Hello": "World"}}
```
Relevant: Yes
Query: Where in the documentation does it talk about the UI?
Snippet:
```/Users/andrew/Projects/bubble_sort/src/lib.rs
fn bubble_sort<T: Ord>(arr: &mut [T]) {{
for i in 0..arr.len() {{
for j in 1..arr.len() - i {{
if arr[j - 1] > arr[j] {{
arr.swap(j - 1, j);
}}
}}
}}
}}
```
Relevant: No
Query: {query}
Snippet:
```{document_id}
{document}
```
Relevant:
"""
async def single_token_reranker(chunk: Chunk, user_input: str, model: LLM) -> float:
compiled_prompt = PROMPT.format(
query=user_input, document=chunk.content, document_id=chunk.digest
)
if False:
return 0.5
# TODO: Continuous ranking with logits
# openai.api_key = openai_api_key
# response = openai.Completion.create(
# model="gpt-3.5-turbo",
# prompt=compiled_prompt,
# max_tokens=1,
# temperature=0.0,
# stop=["```"],
# logit_bias={3363: 1, 1400: 1},
# logprobs=1,
# )
# return response["choices"][0]["logprobs"]["token_logprobs"][0]
else:
try:
completion = await model.complete(
compiled_prompt, log=False, max_tokens=1, temperature=0.0
)
except Exception:
return 0.5
answer = completion.strip().lower().replace('"', "").replace("'", "")
if answer == "yes":
return 1.0
elif answer == "no":
return 0.0
else:
logger.warning(f"Unexpected response from single token reranker: {answer}")
return 0.0
async def single_token_reranker_parallel(
chunks: List[Chunk], user_input: str, n: int, model: LLM
) -> List[Chunk]:
tasks = [single_token_reranker(chunk, user_input, model) for chunk in chunks]
results = await asyncio.gather(*tasks)
# Sort by results, return top n
sorted_chunks = sorted(zip(chunks, results), key=lambda x: x[1], reverse=True)
return [chunk for chunk, _ in sorted_chunks[:n]]

View file

@ -1,53 +0,0 @@
# import faiss
import os
import subprocess
from typing import List
from dotenv import load_dotenv
load_dotenv()
FILE_TYPES_TO_IGNORE = [".pyc", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico"]
def filter_ignored_files(files: List[str], root_dir: str):
"""Further filter files before indexing."""
for file in files:
if (
file.endswith(tuple(FILE_TYPES_TO_IGNORE))
or file.startswith(".git")
or file.startswith("archive")
):
continue # nice
yield root_dir + "/" + file
def get_git_ignored_files(root_dir: str):
"""Get the list of ignored files in a Git repository."""
try:
output = (
subprocess.check_output(
["git", "ls-files", "--ignored", "--others", "--exclude-standard"],
cwd=root_dir,
)
.strip()
.decode()
)
return output.split("\n")
except subprocess.CalledProcessError:
return []
def get_all_files(root_dir: str):
"""Get a list of all files in a directory."""
for dir_path, _, file_names in os.walk(root_dir):
for file_name in file_names:
yield os.path.join(os.path.relpath(dir_path, root_dir), file_name)
def get_input_files(root_dir: str):
"""Get a list of all files in a Git repository that are not ignored."""
ignored_files = set(get_git_ignored_files(root_dir))
all_files = set(get_all_files(root_dir))
nonignored_files = all_files - ignored_files
return filter_ignored_files(nonignored_files, root_dir)

View file

@ -1,21 +0,0 @@
from abc import ABC, abstractmethod
from typing import List
from .chunkers.chunk import Chunk
class VectorDB(ABC):
@abstractmethod
def query(query: str, n: int = 4) -> List[Chunk]:
raise NotImplementedError
@abstractmethod
def insert(chunks: List[Chunk]):
raise NotImplementedError
class ChromaVectorDB(VectorDB):
def query(self, query: str, n: int = 4):
raise NotImplementedError
def insert(self, chunks: List[Chunk]):
raise NotImplementedError

View file

@ -1,14 +0,0 @@
from .anthropic import AnthropicLLM # noqa: F401
from .ggml import GGML # noqa: F401
from .google_palm_api import GooglePaLMAPI # noqa: F401
from .hf_inference_api import HuggingFaceInferenceAPI # noqa: F401
from .hf_tgi import HuggingFaceTGI # noqa: F401
from .llamacpp import LlamaCpp # noqa: F401
from .ollama import Ollama # noqa: F401
from .openai import OpenAI # noqa: F401
from .openai_free_trial import OpenAIFreeTrial # noqa: F401
from .proxy_server import ProxyServer # noqa: F401
from .queued import QueuedLLM # noqa: F401
from .replicate import ReplicateLLM # noqa: F401
from .text_gen_webui import TextGenWebUI # noqa: F401
from .together import TogetherLLM # noqa: F401

View file

@ -1,73 +0,0 @@
from typing import Any, Callable, Coroutine, Optional
from anthropic import AI_PROMPT, HUMAN_PROMPT, AsyncAnthropic
from .base import LLM, CompletionOptions
from .prompts.chat import anthropic_template_messages
class AnthropicLLM(LLM):
"""
To setup Anthropic, add the following to your `config.json` file:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Anthropic",
"provider": "anthropic",
"model": "claude-2",
"api_key": "YOUR_API_KEY"
}]
}
```
Claude 2 is not yet publicly released. You can request early access [here](https://www.anthropic.com/earlyaccess).
"""
api_key: Optional[str]
"Anthropic API key"
model: str = "claude-2"
template_messages: Callable = anthropic_template_messages
class Config:
arbitrary_types_allowed = True
def start(self, *args, **kwargs):
super().start(*args, **kwargs)
if self.model == "claude-2":
self.context_length = 100_000
def collect_args(self, options: CompletionOptions):
options.stop = None
args = super().collect_args(options)
if "max_tokens" in args:
args["max_tokens_to_sample"] = args["max_tokens"]
del args["max_tokens"]
if "frequency_penalty" in args:
del args["frequency_penalty"]
if "presence_penalty" in args:
del args["presence_penalty"]
return args
async def _stream_complete(self, prompt: str, options):
args = self.collect_args(options)
prompt = f"{HUMAN_PROMPT} {prompt} {AI_PROMPT}"
async for chunk in await AsyncAnthropic(
api_key=self.api_key
).completions.create(prompt=prompt, stream=True, **args):
yield chunk.completion
async def _complete(self, prompt: str, options) -> Coroutine[Any, Any, str]:
args = self.collect_args(options)
prompt = f"{HUMAN_PROMPT} {prompt} {AI_PROMPT}"
return (
await AsyncAnthropic(api_key=self.api_key).completions.create(
prompt=prompt, **args
)
).completion

View file

@ -1,478 +0,0 @@
import os
import ssl
from time import time
from typing import Any, AsyncGenerator, Callable, Coroutine, Dict, List, Optional
import aiohttp
import certifi
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
from ..util.count_tokens import (
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
compile_chat_messages,
count_tokens,
format_chat_messages,
prune_raw_prompt_from_top,
)
from ..util.devdata import dev_data_logger
from ..util.logging import logger
from ..util.telemetry import posthog_logger
class LLM(ContinueBaseModel):
title: Optional[str] = Field(
default=None,
description="A title that will identify this model in the model selection dropdown",
)
unique_id: Optional[str] = Field(
default=None, description="The unique ID of the user."
)
model: str = Field(
default=...,
description="The name of the model to be used (e.g. gpt-4, codellama)",
)
system_message: Optional[str] = Field(
default=None,
description="A system message that will always be followed by the LLM",
)
context_length: int = Field(
default=2048,
description="The maximum context length of the LLM in tokens, as counted by count_tokens.",
)
completion_options: BaseCompletionOptions = Field(
default=BaseCompletionOptions(),
description="Options for the completion endpoint. Read more about the completion options in the documentation.",
)
request_options: RequestOptions = Field(
default=RequestOptions(),
description="Options for the HTTP request to the LLM.",
)
prompt_templates: dict = Field(
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.',
)
template_messages: Optional[Callable[[List[ChatMessage]], str]] = Field(
default=None,
description="A function that takes a list of messages and returns a prompt. This ensures that models like llama2, which are trained on specific chat formats, will always receive input in that format.",
)
write_log: Optional[Callable[[str], Coroutine]] = Field(
default=None,
description="A function that is called upon every prompt and completion, by default to log to the file which can be viewed by clicking on the magnifying glass.",
)
llm_request_hook: Optional[Callable[[str, str], Any]] = Field(
default=None,
description="A function that will be called before every request to the LLM. It will be passed the model used (str) and the exact prompt that is sent to the LLM (str).",
)
api_key: Optional[str] = Field(
default=None, description="The API key for the LLM provider."
)
api_base: Optional[str] = Field(
default=None, description="The base URL of the LLM API."
)
class Config:
arbitrary_types_allowed = True
extra = "allow"
fields = {
"title": {
"description": "A title that will identify this model in the model selection dropdown"
},
"system_message": {
"description": "A system message that will always be followed by the LLM"
},
"context_length": {
"description": "The maximum context length of the LLM in tokens, as counted by count_tokens."
},
"unique_id": {"description": "The unique ID of the user."},
"model": {
"description": "The name of the model to be used (e.g. gpt-4, codellama)"
},
"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 OR an instance of the PromptTemplate class if you want to control other parameters. See the documentation for more information.'
},
"template_messages": {
"description": "A function that takes a list of messages and returns a prompt. This ensures that models like llama2, which are trained on specific chat formats, will always receive input in that format."
},
}
@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")
if self.template_messages is not None:
original_dict["template_messages"] = self.template_messages.__name__
original_dict.pop("unique_id")
original_dict["class_name"] = self.__class__.__name__
return original_dict
def start(self, unique_id: Optional[str] = None):
"""Start the connection to the LLM."""
self.unique_id = unique_id
async def stop(self):
"""Stop the connection to the LLM."""
pass
_config_system_message: Optional[str] = None
_config_temperature: Optional[float] = None
def set_main_config_params(
self, system_msg: Optional[str], temperature: Optional[float]
):
self._config_system_message = system_msg
self._config_temperature = temperature
def create_client_session(self):
if self.request_options.verify_ssl is False:
return aiohttp.ClientSession(
connector=aiohttp.TCPConnector(verify_ssl=False),
timeout=aiohttp.ClientTimeout(total=self.request_options.timeout),
headers=self.request_options.headers,
trust_env=True,
)
else:
ca_bundle_path = (
certifi.where()
if self.request_options.ca_bundle_path is None
else self.request_options.ca_bundle_path
)
if os.path.exists(ca_bundle_path):
ssl_context = ssl.create_default_context(cafile=ca_bundle_path)
return aiohttp.ClientSession(
connector=aiohttp.TCPConnector(ssl_context=ssl_context),
timeout=aiohttp.ClientTimeout(total=self.request_options.timeout),
headers=self.request_options.headers,
trust_env=True,
)
else:
logger.warning(
"Could not find CA bundle at %s, using default SSL context",
ca_bundle_path,
)
return aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=self.request_options.timeout),
headers=self.request_options.headers,
trust_env=True,
)
def collect_args(self, options: CompletionOptions) -> Dict[str, Any]:
"""Collect the arguments for the LLM."""
args = {**DEFAULT_ARGS.copy(), "model": self.model}
args.update(options.dict(exclude_unset=True, exclude_none=True))
return args
def compile_log_message(
self, prompt: str, completion_options: CompletionOptions
) -> str:
dict = {"context_length": self.context_length}
dict.update(completion_options.dict(exclude_unset=True, exclude_none=True))
settings = "\n".join([f"{key}: {value}" for key, value in dict.items()])
return f"""\
Settings:
{settings}
############################################
{prompt}"""
def get_system_message(self) -> Optional[str]:
return (
self.system_message
if self.system_message is not None
else self._config_system_message
)
def compile_chat_messages(
self,
options: CompletionOptions,
msgs: List[ChatMessage],
functions: Optional[List[Any]] = None,
) -> List[ChatMessage]:
# In case gpt-3.5-turbo-16k or something else is specified that has longer context_length
context_length = self.context_length
if options.model != self.model and options.model in CONTEXT_LENGTH_FOR_MODEL:
context_length = CONTEXT_LENGTH_FOR_MODEL[options.model]
return compile_chat_messages(
model_name=options.model,
msgs=msgs,
context_length=context_length,
max_tokens=options.max_tokens,
functions=functions,
system_message=self.get_system_message(),
)
def template_prompt_like_messages(self, prompt: str) -> str:
if self.template_messages is None:
return prompt
msgs = [ChatMessage(role="user", content=prompt, summary=prompt)]
if system_message := self.get_system_message():
msgs.insert(
0,
ChatMessage(role="system", content=system_message, summary=""),
)
return self.template_messages(msgs)
def log_tokens_generated(self, model: str, completion: str):
tokens = self.count_tokens(completion)
dev_data_logger.capture(
"tokens_generated",
{"model": model, "tokens": tokens, "model_class": self.__class__.__name__},
)
posthog_logger.capture_event(
"tokens_generated",
{"model": model, "tokens": tokens, "model_class": self.__class__.__name__},
)
async def stream_complete(
self,
prompt: str,
raw: bool = False,
model: Optional[str] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
presence_penalty: Optional[float] = None,
frequency_penalty: Optional[float] = None,
stop: Optional[List[str]] = None,
max_tokens: Optional[int] = None,
functions: Optional[List[Any]] = None,
log: bool = True,
) -> AsyncGenerator[str, None]:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
temperature=temperature or self.completion_options.temperature,
top_p=top_p or self.completion_options.top_p,
top_k=top_k or self.completion_options.top_k,
presence_penalty=presence_penalty
or self.completion_options.presence_penalty,
frequency_penalty=frequency_penalty
or self.completion_options.frequency_penalty,
stop=stop or self.completion_options.stop,
max_tokens=max_tokens or self.completion_options.max_tokens,
functions=functions,
)
prompt = prune_raw_prompt_from_top(
self.model, self.context_length, prompt, options.max_tokens
)
if not raw:
prompt = self.template_prompt_like_messages(prompt)
if log:
if self.write_log:
await self.write_log(self.compile_log_message(prompt, options))
if self.llm_request_hook:
self.llm_request_hook(options.model, prompt)
completion = ""
async for chunk in self._stream_complete(prompt=prompt, options=options):
yield chunk
completion += chunk
# if log:
# self.write_log(f"Completion: \n\n{completion}")
self.log_tokens_generated(options.model, completion)
async def complete(
self,
prompt: str,
raw: bool = False,
model: Optional[str] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
presence_penalty: Optional[float] = None,
frequency_penalty: Optional[float] = None,
stop: Optional[List[str]] = None,
max_tokens: Optional[int] = None,
functions: Optional[List[Any]] = None,
log: bool = True,
) -> str:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
temperature=temperature or self.completion_options.temperature,
top_p=top_p or self.completion_options.top_p,
top_k=top_k or self.completion_options.top_k,
presence_penalty=presence_penalty
or self.completion_options.presence_penalty,
frequency_penalty=frequency_penalty
or self.completion_options.frequency_penalty,
stop=stop or self.completion_options.stop,
max_tokens=max_tokens or self.completion_options.max_tokens,
functions=functions,
)
prompt = prune_raw_prompt_from_top(
self.model, self.context_length, prompt, options.max_tokens
)
if not raw:
prompt = self.template_prompt_like_messages(prompt)
if log:
if self.write_log:
await self.write_log(self.compile_log_message(prompt, options))
if self.llm_request_hook:
self.llm_request_hook(options.model, prompt)
completion = await self._complete(prompt=prompt, options=options)
# if log:
# self.write_log(f"Completion: \n\n{completion}")
self.log_tokens_generated(options.model, completion)
return completion
async def stream_chat(
self,
messages: List[ChatMessage],
model: Optional[str] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
top_k: Optional[int] = None,
presence_penalty: Optional[float] = None,
frequency_penalty: Optional[float] = None,
stop: Optional[List[str]] = None,
max_tokens: Optional[int] = None,
functions: Optional[List[Any]] = None,
log: bool = True,
) -> AsyncGenerator[ChatMessage, None]:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
temperature=temperature or self.completion_options.temperature,
top_p=top_p or self.completion_options.top_p,
top_k=top_k or self.completion_options.top_k,
presence_penalty=presence_penalty
or self.completion_options.presence_penalty,
frequency_penalty=frequency_penalty
or self.completion_options.frequency_penalty,
stop=stop or self.completion_options.stop,
max_tokens=max_tokens or self.completion_options.max_tokens,
functions=functions,
)
messages = self.compile_chat_messages(
options=options, msgs=messages, functions=functions
)
if self.template_messages is not None:
prompt = self.template_messages(messages)
else:
prompt = format_chat_messages(messages)
if log:
if self.write_log:
await self.write_log(self.compile_log_message(prompt, options))
if self.llm_request_hook:
self.llm_request_hook(options.model, prompt)
completion = ""
# Use the template_messages function if it exists and do a raw completion
ti = time()
tf = None
if self.template_messages is None:
async for chunk in self._stream_chat(messages=messages, options=options):
yield chunk
if chunk.content:
completion += chunk.content
if tf is None:
tf = time()
ttft = tf - ti
posthog_logger.capture_event(
"time_to_first_token",
{
"model": self.model,
"model_class": self.__class__.__name__,
"time": ttft,
"tokens": sum(
self.count_tokens(m.content or "") for m in messages
),
},
)
else:
async for chunk in self._stream_complete(prompt=prompt, options=options):
yield ChatMessage(role="assistant", content=chunk, summary=chunk)
completion += chunk
if tf is None:
tf = time()
ttft = tf - ti
posthog_logger.capture_event(
"time_to_first_token",
{
"model": self.model,
"model_class": self.__class__.__name__,
"time": ttft,
"tokens": self.count_tokens(prompt),
},
)
# if log:
# self.write_log(f"Completion: \n\n{completion}")
self.log_tokens_generated(options.model, completion)
def _stream_complete(
self, prompt, options: CompletionOptions
) -> AsyncGenerator[str, None]:
"""Stream the completion through generator."""
raise NotImplementedError
async def _complete(self, prompt: str, options: CompletionOptions) -> str:
"""Return the completion of the text with the given temperature."""
completion = ""
async for chunk in self._stream_complete(prompt=prompt, options=options):
completion += chunk
return completion
async def _stream_chat(
self, messages: List[ChatMessage], options: CompletionOptions
) -> AsyncGenerator[ChatMessage, None]:
"""Stream the chat through generator."""
if self.template_messages is None:
raise NotImplementedError(
"You must either implement template_messages or _stream_chat"
)
async for chunk in self._stream_complete(
prompt=self.template_messages(messages), options=options
):
yield ChatMessage(role="assistant", content=chunk, summary=chunk)
def count_tokens(self, text: str):
"""Return the number of tokens in the given text."""
return count_tokens(text, self.model)

View file

@ -1,92 +0,0 @@
import json
import aiohttp
import requests
IP = "129.213.24.72"
def requests_test():
resp = requests.post(
f"http://{IP}:8000/v1/completions",
json={
"prompt": "Hello! What is your name?",
"model": "mistralai/Mistral-7B-Instruct-v0.1",
},
)
print(resp.json())
async def basic_test():
async with aiohttp.ClientSession() as client_session:
async with client_session.post(
f"http://{IP}:8000/v1/completions",
json={
"prompt": "Hello! What is your name?",
"model": "mistralai/Mistral-7B-Instruct-v0.1",
},
) as resp:
j = await resp.json()
print(j)
return j
async def streaming_test():
headers = {"Content-Type": "application/json"}
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=3600),
headers=headers,
trust_env=True,
) as client_session:
async with client_session.post(
f"http://{IP}:8000/v1/completions",
json={
"prompt": "Hello! What is your name?",
"model": "mistralai/Mistral-7B-Instruct-v0.1",
"stream": True,
},
headers=headers,
) as resp:
if resp.status != 200:
raise Exception(f"Error calling /completions endpoint: {resp.status}")
async for line in resp.content.iter_any():
if line:
chunks = line.decode("utf-8")
for chunk in chunks.split("\n"):
if (
chunk.startswith(": ping - ")
or chunk.startswith("data: [DONE]")
or chunk.strip() == ""
):
continue
elif chunk.startswith("data: "):
chunk = chunk[6:]
try:
j = json.loads(chunk)
except Exception:
continue
if (
"choices" in j
and len(j["choices"]) > 0
and "text" in j["choices"][0]
):
yield j["choices"][0]["text"]
async def main():
# Test requests (you mentioned that this worked before)
requests_test()
# Test non-streaming response
await basic_test()
# Test streaming response, like what happens in Continue
async for i in streaming_test():
print(i)
if __name__ == "__main__":
import asyncio
asyncio.run(main())

View file

@ -1,255 +0,0 @@
import json
from typing import Any, AsyncGenerator, Coroutine, List, Literal, Optional
from pydantic import Field, validator
from ...core.main import ChatMessage, ContinueCustomException
from ..util.logging import logger
from .base import LLM, CompletionOptions
from .openai import CHAT_MODELS
class GGML(LLM):
"""
See our [5 minute quickstart](https://github.com/continuedev/ggml-server-example) to run any model locally with ggml. While these models don't yet perform as well, they are free, entirely private, and run offline.
You can also use this class for [LM Studio](https://lmstudio.ai).
Once the model is running on localhost:8000, change `~/.continue/config.json` to look like this:
```json title="~/.continue/config.json"
{
"models": [{
"title": "GGML",
"provider": "openai-aiohttp",
"model": "MODEL_NAME",
"api_base": "http://localhost:8000"
}]
}
```
"""
api_base: Optional[str] = Field(
"http://127.0.0.1:8000",
description="URL of the OpenAI-compatible server where the model is being served",
)
@validator("api_base", pre=True, always=True)
def set_api_base(cls, api_base):
return api_base or "http://127.0.0.1:8000"
model: str = Field(
"ggml", description="The name of the model to use (optional for the GGML class)"
)
api_type: Optional[Literal["azure", "openai"]] = Field(
default=None, description="OpenAI API type."
)
api_version: Optional[str] = Field(
default=None,
description="OpenAI API version. For use with Azure OpenAI Service.",
)
engine: Optional[str] = Field(
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
def get_headers(self):
headers = {
"Content-Type": "application/json",
}
if self.api_key is not None:
if self.api_type == "azure":
headers["api-key"] = self.api_key
else:
headers["Authorization"] = f"Bearer {self.api_key}"
return headers
def get_full_server_url(self, endpoint: str):
endpoint = endpoint.lstrip("/").rstrip("/")
if self.api_type == "azure":
if self.engine is None or self.api_version is None or self.api_base is None:
raise Exception(
"For Azure OpenAI Service, you must specify engine, api_version, and api_base."
)
return f"{self.api_base}/openai/deployments/{self.engine}/{endpoint}?api-version={self.api_version}"
else:
return f"{self.api_base}/v1/{endpoint}"
async def _raw_stream_complete(self, prompt, options):
args = self.collect_args(options)
async with self.create_client_session() as client_session:
async with client_session.post(
self.get_full_server_url(endpoint=self.completions_endpoint),
json={
"prompt": prompt,
"stream": True,
**args,
},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:
if resp.status != 200:
raise Exception(
f"Error calling /completions endpoint: {resp.status}"
)
async for line in resp.content.iter_any():
if line:
chunks = line.decode("utf-8")
for chunk in chunks.split("\n"):
if (
chunk.startswith(": ping - ")
or chunk.startswith("data: [DONE]")
or chunk.strip() == ""
):
continue
elif chunk.startswith("data: "):
chunk = chunk[6:]
try:
j = json.loads(chunk)
except Exception:
continue
if (
"choices" in j
and len(j["choices"]) > 0
and "text" in j["choices"][0]
):
yield j["choices"][0]["text"]
async def _stream_chat(
self, messages: List[ChatMessage], options
) -> AsyncGenerator[ChatMessage, None]:
args = self.collect_args(options)
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=self.chat_endpoint),
json={
"messages": [msg.to_dict() for msg in messages],
"stream": True,
**args,
},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:
if resp.status != 200:
detail = (
f"Error calling /chat/completions endpoint: {resp.status}"
)
try:
json_detail = await resp.json()
if (
"detail" in json_detail
and "error" in json_detail["detail"]
and "message" in json_detail["detail"]["error"]
):
detail = json_detail["detail"]["error"]["message"]
elif "message" in json_detail:
detail = json_detail["message"]
elif "detail" in json_detail:
detail = json_detail["detail"]
except Exception:
pass
raise ContinueCustomException(
title=f"Error calling /chat/completions endpoint: {resp.status}",
message=detail,
)
async for line, end in resp.content.iter_chunks():
json_chunk = line.decode("utf-8")
chunks = json_chunk.split("\n")
for chunk in chunks:
if (
chunk.strip() == ""
or json_chunk.startswith(": ping - ")
or json_chunk.startswith("data: [DONE]")
):
continue
try:
delta = json.loads(chunk[6:])["choices"][0]["delta"]
yield ChatMessage(
role="assistant", content=delta.get("content", "")
)
except Exception:
pass
# Because quite often the first attempt fails, and it works thereafter
try:
async for chunk in generator():
yield chunk
except Exception as e:
logger.warning(f"Error calling /chat/completions endpoint: {e}")
async for chunk in generator():
yield chunk
async def _raw_complete(self, prompt: str, options) -> Coroutine[Any, Any, str]:
args = self.collect_args(options)
async with self.create_client_session() as client_session:
async with client_session.post(
self.get_full_server_url(endpoint=self.completions_endpoint),
json={
"prompt": prompt,
**args,
},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:
if resp.status != 200:
raise Exception(
f"Error calling /completions endpoint: {resp.status}"
)
text = await resp.text()
try:
completion = json.loads(text)["choices"][0]["text"]
return completion
except Exception as e:
raise Exception(
f"Error calling /completions endpoint: {e}\n\nResponse text: {text}"
)
async def _complete(self, prompt: str, options: CompletionOptions):
completion = ""
if self.model in CHAT_MODELS:
async for chunk in self._stream_chat(
[ChatMessage(role="user", content=prompt)], options
):
completion += chunk.content
else:
async for chunk in self._raw_stream_complete(prompt, options):
completion += chunk
return completion
async def _stream_complete(self, prompt, options: CompletionOptions):
if self.model in CHAT_MODELS:
async for chunk in self._stream_chat(
[ChatMessage(role="user", content=prompt)], options
):
yield chunk.content
else:
async for chunk in self._raw_stream_complete(prompt, options):
yield chunk

View file

@ -1,50 +0,0 @@
from typing import List
import requests
from pydantic import Field
from ...core.main import ChatMessage
from .base import LLM
class GooglePaLMAPI(LLM):
"""
The Google PaLM API is currently in public preview, so production applications are not supported yet. However, you can [create an API key in Google MakerSuite](https://makersuite.google.com/u/2/app/apikey) and begin trying out the `chat-bison-001` model. Change `~/.continue/config.json` to look like this:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Chat Bison",
"provider": "google-palm",
"model": "chat-bison-001",
"api_key": "YOUR_API_KEY"
}]
}
```
"""
api_key: str = Field(..., description="Google PaLM API key")
model: str = "chat-bison-001"
async def _stream_complete(self, prompt, options):
api_url = f"https://generativelanguage.googleapis.com/v1beta2/models/{self.model}:generateMessage?key={self.api_key}"
body = {"prompt": {"messages": [{"content": prompt}]}}
response = requests.post(api_url, json=body)
data = response.json()
if "candidates" in data:
yield data["candidates"][0]["content"]
async def _stream_chat(self, messages: List[ChatMessage], options):
msg_lst = []
for message in messages:
msg_lst.append({"content": message.content})
api_url = f"https://generativelanguage.googleapis.com/v1beta2/models/{self.model}:generateMessage?key={self.api_key}"
body = {"prompt": {"messages": msg_lst}}
response = requests.post(api_url, json=body)
data = response.json()
if "candidates" in data:
yield ChatMessage(
role="assistant", content=data["candidates"][0]["content"]
)

View file

@ -1,66 +0,0 @@
from typing import Optional
from huggingface_hub import InferenceClient
from pydantic import Field
from .base import LLM, CompletionOptions
class HuggingFaceInferenceAPI(LLM):
"""
Hugging Face Inference API is a great option for newly released language models. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Hugging Face Inference API",
"provider": "huggingface-inference-api",
"model": "MODEL_NAME",
"api_key": "YOUR_HF_TOKEN",
"api_base": "INFERENCE_API_ENDPOINT_URL"
}]
}
```
"""
model: str = Field(
"Hugging Face Inference API",
description="The name of the model to use (optional for the HuggingFaceInferenceAPI class)",
)
api_key: str = Field(..., description="Your Hugging Face API token")
api_base: Optional[str] = Field(
None, description="Your Hugging Face Inference API endpoint URL"
)
class Config:
arbitrary_types_allowed = True
def collect_args(self, options: CompletionOptions):
options.stop = None
args = super().collect_args(options)
if "max_tokens" in args:
args["max_new_tokens"] = args["max_tokens"]
del args["max_tokens"]
if "stop" in args:
args["stop_sequences"] = args["stop"]
del args["stop"]
return args
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
client = InferenceClient(self.api_base, token=self.api_key)
stream = client.text_generation(prompt, stream=True, details=True, **args)
for r in stream:
# skip special tokens
if r.token.special:
continue
# stop if we encounter a stop sequence
if options.stop is not None:
if r.token.text in options.stop:
break
yield r.token.text

View file

@ -1,65 +0,0 @@
import json
from typing import Any, Optional
from pydantic import Field, validator
from ..util.count_tokens import DEFAULT_MAX_TOKENS
from .base import LLM, CompletionOptions
class HuggingFaceTGI(LLM):
model: str = "huggingface-tgi"
api_base: Optional[str] = Field(
"http://127.0.0.1:8080", description="URL of your TGI server"
)
@validator("api_base", pre=True, always=True)
def set_api_base(cls, api_base):
return api_base or "http://127.0.0.1:8080"
class Config:
arbitrary_types_allowed = True
def collect_args(self, options: CompletionOptions) -> Any:
args = super().collect_args(options)
args = {
**args,
"max_new_tokens": args.get("max_tokens", DEFAULT_MAX_TOKENS),
"best_of": 1,
}
args.pop("max_tokens", None)
args.pop("model", None)
args.pop("functions", None)
return args
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
async with self.create_client_session() as client_session:
async with client_session.post(
f"{self.api_base}/generate_stream",
json={"inputs": prompt, "parameters": args},
headers={"Content-Type": "application/json"},
proxy=self.request_options.proxy,
) as resp:
async for line in resp.content.iter_any():
if line:
text = line.decode("utf-8")
chunks = text.split("\n")
for chunk in chunks:
if chunk.startswith("data: "):
chunk = chunk[len("data: ") :]
elif chunk.startswith("data:"):
chunk = chunk[len("data:") :]
if chunk.strip() == "":
continue
try:
json_chunk = json.loads(chunk)
except Exception as e:
print(f"Error parsing JSON: {e}")
continue
yield json_chunk["token"]["text"]

View file

@ -1,83 +0,0 @@
import json
from typing import Any, Dict, Optional
from pydantic import Field, validator
from .base import LLM
class LlamaCpp(LLM):
"""
Run the llama.cpp server binary to start the API server. If running on a remote server, be sure to set host to 0.0.0.0:
```shell
.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models\\meta\\llama\\codellama-7b-instruct.Q8_0.gguf
```
After it's up and running, change `~/.continue/config.json` to look like this:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Llama CPP",
"provider": "llama.cpp",
"model": "MODEL_NAME",
"api_base": "http://localhost:8080"
}]
}
```
"""
model: str = "llamacpp"
api_base: Optional[str] = Field(
"http://127.0.0.1:8080", description="URL of the server"
)
@validator("api_base", pre=True, always=True)
def set_api_base(cls, api_base):
return api_base or "http://127.0.0.1:8080"
llama_cpp_args: Dict[str, Any] = Field(
{"stop": ["[INST]"]},
description="A list of additional arguments to pass to llama.cpp. See https://github.com/ggerganov/llama.cpp/tree/master/examples/server#api-endpoints for the complete catalog of options.",
)
class Config:
arbitrary_types_allowed = True
def collect_args(self, options) -> Any:
args = super().collect_args(options)
if "max_tokens" in args:
args["n_predict"] = args["max_tokens"]
del args["max_tokens"]
if "frequency_penalty" in args:
del args["frequency_penalty"]
if "presence_penalty" in args:
del args["presence_penalty"]
for k, v in self.llama_cpp_args.items():
if k not in args:
args[k] = v
return args
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
headers = {"Content-Type": "application/json"}
async def server_generator():
async with self.create_client_session() as client_session:
async with client_session.post(
f"{self.api_base}/completion",
json={"prompt": prompt, "stream": True, **args},
headers=headers,
proxy=self.request_options.proxy,
) as resp:
async for line in resp.content:
content = line.decode("utf-8")
if content.strip() == "":
continue
yield json.loads(content[6:])["content"]
async for chunk in server_generator():
yield chunk

View file

@ -1,116 +0,0 @@
import asyncio
import socket
import subprocess
from typing import List, Optional
from continuedev.core.main import ChatMessage, ContinueCustomException
from continuedev.models.llm import CompletionOptions
from .llamacpp import LlamaCpp
def test_port(PORT):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(("", PORT)) ## Try to open port
except OSError as e:
if e.errno == 98: ## Errorno 98 means address already bound
return True
elif e.errno == 48: ## Errorno 48 means address already in use
return True
return False
s.close()
return False
STARTUP_DELAY = 3.0
class Llamafile(LlamaCpp):
"""
A [llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) is a self-contained binary that can run an open-source LLM. You can configure this provider in your config.json as follows:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Llamafile",
"provider": "llamafile",
"model": "mistral-7b",
}]
}
```
Optionally, you can set the `llamafile_command` property, which will be run to start the llamafile if it isn't already running on port 8080. Be sure to use an absolute path to the llamafile binary. For example: `/Users/yourusername/mistral-7b-instruct-v0.1-Q4_K_M-server.llamafile`.
"""
llamafile_command: Optional[str] = None
llamafile_process: Optional[subprocess.Popen] = None
def check_and_start(self, should_raise: bool) -> bool:
# Try to start the llamafile if it's not already started on port 8080
if not self.llamafile_command:
return False
port = int((self.api_base or ":8080").split(":")[-1])
if not test_port(port):
if should_raise and self.llamafile_process:
# If already tried to start and it isn't started, raise an exception
_, err = self.llamafile_process.communicate()
err = err.decode("utf-8") if err else ""
err_string = f"Error starting llamafile\n\n{err}"
raise ContinueCustomException(err_string, err_string)
import threading
def process_run():
p = subprocess.Popen(
self.llamafile_command.split(" "),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
start_new_session=True,
shell=True,
)
self.llamafile_process = p
t = threading.Thread(target=process_run)
t.start()
return True
return False
def start(self, unique_id: str | None = None):
super().start(unique_id)
self.check_and_start(False)
def dict(self, **kwargs):
d = super().dict(**kwargs)
if "llamafile_process" in d:
del d["llamafile_process"]
return d
async def _stream_chat(
self, messages: List[ChatMessage], options: CompletionOptions
):
if self.check_and_start(True):
await asyncio.sleep(STARTUP_DELAY)
async for message in super()._stream_chat(messages, options):
yield message
async def _stream_complete(self, prompt, options):
if self.check_and_start(True):
await asyncio.sleep(STARTUP_DELAY)
async for message in super()._stream_complete(prompt, options):
yield message
async def _complete(self, prompt: str, options: CompletionOptions):
if self.check_and_start(True):
await asyncio.sleep(STARTUP_DELAY)
return await super()._complete(prompt, options)

View file

@ -1,7 +0,0 @@
from .ggml import GGML
class LMStudio(GGML):
"""LMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue."""
api_base: str = "http://127.0.0.1:1234"

View file

@ -1,138 +0,0 @@
import json
from typing import Any, Dict, Optional
import requests
from pydantic import Field, validator
from ...core.main import ContinueCustomException
from ..util.logging import logger
from .base import LLM, CompletionOptions
class Ollama(LLM):
"""
[Ollama](https://ollama.ai/) is an application for Mac and Linux that makes it easy to locally run open-source models, including Llama-2. Download the app from the website, and it will walk you through setup in a couple of minutes. You can also read more in their [README](https://github.com/jmorganca/ollama). Continue can then be configured to use the `Ollama` LLM class:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Ollama",
"provider": "ollama",
"model": "llama2-7b",
}]
}
```
"""
model: str = "llama2"
api_base: Optional[str] = Field(
"http://127.0.0.1:11434", description="URL of the Ollama server"
)
@validator("api_base", pre=True, always=True)
def set_api_base(cls, api_base):
return api_base or "http://127.0.0.1:11434"
class Config:
arbitrary_types_allowed = True
def collect_args(self, options: CompletionOptions) -> Dict[str, Any]:
return {
"temperature": options.temperature,
"top_p": options.top_p,
"top_k": options.top_k,
"num_predict": options.max_tokens,
"stop": options.stop,
"num_ctx": self.context_length,
}
def get_model_name(self):
return {
"mistral-7b": "mistral:7b",
"llama2-7b": "llama2:7b",
"llama2-13b": "llama2:13b",
"codellama-7b": "codellama:7b",
"codellama-13b": "codellama:13b",
"codellama-34b": "codellama:34b",
"phind-codellama-34b": "phind-codellama:34b-v2",
"wizardcoder-7b": "wizardcoder:7b-python",
"wizardcoder-13b": "wizardcoder:13b-python",
"wizardcoder-34b": "wizardcoder:34b-python",
"zephyr-7b": "zephyr:7b",
"codeup-13b": "codeup:13b",
"deepseek-1b": "deepseek-coder:1.3b",
"deepseek-7b": "deepseek-coder:6.7b",
"deepseek-33b": "deepseek-coder:33b",
"neural-chat-7b": "neural-chat:7b-v3.3",
"phi-2.7b": "phi:2.7b"
}.get(self.model, self.model)
def start(self, *args, **kwargs):
super().start(*args, **kwargs)
try:
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}")
async def get_downloaded_models(self):
async with self.create_client_session() as session:
async with session.get(
f"{self.api_base}/api/tags",
proxy=self.request_options.proxy,
) as resp:
js_data = await resp.json()
return list(map(lambda x: x["name"], js_data["models"]))
async def _stream_complete(self, prompt, options):
async with self.create_client_session() as session:
async with session.post(
f"{self.api_base}/api/generate",
json={
"prompt": prompt,
"raw": True,
"model": self.get_model_name(),
"options": self.collect_args(options),
},
proxy=self.request_options.proxy,
) as resp:
if resp.status == 400:
txt = await resp.text()
extra_msg = ""
if "no such file" in txt:
extra_msg = f"\n\nThis means that the model '{self.get_model_name()}' is not downloaded.\n\nYou have the following models downloaded: {', '.join(await self.get_downloaded_models())}.\n\nTo download this model, run `ollama run {self.get_model_name()}` in your terminal."
raise ContinueCustomException(
f"Ollama returned an error: {txt}{extra_msg}",
"Invalid request to Ollama",
)
elif resp.status == 404:
model_name = self.get_model_name()
raise ContinueCustomException(
f"Ollama returned 404. Make sure the server is running and '{model_name}' is downloaded with `ollama run {model_name}`.\n\n{await resp.text()}",
f"Ollama returned 404. Make sure the server is running and '{model_name}' is downloaded with `ollama run {model_name}`.",
)
elif resp.status != 200:
raise ContinueCustomException(
f"Ollama returned an error: {await resp.text()}",
f"Ollama returned an error: {await resp.text()}",
)
async for line in resp.content.iter_any():
if line:
json_chunk = line.decode("utf-8")
chunks = json_chunk.split("\n")
for chunk in chunks:
if chunk.strip() != "":
try:
j = json.loads(chunk)
except Exception as e:
logger.warning(
f"Error parsing Ollama response: {e} {chunk}"
)
continue
if "response" in j:
yield j["response"]

View file

@ -1,227 +0,0 @@
import asyncio
from contextlib import asynccontextmanager
from typing import AsyncGenerator, List, Literal, Optional
import httpx
import litellm
from litellm import acompletion
from pydantic import Field, validator
from ...core.main import ChatMessage
from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL
from .base import LLM
CHAT_MODELS = {
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview",
}
NON_CHAT_MODELS = {
"gpt-3.5-turbo-instruct",
"text-davinci-003",
"text-davinci-002",
"code-davinci-002",
"babbage-002",
"davinci-002",
"text-curie-001",
"text-babbage-001",
"text-ada-001",
"davinci",
"curie",
"babbage",
"ada",
}
class OpenAI(LLM):
"""
The OpenAI class can be used to access OpenAI models like GPT-4, GPT-4 Turbo, and GPT-3.5 Turbo.
### Azure OpenAI Service
If you'd like to use OpenAI models but are concerned about privacy, you can use the Azure OpenAI service, which is GDPR and HIPAA compliant. After applying for access [here](https://azure.microsoft.com/en-us/products/ai-services/openai-service), you will typically hear back within only a few days. Once you have access, set up a model in `config.json` like so:
```json
"models": [{
"title": "Azure OpenAI",
"provider": "openai",
"model": "gpt-4",
"api_base": "https://my-azure-openai-instance.openai.azure.com/",
"engine": "my-azure-openai-deployment",
"api_version": "2023-07-01-preview",
"api_type": "azure",
"api_key": "<MY_API_KEY>"
}]
```
The easiest way to find this information is from the chat playground in the Azure OpenAI portal. Under the "Chat Session" section, click "View Code" to see each of these parameters.
### OpenAI compatible servers / APIs
OpenAI compatible servers
- [text-gen-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai#setup--installation)
- [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md)
- [LocalAI](https://localai.io/basics/getting_started/)
- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python#web-server)
OpenAI compatible APIs
- [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others)
- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints)
If you are [using an OpenAI compatible server / API](../../model-setup/select-provider#local), you can change the `api_base` like this:
```json title="~/.continue/config.json"
{
"models": [{
"title": "OpenAI-compatible server / API",
"provider": "openai",
"model": "MODEL_NAME",
"api_key": "EMPTY",
"api_base": "http://localhost:8000"
}]
}
```
"""
api_key: str = Field(
...,
description="OpenAI API key",
)
api_base: Optional[str] = Field(default=None, description="OpenAI API base URL.")
api_type: Optional[Literal["azure", "openai"]] = Field(
default=None, description="OpenAI API type."
)
api_version: Optional[str] = Field(
default=None,
description="OpenAI API version. For use with Azure OpenAI Service.",
)
engine: Optional[str] = Field(
default=None, description="OpenAI engine. For use with Azure OpenAI Service."
)
use_legacy_completions_endpoint: bool = Field(
default=False,
description="Manually specify to use the legacy completions endpoint instead of chat completions.",
)
@validator("context_length")
def context_length_for_model(cls, v, values):
return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096)
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)
def collect_args(self, options):
args = super().collect_args(options)
if self.api_type == "azure":
assert self.engine is not None, "engine must be specified for Azure API"
args["model"] = f"azure/{self.engine}"
args["api_version"] = self.api_version
args["api_key"] = self.api_key
args["api_base"] = self.api_base
if not args["model"].endswith("0613") and "functions" in args:
del args["functions"]
return args
def httpx_client(self) -> httpx.AsyncClient:
args = {}
if timeout := self.request_options.timeout:
args["timeout"] = httpx.Timeout(timeout)
if verify_ssl := self.request_options.verify_ssl:
args["verify"] = verify_ssl
if ca_bundle_path := self.request_options.ca_bundle_path:
args["cert"] = ca_bundle_path
if proxy := self.request_options.proxy:
args["proxies"] = {"https": proxy, "http": proxy}
if headers := self.request_options.headers:
args["headers"] = headers
return httpx.AsyncClient(**args)
@asynccontextmanager
async def httpx_client_context(self):
client = self.httpx_client()
litellm.aclient_session = client
try:
yield
finally:
await client.aclose()
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
async with self.httpx_client_context():
resp = await acompletion(
messages=[{"content": prompt, "role": "user"}],
**args,
stream=True,
)
async for chunk in resp:
if chunk.choices[0].delta.content is None:
continue
yield chunk.choices[0].delta.content
async def _stream_chat(
self, messages: List[ChatMessage], options
) -> AsyncGenerator[ChatMessage, None]:
args = self.collect_args(options)
# and not self.use_legacy_completions_endpoint
# headers=self.request_options.headers,
# resp = await acompletion(
# messages=[msg.to_dict() for msg in messages],
# **args,
# api_base=self.api_base,
# api_version=self.api_version,
# # engine=self.engine,
# api_key=self.api_key,
# custom_llm_provider="azure" if self.api_type == "azure" else None,
# )
async with self.httpx_client_context():
resp = await acompletion(
messages=[msg.to_dict() for msg in messages],
**args,
stream=True,
)
async for chunk in resp:
if len(chunk.choices) == 0:
continue # :)
if self.api_type == "azure":
if self.model == "gpt-4":
await asyncio.sleep(0.03)
else:
await asyncio.sleep(0.01)
yield ChatMessage(
role="assistant", content=chunk.choices[0].delta.content or ""
)
async def _complete(self, prompt: str, options):
args = self.collect_args(options)
async with self.httpx_client_context():
resp = await acompletion(
messages=[{"content": prompt, "role": "user"}],
**args,
)
return resp.choices[0].message.content

View file

@ -1,101 +0,0 @@
from typing import List, Optional
from pydantic import Field, validator
from ...core.main import ChatMessage
from ...models.llm import RequestOptions
from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL
from .base import LLM
from .openai import OpenAI
from .proxy_server import ProxyServer
class OpenAIFreeTrial(LLM):
"""
With the `OpenAIFreeTrial` `LLM`, new users can try out Continue with GPT-4 using a proxy server that securely makes calls to OpenAI using our API key. Continue should just work the first time you install the extension in VS Code.
Once you are using Continue regularly though, you will need to add an OpenAI API key that has access to GPT-4 by following these steps:
1. Copy your API key from https://platform.openai.com/account/api-keys
2. Open `~/.continue/config.json`. You can do this by using the '/config' command in Continue
3. Change the default LLMs to look like this:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "GPT-4",
"provider": "openai",
"model": "gpt-4",
"api_key": "YOUR_API_KEY"
},
{
"title": "GPT-3.5-Turbo",
"provider": "openai",
"model": "gpt-3.5-turbo",
"api_key": "YOUR_API_KEY"
}
],
"model_roles": {
"default": "GPT-4",
"summarize": "GPT-3.5-Turbo"
}
}
```
"""
llm: LLM = Field(default=None, description="The LLM to use for completion.")
@validator("llm", pre=True, always=True)
def set_llm(cls, llm, values):
api_key = values.get("api_key")
if api_key is None or api_key.strip() == "":
return ProxyServer(
model=values["model"],
request_options=RequestOptions(
timeout=values["request_options"].timeout,
verify_ssl=values["request_options"].verify_ssl,
),
)
else:
return OpenAI(
api_key=api_key,
model=values["model"],
request_options=RequestOptions(
timeout=values["request_options"].timeout,
verify_ssl=values["request_options"].verify_ssl,
),
)
@validator("context_length", pre=True, always=True)
def context_length_for_model(cls, v, values):
return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096)
def update_llm_properties(self):
self.llm.system_message = self.system_message
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()
async def _complete(self, prompt: str, options):
self.update_llm_properties()
return await self.llm._complete(prompt, options)
async def _stream_complete(self, prompt, options):
self.update_llm_properties()
resp = self.llm._stream_complete(prompt, options)
async for item in resp:
yield item
async def _stream_chat(self, messages: List[ChatMessage], options):
self.update_llm_properties()
resp = self.llm._stream_chat(messages=messages, options=options)
async for item in resp:
yield item
def count_tokens(self, text: str):
return self.llm.count_tokens(text)

View file

@ -1,76 +0,0 @@
from typing import Dict, List, Union
from ...models.filesystem import RangeInFileWithContents
from ...models.filesystem_edit import FileEdit
class MarkdownStyleEncoderDecoder:
# Filename -> the part of the file you care about
range_in_files: List[RangeInFileWithContents]
def __init__(self, range_in_files: List[RangeInFileWithContents]):
self.range_in_files = range_in_files
def encode(self) -> str:
return "\n\n".join(
[
f"File ({rif.filepath})\n```\n{rif.contents}\n```"
for rif in self.range_in_files
]
)
def _suggestions_to_file_edits(self, suggestions: Dict[str, str]) -> List[FileEdit]:
file_edits: List[FileEdit] = []
for suggestion_filepath, suggestion in suggestions.items():
matching_rifs = list(
filter(lambda r: r.filepath == suggestion_filepath, self.range_in_files)
)
if len(matching_rifs) > 0:
range_in_file = matching_rifs[0]
file_edits.append(
FileEdit(
range=range_in_file.range,
filepath=range_in_file.filepath,
replacement=suggestion,
)
)
return file_edits
def _decode_to_suggestions(self, completion: str) -> Dict[str, str]:
if len(self.range_in_files) == 0:
return {}
if "```" not in completion:
completion = "```\n" + completion + "\n```"
if completion.strip().splitlines()[0].strip() == "```":
first_filepath = self.range_in_files[0].filepath
completion = f"File ({first_filepath})\n" + completion
suggestions: Dict[str, str] = {}
current_file_lines: List[str] = []
current_filepath: Union[str, None] = None
last_was_file = False
inside_file = False
for line in completion.splitlines():
if line.strip().startswith("File ("):
last_was_file = True
current_filepath = line.strip()[6:-1]
elif last_was_file and line.startswith("```"):
last_was_file = False
inside_file = True
elif inside_file:
if line.startswith("```"):
inside_file = False
suggestions[current_filepath] = "\n".join(current_file_lines)
current_file_lines = []
current_filepath = None
else:
current_file_lines.append(line)
return suggestions
def decode(self, completion: str) -> List[FileEdit]:
suggestions = self._decode_to_suggestions(completion)
file_edits = self._suggestions_to_file_edits(suggestions)
return file_edits

View file

@ -1,261 +0,0 @@
from textwrap import dedent
from typing import List
from anthropic import AI_PROMPT, HUMAN_PROMPT
from ....core.main import ChatMessage
def anthropic_template_messages(messages: List[ChatMessage]) -> str:
prompt = ""
# Anthropic prompt must start with a Human turn
if (
len(messages) > 0
and messages[0].role != "user"
and messages[0].role != "system"
):
prompt += f"{HUMAN_PROMPT} Hello."
for msg in messages:
prompt += f"{HUMAN_PROMPT if (msg.role == 'user' or msg.role == 'system') else AI_PROMPT} {msg.content} "
prompt += AI_PROMPT
return prompt
def zephyr_template_messages(msgs: List[ChatMessage]) -> str:
""" "
<|system|>
</s>
<|user|>
{prompt}</s>
<|assistant|>
"""
prompt = ""
if msgs[0].role == "system":
prompt += f"<|system|>{msgs[0].content}</s>\n"
msgs.pop(0)
else:
prompt += "<|system|> </s>\n"
for msg in msgs:
prompt += "<|user|>\n" if msg.role == "user" else "<|assistant|>\n"
prompt += f"{msg.content}</s>\n"
prompt += "<|assistant|>\n"
return prompt
def chatml_template_messages(messages: List[ChatMessage]) -> str:
prompt = ""
for msg in messages:
prompt += f"<|im_start|>{msg.role}\n{msg.content}<|im_end|>\n"
prompt += "<|im_start|>assistant\n"
return prompt
def template_alpaca_messages(msgs: List[ChatMessage]) -> str:
prompt = ""
if msgs[0].role == "system":
prompt += f"{msgs[0].content}\n\n"
msgs.pop(0)
for msg in msgs:
prompt += "### Instruction:\n" if msg.role == "user" else "### Response:\n"
prompt += f"{msg.content}\n\n"
prompt += "### Response:\n"
return prompt
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":
system = msgs.pop(0).content
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"
return prompt + "### Response:\n"
def phind_template_messages(msgs: List[ChatMessage]) -> str:
prompt = ""
if msgs[0].role == "system":
prompt += f"### System Prompt\n{msgs[0].content}\n\n"
msgs.pop(0)
for msg in msgs:
prompt += "### User Message\n" if msg.role == "user" else "### Assistant\n"
prompt += f"{msg.content}\n"
prompt += "### Assistant\n"
return prompt
def neuralchat_template_messages(msgs: List[ChatMessage]) -> str:
prompt = ""
if msgs[0].role == "system":
prompt += f"### System:\n{msgs[0].content}\n"
msgs.pop(0)
for msg in msgs:
prompt += "### User:\n" if msg.role == "user" else "### Assistant:\n"
prompt += f"{msg.content}\n"
prompt += "### Assistant:\n"
return prompt
def raw_input_template(msgs: List[ChatMessage]) -> str:
return msgs[-1].content
SQL_CODER_DEFAULT_SCHEMA = """\
CREATE TABLE products (
product_id INTEGER PRIMARY KEY, -- Unique ID for each product
name VARCHAR(50), -- Name of the product
price DECIMAL(10,2), -- Price of each unit of the product
quantity INTEGER -- Current quantity in stock
);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY, -- Unique ID for each customer
name VARCHAR(50), -- Name of the customer
address VARCHAR(100) -- Mailing address of the customer
);
CREATE TABLE salespeople (
salesperson_id INTEGER PRIMARY KEY, -- Unique ID for each salesperson
name VARCHAR(50), -- Name of the salesperson
region VARCHAR(50) -- Geographic sales region
);
CREATE TABLE sales (
sale_id INTEGER PRIMARY KEY, -- Unique ID for each sale
product_id INTEGER, -- ID of product sold
customer_id INTEGER, -- ID of customer who made purchase
salesperson_id INTEGER, -- ID of salesperson who made the sale
sale_date DATE, -- Date the sale occurred
quantity INTEGER -- Quantity of product sold
);
CREATE TABLE product_suppliers (
supplier_id INTEGER PRIMARY KEY, -- Unique ID for each supplier
product_id INTEGER, -- Product ID supplied
supply_price DECIMAL(10,2) -- Unit price charged by supplier
);
-- sales.product_id can be joined with products.product_id
-- sales.customer_id can be joined with customers.customer_id
-- sales.salesperson_id can be joined with salespeople.salesperson_id
-- product_suppliers.product_id can be joined with products.product_id
"""
def _sqlcoder_template_messages(
msgs: List[ChatMessage], schema: str = SQL_CODER_DEFAULT_SCHEMA
) -> str:
question = msgs[-1].content
return f"""\
Your task is to convert a question into a SQL query, given a Postgres database schema.
Adhere to these rules:
- **Deliberately go through the question and database schema word by word** to appropriately answer the question
- **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`.
- When creating a ratio, always cast the numerator as float
### Input:
Generate a SQL query that answers the question `{question}`.
This query will run on a database whose schema is represented in this string:
{schema}
### Response:
Based on your instructions, here is the SQL query I have generated to answer the question `{question}`:
```sql
"""
def sqlcoder_template_messages(schema: str = SQL_CODER_DEFAULT_SCHEMA):
if schema in {"<MY_DATABASE_SCHEMA>", ""}:
schema = SQL_CODER_DEFAULT_SCHEMA
def fn(msgs):
return _sqlcoder_template_messages(msgs, schema=schema)
fn.__name__ = "sqlcoder_template_messages"
return fn
def llama2_template_messages(msgs: List[ChatMessage]) -> str:
if len(msgs) == 0:
return ""
if msgs[0].role == "assistant":
# These models aren't trained to handle assistant message coming first,
# and typically these are just introduction messages from Continue
msgs.pop(0)
prompt = ""
has_system = msgs[0].role == "system"
if has_system and msgs[0].content.strip() == "":
has_system = False
msgs = msgs[1:]
if has_system:
system_message = dedent(
f"""\
<<SYS>>
{msgs[0].content}
<</SYS>>
"""
)
if len(msgs) > 1:
prompt += f"[INST] {system_message}{msgs[1].content} [/INST]"
else:
prompt += f"[INST] {system_message} [/INST]"
return prompt
for i in range(2 if has_system else 0, len(msgs)):
if msgs[i].role == "user":
prompt += f"[INST] {msgs[i].content} [/INST]"
else:
prompt += msgs[i].content + " "
return prompt
def code_llama_template_messages(msgs: List[ChatMessage]) -> str:
return f"[INST] {msgs[-1].content}\n[/INST]"
def extra_space_template_messages(msgs: List[ChatMessage]) -> str:
return f" {msgs[-1].content}"
def code_llama_python_template_messages(msgs: List[ChatMessage]) -> str:
return dedent(
f"""\
[INST]
You are an expert Python programmer and personal assistant, here is your task: {msgs[-1].content}
Your answer should start with a [PYTHON] tag and end with a [/PYTHON] tag.
[/INST]"""
)

View file

@ -1,143 +0,0 @@
from textwrap import dedent
from ....models.llm import PromptTemplate
simplified_edit_prompt = dedent(
"""\
Consider the following code:
```
{{{code_to_edit}}}
```
Edit the code to perfectly satisfy the following user request:
{{{user_input}}}
Output nothing except for the code. No code block, no English explanation, no start/end tags."""
)
simplest_edit_prompt = dedent(
"""\
Here is the code before editing:
```
{{{code_to_edit}}}
```
Here is the edit requested:
"{{{user_input}}}"
Here is the code after editing:"""
)
codellama_infill_edit_prompt = "{{file_prefix}}<FILL>{{file_suffix}}"
_codellama_edit_prompt = dedent(
"""\
[CODE]
{{{code_to_edit}}}
[/CODE]
[INST]
You are an expert programmer and personal assistant, here is your task: "Rewrite the above code in order to {{{user_input}}}"
Your answer should start with a [CODE] tag and end with a [/CODE] tag.
[/INST] Sure! Here's the code you requested:
[CODE]"""
)
_alpaca_edit_prompt = dedent(
"""\
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction: Rewrite the code to satisfy this request: "{{{user_input}}}"
### Input:
```
{{{code_to_edit}}}
```
### Response:
Sure! Here's the code you requested:
```
"""
)
_phind_edit_prompt = dedent(
"""\
### System Prompt
You are an expert programmer and write code on the first attempt without any errors or fillers.
### User Message:
Rewrite the code to satisfy this request: "{{{user_input}}}"
```
{{{code_to_edit}}}
```
### Assistant:
Sure! Here's the code you requested:
```
"""
)
_deepseek_edit_prompt = dedent(
"""\
### System 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.
### Instruction:
Rewrite the code to satisfy this request: "{{{user_input}}}"
```
{{{code_to_edit}}}
```<|EOT|>
### Response:
Sure! Here's the code you requested:
```
"""
)
_zephyr_edit_prompt = dedent(
"""\
<|system|>
You are an expert programmer and write code on the first attempt without any errors or fillers.</s>
<|user|>
Rewrite the code to satisfy this request: "{{{user_input}}}"
```
{{{code_to_edit}}}
```</s>
<|assistant|>
Sure! Here's the code you requested:
```
"""
)
_neuralchat_edit_prompt = dedent(
"""\
### System:
You are an expert programmer and write code on the first attempt without any errors or fillers.
### User:
Rewrite the code to satisfy this request: "{{{user_input}}}"
```
{{{code_to_edit}}}
```
### Assistant:
Sure! Here's the code you requested:
```
"""
)
codellama_edit_prompt = PromptTemplate(
prompt=_codellama_edit_prompt, raw=True, stop=["[/CODE]"]
)
alpaca_edit_prompt = PromptTemplate(prompt=_alpaca_edit_prompt, raw=True, stop=["```"])
phind_edit_prompt = PromptTemplate(prompt=_phind_edit_prompt, raw=True, stop=["```"])
zephyr_edit_prompt = PromptTemplate(prompt=_zephyr_edit_prompt, raw=True, stop=["```"])
deepseek_edit_prompt = PromptTemplate(
prompt=_deepseek_edit_prompt, raw=True, stop=["```"]
)
neuralchat_edit_prompt = PromptTemplate(prompt=_neuralchat_edit_prompt, raw=True, stop=["```"])

View file

@ -1,109 +0,0 @@
import asyncio
import json
from typing import List
from pydantic import validator
from ...core.main import ChatMessage
from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL
from ..util.errors import format_exc
from ..util.telemetry import posthog_logger
from .base import LLM
# SERVER_URL = "http://127.0.0.1:8080"
SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app"
class ProxyServer(LLM):
class Config:
arbitrary_types_allowed = True
def start(
self,
**kwargs,
):
super().start(**kwargs)
self.context_length = CONTEXT_LENGTH_FOR_MODEL[self.model]
def get_headers(self):
return {"unique_id": self.unique_id or "None"}
@validator("context_length")
def context_length_for_model(cls, v, values):
return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096)
async def _complete(self, prompt: str, options):
args = self.collect_args(options)
async with self.create_client_session() as session:
async with session.post(
f"{SERVER_URL}/complete",
json={"messages": [{"role": "user", "content": prompt}], **args},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:
resp_text = await resp.text()
if resp.status != 200:
raise Exception(resp_text)
return resp_text
async def _stream_chat(self, messages: List[ChatMessage], options):
args = self.collect_args(options)
async with self.create_client_session() as session:
async with session.post(
f"{SERVER_URL}/stream_chat",
json={"messages": [msg.to_dict() for msg in messages], **args},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:
if resp.status != 200:
raise Exception(await resp.text())
async for line in resp.content.iter_chunks():
if line[1]:
try:
json_chunk = line[0].decode("utf-8")
json_chunk = "{}" if json_chunk == "" else json_chunk
chunks = json_chunk.split("\n")
for chunk in chunks:
if chunk.strip() != "":
loaded_chunk = json.loads(chunk)
yield ChatMessage(
role="assistant",
content=loaded_chunk.get("content", ""),
)
if self.model == "gpt-4":
await asyncio.sleep(0.03)
else:
await asyncio.sleep(0.01)
except Exception as e:
posthog_logger.capture_event(
"proxy_server_parse_error",
{
"error_title": "Proxy server stream_chat parsing failed",
"error_message": format_exc(e),
},
)
else:
break
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
async with self.create_client_session() as session:
async with session.post(
f"{SERVER_URL}/stream_complete",
json={"messages": [{"role": "user", "content": prompt}], **args},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:
if resp.status != 200:
raise Exception(await resp.text())
async for line in resp.content.iter_any():
if line:
decoded_line = line.decode("utf-8")
yield decoded_line

View file

@ -1,77 +0,0 @@
import asyncio
from typing import Any, List, Union
from pydantic import Field
from ...core.main import ChatMessage
from .base import LLM, CompletionOptions
class QueuedLLM(LLM):
"""
QueuedLLM exists to make up for LLM servers that cannot handle multiple requests at once. It uses a lock to ensure that only one request is being processed at a time.
If you are already using another LLM class and are experiencing this problem, you can just wrap it with the QueuedLLM class like this:
```python title="~/.continue/config.py"
from continuedev.libs.llm.queued import QueuedLLM
config = ContinueConfig(
...
models=Models(
default=QueuedLLM(llm=<OTHER_LLM_CLASS>)
)
)
```
"""
llm: LLM = Field(..., description="The LLM to wrap with a lock")
_lock: asyncio.Lock
model: str = "queued"
def dict(self, **kwargs):
return self.llm.dict(**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
self.prompt_templates = self.llm.prompt_templates
self.context_length = self.llm.context_length
async def stop(self):
await self.llm.stop()
def collect_args(self, options: CompletionOptions):
return self.llm.collect_args(options)
def compile_chat_messages(
self,
options: CompletionOptions,
msgs: List[ChatMessage],
functions: Union[List[Any], None] = None,
):
return self.llm.compile_chat_messages(options, msgs, functions)
def template_prompt_like_messages(self, prompt: str) -> str:
return self.llm.template_prompt_like_messages(prompt)
async def _complete(self, prompt: str, options: CompletionOptions):
async with self._lock:
resp = await self.llm._complete(prompt, options)
return resp
async def _stream_complete(self, prompt: str, options: CompletionOptions):
async with self._lock:
async for chunk in self.llm._stream_complete(prompt, options):
yield chunk
async def _stream_chat(
self, messages: List[ChatMessage], options: CompletionOptions
):
async with self._lock:
async for chunk in self.llm._stream_chat(messages, options):
yield chunk

View file

@ -1,81 +0,0 @@
import concurrent.futures
from typing import List
import replicate
from pydantic import Field
from ...core.main import ChatMessage
from .base import LLM
class ReplicateLLM(LLM):
"""
Replicate is a great option for newly released language models or models that you've deployed through their platform. Sign up for an account [here](https://replicate.ai/), copy your API key, and then select any model from the [Replicate Streaming List](https://replicate.com/collections/streaming-language-models). Change `~/.continue/config.json` to look like this:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Replicate CodeLLama",
"provider": "replicate",
"model": "codellama-13b",
"api_key": "YOUR_API_KEY"
}]
}
```
If you don't specify the `model` parameter, it will default to `replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781`.
"""
api_key: str = Field(..., description="Replicate API key")
model: str = "replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781"
@property
def _client(self) -> replicate.Client:
return replicate.Client(api_token=self.api_key)
def get_model_name(self):
return {
"codellama-7b": "meta/codellama-7b-instruct:6527b83e01e41412db37de5110a8670e3701ee95872697481a355e05ce12af0e",
"codellama-13b": "meta/codellama-13b-instruct:1f01a52ff933873dff339d5fb5e1fd6f24f77456836f514fa05e91c1a42699c7",
"codellama-34b": "meta/codellama-34b-instruct:8281a5c610f6e88237ff3ddaf3c33b56f60809e2bdd19fbec2fda742aa18167e",
"llama2-7b": "meta/llama-2-7b-chat:8e6975e5ed6174911a6ff3d60540dfd4844201974602551e10e9e87ab143d81e",
"llama2-13b": "meta/llama-2-13b-chat:f4e2de70d66816a838a89eeeb621910adffb0dd0baba3976c96980970978018d",
"zephyr-7b": "nateraw/zephyr-7b-beta:b79f33de5c6c4e34087d44eaea4a9d98ce5d3f3a09522f7328eea0685003a931",
"mistral-7b": "mistralai/mistral-7b-instruct-v0.1:83b6a56e7c828e667f21fd596c338fd4f0039b46bcfa18d973e8e70e455fda70",
"wizardcoder-34b": "andreasjansson/wizardcoder-python-34b-v1-gguf:67eed332a5389263b8ede41be3ee7dc119fa984e2bde287814c4abed19a45e54",
"neural-chat-7b": "tomasmcm/neural-chat-7b-v3-1:acb450496b49e19a1e410b50c574a34acacd54820bc36c19cbfe05148de2ba57",
}.get(self.model, self.model)
async def _complete(self, prompt: str, options):
def helper():
output = self._client.run(
self.get_model_name(), input={"message": prompt, "prompt": prompt}
)
completion = ""
for item in output:
completion += item
return completion
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(helper)
completion = future.result()
return completion
async def _stream_complete(self, prompt, options):
for item in self._client.run(
self.get_model_name(), input={"message": prompt, "prompt": prompt}
):
yield item
async def _stream_chat(self, messages: List[ChatMessage], options):
for item in self._client.run(
self.get_model_name(),
input={
"message": messages[-1].content,
"prompt": messages[-1].content,
},
):
yield ChatMessage(role="assistant", content=item)

View file

@ -1,111 +0,0 @@
import json
from typing import Any, AsyncGenerator, List, Optional
import websockets
from pydantic import Field
from ...core.main import ChatMessage
from .base import LLM
class TextGenWebUI(LLM):
"""
TextGenWebUI is a comprehensive, open-source language model UI and local server. You can set it up with an OpenAI-compatible server plugin, but if for some reason that doesn't work, you can use this class like so:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Text Generation WebUI",
"provider": "text-gen-webui",
"model": "MODEL_NAME"
}]
}
```
"""
model: str = "text-gen-webui"
api_base: Optional[str] = Field(
"http://127.0.0.1:5000", description="URL of your TextGenWebUI server"
)
streaming_url: Optional[str] = Field(
"http://127.0.0.1:5005",
description="URL of your TextGenWebUI streaming server (separate from main server URL)",
)
class Config:
arbitrary_types_allowed = True
def collect_args(self, options) -> Any:
args = super().collect_args(options)
args = {**args, "max_new_tokens": options.max_tokens}
args.pop("max_tokens", None)
return args
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
if self.streaming_url is None:
raise Exception("TextGenWebUI streaming server URL was set to None.")
ws_url = f"{self.streaming_url.replace('http://', 'ws://').replace('https://', 'wss://')}"
payload = json.dumps({"prompt": prompt, "stream": True, **args})
async with websockets.connect(
f"{ws_url}/api/v1/stream", ping_interval=None
) as websocket:
await websocket.send(payload)
while True:
incoming_data = await websocket.recv()
incoming_data = json.loads(incoming_data)
incoming_data_event = incoming_data["event"]
if incoming_data_event == "text_stream":
yield incoming_data["text"]
elif incoming_data_event == "stream_end":
break
async def _stream_chat(
self, messages: List[ChatMessage], options
) -> AsyncGenerator[ChatMessage, None]:
args = self.collect_args(options)
async def generator():
if self.streaming_url is None:
raise Exception("TextGenWebUI streaming server URL was set to None.")
ws_url = f"{self.streaming_url.replace('http://', 'ws://').replace('https://', 'wss://')}"
history = list(map(lambda x: x.content, messages))
payload = json.dumps(
{
"user_input": messages[-1].content,
"history": {"internal": [history], "visible": [history]},
"stream": True,
**args,
}
)
async with websockets.connect(
f"{ws_url}/api/v1/chat-stream", ping_interval=None
) as websocket:
await websocket.send(payload)
prev = ""
while True:
incoming_data = await websocket.recv()
incoming_data = json.loads(incoming_data)
incoming_data_event = incoming_data["event"]
if incoming_data_event == "text_stream":
visible = incoming_data["history"]["visible"][-1]
if len(visible) > 0:
yield ChatMessage(
role="assistant", content=visible[-1].replace(prev, "")
)
prev = visible[-1]
elif incoming_data_event == "stream_end":
break
async for chunk in generator():
yield chunk

View file

@ -1,129 +0,0 @@
import json
from typing import Any, Dict, Optional
from pydantic import Field, validator
from continuedev.models.llm import CompletionOptions
from ...core.main import ContinueCustomException
from ..util.logging import logger
from .base import LLM
class TogetherLLM(LLM):
"""
The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/models-inference). Change `~/.continue/config.json` to look like this:
```json title="~/.continue/config.json"
{
"models": [{
"title": "Together CodeLlama",
"provider": "together",
"model": "codellama-13b",
"api_key": "YOUR_API_KEY"
}]
}
```
"""
api_key: str = Field(..., description="Together API key")
model: str = "togethercomputer/RedPajama-INCITE-7B-Instruct"
api_base: Optional[str] = Field(
"https://api.together.xyz",
description="The base URL for your Together API instance",
)
@validator("api_base", pre=True, always=True)
def set_api_base(cls, api_base):
return api_base or "https://api.together.xyz"
def collect_args(self, options: CompletionOptions) -> Dict[str, Any]:
args = super().collect_args(options)
args["model"] = {
"codellama-7b": "togethercomputer/CodeLlama-7b-Instruct",
"codellama-13b": "togethercomputer/CodeLlama-13b-Instruct",
"codellama-34b": "togethercomputer/CodeLlama-34b-Instruct",
"llama2-7b": "togethercomputer/llama-2-7b-chat",
"llama2-13b": "togethercomputer/llama-2-13b-chat",
"llama2-70b": "togethercomputer/llama-2-70b-chat",
"mistral-7b": "mistralai/Mistral-7B-Instruct-v0.1",
"phind-codellama-34b": "Phind/Phind-CodeLlama-34B-v2"
}.get(self.model, self.model)
return args
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
async with self.create_client_session() as session:
async with session.post(
f"{self.api_base}/inference",
json={
"prompt": prompt,
"stream_tokens": True,
**args,
},
headers={"Authorization": f"Bearer {self.api_key}"},
proxy=self.request_options.proxy,
) as resp:
async for line in resp.content.iter_chunks():
if line[1]:
json_chunk = line[0].decode("utf-8")
if json_chunk.startswith(": ping - ") or json_chunk.startswith(
"data: [DONE]"
):
continue
chunks = json_chunk.split("\n")
for chunk in chunks:
if chunk.strip() != "":
if chunk.startswith("data: "):
chunk = chunk[6:]
if chunk == "[DONE]":
break
try:
json_chunk = json.loads(chunk)
except Exception as e:
logger.warning(
f"Invalid JSON chunk: {chunk}\n\n{e}"
)
continue
if "error" in json_chunk:
raise ContinueCustomException(
message=json_chunk["error"],
title="Together API Error",
)
elif "choices" in json_chunk:
yield json_chunk["choices"][0]["text"]
async def _complete(self, prompt: str, options):
args = self.collect_args(options)
async with self.create_client_session() as session:
async with session.post(
f"{self.api_base}/inference",
json={"prompt": prompt, **args},
headers={"Authorization": f"Bearer {self.api_key}"},
proxy=self.request_options.proxy,
) as resp:
text = await resp.text()
j = json.loads(text)
try:
if "choices" not in j["output"]:
raise Exception(text)
if "output" in j:
return j["output"]["choices"][0]["text"]
except Exception as e:
j = await resp.json()
if "error" in j:
if j["error"].startswith("invalid hexlify value"):
raise ContinueCustomException(
message=f"Invalid Together API key:\n\n{j['error']}",
title="Together API Error",
)
else:
raise ContinueCustomException(
message=j["error"], title="Together API Error"
)
raise e

View file

@ -1,154 +0,0 @@
import difflib
from typing import List
from ...models.filesystem import FileEdit
from ...models.main import Position, Range
def calculate_diff(filepath: str, original: str, updated: str) -> List[FileEdit]:
s = difflib.SequenceMatcher(None, original, updated)
offset = 0 # The indices are offset by previous deletions/insertions
edits = []
for tag, i1, i2, j1, j2 in s.get_opcodes():
i1, i2, j1, j2 = i1 + offset, i2 + offset, j1 + offset, j2 + offset
replacement = updated[j1:j2]
if tag == "equal":
pass
elif tag == "delete":
edits.append(
FileEdit.from_deletion(filepath, Range.from_indices(original, i1, i2))
)
offset -= i2 - i1
elif tag == "insert":
edits.append(
FileEdit.from_insertion(
filepath, Position.from_index(original, i1), replacement
)
)
offset += j2 - j1
elif tag == "replace":
edits.append(
FileEdit(
filepath=filepath,
range=Range.from_indices(original, i1, i2),
replacement=replacement,
)
)
offset += (j2 - j1) - (i2 - i1)
else:
raise Exception("Unexpected difflib.SequenceMatcher tag: " + tag)
return edits
def calculate_diff2(filepath: str, original: str, updated: str) -> List[FileEdit]:
# original_lines = original.splitlines()
# updated_lines = updated.splitlines()
# offset = 0
# while len(original_lines) and len(updated_lines) and original_lines[0] == updated_lines[0]:
# original_lines = original_lines[1:]
# updated_lines = updated_lines[1:]
# while len(original_lines) and len(updated_lines) and original_lines[-1] == updated_lines[-1]:
# original_lines = original_lines[:-1]
# updated_lines = updated_lines[:-1]
# original = "\n".join(original_lines)
# updated = "\n".join(updated_lines)
edits = []
max_iterations = 1000
i = 0
while not original == updated:
# TODO - For some reason it can't handle a single newline at the end of the file?
s = difflib.SequenceMatcher(None, original, updated)
opcodes = s.get_opcodes()
for edit_index in range(len(opcodes)):
tag, i1, i2, j1, j2 = s.get_opcodes()[edit_index]
replacement = updated[j1:j2]
if tag == "equal":
continue # ;)
elif tag == "delete":
edits.append(
FileEdit.from_deletion(
filepath, Range.from_indices(original, i1, i2)
)
)
elif tag == "insert":
edits.append(
FileEdit.from_insertion(
filepath, Position.from_index(original, i1), replacement
)
)
elif tag == "replace":
edits.append(
FileEdit(
filepath=filepath,
range=Range.from_indices(original, i1, i2),
replacement=replacement,
)
)
else:
raise Exception("Unexpected difflib.SequenceMatcher tag: " + tag)
break
original = apply_edit_to_str(original, edits[-1])
i += 1
if i > max_iterations:
raise Exception("Max iterations reached")
return edits
def read_range_in_str(s: str, r: Range) -> str:
lines = s.splitlines()[r.start.line : r.end.line + 1]
if len(lines) == 0:
return ""
lines[0] = lines[0][r.start.character :]
lines[-1] = lines[-1][: r.end.character + 1]
return "\n".join(lines)
def apply_edit_to_str(s: str, edit: FileEdit) -> str:
read_range_in_str(s, edit.range)
# Split lines and deal with some edge cases (could obviously be nicer)
lines = s.splitlines()
if s.startswith("\n"):
lines.insert(0, "")
if s.endswith("\n"):
lines.append("")
if len(lines) == 0:
lines = [""]
end = Position(line=edit.range.end.line, character=edit.range.end.character)
if edit.range.end.line == len(lines) and edit.range.end.character == 0:
end = Position(
line=edit.range.end.line - 1,
character=len(lines[min(len(lines) - 1, edit.range.end.line - 1)]),
)
before_lines = lines[: edit.range.start.line]
after_lines = lines[end.line + 1 :]
between_str = (
lines[min(len(lines) - 1, edit.range.start.line)][: edit.range.start.character]
+ edit.replacement
+ lines[min(len(lines) - 1, end.line)][end.character + 1 :]
)
Range(
start=edit.range.start,
end=Position(
line=edit.range.start.line + len(edit.replacement.splitlines()) - 1,
character=edit.range.start.character
+ len(edit.replacement.splitlines()[-1])
if edit.replacement != ""
else 0,
),
)
lines = before_lines + between_str.splitlines() + after_lines
return "\n".join(lines)

View file

@ -1,144 +0,0 @@
# coding: utf-8
import re
from typing import Any
date = re.compile(
"(?:(?<!\:)(?<!\:\d)[0-3]?\d(?:st|nd|rd|th)?\s+(?:of\s+)?(?:jan\.?|january|feb\.?|february|mar\.?|march|apr\.?|april|may|jun\.?|june|jul\.?|july|aug\.?|august|sep\.?|september|oct\.?|october|nov\.?|november|dec\.?|december)|(?:jan\.?|january|feb\.?|february|mar\.?|march|apr\.?|april|may|jun\.?|june|jul\.?|july|aug\.?|august|sep\.?|september|oct\.?|october|nov\.?|november|dec\.?|december)\s+(?<!\:)(?<!\:\d)[0-3]?\d(?:st|nd|rd|th)?)(?:\,)?\s*(?:\d{4})?|[0-3]?\d[-\./][0-3]?\d[-\./]\d{2,4}",
re.IGNORECASE,
)
time = re.compile("\d{1,2}:\d{2} ?(?:[ap]\.?m\.?)?|\d[ap]\.?m\.?", re.IGNORECASE)
phone = re.compile(
"""((?:(?<![\d-])(?:\+?\d{1,3}[-.\s*]?)?(?:\(?\d{3}\)?[-.\s*]?)?\d{3}[-.\s*]?\d{4}(?![\d-]))|(?:(?<![\d-])(?:(?:\(\+?\d{2}\))|(?:\+?\d{2}))\s*\d{2}\s*\d{3}\s*\d{4}(?![\d-])))"""
)
phones_with_exts = re.compile(
"((?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*(?:[2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|(?:[2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?(?:[2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?(?:[0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(?:\d+)?))",
re.IGNORECASE,
)
link = re.compile(
"(?i)((?:https?://|www\d{0,3}[.])?[a-z0-9.\-]+[.](?:(?:international)|(?:construction)|(?:contractors)|(?:enterprises)|(?:photography)|(?:immobilien)|(?:management)|(?:technology)|(?:directory)|(?:education)|(?:equipment)|(?:institute)|(?:marketing)|(?:solutions)|(?:builders)|(?:clothing)|(?:computer)|(?:democrat)|(?:diamonds)|(?:graphics)|(?:holdings)|(?:lighting)|(?:plumbing)|(?:training)|(?:ventures)|(?:academy)|(?:careers)|(?:company)|(?:domains)|(?:florist)|(?:gallery)|(?:guitars)|(?:holiday)|(?:kitchen)|(?:recipes)|(?:shiksha)|(?:singles)|(?:support)|(?:systems)|(?:agency)|(?:berlin)|(?:camera)|(?:center)|(?:coffee)|(?:estate)|(?:kaufen)|(?:luxury)|(?:monash)|(?:museum)|(?:photos)|(?:repair)|(?:social)|(?:tattoo)|(?:travel)|(?:viajes)|(?:voyage)|(?:build)|(?:cheap)|(?:codes)|(?:dance)|(?:email)|(?:glass)|(?:house)|(?:ninja)|(?:photo)|(?:shoes)|(?:solar)|(?:today)|(?:aero)|(?:arpa)|(?:asia)|(?:bike)|(?:buzz)|(?:camp)|(?:club)|(?:coop)|(?:farm)|(?:gift)|(?:guru)|(?:info)|(?:jobs)|(?:kiwi)|(?:land)|(?:limo)|(?:link)|(?:menu)|(?:mobi)|(?:moda)|(?:name)|(?:pics)|(?:pink)|(?:post)|(?:rich)|(?:ruhr)|(?:sexy)|(?:tips)|(?:wang)|(?:wien)|(?:zone)|(?:biz)|(?:cab)|(?:cat)|(?:ceo)|(?:com)|(?:edu)|(?:gov)|(?:int)|(?:mil)|(?:net)|(?:onl)|(?:org)|(?:pro)|(?:red)|(?:tel)|(?:uno)|(?:xxx)|(?:ac)|(?:ad)|(?:ae)|(?:af)|(?:ag)|(?:ai)|(?:al)|(?:am)|(?:an)|(?:ao)|(?:aq)|(?:ar)|(?:as)|(?:at)|(?:au)|(?:aw)|(?:ax)|(?:az)|(?:ba)|(?:bb)|(?:bd)|(?:be)|(?:bf)|(?:bg)|(?:bh)|(?:bi)|(?:bj)|(?:bm)|(?:bn)|(?:bo)|(?:br)|(?:bs)|(?:bt)|(?:bv)|(?:bw)|(?:by)|(?:bz)|(?:ca)|(?:cc)|(?:cd)|(?:cf)|(?:cg)|(?:ch)|(?:ci)|(?:ck)|(?:cl)|(?:cm)|(?:cn)|(?:co)|(?:cr)|(?:cu)|(?:cv)|(?:cw)|(?:cx)|(?:cy)|(?:cz)|(?:de)|(?:dj)|(?:dk)|(?:dm)|(?:do)|(?:dz)|(?:ec)|(?:ee)|(?:eg)|(?:er)|(?:es)|(?:et)|(?:eu)|(?:fi)|(?:fj)|(?:fk)|(?:fm)|(?:fo)|(?:fr)|(?:ga)|(?:gb)|(?:gd)|(?:ge)|(?:gf)|(?:gg)|(?:gh)|(?:gi)|(?:gl)|(?:gm)|(?:gn)|(?:gp)|(?:gq)|(?:gr)|(?:gs)|(?:gt)|(?:gu)|(?:gw)|(?:gy)|(?:hk)|(?:hm)|(?:hn)|(?:hr)|(?:ht)|(?:hu)|(?:id)|(?:ie)|(?:il)|(?:im)|(?:in)|(?:io)|(?:iq)|(?:ir)|(?:is)|(?:it)|(?:je)|(?:jm)|(?:jo)|(?:jp)|(?:ke)|(?:kg)|(?:kh)|(?:ki)|(?:km)|(?:kn)|(?:kp)|(?:kr)|(?:kw)|(?:ky)|(?:kz)|(?:la)|(?:lb)|(?:lc)|(?:li)|(?:lk)|(?:lr)|(?:ls)|(?:lt)|(?:lu)|(?:lv)|(?:ly)|(?:ma)|(?:mc)|(?:md)|(?:me)|(?:mg)|(?:mh)|(?:mk)|(?:ml)|(?:mm)|(?:mn)|(?:mo)|(?:mp)|(?:mq)|(?:mr)|(?:ms)|(?:mt)|(?:mu)|(?:mv)|(?:mw)|(?:mx)|(?:my)|(?:mz)|(?:na)|(?:nc)|(?:ne)|(?:nf)|(?:ng)|(?:ni)|(?:nl)|(?:no)|(?:np)|(?:nr)|(?:nu)|(?:nz)|(?:om)|(?:pa)|(?:pe)|(?:pf)|(?:pg)|(?:ph)|(?:pk)|(?:pl)|(?:pm)|(?:pn)|(?:pr)|(?:ps)|(?:pt)|(?:pw)|(?:py)|(?:qa)|(?:re)|(?:ro)|(?:rs)|(?:ru)|(?:rw)|(?:sa)|(?:sb)|(?:sc)|(?:sd)|(?:se)|(?:sg)|(?:sh)|(?:si)|(?:sj)|(?:sk)|(?:sl)|(?:sm)|(?:sn)|(?:so)|(?:sr)|(?:st)|(?:su)|(?:sv)|(?:sx)|(?:sy)|(?:sz)|(?:tc)|(?:td)|(?:tf)|(?:tg)|(?:th)|(?:tj)|(?:tk)|(?:tl)|(?:tm)|(?:tn)|(?:to)|(?:tp)|(?:tr)|(?:tt)|(?:tv)|(?:tw)|(?:tz)|(?:ua)|(?:ug)|(?:uk)|(?:us)|(?:uy)|(?:uz)|(?:va)|(?:vc)|(?:ve)|(?:vg)|(?:vi)|(?:vn)|(?:vu)|(?:wf)|(?:ws)|(?:ye)|(?:yt)|(?:za)|(?:zm)|(?:zw))(?:/[^\s()<>]+[^\s`!()\[\]{};:'\".,<>?\xab\xbb\u201c\u201d\u2018\u2019])?)",
re.IGNORECASE,
)
email = re.compile(
"([a-z0-9!#$%&'*+\/=?^_`{|.}~-]+@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)",
re.IGNORECASE,
)
ip = re.compile(
"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",
re.IGNORECASE,
)
ipv6 = re.compile(
"\s*(?!.*::.*::)(?:(?!:)|:(?=:))(?:[0-9a-f]{0,4}(?:(?<=::)|(?<!::):)){6}(?:[0-9a-f]{0,4}(?:(?<=::)|(?<!::):)[0-9a-f]{0,4}(?:(?<=::)|(?<!:)|(?<=:)(?<!::):)|(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)){3})\s*",
re.VERBOSE | re.IGNORECASE | re.DOTALL,
)
price = re.compile("[$]\s?[+-]?[0-9]{1,3}(?:(?:,?[0-9]{3}))*(?:\.[0-9]{1,2})?")
hex_color = re.compile("(#(?:[0-9a-fA-F]{8})|#(?:[0-9a-fA-F]{3}){1,2})\\b")
credit_card = re.compile("((?:(?:\\d{4}[- ]?){3}\\d{4}|\\d{15,16}))(?![\\d])")
btc_address = re.compile(
"(?<![a-km-zA-HJ-NP-Z0-9])[13][a-km-zA-HJ-NP-Z0-9]{26,33}(?![a-km-zA-HJ-NP-Z0-9])"
)
street_address = re.compile(
"\d{1,4} [\w\s]{1,20}(?:street|st|avenue|ave|road|rd|highway|hwy|square|sq|trail|trl|drive|dr|court|ct|park|parkway|pkwy|circle|cir|boulevard|blvd)\W?(?=\s|$)",
re.IGNORECASE,
)
zip_code = re.compile(r"\b\d{5}(?:[-\s]\d{4})?\b")
po_box = re.compile(r"P\.? ?O\.? Box \d+", re.IGNORECASE)
ssn = re.compile(
"(?!000|666|333)0*(?:[0-6][0-9][0-9]|[0-7][0-6][0-9]|[0-7][0-7][0-2])[- ](?!00)[0-9]{2}[- ](?!0000)[0-9]{4}"
)
regexes = {
"dates": date,
"times": time,
"phones": phone,
"phones_with_exts": phones_with_exts,
"emails": email,
"ips": ip,
"ipv6s": ipv6,
"prices": price,
"hex_colors": hex_color,
"credit_cards": credit_card,
"btc_addresses": btc_address,
"street_addresses": street_address,
"zip_codes": zip_code,
"po_boxes": po_box,
"ssn_number": ssn,
}
placeholders = {
"dates": "<DATE>",
"times": "<TIME>",
"phones": "<PHONE>",
"phones_with_exts": "<PHONE_WITH_EXT>",
"emails": "<EMAIL>",
"ips": "<IP>",
"ipv6s": "<IPV6>",
"prices": "<PRICE>",
"hex_colors": "<HEX_COLOR>",
"credit_cards": "<CREDIT_CARD>",
"btc_addresses": "<BTC_ADDRESS>",
"street_addresses": "<STREET_ADDRESS>",
"zip_codes": "<ZIP_CODE>",
"po_boxes": "<PO_BOX>",
"ssn_number": "<SSN>",
}
class regex:
def __init__(self, obj, regex):
self.obj = obj
self.regex = regex
def __call__(self, *args):
def regex_method(text=None):
return [x.strip() for x in self.regex.findall(text or self.obj.text)]
return regex_method
class CommonRegex(object):
def __init__(self, text=""):
self.text = text
for k, v in list(regexes.items()):
setattr(self, k, regex(self, v)(self))
if text:
for key in list(regexes.keys()):
method = getattr(self, key)
setattr(self, key, method())
pii_parser = CommonRegex()
def clean_pii_from_str(text: str):
"""Replace personally identifiable information (PII) with placeholders."""
for regex_name, regex in list(regexes.items()):
placeholder = placeholders[regex_name]
text = regex.sub(placeholder, text)
return text
def clean_pii_from_any(v: Any) -> Any:
"""Replace personally identifiable information (PII) with placeholders. Not guaranteed to return same type as input."""
if isinstance(v, str):
return clean_pii_from_str(v)
elif isinstance(v, dict):
cleaned_dict = {}
for key, value in v.items():
cleaned_dict[key] = clean_pii_from_any(value)
return cleaned_dict
elif isinstance(v, list):
return [clean_pii_from_any(x) for x in v]
else:
# Try to convert to string
try:
orig_text = str(v)
cleaned_text = clean_pii_from_str(orig_text)
if orig_text != cleaned_text:
return cleaned_text
else:
return v
except Exception:
return v

View file

@ -1,121 +0,0 @@
import os
import shutil
from pathlib import Path
from typing import Iterable, List, Union
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
from ...core.autopilot import Autopilot
from ...models.filesystem import FileSystem
from ...models.main import (
AddDirectory,
AddFile,
DeleteDirectory,
DeleteFile,
FileSystemEdit,
RenameDirectory,
RenameFile,
SequentialFileSystemEdit,
)
from .map_path import map_path
def create_copy(orig_root: str, copy_root: str = None, ignore: Iterable[str] = []):
# TODO: Make ignore a spec, like .gitignore
if copy_root is None:
copy_root = Path(orig_root) / ".continue-copy"
ignore.append(str(copy_root))
ignore = set(ignore)
os.mkdir(copy_root)
# I think you're messing up a lot of absolute paths here
for child in os.listdir():
if os.path.isdir(child):
if child not in ignore:
os.mkdir(map_path(child))
create_copy(Path(orig_root) / child, Path(copy_root) / child, ignore)
else:
os.symlink(child, map_path(child))
else:
if child not in ignore:
shutil.copyfile(child, map_path(child))
else:
os.symlink(child, map_path(child))
# The whole usage of watchdog here should only be specific to RealFileSystem, you want to have a different "Observer" class for VirtualFileSystem, which would depend on being sent notifications
class CopyCodebaseEventHandler(PatternMatchingEventHandler):
def __init__(
self,
ignore_directories: List[str],
ignore_patterns: List[str],
autopilot: Autopilot,
orig_root: str,
copy_root: str,
filesystem: FileSystem,
):
super().__init__(
ignore_directories=ignore_directories, ignore_patterns=ignore_patterns
)
self.autopilot = autopilot
self.orig_root = orig_root
self.copy_root = copy_root
self.filesystem = filesystem
# For now, we'll just make the update immediately, but eventually need to sync with autopilot.
# It should be the autopilot that makes the update right? It's just another action, everything comes from a single stream.
def _event_to_edit(self, event) -> Union[FileSystemEdit, None]:
# NOTE: You'll need to map paths to create both an action within the copy filesystem (the one you take) and one in the original filesystem (the one you'll record and allow the user to accept). Basically just need a converter built in to the FileSystemEdit class
src = event.src_path()
if event.is_directory:
if event.event_type == "moved":
return RenameDirectory(src, event.dest_path())
elif event.event_type == "deleted":
return DeleteDirectory(src)
elif event.event_type == "created":
return AddDirectory(src)
else:
if event.event_type == "moved":
return RenameFile(src, event.dest_path())
elif event.event_type == "deleted":
return DeleteFile(src)
elif event.event_type == "created":
contents = self.filesystem.read(src)
# Unclear whether it will always pass a "modified" event right after if something like echo "abc" > newfile.txt happens
return AddFile(src, contents)
elif event.event_type == "modified":
# Watchdog doesn't pass the contents or edit, so have to get it myself and diff
updated = self.filesystem.read(src)
copy_filepath = map_path(src, self.orig_root, self.copy_root)
old = self.filesystem.read(copy_filepath)
edits = calculate_diff(src, updated, old)
return SequentialFileSystemEdit(edits)
return None
def on_any_event(self, event):
edit = self._event_to_edit(event)
if edit is None:
return
edit = edit.with_mapped_paths(self.orig_root, self.copy_root)
action = ManualEditAction(edit)
self.autopilot.act(action)
def maintain_copy_workspace(
autopilot: Autopilot, filesystem: FileSystem, orig_root: str, copy_root: str
):
observer = Observer()
event_handler = CopyCodebaseEventHandler(
[".git"], [], autopilot, orig_root, copy_root, filesystem
)
observer.schedule(event_handler, orig_root, recursive=True)
observer.start()
try:
while observer.isAlive():
observer.join(1)
finally:
observer.stop()
observer.join()

View file

@ -1,288 +0,0 @@
import json
import os
import sys
from typing import List, Optional, Union
from ...core.main import ChatMessage
from .templating import render_templated_string
# TODO move many of these into specific LLM.properties() function that
# contains max tokens, if its a chat model or not, default args (not all models
# want to be run at 0.5 temp). also lets custom models made for long contexts
# exist here (likg LLongMA)
aliases = {
"ggml": "gpt-3.5-turbo",
"claude-2": "gpt-3.5-turbo",
}
DEFAULT_MAX_TOKENS = 1000
DEFAULT_ARGS = {
"max_tokens": DEFAULT_MAX_TOKENS,
"temperature": 0.5,
}
CONTEXT_LENGTH_FOR_MODEL = {
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0613": 4096,
"gpt-3.5-turbo-16k": 16_384,
"gpt-4": 8192,
"gpt-35-turbo-16k": 16_384,
"gpt-35-turbo-0613": 4096,
"gpt-35-turbo": 4096,
"gpt-4-32k": 32_768,
"gpt-4-1106-preview": 128_000,
}
already_saw_import_err = False
already_saw_import_err = False
def encoding_for_model(model_name: str):
global already_saw_import_err
if already_saw_import_err:
return None
try:
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
tiktoken_cache = os.path.join(sys._MEIPASS, "tiktoken_cache")
if os.path.exists(tiktoken_cache):
os.environ["TIKTOKEN_CACHE_DIR"] = tiktoken_cache
import tiktoken
from tiktoken_ext import openai_public # noqa: F401
try:
return tiktoken.encoding_for_model(aliases.get(model_name, model_name))
except Exception as _:
return tiktoken.encoding_for_model("gpt-3.5-turbo")
except Exception as e:
print("Error importing tiktoken", e)
already_saw_import_err = True
return None
def count_tokens(text: Optional[str], model_name: Optional[str] = "gpt-4"):
if text is None:
return 0
encoding = encoding_for_model(model_name or "gpt-4")
if encoding is None:
# Make a safe estimate given that tokens are usually typically ~4 characters on average
return len(text) // 2
return len(encoding.encode(text, disallowed_special=()))
def count_chat_message_tokens(model_name: str, chat_message: ChatMessage) -> int:
# Doing simpler, safer version of what is here:
# https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
# every message follows <|start|>{role/name}\n{content}<|end|>\n
TOKENS_PER_MESSAGE = 4
return count_tokens(chat_message.content, model_name) + TOKENS_PER_MESSAGE
def prune_string_from_top(model_name: str, max_tokens: int, prompt: str):
encoding = encoding_for_model(model_name)
if encoding is None:
desired_length_in_chars = max_tokens * 2
return prompt[-desired_length_in_chars:]
tokens = encoding.encode(prompt, disallowed_special=())
if len(tokens) <= max_tokens:
return prompt
return encoding.decode(tokens[-max_tokens:])
def prune_string_from_bottom(model_name: str, max_tokens: int, prompt: str):
encoding = encoding_for_model(model_name)
if encoding is None:
desired_length_in_chars = max_tokens * 2
return prompt[:desired_length_in_chars]
tokens = encoding.encode(prompt, disallowed_special=())
if len(tokens) <= max_tokens:
return prompt
return encoding.decode(tokens[:max_tokens])
def prune_raw_prompt_from_top(
model_name: str, context_length: int, prompt: str, tokens_for_completion: int
):
max_tokens = context_length - tokens_for_completion - TOKEN_BUFFER_FOR_SAFETY
return prune_string_from_top(model_name, max_tokens, prompt)
def prune_chat_history(
model_name: str,
chat_history: List[ChatMessage],
context_length: int,
tokens_for_completion: int,
):
total_tokens = tokens_for_completion + sum(
count_chat_message_tokens(model_name, message) for message in chat_history
)
# 0. Prune any messages that take up more than 1/3 of the context length
longest_messages = sorted(
chat_history, key=lambda message: len(message.content), reverse=True
)
longer_than_one_third = [
message
for message in longest_messages
if count_tokens(message.content, model_name) > context_length / 3
]
distance_from_third = [
count_tokens(message.content, model_name) - context_length / 3
for message in longer_than_one_third
]
for i in range(len(longer_than_one_third)):
# Prune line-by-line
message = longer_than_one_third[i]
lines = message.content.split("\n")
tokens_removed = 0
while (
tokens_removed < distance_from_third[i]
and total_tokens > context_length
and len(lines) > 0
):
delta = count_tokens("\n" + lines.pop(-1), model_name)
tokens_removed += delta
total_tokens -= delta
message.content = "\n".join(lines)
# 1. Replace beyond last 5 messages with summary
i = 0
while total_tokens > context_length and i < len(chat_history) - 5:
message = chat_history[0]
total_tokens -= count_tokens(message.content, model_name)
total_tokens += count_tokens(message.summary, model_name)
message.content = message.summary
i += 1
# 2. Remove entire messages until the last 5
while (
len(chat_history) > 5
and total_tokens > context_length
and len(chat_history) > 0
):
message = chat_history.pop(0)
total_tokens -= count_tokens(message.content, model_name)
# 3. Truncate message in the last 5, except last 1
i = 0
while (
total_tokens > context_length
and len(chat_history) > 0
and i < len(chat_history) - 1
):
message = chat_history[i]
total_tokens -= count_tokens(message.content, model_name)
total_tokens += count_tokens(message.summary, model_name)
message.content = message.summary
i += 1
# 4. Remove entire messages in the last 5, except last 1
while total_tokens > context_length and len(chat_history) > 1:
message = chat_history.pop(0)
total_tokens -= count_tokens(message.content, model_name)
# 5. Truncate last message
if total_tokens > context_length and len(chat_history) > 0:
message = chat_history[0]
message.content = prune_raw_prompt_from_top(
model_name, context_length, message.content, tokens_for_completion
)
total_tokens = context_length
return chat_history
# In case we've missed weird edge cases
TOKEN_BUFFER_FOR_SAFETY = 350
def flatten_messages(msgs: List[ChatMessage]) -> List[ChatMessage]:
"""If there are multiple adjacent messages with same "role", combine them"""
flattened = []
for msg in msgs:
if len(flattened) > 0 and flattened[-1].role == msg.role:
flattened[-1].content += "\n\n" + (msg.content or "")
else:
flattened.append(msg)
return flattened
def compile_chat_messages(
model_name: str,
msgs: Union[List[ChatMessage], None],
context_length: int,
max_tokens: int,
prompt: Union[str, None] = None,
functions: Union[List, None] = None,
system_message: Union[str, None] = None,
) -> List[ChatMessage]:
"""
The total number of tokens is system_message + sum(msgs) + functions + prompt after it is converted to a message
"""
msgs_copy = [msg.copy(deep=True) for msg in msgs] if msgs is not None else []
if prompt is not None:
prompt_msg = ChatMessage(role="user", content=prompt, summary=prompt)
msgs_copy += [prompt_msg]
if system_message is not None and system_message.strip() != "":
# NOTE: System message takes second precedence to user prompt, so it is placed just before
# but move back to start after processing
rendered_system_message = render_templated_string(system_message)
system_chat_msg = ChatMessage(
role="system",
content=rendered_system_message,
summary=rendered_system_message,
)
# insert at second-to-last position
msgs_copy.insert(-1, system_chat_msg)
# Add tokens from functions
function_tokens = 0
if functions is not None:
for function in functions:
function_tokens += count_tokens(json.dumps(function), model_name)
if max_tokens + function_tokens + TOKEN_BUFFER_FOR_SAFETY >= context_length:
raise ValueError(
f"max_tokens ({max_tokens}) is too close to context_length ({context_length}), which doesn't leave room for chat history. This would cause incoherent responses. Try increasing the context_length parameter of the model in your config file."
)
history = prune_chat_history(
model_name,
msgs_copy,
context_length,
function_tokens + max_tokens + TOKEN_BUFFER_FOR_SAFETY,
)
# Move system message back to start
if (
system_message is not None
and len(history) >= 2
and history[-2].role == "system"
):
moved_system_message = history.pop(-2)
history.insert(0, moved_system_message)
history = flatten_messages(history)
return history
def format_chat_messages(messages: List[ChatMessage]) -> str:
formatted = ""
for msg in messages:
formatted += f"<{msg.role.capitalize()}>\n{msg.content or ''}\n\n"
return formatted

View file

@ -1,34 +0,0 @@
import asyncio
import traceback
from typing import Callable, Coroutine, Optional
from .logging import logger
from .telemetry import posthog_logger
def create_async_task(
coro: Coroutine, on_error: Optional[Callable[[Exception], Coroutine]] = None
):
"""asyncio.create_task and log errors by adding a callback"""
task = asyncio.create_task(coro)
def callback(future: asyncio.Future):
try:
future.result()
except Exception as e:
formatted_tb = "\n".join(traceback.format_exception(e))
logger.critical(f"Exception caught from async task: {formatted_tb}")
posthog_logger.capture_event(
"async_task_error",
{
"error_title": e.__str__() or e.__repr__(),
"error_message": "\n".join(traceback.format_exception(e)),
},
)
# Log the error to the GUI
if on_error is not None:
asyncio.create_task(on_error(e))
task.add_done_callback(callback)
return task

View file

@ -1,72 +0,0 @@
"""
This file contains mechanisms for logging development data to files, SQL databases, and other formats.
"""
import json
from datetime import datetime
from typing import Any, Dict, Optional
import aiohttp
from .create_async_task import create_async_task
from .logging import logger
from .paths import getDevDataFilePath
class DevDataLogger:
user_token: Optional[str] = None
data_server_url: Optional[str] = None
def setup(
self, user_token: Optional[str] = None, data_server_url: Optional[str] = None
):
self.user_token = user_token
self.data_server_url = data_server_url
def _to_data_server(self, table_name: str, data: Dict[str, Any]):
async def _async_helper(self, table_name: str, data: Dict[str, Any]):
if self.user_token is None or self.data_server_url is None:
return
async with aiohttp.ClientSession(trust_env=True) as session:
await session.post(
f"{self.data_server_url}/event",
headers={"Authorization": f"Bearer {self.user_token}"},
json={
"table_name": table_name,
"data": data,
"user_token": self.user_token,
},
)
async def on_error(e: Exception):
logger.warning(f"Failed to send dev data: {e}")
create_async_task(
_async_helper(self, table_name, data),
on_error,
)
def _static_columns(self):
return {
"user_token": self.user_token or "NO_USER_TOKEN",
"timestamp": datetime.now().isoformat(),
}
def _to_local(self, table_name: str, data: Dict[str, Any]):
filepath = getDevDataFilePath(table_name)
with open(filepath, "a") as f:
json_line = json.dumps(data)
f.write(f"{json_line}\n")
def capture(self, table_name: str, data: Dict[str, Any]):
try:
data = {**self._static_columns(), **data}
self._to_local(table_name, data)
self._to_data_server(table_name, data)
except Exception as e:
logger.warning(f"Failed to capture dev data: {e}")
dev_data_logger = DevDataLogger()

View file

@ -1,164 +0,0 @@
import threading
from typing import Any, Dict, List, Optional, Union
import redbaron
from .paths import getConfigFilePath
def get_config_source():
config_file_path = getConfigFilePath()
with open(config_file_path, "r") as file:
source_code = file.read()
return source_code
def load_red():
source_code = get_config_source()
red = redbaron.RedBaron(source_code)
return red
def get_config_node(red):
for node in red:
if node.type == "assignment" and node.target.value == "config":
return node
else:
raise Exception("Config file appears to be improperly formatted")
def edit_property(
args: redbaron.RedBaron, key_path: List[str], value: redbaron.RedBaron
):
for i in range(len(args)):
node = args[i]
if node.type != "call_argument":
continue
if node.target.value == key_path[0]:
if len(key_path) > 1:
edit_property(node.value.value[1].value, key_path[1:], value)
else:
args[i].value = value
return
edit_lock = threading.Lock()
def edit_config_property(
key_path: List[str], value: Union[redbaron.RedBaron, str, float]
):
"""
key_path: list of strings representing the path to the property
value: redbaron node representing the value to set
"""
if isinstance(value, str):
value = create_string_node(value)
elif isinstance(value, float):
value = create_float_node(value)
with edit_lock:
red = load_red()
config = get_config_node(red)
config_args = config.value.value[1].value
edit_property(config_args, key_path, value)
with open(getConfigFilePath(), "w") as file:
file.write(red.dumps())
def add_config_import(line: str):
# check if the import already exists
source = get_config_source()
if line in source:
return
with edit_lock:
red = load_red()
# if it doesn't exist, add it
red.insert(1, line)
with open(getConfigFilePath(), "w") as file:
file.write(red.dumps())
filtered_attrs = {
"class_name",
"name",
"llm",
}
filtered_attrs_when_new = {"timeout", "prompt_templates"}
def escape_string(string: str) -> str:
return string.replace('"', '\\"').replace("'", "\\'")
def display_val(v: Any, k: Optional[str] = None):
if k == "template_messages":
return v
elif isinstance(v, str):
return f'"{escape_string(v)}"'
return str(v)
def is_default(llm, k, v):
if k == "template_messages" and llm.__fields__[k].default is not None:
return llm.__fields__[k].default.__name__ == v
return v == llm.__fields__[k].default
def display_llm_class(llm, new: bool = False, overrides: Dict[str, str] = {}):
sep = ",\n\t\t\t"
args = sep.join(
[
f"{k}={display_val(v, k) if k not in overrides else overrides[k]}"
for k, v in llm.dict().items()
if k not in filtered_attrs and v is not None and not is_default(llm, k, v)
]
)
return f"{llm.__class__.__name__}(\n\t\t\t{args}\n\t\t)"
def create_obj_node(
class_name: str, args: Dict[str, str], tabs: int = 1
) -> redbaron.RedBaron:
args_list = [f"{key}={value}" for key, value in args.items()]
t = "\t" * tabs
new_line = "\n\t" + t
sep = "," + new_line
return redbaron.RedBaron(f"{class_name}({new_line}{sep.join(args_list)}\n{t})")[0]
def create_string_node(string: str) -> redbaron.RedBaron:
string = escape_string(string)
if "\n" in string:
return redbaron.RedBaron(f'"""{string}"""')[0]
return redbaron.RedBaron(f'"{string}"')[0]
def create_literal_node(literal: str) -> redbaron.RedBaron:
return redbaron.RedBaron(literal)[0]
def create_bool_node(bool: bool) -> redbaron.RedBaron:
return redbaron.RedBaron(str(bool))[0]
def create_float_node(float: float) -> redbaron.RedBaron:
return redbaron.RedBaron(f"{float}")[0]
# Example:
# edit_config_property(
# [
# "models",
# "default",
# ],
# create_obj_node("OpenAI", {"api_key": '""', "model": '"gpt-4"'}),
# )

View file

@ -1,10 +0,0 @@
import traceback
class SessionNotFound(Exception):
pass
def format_exc(e: Exception) -> str:
lines = traceback.format_exception(Exception, e, e.__traceback__)
return "\n".join(lines)

View file

@ -1,29 +0,0 @@
ext_dict = {
"py": "python",
"js": "javascript",
"ts": "typescript",
"java": "java",
"go": "go",
"rb": "ruby",
"rs": "rust",
"c": "c",
"cpp": "cpp",
"cs": "csharp",
"php": "php",
"scala": "scala",
"swift": "swift",
"kt": "kotlin",
"md": "markdown",
"json": "json",
"html": "html",
"css": "css",
"sh": "shell",
"yaml": "yaml",
"toml": "toml",
"tex": "latex",
"sql": "sql",
}
def ext_to_lang(ext: str) -> str:
return ext_dict.get(ext, "plaintext")

View file

@ -1,39 +0,0 @@
# import fnmatch
from typing import List
import pathspec
DEFAULT_IGNORE_DIRS = [
".git",
".vscode",
".idea",
".vs",
".venv",
"env",
".env",
"node_modules",
"dist",
"build",
"target",
"out",
"bin",
".pytest_cache",
".vscode-test",
".continue",
"__pycache__",
]
DEFAULT_IGNORE_PATTERNS = DEFAULT_IGNORE_DIRS + list(
filter(lambda d: f"**/{d}", DEFAULT_IGNORE_DIRS)
)
def should_filter_path(
path: str, ignore_patterns: List[str] = DEFAULT_IGNORE_PATTERNS
) -> bool:
"""Returns whether a file should be filtered"""
spec = pathspec.PathSpec.from_lines(
pathspec.patterns.gitwildmatch.GitWildMatchPattern, ignore_patterns
)
return spec.match_file(path)
# return any(fnmatch.fnmatch(path, pattern) for pattern in ignore_patterns)

View file

@ -1,45 +0,0 @@
import logging
import os
from .paths import getLogFilePath
logfile_path = getLogFilePath()
try:
# Truncate the logs that are more than a day old
if os.path.exists(logfile_path) and os.path.getsize(logfile_path) > 32 * 1024:
tail = None
with open(logfile_path, "rb") as f:
f.seek(-32 * 1024, os.SEEK_END)
tail = f.read().decode("utf-8")
if tail is not None:
with open(logfile_path, "w") as f:
f.write(tail)
except Exception as e:
print("Error truncating log file: {}".format(e))
# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create a file handler
file_handler = logging.FileHandler(logfile_path)
file_handler.setLevel(logging.DEBUG)
# Create a console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# Create a formatter
formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s")
formatter.datefmt = "%Y-%m-%d %H:%M:%S"
# Add the formatter to the handlers
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)

View file

@ -1,19 +0,0 @@
from pathlib import Path
def map_path(path_str: str, orig_root: str, copy_root: str) -> str:
def get_path() -> Path:
path = Path(path_str)
if path.is_relative_to(orig_root):
if path.is_absolute():
return Path(copy_root) / path.relative_to(orig_root)
else:
return path
else:
if path.is_absolute():
return path
else:
# For this one, you need to know the directory from which the relative path is being used.
return Path(orig_root) / path
return str(get_path().resolve())

View file

@ -1,214 +0,0 @@
import os
import re
from typing import Any, Awaitable, Callable, Optional
from ..constants.default_config import default_config
from ..constants.main import (
CONTINUE_GLOBAL_FOLDER,
CONTINUE_SERVER_FOLDER,
CONTINUE_SESSIONS_FOLDER,
)
def find_data_file(filename):
datadir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(datadir, filename))
def getGlobalFolderPath():
path = os.path.join(os.path.expanduser("~"), CONTINUE_GLOBAL_FOLDER)
os.makedirs(path, exist_ok=True)
return path
def getMigrationsPath():
path = os.path.join(getGlobalFolderPath(), ".migrations")
os.makedirs(path, exist_ok=True)
return path
def hasMigrated(migration_id: str) -> bool:
path = os.path.join(getMigrationsPath(), migration_id)
return os.path.exists(path)
def markMigrated(migration_id: str):
path = os.path.join(getMigrationsPath(), migration_id)
with open(path, "w") as f:
f.write("")
async def migrate(migration_id: str, migrate_func: Callable[[], Awaitable]):
if not hasMigrated(migration_id):
await migrate_func()
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)
return path
def getServerFolderPath():
path = os.path.join(getGlobalFolderPath(), CONTINUE_SERVER_FOLDER)
os.makedirs(path, exist_ok=True)
return path
def getDevDataFolderPath():
path = os.path.join(getGlobalFolderPath(), "dev_data")
os.makedirs(path, exist_ok=True)
return path
def getDiffsFolderPath():
path = os.path.join(getGlobalFolderPath(), "diffs")
os.makedirs(path, exist_ok=True)
return path
def getIndexFolderPath():
path = os.path.join(getGlobalFolderPath(), "index")
os.makedirs(path, exist_ok=True)
return path
def decode_escaped_path(path: str) -> str:
"""We use a custom escaping scheme to record the full path of a file as a
corresponding basename, but withut URL encoding, because then the URI just gets
interpreted as a full path again."""
return path.replace("_f_", "/").replace("_b_", "\\")
def encode_escaped_path(path: str) -> str:
"""We use a custom escaping scheme to record the full path of a file as a
corresponding basename, but withut URL encoding, because then the URI just gets
interpreted as a full path again."""
return path.replace("/", "_f_").replace("\\", "_b_")
def getEmbeddingsPathForBranch(workspace_dir: str, branch_name: str):
path = os.path.join(
getIndexFolderPath(), encode_escaped_path(workspace_dir), branch_name
)
os.makedirs(path, exist_ok=True)
return path
def getDevDataFilePath(table_name: str):
filepath = os.path.join(getDevDataFolderPath(), f"{table_name}.jsonl")
if not os.path.exists(filepath):
with open(filepath, "w") as f:
f.write("")
return filepath
def getMeilisearchExePath():
binary_name = "meilisearch.exe" if os.name == "nt" else "meilisearch"
path = os.path.join(getServerFolderPath(), binary_name)
return path
def getSessionFilePath(session_id: str):
path = os.path.join(getSessionsFolderPath(), f"{session_id}.json")
os.makedirs(os.path.dirname(path), exist_ok=True)
return path
def getSessionsListFilePath():
path = os.path.join(getSessionsFolderPath(), "sessions.json")
os.makedirs(os.path.dirname(path), exist_ok=True)
if not os.path.exists(path):
with open(path, "w") as f:
f.write("[]")
return path
def migrateConfigFile(existing: str) -> Optional[str]:
if existing.strip() == "":
return default_config
migrated = (
existing.replace("MaybeProxyOpenAI", "OpenAIFreeTrial")
.replace("maybe_proxy_openai", "openai_free_trial")
.replace("unused=", "saved=")
.replace("medium=", "summarize=")
.replace("TextGenUI", "TextGenWebUI")
.replace("text_gen_interface", "text_gen_webui")
.replace(".steps.chroma", ".steps.codebase")
.replace("\xa0", " ")
.replace("server_url", "api_base")
)
if migrated != existing:
return migrated
return None
def getConfigFilePath(json: bool = False) -> str:
path = os.path.join(
getGlobalFolderPath(), "config.py" if not json else "config.json"
)
os.makedirs(os.path.dirname(path), exist_ok=True)
# Until migration considered complete, don't do this for .json
if not json:
if not os.path.exists(path):
with open(path, "w") as f:
f.write(default_config)
else:
# Make any necessary migrations
with open(path, "r") as f:
existing_content = f.read()
migrated = migrateConfigFile(existing_content)
if migrated is not None:
with open(path, "w") as f:
f.write(migrated)
return path
def convertConfigImports(shorten: bool):
path = getConfigFilePath()
# Make any necessary migrations
with open(path, "r") as f:
existing_content = f.read()
if shorten:
migrated = existing_content.replace(
"from continuedev.src.continuedev.", "from continuedev."
)
else:
migrated = re.sub(
r"(?<!src\.)continuedev\.(?!src)",
"continuedev.",
existing_content,
)
with open(path, "w") as f:
f.write(migrated)
def getLogFilePath():
path = os.path.join(getGlobalFolderPath(), "continue.log")
os.makedirs(os.path.dirname(path), exist_ok=True)
return path
def getSavedContextGroupsPath():
path = os.path.join(getGlobalFolderPath(), "saved_context_groups.json")
os.makedirs(os.path.dirname(path), exist_ok=True)
if not os.path.exists(path):
with open(path, "w") as f:
f.write("{}")
return path

View file

@ -1,23 +0,0 @@
import asyncio
from typing import Dict
from ...models.websockets import WebsocketsMessage
class WebsocketsSubscriptionQueue:
queues: Dict[str, asyncio.Queue] = {}
def post(self, msg: WebsocketsMessage):
if msg.message_id not in self.queues:
self.queues.update({msg.message_id: asyncio.Queue()})
self.queues[msg.message_id].put_nowait(msg)
async def get(self, message_id: str) -> WebsocketsMessage:
if message_id not in self.queues:
self.queues.update({message_id: asyncio.Queue()})
return await self.queues[message_id].get()
async def delete(self, message_id: str):
if message_id in self.queues:
del self.queues[message_id]

View file

@ -1,26 +0,0 @@
import os
import sys
def get_rg_path():
if os.name == "nt":
paths_to_try = [
f"C:\\Users\\{os.getlogin()}\\AppData\\Local\\Programs\\Microsoft VS Code\\resources\\app\\node_modules.asar.unpacked\\@vscode\\ripgrep\\bin\\rg.exe",
f"C:\\Users\\{os.getlogin()}\\AppData\\Local\\Programs\\Microsoft VS Code\\resources\\app\\node_modules.asar.unpacked\\vscode-ripgrep\\bin\\rg.exe",
]
for path in paths_to_try:
if os.path.exists(path):
rg_path = path
break
elif os.name == "posix":
if "darwin" in sys.platform:
rg_path = "/Applications/Visual Studio Code.app/Contents/Resources/app/node_modules.asar.unpacked/@vscode/ripgrep/bin/rg"
else:
rg_path = "/usr/share/code/resources/app/node_modules.asar.unpacked/vscode-ripgrep/bin/rg"
else:
rg_path = "rg"
if not os.path.exists(rg_path):
rg_path = "rg"
return rg_path

View file

@ -1,93 +0,0 @@
import os
from typing import List, Tuple
def dedent_and_get_common_whitespace(s: str) -> Tuple[str, str]:
lines = s.splitlines()
if len(lines) == 0:
return "", ""
# Longest common whitespace prefix
lcp = lines[0].split(lines[0].strip())[0]
# Iterate through the lines
for i in range(1, len(lines)):
# Empty lines are wildcards
if lines[i].strip() == "":
continue # hey that's us!
# Iterate through the leading whitespace characters of the current line
for j in range(0, len(lcp)):
# If it doesn't have the same whitespace as lcp, then update lcp
if j >= len(lines[i]) or lcp[j] != lines[i][j]:
lcp = lcp[:j]
if lcp == "":
return s, ""
break
return "\n".join(map(lambda x: x.lstrip(lcp), lines)), lcp
def strip_code_block(s: str) -> str:
"""
Strips the code block from a string, if it has one.
"""
if s.startswith("```\n") and s.endswith("\n```"):
return s[4:-4]
elif s.startswith("```") and s.endswith("```"):
return s[3:-3]
elif s.startswith("`") and s.endswith("`"):
return s[1:-1]
return s
def remove_quotes_and_escapes(output: str) -> str:
"""
Clean up the output of the completion API, removing unnecessary escapes and quotes
"""
output = output.strip()
# Replace smart quotes
output = output.replace("“", '"')
output = output.replace("”", '"')
output = output.replace("‘", "'")
output = output.replace("’", "'")
# Remove escapes
output = output.replace('\\"', '"')
output = output.replace("\\'", "'")
output = output.replace("\\n", "\n")
output = output.replace("\\t", "\t")
output = output.replace("\\\\", "\\")
if (output.startswith('"') and output.endswith('"')) or (
output.startswith("'") and output.endswith("'")
):
output = output[1:-1]
return output
def shorten_filepaths(filepaths: List[str]) -> List[str]:
"""
Shortens the filepaths to just the filename,
unless directory names are needed for uniqueness
"""
basenames = list(map(os.path.basename, filepaths))
if len(basenames) == len(filepaths):
return list(basenames)
basename_counts = {}
for filepath in filepaths:
basename = os.path.basename(filepath)
if basename not in basename_counts:
basename_counts[basename] = 0
basename_counts[basename] += 1
for i in range(0, len(filepaths)):
basename = os.path.basename(filepaths[i])
if basename_counts[basename] <= 1:
filepaths[i] = basename
else:
filepaths[i] = os.path.join(
os.path.basename(os.path.dirname(filepaths[i])), basename
)
return filepaths

View file

@ -1,96 +0,0 @@
import os
import socket
from typing import Any, Dict, Optional
from dotenv import load_dotenv
from ..constants.main import CONTINUE_SERVER_VERSION_FILE
from .commonregex import clean_pii_from_any
from .paths import getServerFolderPath
load_dotenv()
in_codespaces = os.getenv("CODESPACES") == "true"
# This key is public
POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs"
def is_connected():
try:
# connect to the host -- tells us if the host is actually reachable
socket.create_connection(("www.google.com", 80))
return True
except OSError:
pass
return False
class PostHogLogger:
unique_id: str = "NO_UNIQUE_ID"
allow_anonymous_telemetry: bool = False
ide_info: Optional[Dict] = None
posthog = None
def __init__(self, api_key: str):
self.api_key = api_key
def setup(
self, unique_id: str, allow_anonymous_telemetry: bool, ide_info: Optional[Dict]
):
self.unique_id = unique_id or "NO_UNIQUE_ID"
self.allow_anonymous_telemetry = allow_anonymous_telemetry or False
self.ide_info = ide_info
# Capture initial event
self.capture_event("session_start", {"os": os.name})
def capture_event(self, event_name: str, event_properties: Any):
"""Safely capture event. Telemetry should never be the reason Continue doesn't work"""
try:
self._capture_event(event_name, event_properties)
except Exception as e:
print(f"Failed to capture event: {e}")
pass
_found_disconnected: bool = False
def _capture_event(self, event_name: str, event_properties: Any):
if not self.allow_anonymous_telemetry:
return
# Clean PII from event properties
event_properties = clean_pii_from_any(event_properties)
# Add additional properties that are on every event
if in_codespaces:
event_properties["codespaces"] = True
server_version_file = os.path.join(
getServerFolderPath(), CONTINUE_SERVER_VERSION_FILE
)
if os.path.exists(server_version_file):
with open(server_version_file, "r") as f:
event_properties["server_version"] = f.read()
# Add operating system
event_properties["os"] = os.name
if self.ide_info:
event_properties["ide_name"] = self.ide_info.get("name", None)
event_properties["ide_version"] = self.ide_info.get("version", None)
event_properties["ide_remote_name"] = self.ide_info.get("remoteName", None)
# Send event to PostHog
if self.posthog is None:
from posthog import Posthog
# The personal API key is necessary only if you want to use local evaluation of feature flags.
self.posthog = Posthog(self.api_key, host="https://app.posthog.com")
if is_connected():
self.posthog.capture(self.unique_id, event_name, event_properties)
else:
if not self._found_disconnected:
self._found_disconnected = True
raise ConnectionError("No internet connection")
posthog_logger = PostHogLogger(api_key=POSTHOG_API_KEY)

View file

@ -1,76 +0,0 @@
import os
from typing import Callable, Dict, List, Union
import chevron
from ...core.main import ChatMessage
def get_vars_in_template(template):
"""
Get the variables in a template
"""
return [
token[1]
for token in chevron.tokenizer.tokenize(template)
if token[0] == "variable"
]
def escape_var(var: str) -> str:
"""
Escape a variable so it can be used in a template
"""
return var.replace(os.path.sep, "").replace(".", "")
def render_templated_string(template: str) -> str:
"""
Render system message or other templated string with mustache syntax.
Right now it only supports rendering absolute file paths as their contents.
"""
vars = get_vars_in_template(template)
args = {}
for var in vars:
if var.startswith(os.path.sep):
# Escape vars which are filenames, because mustache doesn't allow / in variable names
escaped_var = escape_var(var)
template = template.replace(var, escaped_var)
if os.path.exists(var) and os.path.isfile(var):
args[escaped_var] = open(var, "r").read()
else:
args[escaped_var] = ""
return chevron.render(template, args)
"""
A PromptTemplate can either be a template string (mustache syntax, e.g. {{user_input}}) or
a function which takes the history and a dictionary of additional key-value pairs and returns
either a string or a list of ChatMessages.
If a string is returned, it will be assumed that the chat history should be ignored
"""
PromptTemplate = Union[
str, Callable[[List[ChatMessage], Dict[str, str]], Union[str, List[ChatMessage]]]
]
def render_prompt_template(
template: PromptTemplate, history: List[ChatMessage], other_data: Dict[str, str]
) -> Union[str, List[ChatMessage]]:
"""
Render a prompt template.
"""
if isinstance(template, str):
data = {
"history": history,
**other_data,
}
if len(history) > 0 and history[0].role == "system":
data["system_message"] = history.pop(0).content
return chevron.render(template, data)
else:
return template(history, other_data)

View file

@ -1,58 +0,0 @@
from typing import Optional
from boltons import tbutils
from ....models.main import Traceback
PYTHON_TRACEBACK_PREFIX = "Traceback (most recent call last):"
def get_python_traceback(output: str) -> Optional[str]:
if PYTHON_TRACEBACK_PREFIX in output:
tb_string = output.split(PYTHON_TRACEBACK_PREFIX)[-1]
# Then need to remove any lines below the traceback. Do this by noticing that
# the last line of the traceback is the first (other than they prefix) that doesn't begin with whitespace
lines = list(filter(lambda x: x.strip() != "", tb_string.splitlines()))
for i in range(len(lines) - 1):
if not lines[i].startswith(" "):
tb_string = "\n".join(lines[: i + 1])
break
return PYTHON_TRACEBACK_PREFIX + "\n" + tb_string
elif "SyntaxError" in output:
return "SyntaxError" + output.split("SyntaxError")[-1]
else:
return None
def get_javascript_traceback(output: str) -> Optional[str]:
lines = output.splitlines()
first_line = None
for i in range(len(lines) - 1):
segs = lines[i].split(":")
if (
len(segs) > 1
and segs[0] != ""
and segs[1].startswith(" ")
and lines[i + 1].strip().startswith("at")
):
first_line = lines[i]
break
if first_line is not None:
return "\n".join(lines[lines.index(first_line) :])
else:
return None
def parse_python_traceback(tb_string: str) -> Traceback:
# Remove anchor lines - tbutils doesn't always get them right
tb_string = "\n".join(
filter(
lambda x: x.strip().replace("~", "").replace("^", "") != "",
tb_string.splitlines(),
)
)
exc = tbutils.ParsedException.from_string(tb_string)
return Traceback.from_tbutil_parsed_exc(exc)

View file

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

View file

@ -1,32 +0,0 @@
import asyncio
import os
import traceback
from dotenv import load_dotenv
from litellm import acompletion
load_dotenv()
async def completion_call():
try:
print("test acompletion + streaming")
response = await acompletion(
model="gpt-3.5-turbo",
messages=[{"content": "Hello, how are you?", "role": "user"}],
stream=True,
api_key=os.getenv("OPENAI_API_KEY"),
)
print(f"response: {response}")
async for chunk in response:
print(chunk)
except Exception:
print(f"error occurred: {traceback.format_exc()}")
pass
async def complete_n_times(n: int):
await asyncio.gather(*[completion_call() for _ in range(n)])
asyncio.run(completion_call())

View file

@ -1,403 +0,0 @@
import os
from abc import abstractmethod
from typing import Dict, Generator, List, Tuple
from pydantic import BaseModel
from ..libs.util.filter_files import should_filter_path
from ..models.main import AbstractModel, Position, Range
from .filesystem_edit import (
AddDirectory,
AddFile,
DeleteDirectory,
DeleteFile,
EditDiff,
FileEdit,
FileSystemEdit,
RenameDirectory,
RenameFile,
SequentialFileSystemEdit,
)
class RangeInFile(BaseModel):
filepath: str
range: Range
def __hash__(self):
return hash((self.filepath, self.range))
@staticmethod
def from_entire_file(filepath: str, content: str) -> "RangeInFile":
range = Range.from_entire_file(content)
return RangeInFile(filepath=filepath, range=range)
def translated(self, lines: int):
return RangeInFile(filepath=self.filepath, range=self.range.translated(lines))
def with_contents(self, contents: str) -> "RangeInFileWithContents":
return RangeInFileWithContents.from_range_in_file(self, contents)
class RangeInFileWithContents(RangeInFile):
"""A range in a file with the contents of the range."""
contents: str
def __hash__(self):
return hash((self.filepath, self.range, self.contents))
def to_range_in_file(self) -> RangeInFile:
return RangeInFile(filepath=self.filepath, range=self.range)
def union(self, other: "RangeInFileWithContents") -> "RangeInFileWithContents":
assert self.filepath == other.filepath
# Use a placeholder variable for self and swap it with other if other comes before self
first = self
second = other
if other.range.start < self.range.start:
first = other
second = self
assert first.filepath == second.filepath
# Calculate union of contents
num_overlapping_lines = first.range.end.line - second.range.start.line + 1
union_lines = (
first.contents.splitlines()[:-num_overlapping_lines]
+ second.contents.splitlines()
)
return RangeInFileWithContents(
filepath=first.filepath,
range=first.range.union(second.range),
contents="\n".join(union_lines),
)
@staticmethod
def from_entire_file(filepath: str, content: str) -> "RangeInFileWithContents":
lines = content.splitlines()
if not lines:
return RangeInFileWithContents(
filepath=filepath, range=Range.from_shorthand(0, 0, 0, 0), contents=""
)
return RangeInFileWithContents(
filepath=filepath,
range=Range.from_shorthand(0, 0, len(lines) - 1, len(lines[-1]) - 1),
contents=content,
)
@staticmethod
def from_range_in_file(rif: RangeInFile, content: str) -> "RangeInFileWithContents":
return RangeInFileWithContents(
filepath=rif.filepath, range=rif.range, contents=content
)
class FileSystem(AbstractModel):
"""An abstract filesystem that can read/write from a set of files."""
@abstractmethod
def read(self, path) -> str:
raise NotImplementedError
@abstractmethod
def readlines(self, path) -> List[str]:
raise NotImplementedError
@abstractmethod
def write(self, path, content):
raise NotImplementedError
@abstractmethod
def exists(self, path) -> bool:
raise NotImplementedError
@abstractmethod
def read_range_in_file(self, r: RangeInFile) -> str:
raise NotImplementedError
@abstractmethod
def rename_file(self, filepath: str, new_filepath: str):
raise NotImplementedError
@abstractmethod
def rename_directory(self, path: str, new_path: str):
raise NotImplementedError
@abstractmethod
def delete_file(self, filepath: str):
raise NotImplementedError
@abstractmethod
def delete_directory(self, path: str):
raise NotImplementedError
@abstractmethod
def add_directory(self, path: str):
raise NotImplementedError
@abstractmethod
def apply_file_edit(self, edit: FileEdit) -> EditDiff:
raise NotImplementedError
@abstractmethod
def list_directory_contents(self, path: str, recursive: bool = False) -> List[str]:
"""List the contents of a directory"""
raise NotImplementedError
@classmethod
def read_range_in_str(cls, s: str, r: Range) -> str:
lines = s.split("\n")[r.start.line : r.end.line + 1]
if len(lines) == 0:
return ""
lines[0] = lines[0][r.start.character :]
lines[-1] = lines[-1][: r.end.character + 1]
return "\n".join(lines)
@classmethod
def apply_edit_to_str(cls, s: str, edit: FileEdit) -> Tuple[str, EditDiff]:
original = cls.read_range_in_str(s, edit.range)
# Split lines and deal with some edge cases (could obviously be nicer)
lines = s.splitlines()
if s.startswith("\n"):
lines.insert(0, "")
if s.endswith("\n"):
lines.append("")
if len(lines) == 0:
lines = [""]
end = Position(line=edit.range.end.line, character=edit.range.end.character)
if edit.range.end.line == len(lines) and edit.range.end.character == 0:
end = Position(
line=edit.range.end.line - 1,
character=len(lines[min(len(lines) - 1, edit.range.end.line - 1)]),
)
before_lines = lines[: edit.range.start.line]
after_lines = lines[end.line + 1 :]
between_str = (
lines[min(len(lines) - 1, edit.range.start.line)][
: edit.range.start.character
]
+ edit.replacement
+ lines[min(len(lines) - 1, end.line)][end.character + 1 :]
)
new_range = Range(
start=edit.range.start,
end=Position(
line=edit.range.start.line + len(edit.replacement.splitlines()) - 1,
character=edit.range.start.character
+ len(edit.replacement.splitlines()[-1])
if edit.replacement != ""
else 0,
),
)
lines = before_lines + between_str.splitlines() + after_lines
return "\n".join(lines), EditDiff(
forward=edit,
backward=FileEdit(
filepath=edit.filepath, range=new_range, replacement=original
),
)
def reverse_edit_on_str(self, s: str, diff: EditDiff) -> str:
lines = s.splitlines()
replacement_lines = diff.replacement.splitlines()
replacement_d_lines = len(replacement_lines)
replacement_d_chars = len(replacement_lines[-1])
replacement_range = Range(
start=diff.edit.range.start,
end=Position(
line=diff.edit.range.start + replacement_d_lines,
character=diff.edit.range.start.character + replacement_d_chars,
),
)
before_lines = lines[: replacement_range.start.line]
after_lines = lines[replacement_range.end.line + 1 :]
between_str = (
lines[replacement_range.start.line][: replacement_range.start.character]
+ diff.original
+ lines[replacement_range.end.line][replacement_range.end.character + 1 :]
)
lines = before_lines + between_str.splitlines() + after_lines
return "\n".join(lines)
def apply_edit(self, edit: FileSystemEdit) -> EditDiff:
backward = None
if isinstance(edit, FileEdit):
diff = self.apply_file_edit(edit)
backward = diff.backward
elif isinstance(edit, AddFile):
self.write(edit.filepath, edit.content)
backward = DeleteFile(edit.filepath)
elif isinstance(edit, DeleteFile):
contents = self.read(edit.filepath)
backward = AddFile(edit.filepath, contents)
self.delete_file(edit.filepath)
elif isinstance(edit, RenameFile):
self.rename_file(edit.filepath, edit.new_filepath)
backward = RenameFile(
filepath=edit.new_filepath, new_filepath=edit.filepath
)
elif isinstance(edit, AddDirectory):
self.add_directory(edit.path)
backward = DeleteDirectory(edit.path)
elif isinstance(edit, DeleteDirectory):
# This isn't atomic!
backward_edits = []
for root, dirs, files in os.walk(edit.path, topdown=False):
for f in files:
path = os.path.join(root, f)
backward_edits.append(self.apply_edit(DeleteFile(path)))
for d in dirs:
path = os.path.join(root, d)
backward_edits.append(self.apply_edit(DeleteDirectory(path)))
backward_edits.append(self.apply_edit(DeleteDirectory(edit.path)))
backward_edits.reverse()
backward = SequentialFileSystemEdit(edits=backward_edits)
elif isinstance(edit, RenameDirectory):
self.rename_directory(edit.path, edit.new_path)
backward = RenameDirectory(path=edit.new_path, new_path=edit.path)
elif isinstance(edit, FileSystemEdit):
backward_edits = []
for edit in edit.next_edit():
backward_edits.append(self.apply_edit(edit))
backward_edits.reverse()
backward = SequentialFileSystemEdit(edits=backward_edits)
else:
raise TypeError("Unknown FileSystemEdit type: " + str(type(edit)))
return EditDiff(forward=edit, backward=backward)
class RealFileSystem(FileSystem):
"""A filesystem that reads/writes from the actual filesystem."""
def read(self, path) -> str:
with open(path, "r") as f:
return f.read()
def readlines(self, path) -> List[str]:
with open(path, "r") as f:
return f.readlines()
def write(self, path, content):
with open(path, "w") as f:
f.write(content)
def exists(self, path) -> bool:
return os.path.exists(path)
def read_range_in_file(self, r: RangeInFile) -> str:
return FileSystem.read_range_in_str(self.read(r.filepath), r.range)
def rename_file(self, filepath: str, new_filepath: str):
os.rename(filepath, new_filepath)
def rename_directory(self, path: str, new_path: str):
os.rename(path, new_path)
def delete_file(self, filepath: str):
os.remove(filepath)
def delete_directory(self, path: str):
raise NotImplementedError
def add_directory(self, path: str):
os.makedirs(path)
def apply_file_edit(self, edit: FileEdit) -> EditDiff:
old_content = self.read(edit.filepath)
new_content, diff = FileSystem.apply_edit_to_str(old_content, edit)
self.write(edit.filepath, new_content)
return diff
def list_directory_contents(self, path: str, recursive: bool = False) -> List[str]:
"""List the contents of a directory"""
if recursive:
# Walk
paths = []
for root, dirs, files in os.walk(path):
dirs[:] = list(filter(lambda p: not should_filter_path(p), dirs))
for f in files:
paths.append(os.path.join(root, f))
return paths
return list(map(lambda x: os.path.join(path, x), os.listdir(path)))
class VirtualFileSystem(FileSystem):
"""A simulated filesystem from a mapping of filepath to file contents."""
files: Dict[str, str]
def __init__(self, files: Dict[str, str]):
self.files = files
def read(self, path) -> str:
return self.files[path]
def readlines(self, path) -> List[str]:
return self.files[path].splitlines()
def write(self, path, content):
self.files[path] = content
def exists(self, path) -> bool:
return path in self.files
def read_range_in_file(self, r: RangeInFile) -> str:
return FileSystem.read_range_in_str(self.read(r.filepath), r.range)
def rename_file(self, filepath: str, new_filepath: str):
self.files[new_filepath] = self.files[filepath]
del self.files[filepath]
def rename_directory(self, path: str, new_path: str):
for filepath in self.files:
if filepath.startswith(path):
new_filepath = new_path + filepath[len(path) :]
self.files[new_filepath] = self.files[filepath]
del self.files[filepath]
def delete_file(self, filepath: str):
del self.files[filepath]
def delete_directory(self, path: str):
raise NotImplementedError
def add_directory(self, path: str):
# For reasons as seen here and in delete_directory, a Dict[str, str] might not be the best representation. Could just preprocess to something better upon __init__
pass
def apply_file_edit(self, edit: FileEdit) -> EditDiff:
old_content = self.read(edit.filepath)
new_content, original = FileSystem.apply_edit_to_str(old_content, edit)
self.write(edit.filepath, new_content)
return EditDiff(edit=edit, original=original)
def list_directory_contents(
self, path: str, recursive: bool = False
) -> Generator[str, None, None]:
"""List the contents of a directory"""
if recursive:
for filepath in self.files:
if filepath.startswith(path):
yield filepath
for filepath in self.files:
if filepath.startswith(path) and "/" not in filepath[len(path) :]:
yield filepath
# TODO: Uniform errors thrown by any FileSystem subclass.

View file

@ -1,166 +0,0 @@
import os
from abc import abstractmethod
from typing import Generator, List
from pydantic import BaseModel
from ..libs.util.map_path import map_path
from .main import Position, Range
class FileSystemEdit(BaseModel):
@abstractmethod
def next_edit(self) -> Generator["FileSystemEdit", None, None]:
raise NotImplementedError
@abstractmethod
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
raise NotImplementedError
class AtomicFileSystemEdit(FileSystemEdit):
def next_edit(self) -> Generator["FileSystemEdit", None, None]:
yield self
class FileEdit(AtomicFileSystemEdit):
filepath: str
range: Range
replacement: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return FileEdit(
filepath=map_path(self.filepath, orig_root, copy_root),
range=self.range,
replacement=self.replacement,
)
@staticmethod
def from_deletion(filepath: str, range: Range) -> "FileEdit":
return FileEdit(filepath=filepath, range=range, replacement="")
@staticmethod
def from_insertion(filepath: str, position: Position, content: str) -> "FileEdit":
return FileEdit(
filepath=filepath,
range=Range.from_shorthand(
position.line, position.character, position.line, position.character
),
replacement=content,
)
@staticmethod
def from_append(
filepath: str, previous_content: str, appended_content: str
) -> "FileEdit":
return FileEdit(
filepath=filepath,
range=Range.from_position(Position.from_end_of_file(previous_content)),
replacement=appended_content,
)
class FileEditWithFullContents(BaseModel):
fileEdit: FileEdit
fileContents: str
class AddFile(AtomicFileSystemEdit):
filepath: str
content: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return AddFile(
filepath=map_path(self.filepath, orig_root, copy_root), content=self.content
)
class DeleteFile(AtomicFileSystemEdit):
filepath: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return DeleteFile(filepath=map_path(self.filepath, orig_root, copy_root))
class RenameFile(AtomicFileSystemEdit):
filepath: str
new_filepath: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return RenameFile(
filepath=map_path(self.filepath, orig_root, copy_root),
new_filepath=map_path(self.new_filepath, orig_root, copy_root),
)
class AddDirectory(AtomicFileSystemEdit):
path: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return AddDirectory(path=map_path(self.path, orig_root, copy_root))
class DeleteDirectory(AtomicFileSystemEdit):
path: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return DeleteDirectory(path=map_path(self.path, orig_root, copy_root))
class RenameDirectory(AtomicFileSystemEdit):
path: str
new_path: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return RenameDirectory(
path=map_path(self.path, orig_root, copy_root),
new_path=map_path(self.new_path, orig_root, copy_root),
)
class DeleteDirectoryRecursive(FileSystemEdit):
path: str
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return DeleteDirectoryRecursive(path=map_path(self.path, orig_root, copy_root))
def next_edit(self) -> Generator[FileSystemEdit, None, None]:
yield DeleteDirectory(path=self.path)
for child in os.listdir(self.path):
child_path = os.path.join(self.path, child)
if os.path.isdir(child_path):
yield DeleteDirectoryRecursive(path=child_path)
else:
yield DeleteFile(filepath=child_path)
class SequentialFileSystemEdit(FileSystemEdit):
edits: List[FileSystemEdit]
def with_mapped_paths(self, orig_root: str, copy_root: str) -> "FileSystemEdit":
return SequentialFileSystemEdit(
edits=[edit.with_mapped_paths(orig_root, copy_root) for edit in self.edits]
)
def next_edit(self) -> Generator["FileSystemEdit", None, None]:
for edit in self.edits:
yield from edit.next_edit()
class EditDiff(BaseModel):
"""A reversible edit that can be applied to a file."""
forward: FileSystemEdit
backward: FileSystemEdit
@classmethod
def from_sequence(cls, diffs: List["EditDiff"]) -> "EditDiff":
forwards = []
backwards = []
for diff in diffs:
forwards.append(diff.forward)
backwards.insert(0, diff.backward)
return cls(
forward=SequentialFileSystemEdit(edits=forwards),
backward=SequentialFileSystemEdit(edits=backwards),
)

Some files were not shown because too many files have changed in this diff Show more