diff --git a/continue_server.m1.spec b/continue_server.m1.spec index 80ee652df..b64438835 100644 --- a/continue_server.m1.spec +++ b/continue_server.m1.spec @@ -27,17 +27,19 @@ def find_package_location(package_name): chroma_path = find_package_location('chromadb') chroma_toc = list(map(lambda x: (x[1], os.path.dirname(x[0])), Tree(f'{chroma_path}/chromadb/migrations', prefix="chromadb/migrations"))) +tsl_path = find_package_location('tree_sitter_languages') + a = Analysis( ['continue_server.py'], pathex=[], - binaries=[], + binaries=[(os.path.join(tsl_path, 'tree_sitter_languages', 'languages.so'), "tree_sitter_languages")], datas=[ ('server/continuedev', 'continuedev'), (certifi.where(), 'ca_bundle'), - ('.tiktoken_cache', 'tiktoken_cache') + ('.tiktoken_cache', 'tiktoken_cache'), ] + copy_metadata('replicate') + chroma_toc, hiddenimports=[ - 'anthropic', 'github', 'ripgrepy', 'bs4', 'redbaron', + 'anthropic', 'github', 'ripgrepy', 'bs4', 'redbaron', 'tree_sitter', 'tree_sitter_languages', 'chromadb', 'onnxruntime', 'chromadb.telemetry.posthog', 'chromadb.api.segment', 'chromadb.db.impl', diff --git a/continue_server.spec b/continue_server.spec index 04dd0a6ef..1ba987261 100644 --- a/continue_server.spec +++ b/continue_server.spec @@ -28,17 +28,19 @@ def find_package_location(package_name): chroma_path = find_package_location('chromadb') chroma_toc = list(map(lambda x: (x[1], os.path.dirname(x[0])), Tree(f'{chroma_path}/chromadb/migrations', prefix="chromadb/migrations"))) +tsl_path = find_package_location('tree_sitter_languages') + a = Analysis( ['continue_server.py'], pathex=[], - binaries=[], + binaries=[(os.path.join(tsl_path, 'tree_sitter_languages', 'languages.so'), "tree_sitter_languages")], datas=[ ('server/continuedev', 'continuedev'), (certifi.where(), 'ca_bundle'), - ('.tiktoken_cache', 'tiktoken_cache') + ('.tiktoken_cache', 'tiktoken_cache'), ] + copy_metadata('replicate') + chroma_toc, hiddenimports=[ - 'anthropic', 'github', 'ripgrepy', 'bs4', 'redbaron', + 'anthropic', 'github', 'ripgrepy', 'bs4', 'redbaron', 'tree_sitter', 'tree_sitter_languages', 'chromadb', 'onnxruntime', 'chromadb.telemetry.posthog', 'chromadb.api.segment', 'chromadb.db.impl', diff --git a/extension/package-lock.json b/extension/package-lock.json index 849b0f93a..4c643d405 100644 --- a/extension/package-lock.json +++ b/extension/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.1.28", + "version": "0.1.29", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "continue", - "version": "0.1.28", + "version": "0.1.29", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extension/package.json b/extension/package.json index 5f4938f6a..f36765afb 100644 --- a/extension/package.json +++ b/extension/package.json @@ -1,7 +1,7 @@ { "name": "continue", "icon": "media/icon.png", - "version": "0.1.28", + "version": "0.1.29", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extension/react-app/src/components/ErrorStepContainer.tsx b/extension/react-app/src/components/ErrorStepContainer.tsx index 07c0a0461..992a3789b 100644 --- a/extension/react-app/src/components/ErrorStepContainer.tsx +++ b/extension/react-app/src/components/ErrorStepContainer.tsx @@ -37,7 +37,7 @@ function ErrorStepContainer(props: ErrorStepContainerProps) { props.onClose()}> - props.onDelete()}> + props.onDelete()}> diff --git a/server/continuedev/core/main.py b/server/continuedev/core/main.py index 97c60a04b..93ae07b7e 100644 --- a/server/continuedev/core/main.py +++ b/server/continuedev/core/main.py @@ -102,7 +102,7 @@ def step_to_fn_call_arguments(step: "Step") -> str: class HistoryNode(ContinueBaseModel): """A point in history, a list of which make up History""" - step: "Step" + step: Any observation: Union[Observation, None] depth: int deleted: bool = False diff --git a/server/continuedev/libs/chroma/query.py b/server/continuedev/libs/chroma/query.py deleted file mode 100644 index 2da58672d..000000000 --- a/server/continuedev/libs/chroma/query.py +++ /dev/null @@ -1,344 +0,0 @@ -import asyncio -import json -import os -import subprocess -from functools import cached_property -from typing import List, Tuple - -import chromadb -from chromadb.config import Settings -from chromadb.utils import embedding_functions -from dotenv import load_dotenv -from openai.error import RateLimitError - -from ...core.sdk import ContinueSDK -from ..util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path -from ..util.logging import logger -from ..util.paths import getEmbeddingsPathForBranch -from .update import filter_ignored_files - -load_dotenv() - -IGNORE_PATTERNS_FOR_CHROMA = [ - # 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", -] - - -def chunk_document(document: Optional[str], max_length: int = 1000) -> List[str]: - """Chunk a document into smaller pieces.""" - if document is None: - return [] - - chunks = [] - chunk = "" - for line in document.split("\n"): - if len(chunk) + len(line) > max_length: - chunks.append(chunk) - chunk = "" - chunk += line + "\n" - chunks.append(chunk) - return chunks - - -# Mapping of workspace_dir to chromadb collection -collections = {} - - -class ChromaIndexManager: - workspace_dir: str - client: chromadb.Client - openai_api_key: str = None - - def __init__( - self, - workspace_dir: str, - openai_api_key: str = None, - ): - self.workspace_dir = workspace_dir - self.client = chromadb.PersistentClient( - path=os.path.join( - getEmbeddingsPathForBranch(self.workspace_dir, self.current_branch), - "chroma", - ), - settings=Settings(anonymized_telemetry=False), - ) - self.openai_api_key = openai_api_key - os.environ.setdefault("TOKENIZERS_PARALLELISM", "true") - - @cached_property - def current_commit(self) -> str: - """Get the current commit.""" - try: - return ( - subprocess.check_output( - ["git", "rev-parse", "HEAD"], cwd=self.workspace_dir - ) - .decode("utf-8") - .strip() - ) - except subprocess.CalledProcessError: - 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.workspace_dir - ) - .decode("utf-8") - .strip() - ) - except subprocess.CalledProcessError: - return "NONE" - - @cached_property - def index_dir(self) -> str: - return getEmbeddingsPathForBranch(self.workspace_dir, self.current_branch) - - @property - def index_name(self) -> str: - return f"{self.workspace_dir}/{self.current_branch}" - - @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.workspace_dir - ) - .strip() - .decode() - ) - except subprocess.CalledProcessError: - return None - - def check_index_exists(self): - return os.path.exists(os.path.join(self.index_dir, "metadata.json")) - - @property - def collection(self): - if self.workspace_dir in collections: - return collections[self.workspace_dir] - - kwargs = { - "name": self.current_branch, - } - 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", - ) - - return self.client.get_or_create_collection(**kwargs) - - async def create_codebase_index( - self, sdk: ContinueSDK, ignore_files: List[str] = [] - ): - """Create a new index for the current branch.""" - collections[self.workspace_dir] = self.collection - - if self.check_index_exists(): - return - - files = await sdk.ide.listDirectoryContents(sdk.ide.workspace_directory, True) - - # Filter from ignore_directories - files = list( - filter( - lambda file: not should_filter_path( - file, - ignore_files + DEFAULT_IGNORE_PATTERNS + IGNORE_PATTERNS_FOR_CHROMA, - ), - files, - ) - ) - - tasks = [] - - async def readFile(filepath: str) -> Optional[str]: - to = 0.1 - while True: - try: - return await sdk.ide.readFile(filepath) - except Exception as e: - if to > 4: - return None - await asyncio.sleep(to) - to *= 2 - - for file in files: - tasks.append(readFile(file)) - - documents = await asyncio.gather(*tasks) - - chunks = [chunk_document(document) for document in documents] - - flattened_chunks = [] - flattened_metadata = [] - flattened_ids = [] - for i in range(len(chunks)): - for j in range(len(chunks[i])): - flattened_chunks.append(chunks[i][j]) - flattened_metadata.append({"filepath": files[i]}) - flattened_ids.append(f"{files[i]}::{j}") - - for i in range(len(flattened_chunks)): - if len(flattened_chunks[i]) == 0: - flattened_chunks[i] = "EMPTY" - elif len(flattened_chunks[i]) > 6000: - flattened_chunks[i] = flattened_chunks[i][:6000] - - # Attempt to avoid rate-limiting - i = 0 - wait_time = 4.0 - while i < len(flattened_chunks): - try: - self.collection.add( - documents=flattened_chunks[i : i + 100], - metadatas=flattened_metadata[i : i + 100], - ids=flattened_ids[i : i + 100], - ) - i += 100 - await asyncio.sleep(0.5) - 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 - - with open(f"{self.index_dir}/metadata.json", "w") as f: - json.dump( - { - "commit": self.current_commit, - "chunks": {files[i]: len(chunks[i]) for i in range(len(files))}, - }, - f, - indent=4, - ) - - logger.debug("Codebase index created") - - def get_modified_deleted_files(self) -> Tuple[List[str], List[str]]: - """Get a list of all files that have been modified since the last commit.""" - metadata = f"{self.index_dir}/metadata.json" - with open(metadata, "r") as f: - previous_commit = json.load(f)["commit"] - - try: - modified_deleted_files = ( - subprocess.check_output( - ["git", "diff", "--name-only", previous_commit, self.current_commit] - ) - .decode("utf-8") - .strip() - ) - except subprocess.CalledProcessError: - 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.workspace_dir, f)) - ] - modified_files = [ - f - for f in modified_deleted_files - if os.path.exists(os.path.join(self.workspace_dir, f)) - ] - - return filter_ignored_files( - modified_files, self.index_dir - ), filter_ignored_files(deleted_files, self.index_dir) - - def update_codebase_index(self): - """Update the index with a list of files.""" - - if not self.check_index_exists(): - self.create_codebase_index() - else: - modified_files, deleted_files = self.get_modified_deleted_files() - - with open(f"{self.index_dir}/metadata.json", "r") as f: - metadata = json.load(f) - - for file in deleted_files: - num_chunks = metadata["chunks"][file] - for i in range(num_chunks): - self.collection.delete(file) - - del metadata["chunks"][file] - - logger.debug(f"Deleted {file}") - - for file in modified_files: - if file in metadata["chunks"]: - num_chunks = metadata["chunks"][file] - - for i in range(num_chunks): - self.collection.delete(file) - - logger.debug(f"Deleted old version of {file}") - - with open(file, "r") as f: - f.read() - - # for i, text in enumerate(text_chunks): - # index.insert(Document(text=text, doc_id=f"{file}::{i}")) - - # metadata["chunks"][file] = len(text_chunks) - - logger.debug(f"Inserted new version of {file}") - - metadata["commit"] = self.current_commit - - with open(f"{self.index_dir}/metadata.json", "w") as f: - json.dump(metadata, f, indent=4) - - logger.debug("Codebase index updated") - - def query_codebase_index(self, query: str, n: int = 4) -> str: - """Query the codebase index.""" - if not self.check_index_exists(): - logger.debug(f"No index found for the codebase at {self.index_dir}") - return [] - - results = self.collection.query(query_texts=[query], n_results=n) - - return results diff --git a/server/continuedev/libs/chroma/.gitignore b/server/continuedev/libs/index/.gitignore similarity index 100% rename from server/continuedev/libs/chroma/.gitignore rename to server/continuedev/libs/index/.gitignore diff --git a/server/continuedev/libs/index/chunk_metadata.py b/server/continuedev/libs/index/chunk_metadata.py new file mode 100644 index 000000000..461214500 --- /dev/null +++ b/server/continuedev/libs/index/chunk_metadata.py @@ -0,0 +1,11 @@ +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}```" diff --git a/server/continuedev/libs/index/chunkers/__init__.py b/server/continuedev/libs/index/chunkers/__init__.py new file mode 100644 index 000000000..410934abf --- /dev/null +++ b/server/continuedev/libs/index/chunkers/__init__.py @@ -0,0 +1,25 @@ +from typing import List, Optional +from .basic import basic_chunker +from .code import code_chunker, file_extension_to_language +from .chunk import Chunk, ChunkWithoutID + + +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 +) -> List[Chunk]: + chunks = _chunk_document_without_id(filepath, contents, max_chunk_size) + return [chunk.with_id(filepath, i) for i, chunk in enumerate(chunks)] diff --git a/server/continuedev/libs/index/chunkers/basic.py b/server/continuedev/libs/index/chunkers/basic.py new file mode 100644 index 000000000..342a3e1ed --- /dev/null +++ b/server/continuedev/libs/index/chunkers/basic.py @@ -0,0 +1,42 @@ +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 diff --git a/server/continuedev/libs/index/chunkers/chunk.py b/server/continuedev/libs/index/chunkers/chunk.py new file mode 100644 index 000000000..8e56d0e07 --- /dev/null +++ b/server/continuedev/libs/index/chunkers/chunk.py @@ -0,0 +1,41 @@ +from typing import Any, Dict +from ....models.main import ContinueBaseModel +from chromadb.types import Metadata + + +class ChunkWithoutID(ContinueBaseModel): + content: str + start_line: int + end_line: int + other_metadata: Metadata = {} + + def with_id(self, document_id: str, index: int): + return Chunk( + content=self.content, + start_line=self.start_line, + end_line=self.end_line, + other_metadata=self.other_metadata, + document_id=document_id, + index=index, + ) + + +class Chunk(ChunkWithoutID): + document_id: str + index: int # The index of the chunk in the document + + @property + def id(self): + return f"{self.document_id}::{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, + } diff --git a/server/continuedev/libs/index/chunkers/code.py b/server/continuedev/libs/index/chunkers/code.py new file mode 100644 index 000000000..5a249d539 --- /dev/null +++ b/server/continuedev/libs/index/chunkers/code.py @@ -0,0 +1,163 @@ +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": "csharp", + "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]: + parser = get_parser_for_file(filepath) + code = contents or open(filepath).read() + tree = parser.parse(bytes(code, "utf8")) + + return list(get_smart_collapsed_chunks(tree.root_node, code, max_chunk_size)) diff --git a/server/continuedev/libs/index/codebase_index.py b/server/continuedev/libs/index/codebase_index.py new file mode 100644 index 000000000..9320ddbf7 --- /dev/null +++ b/server/continuedev/libs/index/codebase_index.py @@ -0,0 +1,366 @@ +import asyncio + +import json +import os +import re +from functools import cached_property +from typing import AsyncGenerator, Dict, List, Literal, Optional +import chromadb +from chromadb.config import Settings +from chromadb.utils import embedding_functions +from dotenv import load_dotenv +from openai.error import RateLimitError +from pydantic import BaseModel + +from .chunkers.chunk import Chunk +from ...libs.index.git import GitProject +from ...core.sdk import ContinueSDK +from ..util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path +from ..util.logging import logger +from ..util.paths import getEmbeddingsPathForBranch +from .chunkers import chunk_document + +load_dotenv() + +IGNORE_PATTERNS_FOR_CHROMA = [ + # 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", +] + + +# Mapping of workspace_dir to chromadb collection +collections = {} + +EmbeddingsType = Literal["default", "openai"] + +MAX_CHUNK_SIZE = 512 + + +class CodebaseIndexMetadata(BaseModel): + commit: str + chunks: Dict[str, int] + + +class ChromaCodebaseIndex: + directory: str + client: chromadb.Client + openai_api_key: str = None + api_base: str = None + api_version: str = None + api_type: str = None + organization_id: str = None + git_project: GitProject + + def __init__( + self, + directory: str, + openai_api_key: str = None, + api_base: str = None, + api_version: str = None, + api_type: str = None, + organization_id: str = None, + ): + self.directory = directory + self.git_project = GitProject(directory) + 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( + getEmbeddingsPathForBranch(self.directory, self.git_project.current_branch), + self.embeddings_type, + ) + os.makedirs(directory, exist_ok=True) + return directory + + @property + def index_name(self) -> str: + return ( + f"{self.directory}/{self.git_project.current_branch}/{self.embeddings_type}" + ) + + @cached_property + def metadata_path(self) -> str: + return os.path.join(self.index_dir, "metadata.json") + + def exists(self): + """Check whether the codebase index has already been built and saved on disk""" + return os.path.exists(self.metadata_path) + + def get_metadata(self) -> CodebaseIndexMetadata: + return CodebaseIndexMetadata.parse_file(self.metadata_path) + + 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): + if self.directory in collections and os.path.exists(self.chroma_dir): + return collections[self.directory] + + kwargs = { + "name": self.convert_to_valid_chroma_collection( + self.git_project.current_branch + ), + } + 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) + collections[self.directory] = collection + return collection + + async def build( + self, sdk: ContinueSDK, ignore_files: List[str] = [] + ) -> AsyncGenerator[float, None]: + """Create a new index for the current branch.""" + + if self.exists(): + return + + # Get list of filenames to index + files = await sdk.ide.listDirectoryContents(sdk.ide.workspace_directory, True) + + # Filter from ignore_directories + files = list( + filter( + lambda file: not should_filter_path( + file, + ignore_files + DEFAULT_IGNORE_PATTERNS + IGNORE_PATTERNS_FOR_CHROMA, + ), + files, + ) + ) + + # Get file contents for all at once + tasks = [] + + async def readFile(filepath: str) -> Optional[str]: + to = 0.1 + while True: + try: + return await sdk.ide.readFile(filepath) + except Exception as e: + if to > 4: + return None + await asyncio.sleep(to) + to *= 2 + + for file in files: + tasks.append(readFile(file)) + + file_contents = await asyncio.gather(*tasks) + + # Construct list of chunks for each file + chunks: List[Chunk] = [] + num_chunks_per_file = {} + for i in range(len(files)): + document_chunks = [ + c + for c in chunk_document(files[i], file_contents[i], MAX_CHUNK_SIZE) + if len(c.content.strip()) > 0 + ] + num_chunks_per_file[files[i]] = len(document_chunks) + chunks.extend(document_chunks) + + # Flatten chunks, metadata, and ids for insertion to Chroma + documents = [] + metadatas = [] + ids = [] + + for chunk in chunks: + documents.append(chunk.content) + metadatas.append(chunk.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: + self.collection.add( + documents=documents[i : i + 100], + metadatas=metadatas[i : i + 100], + ids=ids[i : i + 100], + ) + i += 100 + + # Give a progress update (1.0 is completed) + yield min(1.0, i / len(ids)) + await asyncio.sleep(0.05) + 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}") + # os.chmod(self.chroma_dir, 0o777) + # os.chmod(os.path.join(self.chroma_dir, "chroma.sqlite3"), 0o777) + + # Metadata keeps track of number of chunks per file, used in update() + with open(f"{self.index_dir}/metadata.json", "w") as f: + json.dump( + { + "commit": self.git_project.current_commit, + "chunks": num_chunks_per_file, + }, + f, + indent=4, + ) + + logger.debug("Codebase index created") + + async def update(self): + """Update the index with a list of files.""" + + if not self.exists(): + self.build() + else: + metadata = self.get_metadata() + ( + modified_files, + deleted_files, + ) = self.git_project.get_modified_deleted_files(metadata.commit) + + for file in deleted_files: + num_chunks = metadata.chunks[file] + for i in range(num_chunks): + self.collection.delete(file) + + del metadata.chunks[file] + + logger.debug(f"Deleted {file}") + + for file in modified_files: + if file in metadata.chunks: + num_chunks = metadata.chunks[file] + + for i in range(num_chunks): + self.collection.delete(file) + + logger.debug(f"Deleted old version of {file}") + + with open(file, "r") as f: + f.read() + + # for i, text in enumerate(text_chunks): + # index.insert(Document(text=text, doc_id=f"{file}::{i}")) + + # metadata.chunks[file] = len(text_chunks) + + logger.debug(f"Inserted new version of {file}") + + metadata.commit = self.git_project.current_commit + + with open(self.metadata_path, "w") as f: + f.write(metadata.json()) + + logger.debug("Codebase index updated") + + 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) + + 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") + chunks.append( + Chunk( + content=documents[i], + start_line=start_line, + end_line=end_line, + other_metadata=other_metadata, + document_id=document_id, + index=index, + ) + ) + return chunks diff --git a/server/continuedev/libs/index/git.py b/server/continuedev/libs/index/git.py new file mode 100644 index 000000000..eb7ff169e --- /dev/null +++ b/server/continuedev/libs/index/git.py @@ -0,0 +1,89 @@ +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) diff --git a/server/continuedev/libs/index/rerankers/default.py b/server/continuedev/libs/index/rerankers/default.py new file mode 100644 index 000000000..bf093ebe5 --- /dev/null +++ b/server/continuedev/libs/index/rerankers/default.py @@ -0,0 +1,168 @@ +import asyncio +import os +from typing import Dict, List + +from ..chunkers.chunk import Chunk + +from continuedev.core.sdk import ContinueSDK + + +async def decide_include_remove( + chunks: List[Chunk], user_input: str, n: int, sdk: ContinueSDK +) -> 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 = sdk.models.summarize.complete(include_prompt, log=False) + remove = sdk.models.summarize.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, sdk: ContinueSDK +) -> 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) == 10: + 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, sdk)) + + 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.document_id not in counts_per_document: + counts_per_document[chunk.document_id] = 0 + counts_per_document[chunk.document_id] += 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.document_id 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] diff --git a/server/continuedev/libs/chroma/update.py b/server/continuedev/libs/index/update.py similarity index 100% rename from server/continuedev/libs/chroma/update.py rename to server/continuedev/libs/index/update.py diff --git a/server/continuedev/libs/index/vectordb.py b/server/continuedev/libs/index/vectordb.py new file mode 100644 index 000000000..e141eae45 --- /dev/null +++ b/server/continuedev/libs/index/vectordb.py @@ -0,0 +1,21 @@ +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 diff --git a/server/continuedev/libs/llm/base.py b/server/continuedev/libs/llm/base.py index f95cb38e1..81a16653d 100644 --- a/server/continuedev/libs/llm/base.py +++ b/server/continuedev/libs/llm/base.py @@ -13,6 +13,7 @@ from ...models.main import ContinueBaseModel from ..util.count_tokens import ( DEFAULT_ARGS, DEFAULT_MAX_TOKENS, + MAX_TOKENS_FOR_MODEL, compile_chat_messages, count_tokens, format_chat_messages, @@ -280,10 +281,15 @@ Settings: msgs: List[ChatMessage], functions: Optional[List[Any]] = None, ) -> List[Dict]: + # 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 MAX_TOKENS_FOR_MODEL: + context_length = MAX_TOKENS_FOR_MODEL[options.model] + return compile_chat_messages( model_name=options.model, msgs=msgs, - context_length=self.context_length, + context_length=context_length, max_tokens=options.max_tokens, functions=functions, system_message=self.get_system_message(), @@ -532,4 +538,4 @@ Settings: def count_tokens(self, text: str): """Return the number of tokens in the given text.""" - return count_tokens(self.model, text) + return count_tokens(text, self.model) diff --git a/server/continuedev/libs/llm/openai.py b/server/continuedev/libs/llm/openai.py index f3d3d75fb..d3407fc57 100644 --- a/server/continuedev/libs/llm/openai.py +++ b/server/continuedev/libs/llm/openai.py @@ -1,6 +1,7 @@ from typing import Callable, List, Literal, Optional import certifi +from ..util.count_tokens import MAX_TOKENS_FOR_MODEL from .prompts.chat import template_alpaca_messages import openai from pydantic import Field @@ -30,16 +31,6 @@ NON_CHAT_MODELS = { "babbage", "ada", } -MAX_TOKENS_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, -} class OpenAI(LLM): diff --git a/server/continuedev/libs/llm/proxy_server.py b/server/continuedev/libs/llm/proxy_server.py index 7c3462ebd..19a5da5c2 100644 --- a/server/continuedev/libs/llm/proxy_server.py +++ b/server/continuedev/libs/llm/proxy_server.py @@ -3,6 +3,7 @@ import traceback from typing import List import aiohttp +from ..util.count_tokens import MAX_TOKENS_FOR_MODEL from ...core.main import ChatMessage from ..util.telemetry import posthog_logger @@ -11,13 +12,6 @@ from .base import LLM # SERVER_URL = "http://127.0.0.1:8080" SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app" -MAX_TOKENS_FOR_MODEL = { - "gpt-3.5-turbo": 4096, - "gpt-3.5-turbo-0613": 4096, - "gpt-3.5-turbo-16k": 16384, - "gpt-4": 8192, -} - class ProxyServer(LLM): _client_session: aiohttp.ClientSession diff --git a/server/continuedev/libs/util/count_tokens.py b/server/continuedev/libs/util/count_tokens.py index 9066d0e30..59751a1ce 100644 --- a/server/continuedev/libs/util/count_tokens.py +++ b/server/continuedev/libs/util/count_tokens.py @@ -1,7 +1,7 @@ import json import os import sys -from typing import Dict, List, Union +from typing import Dict, List, Optional, Union from ...core.main import ChatMessage from .templating import render_templated_string @@ -20,6 +20,17 @@ DEFAULT_ARGS = { "temperature": 0.5, } +MAX_TOKENS_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, +} + already_saw_import_err = False @@ -50,10 +61,10 @@ def encoding_for_model(model_name: str): return None -def count_tokens(model_name: str, text: Union[str, 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) + 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 @@ -65,7 +76,7 @@ def count_chat_message_tokens(model_name: str, chat_message: ChatMessage) -> int # 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(model_name, chat_message.content) + TOKENS_PER_MESSAGE + return count_tokens(chat_message.content, model_name) + TOKENS_PER_MESSAGE def prune_raw_prompt_from_top( @@ -102,10 +113,10 @@ def prune_chat_history( longer_than_one_third = [ message for message in longest_messages - if count_tokens(model_name, message.content) > context_length / 3 + if count_tokens(message.content, model_name) > context_length / 3 ] distance_from_third = [ - count_tokens(model_name, message.content) - context_length / 3 + count_tokens(message.content, model_name) - context_length / 3 for message in longer_than_one_third ] total_tokens_removed = 0 @@ -118,7 +129,7 @@ def prune_chat_history( tokens_removed < distance_from_third[i] and total_tokens - total_tokens_removed > context_length ): - delta = count_tokens(model_name, lines.pop(-1)) + delta = count_tokens(lines.pop(-1), model_name) tokens_removed += delta total_tokens_removed += delta @@ -128,8 +139,8 @@ def prune_chat_history( i = 0 while total_tokens > context_length and i < len(chat_history) - 5: message = chat_history[0] - total_tokens -= count_tokens(model_name, message.content) - total_tokens += count_tokens(model_name, message.summary) + total_tokens -= count_tokens(message.content, model_name) + total_tokens += count_tokens(message.summary, model_name) message.content = message.summary i += 1 @@ -140,7 +151,7 @@ def prune_chat_history( and len(chat_history) > 0 ): message = chat_history.pop(0) - total_tokens -= count_tokens(model_name, message.content) + total_tokens -= count_tokens(message.content, model_name) # 3. Truncate message in the last 5, except last 1 i = 0 @@ -150,15 +161,15 @@ def prune_chat_history( and i < len(chat_history) - 1 ): message = chat_history[i] - total_tokens -= count_tokens(model_name, message.content) - total_tokens += count_tokens(model_name, message.summary) + 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(model_name, message.content) + total_tokens -= count_tokens(message.content, model_name) # 5. Truncate last message if total_tokens > context_length and len(chat_history) > 0: @@ -222,7 +233,7 @@ def compile_chat_messages( function_tokens = 0 if functions is not None: for function in functions: - function_tokens += count_tokens(model_name, json.dumps(function)) + function_tokens += count_tokens(json.dumps(function), model_name) if max_tokens + function_tokens + TOKEN_BUFFER_FOR_SAFETY >= context_length: raise ValueError( diff --git a/server/continuedev/libs/util/strings.py b/server/continuedev/libs/util/strings.py index f2b6035fa..d99a04140 100644 --- a/server/continuedev/libs/util/strings.py +++ b/server/continuedev/libs/util/strings.py @@ -1,4 +1,5 @@ -from typing import Tuple +import os +from typing import List, Tuple def dedent_and_get_common_whitespace(s: str) -> Tuple[str, str]: @@ -62,3 +63,31 @@ def remove_quotes_and_escapes(output: str) -> str: 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 diff --git a/server/continuedev/plugins/context_providers/embeddings.py b/server/continuedev/plugins/context_providers/embeddings.py index 86cba3112..32eaaaf34 100644 --- a/server/continuedev/plugins/context_providers/embeddings.py +++ b/server/continuedev/plugins/context_providers/embeddings.py @@ -6,7 +6,7 @@ from pydantic import BaseModel from ...core.context import ContextProvider from ...core.main import ContextItem, ContextItemDescription, ContextItemId -from ...libs.chroma.query import ChromaIndexManager +from ...libs.index.codebase_index import ChromaIndexManager class EmbeddingResult(BaseModel): diff --git a/server/continuedev/plugins/steps/chat.py b/server/continuedev/plugins/steps/chat.py index a58e14f57..25a14e4aa 100644 --- a/server/continuedev/plugins/steps/chat.py +++ b/server/continuedev/plugins/steps/chat.py @@ -2,7 +2,8 @@ import html import json import os from textwrap import dedent -from typing import Any, Coroutine, List +from typing import Any, Coroutine, List, Optional +from ...libs.llm.base import CompletionOptions import openai from directory_tree import display_tree @@ -38,11 +39,13 @@ class SimpleChatStep(Step): description: str = "" messages: List[ChatMessage] = None + completion_options: Optional[CompletionOptions] = None + async def run(self, sdk: ContinueSDK): # Check if proxy server API key if ( - False and - isinstance(sdk.models.default, OpenAIFreeTrial) + False + and isinstance(sdk.models.default, OpenAIFreeTrial) and ( sdk.models.default.api_key is None or sdk.models.default.api_key.strip() == "" @@ -85,7 +88,8 @@ class SimpleChatStep(Step): messages = self.messages or await sdk.get_chat_context() - generator = sdk.models.chat.stream_chat(messages) + kwargs = self.completion_options.dict() if self.completion_options else {} + generator = sdk.models.chat.stream_chat(messages, **kwargs) posthog_logger.capture_event( "model_use", diff --git a/server/continuedev/plugins/steps/chroma.py b/server/continuedev/plugins/steps/chroma.py index 3becc16b9..08614a8ee 100644 --- a/server/continuedev/plugins/steps/chroma.py +++ b/server/continuedev/plugins/steps/chroma.py @@ -1,14 +1,17 @@ -import asyncio import os from typing import Coroutine, Dict, List, Optional, Union +from ...libs.llm.base import CompletionOptions +from ...libs.index.rerankers.default import default_reranker_parallel +from ...libs.util.strings import shorten_filepaths + from pydantic import Field from ...core.main import ContextItem, ContextItemDescription, ContextItemId, Step from ...core.observation import Observation from ...core.sdk import ContinueSDK -from ...core.steps import EditFileStep, UserInputStep -from ...libs.chroma.query import ChromaIndexManager +from ...core.steps import EditFileStep +from ...libs.index.codebase_index import ChromaCodebaseIndex from ..context_providers.util import remove_meilisearch_disallowed_chars from .chat import SimpleChatStep from ...core.steps import EditFileStep @@ -17,8 +20,12 @@ from ...core.steps import EditFileStep class CreateCodebaseIndexChroma(Step): name: str = "Create Codebase Index" hide: bool = True - description: str = "Generating codebase embeddings..." - openai_api_key: Optional[str] = None + description: str = "Generating codebase embeddings... 1%" + openai_api_key: Optional[str] = Field(None, description="OpenAI API key") + api_base: Optional[str] = Field(None, description="OpenAI API base URL") + api_type: Optional[str] = Field(None, description="OpenAI API type") + api_version: Optional[str] = Field(None, description="OpenAI API version") + organization_id: Optional[str] = Field(None, description="OpenAI organization ID") ignore_files: List[str] = Field( [], @@ -29,203 +36,21 @@ class CreateCodebaseIndexChroma(Step): return "Generated codebase embeddings." async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]: - index = ChromaIndexManager( + index = ChromaCodebaseIndex( sdk.ide.workspace_directory, openai_api_key=self.openai_api_key, + api_base=self.api_base, + api_type=self.api_type, + api_version=self.api_version, + organization_id=self.organization_id, ) - if not index.check_index_exists(): - self.hide = False + if index.exists(): + return - await index.create_codebase_index(sdk, ignore_files=self.ignore_files) - - -async def rerank_chroma_results_group( - results: Dict[str, str], user_input: str, n: int, sdk: ContinueSDK -): - """ - Reranks the results from the codebase index based on the user input - """ - results_prompt = "\n\n".join( - map( - lambda kv: f"{kv[0]}\n```\n{kv[1][:500]}\n```", - results.items(), - ) - ) - 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(results)} 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(results)} 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 = sdk.models.summarize.complete(include_prompt, log=False) - remove = sdk.models.summarize.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 rerank_chroma_results( - results: Dict[str, str], user_input: str, n: int, sdk: ContinueSDK -): - """ - Reranks the results from the codebase index based on the user input - """ - # Split the results into groups - groups = [] - group = {} - keys = list(results.keys()) - for i in range(len(keys)): - if len(group) == 10: - groups.append(group) - group = {} - group[keys[i]] = results[keys[i]] - - if len(group) > 0: - groups.append(group) - - # Gather the include/remove results from each group - include = set([]) - remove = set([]) - - tasks = [] - for group in groups: - tasks.append(rerank_chroma_results_group(group, user_input, n, sdk)) - - reranking_results = await asyncio.gather(*tasks) - for rr in reranking_results: - include.update(rr[0]) - remove.update(rr[1]) - - # Use these results to whittle down the results - counts_per_files = {} - for id in results: - filename = id.split("::")[0] - if filename not in counts_per_files: - counts_per_files[filename] = 0 - counts_per_files[filename] += 1 - - repeated_files = set(filter(lambda x: counts_per_files[x] > 1, counts_per_files)) - - selected = { - key: value - for key, value in results.items() - if key not in remove or key.split("::")[0] in repeated_files - } - selected = {key: value for key, value in selected.items() if key in include} - - for key in selected: - del results[key] - - additional = n - len(selected) - for i in range(additional): - if len(results) == 0: - break - - # Get an item from the results - key = list(results.keys())[0] - selected[key] = results[key] - del results[key] - - if additional < 0: - # We need to remove some items - additional = -additional - for i in range(additional): - if len(selected) == 0: - break - - # Get an item from the results - key = list(selected.keys())[0] - del selected[key] - - return selected - - -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 + self.hide = False + async for progress in index.build(sdk, ignore_files=self.ignore_files): + self.description = f"Generating codebase embeddings... {int(progress*100)}%" + await sdk.update_ui() class AnswerQuestionChroma(Step): @@ -254,53 +79,58 @@ class AnswerQuestionChroma(Step): return self._answer async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]: - index = ChromaIndexManager(sdk.ide.workspace_directory) - self.description = f"Reading from {self.n_retrieve} files..." + index = ChromaCodebaseIndex(sdk.ide.workspace_directory) + self.hide = False + self.description = f"Scanning {self.n_retrieve} files..." await sdk.update_ui() - results = index.query_codebase_index( + + # Get top chunks from index + chunks = index.query( self.user_input, n=self.n_retrieve if self.use_reranking else self.n_final ) - shortened_filepaths = shorten_filepaths(results["ids"][0]) - results_dict = { - filename: document - for filename, document in zip(shortened_filepaths, results["documents"][0]) - if document.strip() != "" - } + # Rerank to select top results + self.description = f"Selecting most important files..." + await sdk.update_ui() if self.use_reranking: - results_dict = await rerank_chroma_results( - results_dict, self.user_input, self.n_final, sdk + chunks = await default_reranker_parallel( + chunks, self.user_input, self.n_final, sdk ) - filepaths = set([]) + # Add context items context_items: List[ContextItem] = [] - for id, document in results_dict.items(): - filename = id.split("::")[0] - filepath = results["ids"][0][shortened_filepaths.index(id)].split("::")[0] - if filepath in filepaths: - continue - + for chunk in chunks: + # Can we select the context item through the normal means so that the name is disambiguated? + # Also so you don't have to understand the internals of the context provider + # OR have a chunk context provider??? Nice short-term, but I don't like it for long-term ctx_item = ContextItem( - content=document, + content=chunk.content, description=ContextItemDescription( - name=filename, - description=filepath, + name=f"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})", + description=chunk.document_id, id=ContextItemId( provider_title="file", - item_id=remove_meilisearch_disallowed_chars(filepath), + item_id=remove_meilisearch_disallowed_chars(chunk.document_id), ), ), - ) + ) # Should be 'code' not file! And eventually should be able to embed all context providers automatically! + context_items.append(ctx_item) await sdk.add_context_item(ctx_item) - filepaths.add(filepath) - await sdk.update_ui() + self.hide = True + model = sdk.models.chat.model + # if model == "gpt-4": + # model = "gpt-4-32k" # Not publicly available yet? + if model == "gpt-3.5-turbo": + model = "gpt-3.5-turbo-16k" + await sdk.run_step( SimpleChatStep( name="Answer Question", - description=f"Reading from {self.n_final} files...", + description=f"Reading from {len(context_items)} files...", + completion_options=CompletionOptions(model=model), ) ) @@ -313,7 +143,7 @@ class EditFileChroma(Step): hide: bool = True async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]: - index = ChromaIndexManager(sdk.ide.workspace_directory) + index = ChromaCodebaseIndex(sdk.ide.workspace_directory) results = index.query_codebase_index(self.user_input) resource_name = list(results.source_nodes[0].node.relationships.values())[0] diff --git a/server/continuedev/server/gui.py b/server/continuedev/server/gui.py index 20cdfeb6c..c6c2f9879 100644 --- a/server/continuedev/server/gui.py +++ b/server/continuedev/server/gui.py @@ -195,12 +195,23 @@ class GUIProtocolServer: def on_show_logs_at_index(self, index: int): name = "Continue Prompt" - logs = "\n\n############################################\n\n".join( + + logs = None + timeline = self.session.autopilot.continue_sdk.history.timeline + while logs is None and index < len(timeline): + if len(timeline[index].logs) > 0: + logs = timeline[index].logs + break + elif timeline[index].step.name == "User Input": + break + index += 1 + + content = "Logs not found" if logs is None else "\n\n############################################\n\n".join( ["This is the prompt that was sent to the LLM during this step"] - + self.session.autopilot.continue_sdk.history.timeline[index].logs + + logs ) create_async_task( - self.session.autopilot.ide.showVirtualFile(name, logs), self.on_error + self.session.autopilot.ide.showVirtualFile(name, content), self.on_error ) posthog_logger.capture_event("show_logs_at_index", {}) diff --git a/server/poetry.lock b/server/poetry.lock index 772d64f85..9811f2cb7 100644 --- a/server/poetry.lock +++ b/server/poetry.lock @@ -2290,6 +2290,20 @@ files = [ [package.dependencies] mpmath = ">=0.19" +[[package]] +name = "tenacity" +version = "8.2.3" +description = "Retry code until it succeeds" +optional = false +python-versions = ">=3.7" +files = [ + {file = "tenacity-8.2.3-py3-none-any.whl", hash = "sha256:ce510e327a630c9e1beaf17d42e6ffacc88185044ad85cf74c0a8887c6a0f88c"}, + {file = "tenacity-8.2.3.tar.gz", hash = "sha256:5398ef0d78e63f40007c1fb4c0bff96e1911394d2fa8d194f77619c05ff6cc8a"}, +] + +[package.extras] +doc = ["reno", "sphinx", "tornado (>=4.5)"] + [[package]] name = "tiktoken" version = "0.4.0" @@ -2420,6 +2434,132 @@ notebook = ["ipywidgets (>=6)"] slack = ["slack-sdk"] telegram = ["requests"] +[[package]] +name = "tree-sitter" +version = "0.20.2" +description = "Python bindings for the Tree-Sitter parsing library" +optional = false +python-versions = ">=3.3" +files = [ + {file = "tree_sitter-0.20.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1a151ccf9233b0b84850422654247f68a4d78f548425c76520402ea6fb6cdb24"}, + {file = "tree_sitter-0.20.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:52ca2738c3c4c660c83054ac3e44a49cbecb9f89dc26bb8e154d6ca288aa06b0"}, + {file = "tree_sitter-0.20.2-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a8d51478ea078da7cc6f626e9e36f131bbc5fac036cf38ea4b5b81632cbac37d"}, + {file = "tree_sitter-0.20.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d0b2b59e1633efbf19cd2ed1ceb8d51b2c44a278153b1113998c70bc1570b750"}, + {file = "tree_sitter-0.20.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:7f691c57d2a65d6e53e2f3574153c9cd0c157ff938b8d6f252edd5e619811403"}, + {file = "tree_sitter-0.20.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:ba72a363387eebaff9a0b788f864fe47da425136cbd4cac6cd125051f043c296"}, + {file = "tree_sitter-0.20.2-cp310-cp310-win32.whl", hash = "sha256:55e33eb206446d5046d3b5fe36ab300840f5a8a844246adb0ccc68c55c30b722"}, + {file = "tree_sitter-0.20.2-cp310-cp310-win_amd64.whl", hash = "sha256:24ce9d14daba0a71a778417d9d61dd4038ca96981ddec19e1e8990881469321c"}, + {file = "tree_sitter-0.20.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:942dbfb8bc380f09b0e323d3884de07d19022930516f33b7503a6eb5f6e18979"}, + {file = "tree_sitter-0.20.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ee5651c11924d426f8d6858a40fd5090ae31574f81ef180bef2055282f43bf62"}, + {file = "tree_sitter-0.20.2-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8fb6982b480031628dad7f229c4c8d90b17d4c281ba97848d3b100666d7fa45f"}, + {file = "tree_sitter-0.20.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:067609c6c7cb6e5a6c4be50076a380fe52b6e8f0641ee9d0da33b24a5b972e82"}, + {file = "tree_sitter-0.20.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:849d7e6b66fe7ded08a633943b30e0ed807eee76104288e6c6841433f4a9651b"}, + {file = "tree_sitter-0.20.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e85689573797e49f86e2d7cf48b9dd23bc044c477df074a78546e666d6990a29"}, + {file = "tree_sitter-0.20.2-cp311-cp311-win32.whl", hash = "sha256:098906148e44ea391a91b019d584dd8d0ea1437af62a9744e280e93163fd35ca"}, + {file = "tree_sitter-0.20.2-cp311-cp311-win_amd64.whl", hash = "sha256:2753a87094b72fe7f02276b3948155618f53aa14e1ca20588f0eeed510f68512"}, + {file = "tree_sitter-0.20.2-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:5de192cb9e7b1c882d45418decb7899f1547f7056df756bcae186bbf4966d96e"}, + {file = "tree_sitter-0.20.2-cp36-cp36m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f3a77e663293a73a97edbf2a2e05001de08933eb5d311a16bdc25b9b2fac54f3"}, + {file = "tree_sitter-0.20.2-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:415da4a70c56a003758537517fe9e60b8b0c5f70becde54cc8b8f3ba810adc70"}, + {file = "tree_sitter-0.20.2-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:707fb4d7a6123b8f9f2b005d61194077c3168c0372556e7418802280eddd4892"}, + {file = "tree_sitter-0.20.2-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:75fcbfb0a61ad64e7f787eb3f8fbf29b8e2b858dc011897ad039d838a06cee02"}, + {file = "tree_sitter-0.20.2-cp36-cp36m-win32.whl", hash = "sha256:622926530895d939fa6e1e2487e71a311c71d3b09f4c4f19301695ea866304a4"}, + {file = "tree_sitter-0.20.2-cp36-cp36m-win_amd64.whl", hash = "sha256:5c0712f031271d9bc462f1db7623d23703ed9fbcbaa6dc19ba535f58d6110774"}, + {file = "tree_sitter-0.20.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:2dfdf680ecf5619447243c4c20e4040a7b5e7afca4e1569f03c814e86bfda248"}, + {file = "tree_sitter-0.20.2-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:79650ee23a15559b69542c71ed9eb3297dce21932a7c5c148be384dd0f2cd49d"}, + {file = "tree_sitter-0.20.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d63059746b4b2f2f87dd19c208141c69452694aae32459b7a4ebca8539d13bf4"}, + {file = "tree_sitter-0.20.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:9398d1e214d4915032cf68a678de7eb803f64d25ef04724d70b88db7bb7746e9"}, + {file = "tree_sitter-0.20.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:b506fb2e2bd7a5a1603c644bbb90401fe488f86bbca39706addaa8d2bfc80815"}, + {file = "tree_sitter-0.20.2-cp37-cp37m-win32.whl", hash = "sha256:405e83804ba60ca1c3dbd258adbe0d7b0f1bdce948e5eec5587a2ebedcf930ba"}, + {file = "tree_sitter-0.20.2-cp37-cp37m-win_amd64.whl", hash = "sha256:a1e66d211c04144484e223922ac094a2367476e6f57000f986c5560dc5a83c6e"}, + {file = "tree_sitter-0.20.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:f8adc325c74c042204ed47d095e0ec86f83de3c7ec4979645f86b58514f60297"}, + {file = "tree_sitter-0.20.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:beb49c861e1d111e0df119ecbfaa409e6413b8d91e8f56bcdb15f07fbc35594e"}, + {file = "tree_sitter-0.20.2-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e17ee83409b01fdd09021997b0c747be2f773bb2bb140ba6fb48b7e12fdd039a"}, + {file = "tree_sitter-0.20.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:475ab841647a0d1bc1266c8978279f8e4f7b9520b9a7336d532e5dfc8910214d"}, + {file = "tree_sitter-0.20.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:222350189675d9814966a5c88c6c1378a2ee2f3041c439a6f1d1ff2006f403aa"}, + {file = "tree_sitter-0.20.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:31ea52f0deee70f2cb00aff01e40aae325a34ebe1661de274c9107322fb95f54"}, + {file = "tree_sitter-0.20.2-cp38-cp38-win32.whl", hash = "sha256:cceaf7287137cbca707006624a4a8d4b5ccbfec025793fde84d90524c2bb0946"}, + {file = "tree_sitter-0.20.2-cp38-cp38-win_amd64.whl", hash = "sha256:25b9669911f21ec2b3727bb2f4dfeff6ddb6f81898c3e968d378a660e0d7f90e"}, + {file = "tree_sitter-0.20.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ce30a17f46a6b39a04a599dea88c127a19e3e1f43a2ad0ced71b5c032d585077"}, + {file = "tree_sitter-0.20.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e9576e8b2e663639527e01ab251b87f0bd370bfdd40515588689ebc424aec786"}, + {file = "tree_sitter-0.20.2-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d03731a498f624ce3536c821ef23b03d1ad569b3845b326a5b7149ef189d732c"}, + {file = "tree_sitter-0.20.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ef0116ecb163573ebaa0fc04cc99c90bd94c0be5cc4d0a1ebeb102de9cc9a054"}, + {file = "tree_sitter-0.20.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:0943b00d3700f253c3ee6a53a71b9a6ca46defd9c0a33edb07a9388e70dc3a9e"}, + {file = "tree_sitter-0.20.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8cb566b6f0b5457148cb8310a1ca3d764edf28e47fcccfe0b167861ecaa50c12"}, + {file = "tree_sitter-0.20.2-cp39-cp39-win32.whl", hash = "sha256:4544204a24c2b4d25d1731b0df83f7c819ce87c4f2538a19724b8753815ef388"}, + {file = "tree_sitter-0.20.2-cp39-cp39-win_amd64.whl", hash = "sha256:9517b204e471d6aa59ee2232f6220f315ed5336079034d5c861a24660d6511d6"}, + {file = "tree_sitter-0.20.2-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:84343678f58cb354d22ed14b627056ffb33c540cf16c35a83db4eeee8827b935"}, + {file = "tree_sitter-0.20.2-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:611a80171d8fa6833dd0c8b022714d2ea789de15a955ec42ec4fd5fcc1032edb"}, + {file = "tree_sitter-0.20.2-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bacecfb61694c95ccee462742b3fcea50ba1baf115c42e60adf52b549ef642ce"}, + {file = "tree_sitter-0.20.2-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:f344ae94a268479456f19712736cc7398de5822dc74cca7d39538c28085721d0"}, + {file = "tree_sitter-0.20.2-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:221784d7f326fe81ce7174ac5972800f58b9a7c5c48a03719cad9830c22e5a76"}, + {file = "tree_sitter-0.20.2-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:64210ed8d2a1b7e2951f6576aa0cb7be31ad06d87da26c52961318fc54c7fe77"}, + {file = "tree_sitter-0.20.2-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2634ac73b39ceacfa431d6d95692eae7465977fa0b9e9f7ae6cb445991e829a5"}, + {file = "tree_sitter-0.20.2-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:71663a0e8230dae99d9c55e6895bd2c9e42534ec861b255775f704ae2db70c1d"}, + {file = "tree_sitter-0.20.2-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:32c3e0f30b45a58d36bf6a0ec982ca3eaa23c7f924628da499b7ad22a8abad71"}, + {file = "tree_sitter-0.20.2-pp39-pypy39_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9b02e4ab2158c25f6f520c93318d562da58fa4ba53e1dbd434be008f48104980"}, + {file = "tree_sitter-0.20.2-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:10e567eb6961a1e86aebbe26a9ca07d324f8529bca90937a924f8aa0ea4dc127"}, + {file = "tree_sitter-0.20.2-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:63f8e8e69f5f25c2b565449e1b8a2aa7b6338b4f37c8658c5fbdec04858c30be"}, + {file = "tree_sitter-0.20.2.tar.gz", hash = "sha256:0a6c06abaa55de174241a476b536173bba28241d2ea85d198d33aa8bf009f028"}, +] + +[[package]] +name = "tree-sitter-languages" +version = "1.7.0" +description = "Binary Python wheels for all tree sitter languages." +optional = false +python-versions = "*" +files = [ + {file = "tree_sitter_languages-1.7.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:fd8b856c224a74c395ed9495761c3ef8ba86014dbf6037d73634436ae683c808"}, + {file = "tree_sitter_languages-1.7.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:277d1bec6e101a26a4445cd7cb1eb8f8cf5a9bbad1ca80692bfae1af63568272"}, + {file = "tree_sitter_languages-1.7.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0473bd896799ccc87f428766813ddedd3506cad8430dbe863b663c81d7387680"}, + {file = "tree_sitter_languages-1.7.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cb6799419bc7e3029112f2a3f8b77b6c299f94f03bb70e5c31a437b3180486be"}, + {file = "tree_sitter_languages-1.7.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:e5b705c8ce6ef47fc461484878956ecd42a67cbeb0a17e323b86a4439a8fdc3d"}, + {file = "tree_sitter_languages-1.7.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:28a732be6fced2f70184c1b34f64961e3b6259fe6d5f7540c91028c2a43a7109"}, + {file = "tree_sitter_languages-1.7.0-cp310-cp310-win32.whl", hash = "sha256:f5cdb1ec88f0b8c617330c953555a20cc7e96ca6b1f5c68ab6db347e869cfeeb"}, + {file = "tree_sitter_languages-1.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:26cb344a75798fce1a73b690504d8e7789f6ba25a178efcd203444d7868caf38"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:433b56cb3dca02b30f21c596f431a2cff90905326be1f8913c3515acb984b21e"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:96686390e1a01af44aedef7b33d6be82de3cf674a98a5c7b417e540e6afa62cc"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:25a4b6d559fbd76c6ec1b73cf03d09f53aaa5a1b61078a3f518b162866d9d97e"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e504f199c7a4c8b1b1efb05a063450aa23234feea6fa6c06f4077f7248ea9c98"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:6b29856e9314b5f68f05dfa45e6674f47535229dda32294ba6d129077a97759c"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:786fdaf3d2120eef9384b0f22d7e2e42a561073ba753c7b438e90a1e7b351650"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-win32.whl", hash = "sha256:a55a7007056d0927b78481b437d79ea0487cc991c7f9c19d67adcceac3d47f53"}, + {file = "tree_sitter_languages-1.7.0-cp311-cp311-win_amd64.whl", hash = "sha256:4b01d3bdf7ce2aeee4d0df62071a0ca91e618a29845686a5bd714d93c5ef3b36"}, + {file = "tree_sitter_languages-1.7.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9b603f1ad01bfb9d178f965125e2528cb7da9666d180f4a9a1acfaedbf5862ea"}, + {file = "tree_sitter_languages-1.7.0-cp36-cp36m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:70610aa26dd985d2fb9eb07ea8eacc3ceb0cc9c2e91416f51305120cfd919e28"}, + {file = "tree_sitter_languages-1.7.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0444ebc8bdb7dc0d66a816050cfd52376c4e62a94a9c54fde90b29acf3e4bab1"}, + {file = "tree_sitter_languages-1.7.0-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:7eeb5a3307ff1c0994ffff5ea37ec656a716a728b8c9359374104da521a76ded"}, + {file = "tree_sitter_languages-1.7.0-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:6c319cef16f2df667f1c165fe4eee160f2b51a0c4b61db1e70de2ab86420ca9a"}, + {file = "tree_sitter_languages-1.7.0-cp36-cp36m-win32.whl", hash = "sha256:b216650126d95d494f927393903e836a7ef5f0c4db0834f3a0b576f97c13abaf"}, + {file = "tree_sitter_languages-1.7.0-cp36-cp36m-win_amd64.whl", hash = "sha256:f6c96e5785d164a205962a10256808b3d12dccee9827ec88a46899063a2a2d28"}, + {file = "tree_sitter_languages-1.7.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:adafeabbd8d47b80122fad18bb61c25ed3da04f5347b7d774b53826accb27b7a"}, + {file = "tree_sitter_languages-1.7.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:50e2bc5d2da770ecd5af94f9d716faa4764f890fd61bc0a488e9269653d9fb71"}, + {file = "tree_sitter_languages-1.7.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ac773097cff7de6cf265c5be9990b4c6690161452da1d9fc41021d4bf7e8c73a"}, + {file = "tree_sitter_languages-1.7.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:b233bfc48cf0f16436200afc7d7643cd87101c321de25b919b61f21f1693aa52"}, + {file = "tree_sitter_languages-1.7.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:eab3caedf50467045ed5cab776a57b494332616376d387c6600fd7ea4f5483cf"}, + {file = "tree_sitter_languages-1.7.0-cp37-cp37m-win32.whl", hash = "sha256:d533f743a22f5696494d3a5a60adb4cfbef63d58b8b5622993d93d6d0a602444"}, + {file = "tree_sitter_languages-1.7.0-cp37-cp37m-win_amd64.whl", hash = "sha256:aab96f64be30c9f73d6dc958ec22bb1a9fe70e90b2d2a3d233d537b347cea729"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1bf89d771621e28847036b377f865f947e555a6654356d21beab738bb2531a69"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:b2f171089ec3c4f1de275edc8f0722e1e3dc7a54e83107098315ea2f0952cfcd"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a091577d3a8454c40f813ee2834314c73cc504522f70f9e33d7c2268d33973f9"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8287efa87d080b340b583a6e81266cc3d8266deb61b8f3312649a9d1562e665a"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:9c5080c06a2df7a59c69d2422a6ae83a5e37e92d57c4bd5e572d0eb5226ab3b0"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:ca8f629cfb406a2f9b9f8a3a5c804d4d1ba4cdca41cccba63f51fc1bab13e5de"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-win32.whl", hash = "sha256:fd3561b37a99c9d501719819a8736529ae3a6d597128c15be432d1855f3cb0d9"}, + {file = "tree_sitter_languages-1.7.0-cp38-cp38-win_amd64.whl", hash = "sha256:377ad60f7a7bf27315676c4fa84cc766aa0019c1e556083763136ed951e934c0"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a1dc71b68e48f58cd5b6a9ab7a541714201815629a6554a969cfc579a6ee6e53"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:fb1521367b14c275bef70997ea90526e7049f840ba1bbd3ef56c72f5b15596e9"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f73651f7e78371dc3d455e8aba510cc6fb9e1ac1d648c3334157950781eb295"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:049b0dd63be721fe3f9642a2b5a044bea2852de2b35818467996242ae4b7f01f"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:c428a8e1f5ecc4eb5c79abff3eb2881123446cde16fd1d8866d527470a6fdd2f"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:40fb3fc11ff90caf65b4713feeb6c4852e5d2a04ef8ae6a2ac734a702a6a6c7e"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-win32.whl", hash = "sha256:f28e9904833b7a909f8227c4560401049bd3310cebe3e0a884d9461f783b9af2"}, + {file = "tree_sitter_languages-1.7.0-cp39-cp39-win_amd64.whl", hash = "sha256:ea47ee390ec2e1c9bf96d7b418775263766021a834910c9f2d578f95a3e27d0f"}, +] + +[package.dependencies] +tree-sitter = "*" + [[package]] name = "typer" version = "0.9.0" @@ -2909,4 +3049,4 @@ testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "p [metadata] lock-version = "2.0" python-versions = "^3.8.1" -content-hash = "52b918568321ba9bb5289ce45bd2be5f29ef4cc900bfcf3019b0b524d2d19404" +content-hash = "7a5cc2f989f9bb12ed7735355fbe27d1fc590edde5bb9727dfc6f9898b0d2254" diff --git a/server/pyproject.toml b/server/pyproject.toml index da76e9783..247c2369b 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "continuedev" -version = "0.1.60" +version = "0.1.61" description = "" authors = ["Nate Sesti "] readme = "README.md" @@ -35,6 +35,8 @@ huggingface-hub = "^0.16.4" typer = "^0.9.0" chromadb = "^0.4.12" fastapi = "0.95.2" +tree-sitter = "^0.20.2" +tree-sitter-languages = "^1.7.0" [tool.poetry.scripts] typegen = "continuedev.models.generate_json_schema:main" diff --git a/server/requirements.txt b/server/requirements.txt index 2b649d0b2..97ee881cc 100644 --- a/server/requirements.txt +++ b/server/requirements.txt @@ -25,4 +25,6 @@ bs4==0.0.1 redbaron==0.9.2 python-lsp-server[websockets]==1.8.0 huggingface-hub==0.16.4 -chromadb==0.4.12 \ No newline at end of file +chromadb==0.4.12 +tree-sitter==0.20.2 +tree-sitter-languages==1.7.0 \ No newline at end of file