Skip to content

Commit eab4abd

Browse files
authored
Merge pull request #346 from Tanzania-AI-Community/main
sync development with main
2 parents 4acdef7 + c36d897 commit eab4abd

17 files changed

Lines changed: 1261 additions & 206 deletions

‎.env.template‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,14 @@ LLM_MODEL_NAME=
1010

1111
# API Key for the Embedding provider (either OpenAI or Together AI)
1212
EMBEDDING_API_KEY=
13-
# Choose your Embedding provider: together / openai / ollama
13+
# Choose your Embedding provider: google / together / openai / ollama
1414
EMBEDDING_PROVIDER=
15+
# For Google Vertex AI, set provider=google and model=gemini-embedding-001.
16+
# ADC authentication; EMBEDDING_API_KEY is not used for Google.
17+
EMBEDDING_MODEL=
18+
EMBEDDING_DIMENSIONS=1024
19+
GOOGLE_CLOUD_PROJECT=
20+
GOOGLE_CLOUD_LOCATION=global
1521

1622
# Enable Agentic Mode (True/False)
1723
AGENTIC_MODE_ENABLED=

‎.env.template.simple‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,14 @@ LLM_MODEL_NAME=
99

1010
# API Key for the Embedding provider (either OpenAI or Together AI)
1111
EMBEDDING_API_KEY=
12-
# Choose your Embedding provider: together / openai / ollama
12+
# Choose your Embedding provider: google / together / openai / ollama
1313
EMBEDDING_PROVIDER=
14+
# For Google Vertex AI, set provider=google and model=gemini-embedding-001.
15+
# ADC authentication; EMBEDDING_API_KEY is not used for Google.
16+
EMBEDDING_MODEL=
17+
EMBEDDING_DIMENSIONS=1024
18+
GOOGLE_CLOUD_PROJECT=
19+
GOOGLE_CLOUD_LOCATION=global
1420

1521
# Postgres database URL
1622
DATABASE_USER=

‎app/config.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class LLMProvider(str, Enum):
3535

3636

3737
class EmbeddingProvider(str, Enum):
38+
GOOGLE = "google"
3839
TOGETHER = BaseProviders.TOGETHER.value
3940
OPENAI = BaseProviders.OPENAI.value
4041
OLLAMA = BaseProviders.OLLAMA.value
@@ -194,6 +195,9 @@ class EmbeddingSettings(BaseSettings):
194195
default=yaml_config["embedding"]["model_name"],
195196
validation_alias="embedding_model",
196197
)
198+
dimensions: int = Field(default=1024, validation_alias="embedding_dimensions")
199+
google_cloud_project: Optional[str] = None
200+
google_cloud_location: str = "global"
197201

