continue-custom/server/continuedev/core/main.py
Bishwendu Kundu 0752c15c1a
Initial intelliJ plugin changes to support webview (#457)
* Initial intelliJ plugin changes to support webview

* connect webview websockets

* Starting work on downloading server binary from S3

* fix color theme in intellij

* refactor name to continuedev

* correctly set important variables for onLoad

* highlighted code now working

* keyboard shortcuts (Actions)

* fix: 🐛 hf_tgi fix, proxy support for ggml

* fix: 🐛 remove unecessary logging

* Sync the changes

* Clean up code

* updating how continue works

* ci: 🏷 Update PyPI version [skip ci]

* docs: 📝 docs for customizing chat / edit templates

* docs: 📝 headless mode docs (start)

* docs: 📝 updated setup docs

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 compatibility with python 3.8

* feat: ✨ verify_ssl option for all LLMs

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 verify_ssl and ssl_context mutual exclusivity

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* feat: 🩹 ca_bundle_path for maybeproxyopenai

* fix: 🐛 a few minor fixes

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 custom escaping instead of URI for diff paths

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix huggingface tgi

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* docs: 📝 small docs update on how continue works

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* Clarifying `logs` instructions in troubleshooting.md (#476)

* fix: 🐛 fixes to templating messages

* fix: some typos (#478)

* fix: 🐛 fix for lmstudio defaults

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* Implement design patterns for better extensibility

* Fix: Ensure read operations in ContinuePluginSelectionListener are run within the correct context using runReadAction.

* feat: ✨ implement most other ideProtocolClient methods

* wait until server is running to connect

* remove unnecessary imports, update version

* reformat code and optimize the imports

* fix: 🐛 fix serialization bug

* fix: 🐛 attempt to fix error from jetbrains marketplace

* a few updates

* fix: 🐛 bringing jetbrains up to par

* feat: ✨ highlighted code updates in intellij

* fix: 🚑 fix freezing issue

* fix: 🐛 fix icons, bump version

* feat: ✨ /edit support, other fixes

* quick input, keyboard shortcuts

* fix: 🐛 fix /edit and keyboard shortcuts and lagging on scroll

* feat: 💄 welcome panel

* chore: 🔖 update version

* ide endpoint for websockets

* fix: 🚑 fix freezing problem

* quick input

* fix: 🐛 small jetbrains fixes

* fix: 💄 nicer dropdown that can "drop up"

* fix: 🐛 fix font size for dropdown

* fix: 💄 fix textarea for quickinput

* Preview (#541)

* Strong typing (#533)

* refactor: ♻️ get rid of continuedev.src.continuedev structure

* refactor: ♻️ switching back to server folder

* feat: ✨ make config.py imports shorter

* feat: 🔖 publish as pre-release vscode extension

* refactor: ♻️ refactor and add more completion params to ui

* build: 🏗️ download from preview S3

* fix: 🐛 fix paths

* fix: 💚 package:pre-release

* ci: 💚 more time for tests

* fix: 💚 fix build scripts

* fix: 🐛 fix import in run.py

* fix: 🔖 update version to try again

* ci: 💚 Update package.json version [skip ci]

* refactor: 🔥 don't check for old extensions version

* fix: 🐛 small bug fixes

* fix: 🐛 fix config.py import paths

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 platform-specific builds test #1

* feat: 💚 ship with binary

* fix: 💚 fix copy statement to include.exe for windows

* fix: 💚 cd extension before packaging

* chore: 🔊 count tokens generated

* fix: 💚 remove npm_config_arch

* fix: 💚 publish as pre-release!

* chore: 🔖 update version

* perf: 💚 hardcode distro paths

* fix: 🐛 fix yaml syntax error

* chore: 🔖 update version

* fix: 💚 update permissions and version

* feat: 🐛 kill old server if needed

* feat: 💄 update marketplace icon for pre-release

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ auto-reload for config.py

* feat: 🔧 update default config.py imports

* feat: ✨ codelens in config.py

* feat: ✨ select model param count from UI

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ more model options, ollama error handling

* perf: ⚡ don't show server loading immediately

* fix: 🐛 fixing small UI details

* ci: 💚 Update package.json version [skip ci]

* feat: 🚀 headers param on LLM class

* fix: 🐛 fix headers for openai.;y

* feat: ✨ highlight code on cmd+shift+L

* ci: 💚 Update package.json version [skip ci]

* feat: 💄 sticky top bar in gui.tsx

* fix: 🔊 websocket logging and horizontal scrollbar

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ allow AzureOpenAI Service through GGML

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix automigration

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 upload binaries in ci, download apple silicon

* chore: 🔥 remove notes

* fix: 💚 use curl to download binary

* fix: 💚 set permissions on apple silicon binary

* fix: 💚 testing

* fix: 💚 cleanup file

* fix: 💚 fix preview.yaml

* fix: 💚 only upload once per binary

* fix: 💚 install rosetta

* ci: 💚 download binary after tests

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 prepare ci for merge to main

---------

Co-authored-by: GitHub Action <action@github.com>

* fix: 📝 fix deployent readme

* fix: 🐛 do read operation in readAction

* chore: 🔖 update version

* 🐛 small jetbrains fixes

* ⚡️ exponential backoff jetbrains

* 🐛 fix history loading bug

* 💄 many small ui fixes

* 🐛 fixes freezing problem (actually)

* 🥅 catch errors, other stuff

* 🐛 many jetbrains fixes

* 💄 when no context items found, say in dropdown

* 🎉 VS Code tutorial

* ✨ jetbrains tutorial file

* ⚡️ exponential backoff for ide websockets

* 🎉 unused work on intellij editor inlay

* ✨ server loading progress messages

* ✨ additional progress update

* 💄 fix /edit flickering, keyboard interactions

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Ty Dunn <ty@tydunn.com>
Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: Aaron Mihalik <amihalik@users.noreply.github.com>
Co-authored-by: LangLangBart <92653266+LangLangBart@users.noreply.github.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
2023-10-16 23:14:00 -07:00

437 lines
12 KiB
Python

import json
from typing import Any, Coroutine, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, 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: Optional[str] = None
name: Optional[str] = None
# A summary for pruning chat context to fit context window. Often the Step name.
summary: str
function_call: Optional[FunctionCall] = None
def to_dict(self, with_functions: bool) -> Dict:
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) -> str:
pydantic_class = step.__class__
schema_data = schema([pydantic_class])
resolved_schema = 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 HistoryNode(ContinueBaseModel):
"""A point in history, a list of which make up History"""
step: "Step"
observation: Union[Observation, None]
depth: int
deleted: bool = False
active: bool = True
logs: List[str] = []
context_used: List["ContextItem"] = []
def to_chat_messages(self) -> List[ChatMessage]:
if self.step.description is None or self.step.manage_own_chat_context:
return self.step.chat_context
return self.step.chat_context + [
ChatMessage(
role="assistant",
name=self.step.__class__.__name__,
content=self.step.description or f"Ran function {self.step.name}",
summary=f"Called function {self.step.name}",
)
]
class History(ContinueBaseModel):
"""A history of steps taken and their results"""
timeline: List[HistoryNode]
current_index: int
def to_chat_history(self) -> List[ChatMessage]:
msgs = []
for node in self.timeline:
if not node.step.hide:
msgs += node.to_chat_messages()
return msgs
def add_node(self, node: HistoryNode) -> int:
"""Add node and return the index where it was added"""
self.timeline.insert(self.current_index + 1, node)
self.current_index += 1
return self.current_index
def get_current(self) -> Union[HistoryNode, None]:
if self.current_index < 0:
return None
return self.timeline[self.current_index]
def get_last_at_depth(
self, depth: int, include_current: bool = False
) -> Union[HistoryNode, None]:
i = self.current_index if include_current else self.current_index - 1
while i >= 0:
if (
self.timeline[i].depth == depth
and type(self.timeline[i].step).__name__ != "ManualEditStep"
):
return self.timeline[i]
i -= 1
return None
def get_last_at_same_depth(self) -> Union[HistoryNode, None]:
return self.get_last_at_depth(self.get_current().depth)
def remove_current_and_substeps(self):
self.timeline.pop(self.current_index)
while self.get_current() is not None and self.get_current().depth > 0:
self.timeline.pop(self.current_index)
def take_next_step(self) -> Union["Step", None]:
if self.has_future():
self.current_index += 1
current_state = self.get_current()
if current_state is None:
return None
return current_state.step
return None
def get_current_index(self) -> int:
return self.current_index
def has_future(self) -> bool:
return self.current_index < len(self.timeline) - 1
def step_back(self):
self.current_index -= 1
def last_observation(self) -> Union[Observation, None]:
state = self.get_last_at_same_depth()
if state is None:
return None
return state.observation
def pop_step(self, index: int = None) -> Union[HistoryNode, None]:
index = index if index is not None else self.current_index
if index < 0 or self.current_index < 0:
return None
node = self.timeline.pop(index)
if index <= self.current_index:
self.current_index -= 1
return node.step
@classmethod
def from_empty(cls):
return cls(timeline=[], current_index=-1)
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}"
@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 FullState(ContinueBaseModel):
"""A full state of the program, including the history"""
history: History
active: bool
user_input_queue: List[str]
slash_commands: List[SlashCommandDescription]
adding_highlighted_code: bool
selected_context_items: List[ContextItem]
session_info: Optional[SessionInfo] = None
config: ContinueConfig
saved_context_groups: Dict[str, List[ContextItem]] = {}
context_providers: List[ContextProviderDescription] = []
meilisearch_url: Optional[str] = None
class ContinueSDK:
...
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, history: History = History.from_empty()
) -> "Step":
raise NotImplementedError
class Step(ContinueBaseModel):
name: str = None
hide: bool = False
description: Union[str, None] = None
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) -> Coroutine[str, None, None]:
if self.description is not None:
return self.description
return "Running step: " + self.name
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) -> Coroutine[Observation, None, None]:
raise NotImplementedError
async def __call__(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:
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) -> Coroutine[Observation, None, None]:
for step in self.steps:
observation = await sdk.run_step(step)
return observation
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
HistoryNode.update_forward_refs()