Skip to content

Commit eb699ad

Browse files
author
Zhe Yu
committed
refactor(cli): Separate embedding function from collection
1 parent c19c4c3 commit eb699ad

4 files changed

Lines changed: 18 additions & 8 deletions

File tree

src/vectorcode/cli_utils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ class Config:
114114
files_action: Optional[FilesAction] = None
115115
rm_paths: list[str] = field(default_factory=list)
116116

117+
def __hash__(self) -> int:
118+
return hash(self.__repr__())
119+
117120
@classmethod
118121
async def import_from(cls, config_dict: dict[str, Any]) -> "Config":
119122
"""

src/vectorcode/common.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import sys
99
from asyncio.subprocess import Process
1010
from dataclasses import dataclass
11+
from functools import cache
1112
from typing import Any, AsyncGenerator, Optional
1213
from urllib.parse import urlparse
1314

@@ -127,11 +128,15 @@ def get_collection_name(full_path: str) -> str:
127128
return collection_id
128129

129130

130-
def get_embedding_function(configs: Config) -> chromadb.EmbeddingFunction | None:
131+
@cache
132+
def get_embedding_function(configs: Config) -> chromadb.EmbeddingFunction:
131133
try:
132-
return getattr(embedding_functions, configs.embedding_function)(
134+
ef = getattr(embedding_functions, configs.embedding_function)(
133135
**configs.embedding_params
134136
)
137+
if ef is None:
138+
raise AttributeError()
139+
return ef
135140
except AttributeError:
136141
logger.warning(
137142
f"Failed to use {configs.embedding_function}. Falling back to Sentence Transformer.",
@@ -161,7 +166,6 @@ async def get_collection(
161166
full_path = str(expand_path(str(configs.project_root), absolute=True))
162167
if __COLLECTION_CACHE.get(full_path) is None:
163168
collection_name = get_collection_name(full_path)
164-
embedding_function = get_embedding_function(configs)
165169

166170
collection_meta: dict[str, str | int] = {
167171
"path": full_path,
@@ -183,14 +187,11 @@ async def get_collection(
183187
f"Getting/Creating collection with the following metadata: {collection_meta}"
184188
)
185189
if not make_if_missing:
186-
__COLLECTION_CACHE[full_path] = await client.get_collection(
187-
collection_name, embedding_function
188-
)
190+
__COLLECTION_CACHE[full_path] = await client.get_collection(collection_name)
189191
else:
190192
collection = await client.get_or_create_collection(
191193
collection_name,
192194
metadata=collection_meta,
193-
embedding_function=embedding_function,
194195
)
195196
if (
196197
not collection.metadata.get("hostname") == socket.gethostname()

src/vectorcode/subcommands/query/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from vectorcode.common import (
2020
ClientManager,
2121
get_collection,
22+
get_embedding_function,
2223
verify_ef,
2324
)
2425
from vectorcode.subcommands.query.reranker import (
@@ -67,7 +68,7 @@ async def get_query_result_files(
6768
)
6869
logger.info(f"Querying {num_query} chunks for reranking.")
6970
results = await collection.query(
70-
query_texts=query_chunks,
71+
query_embeddings=get_embedding_function(configs)(query_chunks),
7172
n_results=num_query,
7273
include=[
7374
IncludeEnum.metadatas,

src/vectorcode/subcommands/vectorise.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from vectorcode.common import (
2929
ClientManager,
3030
get_collection,
31+
get_embedding_function,
3132
list_collection_files,
3233
verify_ef,
3334
)
@@ -92,6 +93,7 @@ async def chunked_add(
9293
max_batch_size: int,
9394
semaphore: asyncio.Semaphore,
9495
):
96+
embedding_function = get_embedding_function(configs)
9597
full_path_str = str(expand_path(str(file_path), True))
9698
orig_sha256 = None
9799
new_sha256 = hash_file(full_path_str)
@@ -147,6 +149,9 @@ async def chunked_add(
147149
await collection.add(
148150
ids=[get_uuid() for _ in inserted_chunks],
149151
documents=[str(i) for i in inserted_chunks],
152+
embeddings=embedding_function(
153+
list(str(c) for c in inserted_chunks)
154+
),
150155
metadatas=metas,
151156
)
152157
except (UnicodeDecodeError, UnicodeError): # pragma: nocover

0 commit comments

Comments
 (0)