198202
ollama_model: Optional[str] = Field(
199203
default=yaml_config["embedding"]["ollama"]["model_name"],

‎app/database/db.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
import logging
23
from datetime import datetime, timedelta, timezone
34

@@ -325,7 +326,7 @@ async def create_new_message_by_fields(
325326

326327
async def vector_search(query: str, n_results: int, where: dict) -> list[Chunk]:
327328
try:
328-
query_vector = embedder.get_embedding(query)
329+
query_vector = await asyncio.to_thread(embedder.get_embedding, query)
329330
except Exception as e:
330331
logger.error(f"Failed to get embedding for query {query}: {str(e)}")
331332
raise Exception(f"Failed to get embedding for query: {str(e)}")

‎app/utils/embedder.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
from functools import lru_cache
23

34
import requests
45
from langchain_openai import OpenAIEmbeddings
@@ -51,9 +52,19 @@ def embed_documents(self, texts: list[str]) -> list[list[float]]:
5152
return [self._request_embedding(text) for text in texts]
5253

5354

55+
@lru_cache(maxsize=1)
5456
def get_embedding_client():
5557
"""Get the appropriate LangChain embedding client."""
56-
if embedding_settings.provider == EmbeddingProvider.OPENAI:
58+
if embedding_settings.provider == EmbeddingProvider.GOOGLE:
59+
from app.utils.google_embedder import GoogleEmbeddingClient
60+
61+
return GoogleEmbeddingClient(
62+
project=embedding_settings.google_cloud_project,
63+
location=embedding_settings.google_cloud_location,
64+
model=embedding_settings.embedder_name,
65+
dimensions=embedding_settings.dimensions,
66+
)
67+
elif embedding_settings.provider == EmbeddingProvider.OPENAI:
5768
if not embedding_settings.api_key:
5869
raise ValueError("OpenAI embeddings require EMBEDDING_API_KEY to be set.")
5970
return OpenAIEmbeddings(

‎app/utils/google_embedder.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"""Vertex AI embeddings, shared by retrieval and the re-embedding scripts."""
2+
3+
import math
4+
from concurrent.futures import ThreadPoolExecutor
5+
from typing import Sequence
6+
7+
from google import genai
8+
from google.genai import types
9+
10+
DEFAULT_MODEL = "gemini-embedding-001"
11+
DEFAULT_DIMENSIONS = 1024
12+
DOCUMENT_MAX_BYTES = 2048
13+
14+
15+
def validate_embedding(values: list[float], dimensions: int) -> list[float]:
16+
if len(values) != dimensions or not all(math.isfinite(v) for v in values):
17+
raise ValueError(f"Expected {dimensions} finite embedding values.")
18+
if not any(values):
19+
raise ValueError("Embedding must not be a zero vector.")
20+
return values
21+
22+
23+
class GoogleEmbeddingClient:
24+
provider = "google"
25+
document_max_bytes = DOCUMENT_MAX_BYTES
26+
27+
def __init__(
28+
self,
29+
project: str,
30+
location: str = "global",
31+
model: str = DEFAULT_MODEL,
32+
dimensions: int = DEFAULT_DIMENSIONS,
33+
timeout_seconds: int = 60,
34+
max_workers: int = 4,
35+
):
36+
if not project or not project.strip():
37+
raise ValueError(
38+
"GOOGLE_CLOUD_PROJECT is required for Vertex AI embeddings."
39+
)
40+
if dimensions != DEFAULT_DIMENSIONS:
41+
raise ValueError("Twiga's database requires EMBEDDING_DIMENSIONS=1024.")
42+
if max_workers < 1 or timeout_seconds < 1:
43+
raise ValueError("Embedding workers and timeout must be positive.")
44+
self.model = model
45+
self.dimensions = dimensions
46+
self.max_workers = max_workers
47+
# Explicit Vertex configuration avoids changing the Google chat provider.
48+
# Credentials are resolved via ADC, never via EMBEDDING_API_KEY.
49+
self.client = genai.Client(
50+
vertexai=True,
51+
project=project,
52+
location=location,
53+
http_options=types.HttpOptions(
54+
api_version="v1",
55+
timeout=timeout_seconds * 1000,
56+
retry_options=types.HttpRetryOptions(
57+
attempts=5,
58+
initial_delay=1,
59+
max_delay=20,
60+
http_status_codes=[429, 500, 502, 503, 504],
61+
),
62+
),
63+
)
64+
65+
def _embed(self, texts: list[str], task_type: str) -> list[list[float]]:
66+
if any(not text.strip() for text in texts):
67+
raise ValueError("Cannot embed empty text.")
68+
response = self.client.models.embed_content(
69+
model=self.model,
70+
contents=texts,
71+
config=types.EmbedContentConfig(
72+
task_type=task_type,
73+
output_dimensionality=self.dimensions,
74+
auto_truncate=False,
75+
),
76+
)
77+
if not response.embeddings or len(response.embeddings) != len(texts):
78+
raise ValueError("Google must return exactly one embedding per input.")
79+
vectors = []
80+
for embedding in response.embeddings:
81+
if embedding.statistics and embedding.statistics.truncated:
82+
raise ValueError("Google truncated the embedding input.")
83+
vectors.append(validate_embedding(embedding.values or [], self.dimensions))
84+
return vectors
85+
86+
def embed_query(self, text: str) -> list[float]:
87+
return self._embed([text], "RETRIEVAL_QUERY")[0]
88+
89+
def embed_documents(self, texts: Sequence[str]) -> list[list[float]]:
90+
# Small batches bound request size; map preserves order across concurrent calls.
91+
# Verified against gemini-embedding-001 on Vertex's global endpoint.
92+
# Preserve stored content; only the document embedding input is bounded.
93+
# UTF-8 bytes are a conservative bound, unlike a different model's tokenizer.
94+
prepared = [
95+
text.encode("utf-8")[: self.document_max_bytes].decode(
96+
"utf-8", errors="ignore"
97+
)
98+
for text in texts
99+
]
100+
batches = [prepared[start : start + 8] for start in range(0, len(prepared), 8)]
101+
with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
102+
results = executor.map(self._embed_documents_batch, batches)
103+
return [vector for batch in results for vector in batch]
104+
105+
def _embed_documents_batch(self, texts: list[str]) -> list[list[float]]:
106+
return self._embed(texts, "RETRIEVAL_DOCUMENT")
107+
108+
def close(self) -> None:
109+
self.client.close()

‎pyproject.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ dependencies = [
4444
"Pillow>=11.0.0",
4545
"reportlab>=4.4.10",
4646
"requests>=2.32.3",
47+
"google-genai>=1.30,<2",
48+
# google-genai requires httpx >=0.28; older OpenAI clients pass removed proxies arguments.
49+
"openai>=1.55.3,<2",
4750
]
4851

4952
[build-system]
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
"""Validate staged embeddings and optionally apply them with an atomic backup.
2+
3+
Retrieval must be paused and the query provider coordinated before --apply.
4+
Validation is read-only by default. No Google credentials or API calls are needed.
5+
"""
6+
7+
import argparse
8+
import asyncio
9+
import json
10+
from pathlib import Path
11+
12+
from sqlalchemy import text
13+
from sqlalchemy.ext.asyncio import create_async_engine
14+
15+
from app.utils.google_embedder import DOCUMENT_MAX_BYTES
16+
from scripts.database.reembed_chunks_in_db import (
17+
_quote_identifier,
18+
normalize_database_url,
19+
rewrite_container_hostname,
20+
validate_table_name,
21+
)
22+
from scripts.database.reembedding_utils import project_root, read_env_value
23+
24+
25+
async def promote_embeddings(
26+
database_url: str,
27+
target_table: str,
28+
*,
29+
source_table: str = "chunks",
30+
backup_table: str = "chunks_embeddings_before_google",
31+
model: str = "gemini-embedding-001",
32+
apply: bool = False,
33+
) -> int:
34+
names = [source_table, target_table, backup_table]
35+
if len(set(names)) != 3:
36+
raise ValueError("Source, staging and backup tables must be different.")
37+
source, target, backup = [
38+
_quote_identifier(validate_table_name(name)) for name in names
39+
]
40+
engine = create_async_engine(
41+
normalize_database_url(rewrite_container_hostname(database_url))
42+
)
43+
try:
44+
async with engine.begin() as conn:
45+
if apply:
46+
locked = (
47+
await conn.execute(
48+
text("SELECT pg_try_advisory_xact_lock(hashtext(:name))"),
49+
{"name": target_table},
50+
)
51+
).scalar_one()
52+
if not locked:
53+
raise ValueError("A migration is still using this staging table.")
54+
await conn.execute(text("SET LOCAL lock_timeout = '10s'"))
55+
# Block ingestion/staging writes until validation, backup and update commit.
56+
await conn.execute(
57+
text(f"LOCK TABLE {source}, {target} IN SHARE ROW EXCLUSIVE MODE")
58+
)
59+
else:
60+
await conn.execute(
61+
text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
62+
)
63+
comment = (
64+
await conn.execute(
65+
text("SELECT obj_description(to_regclass(:name), 'pg_class')"),
66+
{"name": target},
67+
)
68+
).scalar_one()
69+
manifest = json.loads(comment or "null")
70+
expected = {
71+
"migration": "twiga-reembedding-v1",
72+
"source": source_table,
73+
"provider": "google",
74+
"model": model,
75+
"dimensions": 1024,
76+
"task_type": "RETRIEVAL_DOCUMENT",
77+
"document_max_bytes": DOCUMENT_MAX_BYTES,
78+
"max_token_estimate": None,
79+
}
80+
if not isinstance(manifest, dict) or any(
81+
manifest.get(k) != v for k, v in expected.items()
82+
):
83+
raise ValueError(
84+
"Staging manifest does not match the requested Google embedding configuration."
85+
)
86+
count = (
87+
await conn.execute(text(f"SELECT count(*) FROM {source}"))
88+
).scalar_one()
89+
if not count:
90+
raise ValueError("Refusing to promote an empty corpus.")
91+
mismatches = (
92+
await conn.execute(
93+
text(
94+
f"""
95+
SELECT count(*) FROM {source} s FULL JOIN {target} t USING (id)
96+
WHERE s.id IS NULL OR t.id IS NULL
97+
OR (to_jsonb(s) - 'embedding') IS DISTINCT FROM (to_jsonb(t) - 'embedding')
98+
OR t.embedding IS NULL OR vector_dims(t.embedding) <> 1024
99+
OR (t.embedding <#> t.embedding) >= 0
100+
"""
101+
)
102+
)
103+
).scalar_one()
104+
if mismatches:
105+
raise ValueError(
106+
f"{mismatches} chunks are missing, changed or have invalid/incomplete embeddings."
107+
)
108+
if apply:
109+
# CREATE (without IF NOT EXISTS) prevents overwriting an earlier backup.
110+
await conn.execute(
111+
text(f"CREATE TABLE {backup} AS SELECT id, embedding FROM {source}")
112+
)
113+
await conn.execute(text(f"ALTER TABLE {backup} ADD PRIMARY KEY (id)"))
114+
result = await conn.execute(
115+
text(
116+
f"UPDATE {source} s SET embedding = t.embedding FROM {target} t WHERE s.id = t.id"
117+
)
118+
)
119+
if result.rowcount != count:
120+
raise ValueError(
121+
"Updated row count does not match the validated corpus."
122+
)
123+
return count
124+
finally:
125+
await engine.dispose()
126+
127+
128+
def main() -> None:
129+
parser = argparse.ArgumentParser(description=__doc__)
130+
parser.add_argument("--env-file", type=Path, default=project_root() / ".env")
131+
parser.add_argument("--target-table-name", default="chunks_tmp_reembed")
132+
parser.add_argument("--source-table-name", default="chunks")
133+
parser.add_argument(
134+
"--backup-table-name", default="chunks_embeddings_before_google"
135+
)
136+
parser.add_argument("--model", default="gemini-embedding-001")
137+
parser.add_argument(
138+
"--apply",
139+
action="store_true",
140+
help="Apply validated vectors and save old vectors. Requires coordinated retrieval downtime.",
141+
)
142+
args = parser.parse_args()
143+
database_url = read_env_value("DATABASE_URL", env_file=args.env_file)
144+
if not database_url:
145+
raise ValueError("DATABASE_URL is required.")
146+
count = asyncio.run(
147+
promote_embeddings(
148+
database_url,
149+
args.target_table_name,
150+
source_table=args.source_table_name,
151+
backup_table=args.backup_table_name,
152+
model=args.model,
153+
apply=args.apply,
154+
)
155+
)
156+
print(
157+
f"{'Applied and backed up' if args.apply else 'Validated'} {count} chunk embeddings."
158+
)
159+
160+
161+
if __name__ == "__main__":
162+
main()

0 commit comments

Comments
 (0)