⚡️ stream-based indexing

This commit is contained in:
Nate Sesti 2023-11-07 19:12:51 -08:00
parent 70671ee10e
commit 144ed2421e
5 changed files with 136 additions and 85 deletions

View file

@ -1,7 +1,10 @@
import asyncio
from typing import AsyncGenerator
from ...core.config import ContinueConfig
from ...server.protocols.ide_protocol import AbstractIdeProtocolServer
from ...libs.index.chunkers.chunk_directory import chunk_directory
from ...libs.index.chunkers.chunk_directory import (
stream_chunk_directory,
)
from ...libs.index.indices.meilisearch_index import MeilisearchCodebaseIndex
from ...libs.index.indices.chroma_index import MAX_CHUNK_SIZE, ChromaCodebaseIndex
@ -20,32 +23,52 @@ async def build_index(
)
meilisearch_index = MeilisearchCodebaseIndex(ide.workspace_directory)
indices_to_build = 0
chroma_exists = await chroma_index.exists()
# meilisearch_exists = await meilisearch_index.exists()
meilisearch_exists = chroma_exists
if not chroma_exists:
indices_to_build += 1
if not meilisearch_exists:
indices_to_build += 1
if indices_to_build == 0:
if chroma_exists and meilisearch_exists:
yield 1
return
chunks = await chunk_directory(ide, MAX_CHUNK_SIZE)
n = 2
done = False
buffers = [[] for _ in range(n)]
total_progress = 0
if not chroma_exists:
async for progress in chroma_index.build(
ide, ignore_files=settings.ignore_files, chunks=chunks
):
yield progress / indices_to_build
async def generator_for_chroma():
nonlocal buffers
while not done or len(buffers[0]) > 0:
if len(buffers[0]) > 0:
yield buffers[0].pop(0)
else:
await asyncio.sleep(0.1)
total_progress += 50
async def generator_for_meilisearch():
nonlocal buffers
while not done or len(buffers[1]) > 0:
if len(buffers[1]) > 0:
yield buffers[1].pop(0)
else:
await asyncio.sleep(0.1)
if not meilisearch_exists:
async for progress in meilisearch_index.build(
ide, ignore_files=settings.ignore_files, chunks=chunks
):
yield progress / indices_to_build + total_progress / 100
async def chroma_task():
if not chroma_exists:
await chroma_index.build(generator_for_chroma())
async def meilisearch_task():
if not meilisearch_exists:
await meilisearch_index.build(generator_for_meilisearch())
chroma_task = asyncio.create_task(chroma_task())
meilisearch_task = asyncio.create_task(meilisearch_task())
async for chunk, progress in stream_chunk_directory(ide, MAX_CHUNK_SIZE):
buffers[0].append(chunk)
buffers[1].append(chunk)
yield progress
done = True
while not chroma_task.done() or not meilisearch_task.done():
await asyncio.sleep(0.1)
yield 1

View file

