Skip to content

Commit 875a06f

Browse files
laxmancloAlex-Hunterz
authored andcommitted
chore: fix ruff linting errors and remove duplicate methods
1 parent a302068 commit 875a06f

10 files changed

Lines changed: 62 additions & 424 deletions

File tree

test_conflict.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import asyncio
2-
from vektori.storage.memory import MemoryBackend
2+
33
from vektori.ingestion.extractor import FactExtractor
4-
from vektori.models.base import LLMProvider, EmbeddingProvider
4+
from vektori.models.base import EmbeddingProvider, LLMProvider
5+
from vektori.storage.memory import MemoryBackend
6+
57

68
class MockEmbedder(EmbeddingProvider):
79
@property
8-
def dimension(self): return 2
10+
def dimension(self):
11+
return 2
12+
913
async def embed(self, text):
10-
if "hate" in text: return [0.5, -0.5]
14+
if "hate" in text:
15+
return [0.5, -0.5]
1116
return [0.5, 0.5]
1217
async def embed_batch(self, texts):
1318
return [await self.embed(t) for t in texts]
@@ -22,19 +27,19 @@ async def test():
2227
embedder = MockEmbedder()
2328
llm = MockLLM()
2429
extractor = FactExtractor(db, embedder, llm)
25-
30+
2631
# insert first fact
2732
await extractor._process_facts(
2833
[{"text": "User loves apples"}],
2934
session_id="s1", user_id="u1", agent_id=None, conversation="User: I love apples"
3035
)
31-
36+
3237
# insert second fact
3338
await extractor._process_facts(
3439
[{"text": "User hates apples"}],
3540
session_id="s2", user_id="u1", agent_id=None, conversation="User: Actually I hate apples"
3641
)
37-
42+
3843
facts = await db.get_active_facts("u1")
3944
print("Active facts count:", len(facts))
4045
for f in facts:

test_conflict2.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
import asyncio
2-
from vektori.storage.memory import MemoryBackend
3-
from vektori.ingestion.extractor import FactExtractor
4-
from vektori.models.base import LLMProvider, EmbeddingProvider
52
import logging
63

4+
from vektori.ingestion.extractor import FactExtractor
5+
from vektori.models.base import EmbeddingProvider, LLMProvider
6+
from vektori.storage.memory import MemoryBackend
7+
78
logging.basicConfig(level=logging.DEBUG)
89

910
class MockEmbedder(EmbeddingProvider):
1011
@property
11-
def dimension(self): return 2
12+
def dimension(self):
13+
return 2
14+
1215
async def embed(self, text):
13-
if "hate" in text: return [0.5, 0.4] # High similarity to trigger check
16+
if "hate" in text:
17+
return [0.5, 0.4] # High similarity to trigger check
1418
return [0.5, 0.5]
1519
async def embed_batch(self, texts):
1620
return [await self.embed(t) for t in texts]
@@ -28,12 +32,13 @@ async def test():
2832
embedder = MockEmbedder()
2933
llm = MockLLM()
3034
extractor = FactExtractor(db, embedder, llm)
31-
35+
3236
await extractor._process_facts([{"text": "User loves apples"}], "s1", "u1", None, "")
3337
await extractor._process_facts([{"text": "User hates apples"}], "s2", "u1", None, "")
34-
38+
3539
facts = await db.get_active_facts("u1")
3640
print("Active facts count:", len(facts))
37-
for f in facts: print("-", f["text"])
41+
for f in facts:
42+
print("-", f["text"])
3843

3944
asyncio.run(test())

test_llm_dedup_check.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import asyncio
2-
from vektori.storage.memory import MemoryBackend
2+
33
from vektori.ingestion.extractor import FactExtractor
4-
from vektori.models.base import LLMProvider, EmbeddingProvider
4+
from vektori.models.base import EmbeddingProvider, LLMProvider
5+
from vektori.storage.memory import MemoryBackend
6+
57

68
class MockEmbedder(EmbeddingProvider):
79
@property
8-
def dimension(self): return 2
10+
def dimension(self):
11+
return 2
12+
913
async def embed(self, text):
10-
if "hate" in text: return [0.5, 0.4] # Give sim around 0.8 to test LLM
14+
if "hate" in text:
15+
return [0.5, 0.4] # Give sim around 0.8 to test LLM
1116
return [0.5, 0.5]
1217
async def embed_batch(self, texts):
1318
return [await self.embed(t) for t in texts]
@@ -26,8 +31,8 @@ async def test():
2631
await db.initialize()
2732
embedder = MockEmbedder()
2833
llm = MockLLM()
29-
extractor = FactExtractor(db, embedder, llm)
30-
34+
_ = FactExtractor(db, embedder, llm)
35+
3136
# Needs actual logic in Extractor...
32-
37+
3338
asyncio.run(test())

