|
| 1 | +"""Turso client for slack thread search.""" |
| 2 | + |
| 3 | +import os |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +import httpx |
| 7 | + |
| 8 | +TURSO_URL = os.environ.get("TURSO_URL", "") |
| 9 | +TURSO_TOKEN = os.environ.get("TURSO_TOKEN", "") |
| 10 | +VOYAGE_API_KEY = os.environ.get("VOYAGE_API_KEY", "") |
| 11 | + |
| 12 | + |
| 13 | +def _get_turso_host() -> str: |
| 14 | + """Strip libsql:// prefix if present.""" |
| 15 | + url = TURSO_URL |
| 16 | + if url.startswith("libsql://"): |
| 17 | + url = url[len("libsql://") :] |
| 18 | + return url |
| 19 | + |
| 20 | + |
| 21 | +async def turso_query(sql: str, args: list | None = None) -> list[dict[str, Any]]: |
| 22 | + """Execute a query against Turso and return rows.""" |
| 23 | + if not TURSO_URL or not TURSO_TOKEN: |
| 24 | + raise RuntimeError("TURSO_URL and TURSO_TOKEN must be set") |
| 25 | + |
| 26 | + stmt: dict[str, Any] = {"sql": sql} |
| 27 | + if args: |
| 28 | + stmt["args"] = [{"type": "text", "value": str(a)} for a in args] |
| 29 | + |
| 30 | + async with httpx.AsyncClient() as client: |
| 31 | + response = await client.post( |
| 32 | + f"https://{_get_turso_host()}/v2/pipeline", |
| 33 | + headers={ |
| 34 | + "Authorization": f"Bearer {TURSO_TOKEN}", |
| 35 | + "Content-Type": "application/json", |
| 36 | + }, |
| 37 | + json={"requests": [{"type": "execute", "stmt": stmt}, {"type": "close"}]}, |
| 38 | + timeout=30, |
| 39 | + ) |
| 40 | + response.raise_for_status() |
| 41 | + data = response.json() |
| 42 | + |
| 43 | + result = data["results"][0] |
| 44 | + if result["type"] == "error": |
| 45 | + raise Exception(f"Turso error: {result['error']}") |
| 46 | + |
| 47 | + cols = [c["name"] for c in result["response"]["result"]["cols"]] |
| 48 | + rows = result["response"]["result"]["rows"] |
| 49 | + |
| 50 | + def extract_value(cell: Any) -> Any: |
| 51 | + if cell is None: |
| 52 | + return None |
| 53 | + if isinstance(cell, dict): |
| 54 | + return cell.get("value") |
| 55 | + return cell |
| 56 | + |
| 57 | + return [dict(zip(cols, [extract_value(cell) for cell in row])) for row in rows] |
| 58 | + |
| 59 | + |
| 60 | +async def voyage_embed(text: str) -> list[float]: |
| 61 | + """Generate embedding for a query using Voyage AI.""" |
| 62 | + if not VOYAGE_API_KEY: |
| 63 | + raise RuntimeError("VOYAGE_API_KEY must be set for semantic search") |
| 64 | + |
| 65 | + async with httpx.AsyncClient() as client: |
| 66 | + response = await client.post( |
| 67 | + "https://api.voyageai.com/v1/embeddings", |
| 68 | + headers={ |
| 69 | + "Authorization": f"Bearer {VOYAGE_API_KEY}", |
| 70 | + "Content-Type": "application/json", |
| 71 | + }, |
| 72 | + json={ |
| 73 | + "input": [text], |
| 74 | + "model": "voyage-3-lite", |
| 75 | + "input_type": "query", |
| 76 | + }, |
| 77 | + timeout=30, |
| 78 | + ) |
| 79 | + response.raise_for_status() |
| 80 | + data = response.json() |
| 81 | + |
| 82 | + return data["data"][0]["embedding"] |
0 commit comments