@ -1,6 +1,6 @@
import asyncio
import os
from typing import Dict, List
from typing import AsyncGenerator, Dict, List, Tuple
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from ...util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path
@ -82,10 +82,9 @@ def gi_basename(path: str) -> str:
return path
async def get_all_file_contents(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = [], group_size: int = 100
) -> Dict[str, str]:
# Get list of filenames to index
async def get_non_ignored_filepaths(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = []
):
files = await ide.listDirectoryContents(ide.workspace_directory, True)
# Get all .gitignores first
@ -130,6 +129,14 @@ async def get_all_file_contents(
files,
)
)
return files
async def get_all_file_contents(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = [], group_size: int = 100
) -> Dict[str, str]:
# Get list of filenames to index
files = await get_non_ignored_filepaths(ide, ignore_files)
items = []
i = 0
@ -153,3 +160,27 @@ async def chunk_directory(
chunks += chunk_document(filepath, contents, max_chunk_size)
return chunks
async def stream_file_contents(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = [], group_size: int = 100
) -> AsyncGenerator[Tuple[str, str, float], None]:
# Get list of filenames to index
# TODO: Don't get all at once, walk the tree, or break up
files = await get_non_ignored_filepaths(ide, ignore_files)
# Don't want to flood with too many requests
i = 0
total = len(files)
for file in files:
contents = await get_file_contents(file, ide)
yield (file, contents, i / total)
i += 1
async def stream_chunk_directory(
ide: AbstractIdeProtocolServer, max_chunk_size: int
) -> AsyncGenerator[Tuple[Chunk, float], None]:
async for file, contents, progress in stream_file_contents(ide):
for chunk in chunk_document(file, contents, max_chunk_size):
yield (chunk, progress)

View file

@ -19,13 +19,8 @@ class CodebaseIndex(ABC):
raise NotImplementedError()
@abstractmethod
async def build(
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Builds the index, yielding progress as a float between 0 and 1. Optionally takes a list of chunks, otherwise builds its own"""
async def build(self, chunks: AsyncGenerator[Chunk, None]):
"""Builds the index, yielding progress as a float between 0 and 1. Chunks are yielded from the given generator."""
raise NotImplementedError()
@abstractmethod

View file

@ -150,34 +150,7 @@ class ChromaCodebaseIndex(CodebaseIndex):
collections[self.directory] = collection
return collection
async def build(
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Create a new index for the current branch."""
if await self.exists():
return
if chunks is None:
raise Exception("Chunks must be passed in to build Chroma index")
# Construct list of chunks for each file
chunks = list(
filter(
lambda c: len(c.content.strip()) > 0,
chunks,
)
)
num_chunks_per_file = {}
for chunk in chunks:
num_chunks_per_file[chunk.document_id] = (
num_chunks_per_file.get(chunk.document_id, 0) + 1
)
async def add_chunks(self, chunks: List[Chunk]):
# Flatten chunks, metadata, and ids for insertion to Chroma
documents = []
metadatas = []
@ -194,6 +167,9 @@ class ChromaCodebaseIndex(CodebaseIndex):
wait_time = 4.0
while i < len(ids):
try:
if i > 0:
await asyncio.sleep(0.05)
self.collection.add(
documents=documents[i : i + 100],
metadatas=metadatas[i : i + 100],
@ -201,25 +177,47 @@ class ChromaCodebaseIndex(CodebaseIndex):
)
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}")
del collections[self.directory]
async def build(
self,
chunks: AsyncGenerator[Chunk, None],
):
"""Create a new index for the current branch."""
if await self.exists():
return
group = []
group_size = 100
async for chunk in chunks:
if chunk.content.strip() == "":
continue
if len(group) < group_size:
group.append(chunk)
continue
await self.add_chunks([chunk])
if len(group) > 0:
await self.add_chunks(group)
# 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,
"chunks": {}, # TODO: This was removed, is it necessary?
},
f,
indent=4,

View file

@ -1,12 +1,12 @@
import asyncio
from functools import cached_property
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from meilisearch_python_async import Client
from meilisearch_python_async.errors import MeilisearchApiError
from meilisearch_python_async.index import Index
from ....server.meilisearch_server import get_meilisearch_url
from .base import CodebaseIndex
from ..chunkers import Chunk
from typing import Any, AsyncGenerator, Dict, List, Optional
from typing import Any, AsyncGenerator, Dict, List
from ....server.meilisearch_server import remove_meilisearch_disallowed_chars
from ...util.logging import logger
@ -63,17 +63,16 @@ class MeilisearchCodebaseIndex(CodebaseIndex):
other_metadata=other_metadata,
)
async def build(
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Builds the index, yielding progress as a float between 0 and 1"""
if chunks is None:
logger.warning("Meilisearch index requires chunks to be passed in")
yield 1
async def add_chunks(self, chunks: List[Chunk], index: Index, offset: int):
await index.add_documents(
[
self.chunk_to_meilisearch_document(chunk, j + offset)
for j, chunk in enumerate(chunks)
]
)
async def build(self, chunks: AsyncGenerator[Chunk, None]):
"""Builds the index, yielding progress as a float between 0 and 1"""
async with Client(get_meilisearch_url()) as search_client:
try:
await search_client.create_index(self.index_name)
@ -85,23 +84,28 @@ class MeilisearchCodebaseIndex(CodebaseIndex):
i = 0
GROUP_SIZE = 100
while i < len(chunks):
await index.add_documents(
[
self.chunk_to_meilisearch_document(chunk, j)
for j, chunk in enumerate(chunks[i : i + GROUP_SIZE])
]
group = []
async for chunk in chunks:
if len(group) < GROUP_SIZE:
group.append(chunk)
continue
await self.add_chunks(
group,
index,
i,
)
i += GROUP_SIZE
yield i / len(chunks)
group = []
await asyncio.sleep(0.1)
if len(group) > 0:
await self.add_chunks(group, index, i)
except Exception as e:
logger.warning(f"Error while building meilisearch index: {e}")
yield 1
async def update(self) -> AsyncGenerator[float, None]:
"""Updates the index, yielding progress as a float between 0 and 1"""
raise NotImplementedError()