test_synthesis.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import asyncio
2+
23
from vektori import Vektori
34

5+
46
async def test():
57
v = Vektori(storage_backend="memory")
68
await v._ensure_initialized()
@@ -11,15 +13,15 @@ async def mock_emb(*args, **kwargs):
1113
return [[0.1, 0.2]]
1214
v.llm.generate = mock_gen
1315
v.embedder.embed_batch = mock_emb
14-
16+
1517
# add dummy facts so synthesize triggers (needs >=5 base facts)
1618
for i in range(5):
1719
await v.db.insert_fact(f"fact {i}", [0.1, 0.2], "u1", confidence=1.0)
18-
20+
1921
n = await v.synthesize("u1")
2022
print("New synthesized facts:", n)
2123
syntheses = await v.db.search_syntheses([0.1, 0.2], "u1", limit=100)
2224
for s in syntheses:
2325
print("Synthesized:", s["text"])
24-
26+
2527
asyncio.run(test())

vektori/client.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ async def add(
164164
{"status": "ok", "sentences_stored": N, "extraction": "queued"|"done"|"skipped"}
165165
"""
166166
await self._ensure_initialized()
167-
167+
168168
result = await self._pipeline.ingest(
169169
messages, session_id, user_id, agent_id, metadata, session_time=session_time
170170
)
@@ -185,7 +185,7 @@ async def _bg_synthesize(uid: str, aid: str | None) -> None:
185185
await self.synthesize(user_id=uid, agent_id=aid)
186186
except Exception as e:
187187
logger.error("Auto-synthesis failed: %s", e)
188-
188+
189189
task = asyncio.create_task(_bg_synthesize(user_id, agent_id))
190190
self._bg_tasks.add(task)
191191
task.add_done_callback(self._bg_tasks.discard)
@@ -201,7 +201,7 @@ async def synthesize(self, user_id: str, agent_id: str | None = None) -> int:
201201
Run a cross-session synthesis pass for the user.
202202
Examines active facts across sessions to form aggregate/macro facts
203203
(e.g., "User consistently prefers X", "User has done Y across multiple sessions").
204-
204+
205205
Returns the number of new aggregate facts inserted.
206206
"""
207207
await self._ensure_initialized()

vektori/ingestion/synthesis.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
import json
21
import logging
3-
from datetime import datetime, timezone
4-
from typing import Any
52

6-
from vektori.models.base import LLMProvider, EmbeddingProvider
7-
from vektori.storage.base import StorageBackend
83
from vektori.ingestion.extractor import _parse_json_response
4+
from vektori.models.base import EmbeddingProvider, LLMProvider
5+
from vektori.storage.base import StorageBackend
96

107
logger = logging.getLogger(__name__)
118

@@ -45,17 +42,17 @@ def __init__(
4542
async def synthesize(self, user_id: str, agent_id: str | None = None) -> int:
4643
# Get active facts for the user
4744
facts = await self.db.get_active_facts(user_id=user_id, agent_id=agent_id, limit=300)
48-
45+
4946
# Filter out existing synthesis facts so we don't synthesize the syntheses too much,
5047
# or maybe we do want to? For now, let's keep it simple: filter them out to avoid feedback loops unless needed.
5148
# Actually, let's just feed them all, but maybe limit to non-synthesis for base patterns.
5249
base_facts = [f for f in facts if f.get("metadata", {}).get("source") != "synthesis"]
53-
50+
5451
if len(base_facts) < 5:
5552
return 0 # Not enough facts to form a pattern
56-
53+
5754
facts_list = "\n".join(f"- {f['text']} (Session: {f.get('session_id', 'unknown')}, Date: {f.get('created_at', 'unknown')})" for f in base_facts)
58-
55+
5956
prompt = SYNTHESIS_PROMPT.format(facts_list=facts_list, max_facts=5)
6057
try:
6158
response = await self.llm.generate(prompt, max_tokens=1000)
@@ -64,18 +61,18 @@ async def synthesize(self, user_id: str, agent_id: str | None = None) -> int:
6461
except Exception as e:
6562
logger.warning("Synthesis LLM call failed: %s", e)
6663
return 0
67-
64+
6865
if not new_facts:
6966
return 0
70-
67+
7168
texts = [f["text"] for f in new_facts]
7269
try:
7370
embeddings = await self.embedder.embed_batch(texts)
7471
except Exception as e:
7572
logger.error("Synthesis batch embed failed: %s", e)
7673
return 0
7774

78-
now = datetime.now(timezone.utc)
75+
7976
inserted = 0
8077

8178
for fact_dict, emb in zip(new_facts, embeddings):
@@ -86,22 +83,22 @@ async def synthesize(self, user_id: str, agent_id: str | None = None) -> int:
8683
agent_id=agent_id,
8784
limit=1
8885
)
89-
86+
9087
skip = False
9188
if existing:
9289
best = existing[0]
9390
sim = 1.0 - best.get("distance", 1.0)
9491
if sim > 0.85:
9592
# We already have this synthesis, let's just skip it
9693
skip = True
97-
94+
9895
if skip:
9996
continue
100-
97+
10198
try:
10299
# Need to link the synthesis to the facts that generated it if we want graph traversal
103100
# But for now we just insert it
104-
synthesis_id = await self.db.insert_synthesis(
101+
_ = await self.db.insert_synthesis(
105102
text=fact_dict["text"],
106103
embedding=emb,
107104
user_id=user_id,
@@ -111,5 +108,5 @@ async def synthesize(self, user_id: str, agent_id: str | None = None) -> int:
111108
inserted += 1
112109
except Exception as e:
113110
logger.warning("Failed to insert synthesis: %s", e)
114-
111+
115112
return inserted

vektori/storage/base.py

Lines changed: 3 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -198,48 +198,19 @@ async def insert_fact_sources(self, pairs: list[tuple[str, str]]) -> None:
198198

199199
# ── Syntheses ──
200200

201-
202-
async def insert_synthesis(self, text: str, embedding: list[float], user_id: str, agent_id: str | None = None, score: float = 1.0, mentions: int = 1, metadata: dict | None = None) -> str:
203-
raise NotImplementedError()
204-
205-
206-
async def insert_synthesis_fact(self, synthesis_id: str, fact_id: str) -> None:
207-
raise NotImplementedError()
208-
209-
210-
async def get_syntheses_for_facts(self, fact_ids: list[str]) -> list[dict[str, Any]]:
211-
return []
212-
213-
214-
async def search_syntheses(self, embedding: list[float], user_id: str, agent_id: str | None = None, limit: int = 10, threshold: float = 0.0) -> list[dict[str, Any]]:
215-
return []
216-
217-
@abstractmethod
218-
async def get_source_sentences(self, fact_ids: list[str]) -> list[str]:
219-
"""Return sentence IDs that are sources for the given facts (via fact_sources)."""
220-
...
221201

222-
@abstractmethod
223-
async def get_sentences_by_ids(self, sentence_ids: list[str]) -> list[dict[str, Any]]:
224-
"""Fetch full sentence rows for the given IDs."""
225-
...
226-
227-
228-
# ── Syntheses ──
229-
230-
231202
async def insert_synthesis(self, text: str, embedding: list[float], user_id: str, agent_id: str | None = None, score: float = 1.0, mentions: int = 1, metadata: dict | None = None) -> str:
232203
raise NotImplementedError()
233204

234-
205+
235206
async def insert_synthesis_fact(self, synthesis_id: str, fact_id: str) -> None:
236207
raise NotImplementedError()
237208

238-
209+
239210
async def get_syntheses_for_facts(self, fact_ids: list[str]) -> list[dict[str, Any]]:
240211
return []
241212

242-
213+
243214
async def search_syntheses(self, embedding: list[float], user_id: str, agent_id: str | None = None, limit: int = 10, threshold: float = 0.0) -> list[dict[str, Any]]:
244215
return []
245216

@@ -252,8 +223,6 @@ async def get_source_sentences(self, fact_ids: list[str]) -> list[str]:
252223
async def get_sentences_by_ids(self, sentence_ids: list[str]) -> list[dict[str, Any]]:
253224
"""Fetch full sentence rows for the given IDs."""
254225
...
255-
256-
257226
# ── Episodes ──
258227

259228
@abstractmethod
@@ -303,16 +272,6 @@ async def search_episodes(
303272
"""
304273
...
305274

306-
@abstractmethod
307-
async def get_source_sentences(self, fact_ids: list[str]) -> list[str]:
308-
"""Return sentence IDs that are sources for the given facts (via fact_sources)."""
309-
...
310-
311-
@abstractmethod
312-
async def get_sentences_by_ids(self, sentence_ids: list[str]) -> list[dict[str, Any]]:
313-
"""Fetch full sentence rows for the given IDs."""
314-
...
315-
316275
# ── Sessions ──
317276

318277
@abstractmethod

0 commit comments

Comments
 (0)