kodit 0.1.10__py3-none-any.whl → 0.1.12__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of kodit might be problematic. Click here for more details.
- kodit/_version.py +2 -2
- kodit/bm25/bm25.py +1 -1
- kodit/cli.py +22 -52
- kodit/config.py +43 -3
- kodit/embedding/embedding.py +161 -10
- kodit/indexing/{models.py → indexing_models.py} +2 -2
- kodit/indexing/{repository.py → indexing_repository.py} +5 -5
- kodit/indexing/{service.py → indexing_service.py} +17 -12
- kodit/log.py +1 -0
- kodit/mcp.py +27 -34
- kodit/migrations/env.py +3 -3
- kodit/search/__init__.py +1 -0
- kodit/search/search_repository.py +178 -0
- kodit/{retreival/service.py → search/search_service.py} +40 -17
- kodit/snippets/snippets.py +3 -1
- kodit/{sources/repository.py → source/source_repository.py} +2 -7
- kodit/{sources/service.py → source/source_service.py} +2 -2
- {kodit-0.1.10.dist-info → kodit-0.1.12.dist-info}/METADATA +3 -1
- kodit-0.1.12.dist-info/RECORD +44 -0
- kodit/retreival/__init__.py +0 -1
- kodit/retreival/repository.py +0 -183
- kodit-0.1.10.dist-info/RECORD +0 -44
- /kodit/embedding/{models.py → embedding_models.py} +0 -0
- /kodit/{sources → source}/__init__.py +0 -0
- /kodit/{sources/models.py → source/source_models.py} +0 -0
- {kodit-0.1.10.dist-info → kodit-0.1.12.dist-info}/WHEEL +0 -0
- {kodit-0.1.10.dist-info → kodit-0.1.12.dist-info}/entry_points.txt +0 -0
- {kodit-0.1.10.dist-info → kodit-0.1.12.dist-info}/licenses/LICENSE +0 -0
kodit/_version.py
CHANGED
kodit/bm25/bm25.py
CHANGED
|
@@ -52,7 +52,7 @@ class BM25Service:
|
|
|
52
52
|
self.log.warning("No documents to retrieve from, returning empty list")
|
|
53
53
|
return []
|
|
54
54
|
|
|
55
|
-
top_k = min(top_k, len(
|
|
55
|
+
top_k = min(top_k, len(self.retriever.scores))
|
|
56
56
|
self.log.debug(
|
|
57
57
|
"Retrieving from index", query=query, top_k=top_k, num_docs=len(doc_ids)
|
|
58
58
|
)
|
kodit/cli.py
CHANGED
|
@@ -12,35 +12,21 @@ from pytable_formatter import Cell, Table
|
|
|
12
12
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
13
13
|
|
|
14
14
|
from kodit.config import (
|
|
15
|
-
DEFAULT_BASE_DIR,
|
|
16
|
-
DEFAULT_DB_URL,
|
|
17
|
-
DEFAULT_DISABLE_TELEMETRY,
|
|
18
|
-
DEFAULT_EMBEDDING_MODEL_NAME,
|
|
19
|
-
DEFAULT_LOG_FORMAT,
|
|
20
|
-
DEFAULT_LOG_LEVEL,
|
|
21
15
|
AppContext,
|
|
22
16
|
with_app_context,
|
|
23
17
|
with_session,
|
|
24
18
|
)
|
|
25
|
-
from kodit.
|
|
26
|
-
from kodit.indexing.
|
|
19
|
+
from kodit.embedding.embedding import embedding_factory
|
|
20
|
+
from kodit.indexing.indexing_repository import IndexRepository
|
|
21
|
+
from kodit.indexing.indexing_service import IndexService
|
|
27
22
|
from kodit.log import configure_logging, configure_telemetry, log_event
|
|
28
|
-
from kodit.
|
|
29
|
-
from kodit.
|
|
30
|
-
from kodit.
|
|
31
|
-
from kodit.
|
|
23
|
+
from kodit.search.search_repository import SearchRepository
|
|
24
|
+
from kodit.search.search_service import SearchRequest, SearchService
|
|
25
|
+
from kodit.source.source_repository import SourceRepository
|
|
26
|
+
from kodit.source.source_service import SourceService
|
|
32
27
|
|
|
33
28
|
|
|
34
29
|
@click.group(context_settings={"max_content_width": 100})
|
|
35
|
-
@click.option("--log-level", help=f"Log level [default: {DEFAULT_LOG_LEVEL}]")
|
|
36
|
-
@click.option("--log-format", help=f"Log format [default: {DEFAULT_LOG_FORMAT}]")
|
|
37
|
-
@click.option(
|
|
38
|
-
"--disable-telemetry",
|
|
39
|
-
is_flag=True,
|
|
40
|
-
help=f"Disable telemetry [default: {DEFAULT_DISABLE_TELEMETRY}]",
|
|
41
|
-
)
|
|
42
|
-
@click.option("--db-url", help=f"Database URL [default: {DEFAULT_DB_URL}]")
|
|
43
|
-
@click.option("--data-dir", help=f"Data directory [default: {DEFAULT_BASE_DIR}]")
|
|
44
30
|
@click.option(
|
|
45
31
|
"--env-file",
|
|
46
32
|
help="Path to a .env file [default: .env]",
|
|
@@ -52,13 +38,8 @@ from kodit.sources.service import SourceService
|
|
|
52
38
|
),
|
|
53
39
|
)
|
|
54
40
|
@click.pass_context
|
|
55
|
-
def cli(
|
|
41
|
+
def cli(
|
|
56
42
|
ctx: click.Context,
|
|
57
|
-
log_level: str | None,
|
|
58
|
-
log_format: str | None,
|
|
59
|
-
disable_telemetry: bool | None,
|
|
60
|
-
db_url: str | None,
|
|
61
|
-
data_dir: str | None,
|
|
62
43
|
env_file: Path | None,
|
|
63
44
|
) -> None:
|
|
64
45
|
"""kodit CLI - Code indexing for better AI code generation.""" # noqa: D403
|
|
@@ -67,17 +48,6 @@ def cli( # noqa: PLR0913
|
|
|
67
48
|
if env_file:
|
|
68
49
|
config = AppContext(_env_file=env_file) # type: ignore[reportCallIssue]
|
|
69
50
|
|
|
70
|
-
# Now override with CLI arguments, if set
|
|
71
|
-
if data_dir:
|
|
72
|
-
config.data_dir = Path(data_dir)
|
|
73
|
-
if db_url:
|
|
74
|
-
config.db_url = db_url
|
|
75
|
-
if log_level:
|
|
76
|
-
config.log_level = log_level
|
|
77
|
-
if log_format:
|
|
78
|
-
config.log_format = log_format
|
|
79
|
-
if disable_telemetry:
|
|
80
|
-
config.disable_telemetry = disable_telemetry
|
|
81
51
|
configure_logging(config)
|
|
82
52
|
configure_telemetry(config)
|
|
83
53
|
|
|
@@ -102,7 +72,7 @@ async def index(
|
|
|
102
72
|
repository,
|
|
103
73
|
source_service,
|
|
104
74
|
app_context.get_data_dir(),
|
|
105
|
-
|
|
75
|
+
embedding_service=embedding_factory(app_context.get_default_openai_client()),
|
|
106
76
|
)
|
|
107
77
|
|
|
108
78
|
if not sources:
|
|
@@ -159,14 +129,14 @@ async def code(
|
|
|
159
129
|
|
|
160
130
|
This works best if your query is code.
|
|
161
131
|
"""
|
|
162
|
-
repository =
|
|
163
|
-
service =
|
|
132
|
+
repository = SearchRepository(session)
|
|
133
|
+
service = SearchService(
|
|
164
134
|
repository,
|
|
165
135
|
app_context.get_data_dir(),
|
|
166
|
-
|
|
136
|
+
embedding_service=embedding_factory(app_context.get_default_openai_client()),
|
|
167
137
|
)
|
|
168
138
|
|
|
169
|
-
snippets = await service.
|
|
139
|
+
snippets = await service.search(SearchRequest(code_query=query, top_k=top_k))
|
|
170
140
|
|
|
171
141
|
if len(snippets) == 0:
|
|
172
142
|
click.echo("No snippets found")
|
|
@@ -192,14 +162,14 @@ async def keyword(
|
|
|
192
162
|
top_k: int,
|
|
193
163
|
) -> None:
|
|
194
164
|
"""Search for snippets using keyword search."""
|
|
195
|
-
repository =
|
|
196
|
-
service =
|
|
165
|
+
repository = SearchRepository(session)
|
|
166
|
+
service = SearchService(
|
|
197
167
|
repository,
|
|
198
168
|
app_context.get_data_dir(),
|
|
199
|
-
|
|
169
|
+
embedding_service=embedding_factory(app_context.get_default_openai_client()),
|
|
200
170
|
)
|
|
201
171
|
|
|
202
|
-
snippets = await service.
|
|
172
|
+
snippets = await service.search(SearchRequest(keywords=keywords, top_k=top_k))
|
|
203
173
|
|
|
204
174
|
if len(snippets) == 0:
|
|
205
175
|
click.echo("No snippets found")
|
|
@@ -227,18 +197,18 @@ async def hybrid(
|
|
|
227
197
|
code: str,
|
|
228
198
|
) -> None:
|
|
229
199
|
"""Search for snippets using hybrid search."""
|
|
230
|
-
repository =
|
|
231
|
-
service =
|
|
200
|
+
repository = SearchRepository(session)
|
|
201
|
+
service = SearchService(
|
|
232
202
|
repository,
|
|
233
203
|
app_context.get_data_dir(),
|
|
234
|
-
|
|
204
|
+
embedding_service=embedding_factory(app_context.get_default_openai_client()),
|
|
235
205
|
)
|
|
236
206
|
|
|
237
207
|
# Parse keywords into a list of strings
|
|
238
208
|
keywords_list = [k.strip().lower() for k in keywords.split(",")]
|
|
239
209
|
|
|
240
|
-
snippets = await service.
|
|
241
|
-
|
|
210
|
+
snippets = await service.search(
|
|
211
|
+
SearchRequest(keywords=keywords_list, code_query=code, top_k=top_k)
|
|
242
212
|
)
|
|
243
213
|
|
|
244
214
|
if len(snippets) == 0:
|
kodit/config.py
CHANGED
|
@@ -4,10 +4,11 @@ import asyncio
|
|
|
4
4
|
from collections.abc import Callable, Coroutine
|
|
5
5
|
from functools import wraps
|
|
6
6
|
from pathlib import Path
|
|
7
|
-
from typing import Any, TypeVar
|
|
7
|
+
from typing import Any, Literal, TypeVar
|
|
8
8
|
|
|
9
9
|
import click
|
|
10
|
-
from
|
|
10
|
+
from openai import AsyncOpenAI
|
|
11
|
+
from pydantic import BaseModel, Field
|
|
11
12
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
12
13
|
|
|
13
14
|
from kodit.database import Database
|
|
@@ -22,16 +23,40 @@ DEFAULT_EMBEDDING_MODEL_NAME = TINY
|
|
|
22
23
|
T = TypeVar("T")
|
|
23
24
|
|
|
24
25
|
|
|
26
|
+
class Endpoint(BaseModel):
|
|
27
|
+
"""Endpoint provides configuration for an AI service."""
|
|
28
|
+
|
|
29
|
+
type: Literal["openai"] = Field(default="openai")
|
|
30
|
+
api_key: str | None = None
|
|
31
|
+
base_url: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
25
34
|
class AppContext(BaseSettings):
|
|
26
35
|
"""Global context for the kodit project. Provides a shared state for the app."""
|
|
27
36
|
|
|
28
|
-
model_config = SettingsConfigDict(
|
|
37
|
+
model_config = SettingsConfigDict(
|
|
38
|
+
env_file=".env",
|
|
39
|
+
env_file_encoding="utf-8",
|
|
40
|
+
env_nested_delimiter="_",
|
|
41
|
+
nested_model_default_partial_update=True,
|
|
42
|
+
env_nested_max_split=1,
|
|
43
|
+
)
|
|
29
44
|
|
|
30
45
|
data_dir: Path = Field(default=DEFAULT_BASE_DIR)
|
|
31
46
|
db_url: str = Field(default=DEFAULT_DB_URL)
|
|
32
47
|
log_level: str = Field(default=DEFAULT_LOG_LEVEL)
|
|
33
48
|
log_format: str = Field(default=DEFAULT_LOG_FORMAT)
|
|
34
49
|
disable_telemetry: bool = Field(default=DEFAULT_DISABLE_TELEMETRY)
|
|
50
|
+
default_endpoint: Endpoint | None = Field(
|
|
51
|
+
default=Endpoint(
|
|
52
|
+
type="openai",
|
|
53
|
+
base_url="https://api.openai.com/v1",
|
|
54
|
+
),
|
|
55
|
+
description=(
|
|
56
|
+
"Default endpoint to use for all AI interactions "
|
|
57
|
+
"(can be overridden by task-specific configuration)."
|
|
58
|
+
),
|
|
59
|
+
)
|
|
35
60
|
_db: Database | None = None
|
|
36
61
|
|
|
37
62
|
def model_post_init(self, _: Any) -> None:
|
|
@@ -58,6 +83,21 @@ class AppContext(BaseSettings):
|
|
|
58
83
|
await self._db.run_migrations(self.db_url)
|
|
59
84
|
return self._db
|
|
60
85
|
|
|
86
|
+
def get_default_openai_client(self) -> AsyncOpenAI | None:
|
|
87
|
+
"""Get the default OpenAI client, if it is configured."""
|
|
88
|
+
endpoint = self.default_endpoint
|
|
89
|
+
if not (
|
|
90
|
+
endpoint
|
|
91
|
+
and endpoint.type == "openai"
|
|
92
|
+
and endpoint.api_key
|
|
93
|
+
and endpoint.base_url
|
|
94
|
+
):
|
|
95
|
+
return None
|
|
96
|
+
return AsyncOpenAI(
|
|
97
|
+
api_key=endpoint.api_key,
|
|
98
|
+
base_url=endpoint.base_url,
|
|
99
|
+
)
|
|
100
|
+
|
|
61
101
|
|
|
62
102
|
with_app_context = click.make_pass_decorator(AppContext)
|
|
63
103
|
|
kodit/embedding/embedding.py
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
"""Embedding service."""
|
|
2
2
|
|
|
3
|
+
import asyncio
|
|
3
4
|
import os
|
|
4
|
-
from
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from collections.abc import AsyncGenerator
|
|
7
|
+
from typing import NamedTuple
|
|
5
8
|
|
|
6
9
|
import structlog
|
|
10
|
+
import tiktoken
|
|
11
|
+
from openai import AsyncOpenAI
|
|
7
12
|
from sentence_transformers import SentenceTransformer
|
|
8
13
|
|
|
9
14
|
TINY = "tiny"
|
|
@@ -17,14 +22,59 @@ COMMON_EMBEDDING_MODELS = {
|
|
|
17
22
|
}
|
|
18
23
|
|
|
19
24
|
|
|
20
|
-
class
|
|
21
|
-
"""
|
|
25
|
+
class EmbeddingInput(NamedTuple):
|
|
26
|
+
"""Input for embedding."""
|
|
27
|
+
|
|
28
|
+
id: int
|
|
29
|
+
text: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class EmbeddingOutput(NamedTuple):
|
|
33
|
+
"""Output for embedding."""
|
|
34
|
+
|
|
35
|
+
id: int
|
|
36
|
+
embedding: list[float]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Embedder(ABC):
|
|
40
|
+
"""Embedder interface."""
|
|
41
|
+
|
|
42
|
+
@abstractmethod
|
|
43
|
+
def embed(
|
|
44
|
+
self, data: list[EmbeddingInput]
|
|
45
|
+
) -> AsyncGenerator[EmbeddingOutput, None]:
|
|
46
|
+
"""Embed a list of documents.
|
|
47
|
+
|
|
48
|
+
The embedding service accepts a massive list of id,strings to embed. Behind the
|
|
49
|
+
scenes it batches up requests and parallelizes them for performance according to
|
|
50
|
+
the specifics of the embedding service.
|
|
51
|
+
|
|
52
|
+
The id reference is required because the parallelization may return results out
|
|
53
|
+
of order.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
@abstractmethod
|
|
57
|
+
def query(self, data: list[str]) -> AsyncGenerator[list[float], None]:
|
|
58
|
+
"""Query the embedding model."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def embedding_factory(openai_client: AsyncOpenAI | None = None) -> Embedder:
|
|
62
|
+
"""Create an embedding service."""
|
|
63
|
+
if openai_client is not None:
|
|
64
|
+
return OpenAIEmbedder(openai_client)
|
|
65
|
+
return LocalEmbedder(model_name=TINY)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LocalEmbedder(Embedder):
|
|
69
|
+
"""Local embedder."""
|
|
22
70
|
|
|
23
71
|
def __init__(self, model_name: str) -> None:
|
|
24
|
-
"""Initialize the
|
|
72
|
+
"""Initialize the local embedder."""
|
|
25
73
|
self.log = structlog.get_logger(__name__)
|
|
74
|
+
self.log.info("Creating local embedder", model_name=model_name)
|
|
26
75
|
self.model_name = COMMON_EMBEDDING_MODELS.get(model_name, model_name)
|
|
27
76
|
self.embedding_model = None
|
|
77
|
+
self.encoding = tiktoken.encoding_for_model("text-embedding-3-small")
|
|
28
78
|
|
|
29
79
|
def _model(self) -> SentenceTransformer:
|
|
30
80
|
"""Get the embedding model."""
|
|
@@ -37,16 +87,117 @@ class EmbeddingService:
|
|
|
37
87
|
)
|
|
38
88
|
return self.embedding_model
|
|
39
89
|
|
|
40
|
-
def embed(
|
|
90
|
+
async def embed(
|
|
91
|
+
self, data: list[EmbeddingInput]
|
|
92
|
+
) -> AsyncGenerator[EmbeddingOutput, None]:
|
|
41
93
|
"""Embed a list of documents."""
|
|
42
94
|
model = self._model()
|
|
43
|
-
embeddings = model.encode(snippets, show_progress_bar=False, batch_size=4)
|
|
44
|
-
for embedding in embeddings:
|
|
45
|
-
yield [float(x) for x in embedding]
|
|
46
95
|
|
|
47
|
-
|
|
96
|
+
batched_data = _split_sub_batches(self.encoding, data)
|
|
97
|
+
|
|
98
|
+
for batch in batched_data:
|
|
99
|
+
embeddings = model.encode(
|
|
100
|
+
[i.text for i in batch], show_progress_bar=False, batch_size=4
|
|
101
|
+
)
|
|
102
|
+
for i, x in zip(batch, embeddings, strict=False):
|
|
103
|
+
yield EmbeddingOutput(i.id, [float(y) for y in x])
|
|
104
|
+
|
|
105
|
+
async def query(self, data: list[str]) -> AsyncGenerator[list[float], None]:
|
|
48
106
|
"""Query the embedding model."""
|
|
49
107
|
model = self._model()
|
|
50
|
-
embeddings = model.encode(
|
|
108
|
+
embeddings = model.encode(data, show_progress_bar=False, batch_size=4)
|
|
51
109
|
for embedding in embeddings:
|
|
52
110
|
yield [float(x) for x in embedding]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
OPENAI_MAX_EMBEDDING_SIZE = 8192
|
|
114
|
+
OPENAI_NUM_PARALLEL_TASKS = 10
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _split_sub_batches(
|
|
118
|
+
encoding: tiktoken.Encoding, data: list[EmbeddingInput]
|
|
119
|
+
) -> list[list[EmbeddingInput]]:
|
|
120
|
+
"""Split a list of strings into smaller sub-batches."""
|
|
121
|
+
log = structlog.get_logger(__name__)
|
|
122
|
+
result = []
|
|
123
|
+
data_to_process = [s for s in data if s.text.strip()] # Filter out empty strings
|
|
124
|
+
|
|
125
|
+
while data_to_process:
|
|
126
|
+
next_batch = []
|
|
127
|
+
current_tokens = 0
|
|
128
|
+
|
|
129
|
+
while data_to_process:
|
|
130
|
+
next_item = data_to_process[0]
|
|
131
|
+
item_tokens = len(encoding.encode(next_item.text))
|
|
132
|
+
|
|
133
|
+
if item_tokens > OPENAI_MAX_EMBEDDING_SIZE:
|
|
134
|
+
log.warning("Skipping too long snippet", snippet=data_to_process.pop(0))
|
|
135
|
+
continue
|
|
136
|
+
|
|
137
|
+
if current_tokens + item_tokens > OPENAI_MAX_EMBEDDING_SIZE:
|
|
138
|
+
break
|
|
139
|
+
|
|
140
|
+
next_batch.append(data_to_process.pop(0))
|
|
141
|
+
current_tokens += item_tokens
|
|
142
|
+
|
|
143
|
+
if next_batch:
|
|
144
|
+
result.append(next_batch)
|
|
145
|
+
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class OpenAIEmbedder(Embedder):
|
|
150
|
+
"""OpenAI embedder."""
|
|
151
|
+
|
|
152
|
+
def __init__(
|
|
153
|
+
self, openai_client: AsyncOpenAI, model_name: str = "text-embedding-3-small"
|
|
154
|
+
) -> None:
|
|
155
|
+
"""Initialize the OpenAI embedder."""
|
|
156
|
+
self.log = structlog.get_logger(__name__)
|
|
157
|
+
self.log.info("Creating OpenAI embedder", model_name=model_name)
|
|
158
|
+
self.openai_client = openai_client
|
|
159
|
+
self.encoding = tiktoken.encoding_for_model(model_name)
|
|
160
|
+
self.log = structlog.get_logger(__name__)
|
|
161
|
+
|
|
162
|
+
async def embed(
|
|
163
|
+
self,
|
|
164
|
+
data: list[EmbeddingInput],
|
|
165
|
+
) -> AsyncGenerator[EmbeddingOutput, None]:
|
|
166
|
+
"""Embed a list of documents."""
|
|
167
|
+
# First split the list into a list of list where each sublist has fewer than
|
|
168
|
+
# max tokens.
|
|
169
|
+
batched_data = _split_sub_batches(self.encoding, data)
|
|
170
|
+
|
|
171
|
+
# Process batches in parallel with a semaphore to limit concurrent requests
|
|
172
|
+
sem = asyncio.Semaphore(OPENAI_NUM_PARALLEL_TASKS)
|
|
173
|
+
|
|
174
|
+
async def process_batch(batch: list[EmbeddingInput]) -> list[EmbeddingOutput]:
|
|
175
|
+
async with sem:
|
|
176
|
+
try:
|
|
177
|
+
response = await self.openai_client.embeddings.create(
|
|
178
|
+
model="text-embedding-3-small",
|
|
179
|
+
input=[i.text for i in batch],
|
|
180
|
+
)
|
|
181
|
+
return [
|
|
182
|
+
EmbeddingOutput(i.id, x.embedding)
|
|
183
|
+
for i, x in zip(batch, response.data, strict=False)
|
|
184
|
+
]
|
|
185
|
+
except Exception as e:
|
|
186
|
+
self.log.exception("Error embedding batch", error=str(e))
|
|
187
|
+
return []
|
|
188
|
+
|
|
189
|
+
# Create tasks for all batches
|
|
190
|
+
tasks = [process_batch(batch) for batch in batched_data]
|
|
191
|
+
|
|
192
|
+
# Process all batches and yield results as they complete
|
|
193
|
+
for task in asyncio.as_completed(tasks):
|
|
194
|
+
embeddings = await task
|
|
195
|
+
for e in embeddings:
|
|
196
|
+
yield e
|
|
197
|
+
|
|
198
|
+
async def query(self, data: list[str]) -> AsyncGenerator[list[float], None]:
|
|
199
|
+
"""Query the embedding model."""
|
|
200
|
+
async for e in self.embed(
|
|
201
|
+
[EmbeddingInput(i, text) for i, text in enumerate(data)]
|
|
202
|
+
):
|
|
203
|
+
yield e.embedding
|
|
@@ -31,8 +31,8 @@ class Snippet(Base, CommonMixin):
|
|
|
31
31
|
|
|
32
32
|
__tablename__ = "snippets"
|
|
33
33
|
|
|
34
|
-
file_id: Mapped[int] = mapped_column(ForeignKey("files.id"))
|
|
35
|
-
index_id: Mapped[int] = mapped_column(ForeignKey("indexes.id"))
|
|
34
|
+
file_id: Mapped[int] = mapped_column(ForeignKey("files.id"), index=True)
|
|
35
|
+
index_id: Mapped[int] = mapped_column(ForeignKey("indexes.id"), index=True)
|
|
36
36
|
content: Mapped[str] = mapped_column(UnicodeText, default="")
|
|
37
37
|
|
|
38
38
|
def __init__(self, file_id: int, index_id: int, content: str) -> None:
|
|
@@ -11,9 +11,9 @@ from typing import TypeVar
|
|
|
11
11
|
from sqlalchemy import delete, func, select
|
|
12
12
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
13
13
|
|
|
14
|
-
from kodit.embedding.
|
|
15
|
-
from kodit.indexing.
|
|
16
|
-
from kodit.
|
|
14
|
+
from kodit.embedding.embedding_models import Embedding
|
|
15
|
+
from kodit.indexing.indexing_models import Index, Snippet
|
|
16
|
+
from kodit.source.source_models import File, Source
|
|
17
17
|
|
|
18
18
|
T = TypeVar("T")
|
|
19
19
|
|
|
@@ -156,14 +156,14 @@ class IndexRepository:
|
|
|
156
156
|
result = await self.session.execute(query)
|
|
157
157
|
return list(result.scalars())
|
|
158
158
|
|
|
159
|
-
async def get_all_snippets(self) -> list[Snippet]:
|
|
159
|
+
async def get_all_snippets(self, index_id: int) -> list[Snippet]:
|
|
160
160
|
"""Get all snippets.
|
|
161
161
|
|
|
162
162
|
Returns:
|
|
163
163
|
A list of all snippets.
|
|
164
164
|
|
|
165
165
|
"""
|
|
166
|
-
query = select(Snippet).order_by(Snippet.id)
|
|
166
|
+
query = select(Snippet).where(Snippet.index_id == index_id).order_by(Snippet.id)
|
|
167
167
|
result = await self.session.execute(query)
|
|
168
168
|
return list(result.scalars())
|
|
169
169
|
|
|
@@ -14,12 +14,12 @@ import structlog
|
|
|
14
14
|
from tqdm.asyncio import tqdm
|
|
15
15
|
|
|
16
16
|
from kodit.bm25.bm25 import BM25Service
|
|
17
|
-
from kodit.embedding.embedding import
|
|
18
|
-
from kodit.embedding.
|
|
19
|
-
from kodit.indexing.
|
|
20
|
-
from kodit.indexing.
|
|
17
|
+
from kodit.embedding.embedding import Embedder, EmbeddingInput
|
|
18
|
+
from kodit.embedding.embedding_models import Embedding, EmbeddingType
|
|
19
|
+
from kodit.indexing.indexing_models import Snippet
|
|
20
|
+
from kodit.indexing.indexing_repository import IndexRepository
|
|
21
21
|
from kodit.snippets.snippets import SnippetService
|
|
22
|
-
from kodit.
|
|
22
|
+
from kodit.source.source_service import SourceService
|
|
23
23
|
|
|
24
24
|
# List of MIME types that are blacklisted from being indexed
|
|
25
25
|
MIME_BLACKLIST = ["unknown/unknown"]
|
|
@@ -52,7 +52,7 @@ class IndexService:
|
|
|
52
52
|
repository: IndexRepository,
|
|
53
53
|
source_service: SourceService,
|
|
54
54
|
data_dir: Path,
|
|
55
|
-
|
|
55
|
+
embedding_service: Embedder,
|
|
56
56
|
) -> None:
|
|
57
57
|
"""Initialize the index service.
|
|
58
58
|
|
|
@@ -66,7 +66,7 @@ class IndexService:
|
|
|
66
66
|
self.snippet_service = SnippetService()
|
|
67
67
|
self.log = structlog.get_logger(__name__)
|
|
68
68
|
self.bm25 = BM25Service(data_dir)
|
|
69
|
-
self.code_embedding_service =
|
|
69
|
+
self.code_embedding_service = embedding_service
|
|
70
70
|
|
|
71
71
|
async def create(self, source_id: int) -> IndexView:
|
|
72
72
|
"""Create a new index for a source.
|
|
@@ -132,7 +132,7 @@ class IndexService:
|
|
|
132
132
|
# Create snippets for supported file types
|
|
133
133
|
await self._create_snippets(index_id)
|
|
134
134
|
|
|
135
|
-
snippets = await self.repository.get_all_snippets()
|
|
135
|
+
snippets = await self.repository.get_all_snippets(index_id)
|
|
136
136
|
|
|
137
137
|
self.log.info("Creating keyword index")
|
|
138
138
|
self.bm25.index(
|
|
@@ -143,12 +143,17 @@ class IndexService:
|
|
|
143
143
|
)
|
|
144
144
|
|
|
145
145
|
self.log.info("Creating semantic code index")
|
|
146
|
-
for
|
|
147
|
-
|
|
146
|
+
async for e in tqdm(
|
|
147
|
+
self.code_embedding_service.embed(
|
|
148
|
+
[EmbeddingInput(snippet.id, snippet.content) for snippet in snippets]
|
|
149
|
+
),
|
|
150
|
+
total=len(snippets),
|
|
151
|
+
leave=False,
|
|
152
|
+
):
|
|
148
153
|
await self.repository.add_embedding(
|
|
149
154
|
Embedding(
|
|
150
|
-
snippet_id=
|
|
151
|
-
embedding=embedding,
|
|
155
|
+
snippet_id=e.id,
|
|
156
|
+
embedding=e.embedding,
|
|
152
157
|
type=EmbeddingType.CODE,
|
|
153
158
|
)
|
|
154
159
|
)
|
kodit/log.py
CHANGED