loopgate-research 0.2.1__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.
src/utils/ollama.py ADDED
@@ -0,0 +1,63 @@
1
+ """Minimal asynchronous client for non-streaming local Ollama chat requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+
11
+ @dataclass(slots=True)
12
+ class OllamaResponse:
13
+ """LangChain-shaped response fields consumed by the graph compiler."""
14
+
15
+ content: Any
16
+ usage_metadata: dict[str, int]
17
+
18
+
19
+ @dataclass(slots=True)
20
+ class OllamaChatClient:
21
+ """Call a local Ollama server without downloading or managing models."""
22
+
23
+ base_url: str
24
+ model: str
25
+ temperature: float
26
+ timeout: float
27
+ max_completion_tokens: int
28
+ transport: httpx.AsyncBaseTransport | None = None
29
+
30
+ async def ainvoke(self, prompt: str) -> OllamaResponse:
31
+ """Return one complete chat response with normalized token usage."""
32
+ async with httpx.AsyncClient(
33
+ timeout=self.timeout, transport=self.transport
34
+ ) as client:
35
+ response = await client.post(
36
+ f"{self.base_url.rstrip('/')}/api/chat",
37
+ json={
38
+ "model": self.model,
39
+ "messages": [{"role": "user", "content": prompt}],
40
+ "stream": False,
41
+ "options": {
42
+ "temperature": self.temperature,
43
+ "num_predict": self.max_completion_tokens,
44
+ },
45
+ },
46
+ )
47
+ response.raise_for_status()
48
+ payload = response.json()
49
+
50
+ message = payload.get("message") if isinstance(payload, dict) else None
51
+ content = message.get("content") if isinstance(message, dict) else None
52
+ usage: dict[str, int] = {}
53
+ if isinstance(payload, dict):
54
+ for name, source in (
55
+ ("input_tokens", "prompt_eval_count"),
56
+ ("output_tokens", "eval_count"),
57
+ ):
58
+ value = payload.get(source)
59
+ if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
60
+ usage[name] = value
61
+ if len(usage) == 2:
62
+ usage["total_tokens"] = usage["input_tokens"] + usage["output_tokens"]
63
+ return OllamaResponse(content=content, usage_metadata=usage)
src/utils/ranking.py ADDED
@@ -0,0 +1,52 @@
1
+ """Optional query-relevance ranking backed by a lazily imported PyTorch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from importlib import import_module
8
+ from typing import Any
9
+
10
+ _VECTOR_SIZE = 1_024
11
+ _TOKEN_PATTERN = re.compile(r"[a-z0-9]+")
12
+
13
+
14
+ def _token_index(token: str) -> int:
15
+ digest = hashlib.blake2b(token.encode("utf-8"), digest_size=8).digest()
16
+ return int.from_bytes(digest, "big") % _VECTOR_SIZE
17
+
18
+
19
+ def _hashed_vector(text: str) -> list[float]:
20
+ vector = [0.0] * _VECTOR_SIZE
21
+ for token in _TOKEN_PATTERN.findall(text.lower()):
22
+ vector[_token_index(token)] += 1.0
23
+ return vector
24
+
25
+
26
+ def rank_sources(
27
+ query: str, sources: list[dict[str, Any]]
28
+ ) -> list[dict[str, Any]]:
29
+ """Sort sources by cosine similarity to the query using local PyTorch tensors.
30
+
31
+ ImportError propagates to the caller so deployments without the optional extra
32
+ can retain provider ordering. Ties retain the original provider order.
33
+ """
34
+ if not sources:
35
+ return []
36
+
37
+ torch = import_module("torch")
38
+ query_vector = torch.tensor(_hashed_vector(query), dtype=torch.float32)
39
+ source_vectors = torch.tensor(
40
+ [
41
+ _hashed_vector(f"{item.get('title', '')} {item.get('content', '')}")
42
+ for item in sources
43
+ ],
44
+ dtype=torch.float32,
45
+ )
46
+ scores = torch.nn.functional.cosine_similarity(
47
+ query_vector.unsqueeze(0), source_vectors, dim=1
48
+ ).tolist()
49
+ ordered = sorted(
50
+ enumerate(sources), key=lambda item: (-scores[item[0]], item[0])
51
+ )
52
+ return [source for _, source in ordered]
src/utils/telegram.py ADDED
@@ -0,0 +1,158 @@
1
+ """Minimal async Telegram Bot API client for approval prompts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ from src.config import Settings
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ TELEGRAM_API_BASE = "https://api.telegram.org"
15
+ MAX_MESSAGE_LENGTH = 4_096
16
+ MAX_CALLBACK_DATA_BYTES = 64
17
+
18
+
19
+ def _truncate(text: str, limit: int) -> str:
20
+ if len(text) <= limit:
21
+ return text
22
+ return text[: max(0, limit - 3)].rstrip() + "..."
23
+
24
+
25
+ def _split_text(text: str, limit: int) -> list[str]:
26
+ """Split without dropping text, preferring newline boundaries."""
27
+ if not text:
28
+ return [""]
29
+ parts: list[str] = []
30
+ remaining = text
31
+ while len(remaining) > limit:
32
+ newline = remaining.rfind("\n", 0, limit + 1)
33
+ split_at = newline + 1 if newline >= limit // 2 else limit
34
+ parts.append(remaining[:split_at])
35
+ remaining = remaining[split_at:]
36
+ parts.append(remaining)
37
+ return parts
38
+
39
+
40
+ class TelegramClient:
41
+ """Small wrapper around the Telegram Bot API.
42
+
43
+ Delivery failures are logged and reported via ``False`` rather than raised:
44
+ a Telegram outage must never crash the pipeline.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ *,
50
+ bot_token: str | None = None,
51
+ chat_id: str | None = None,
52
+ timeout: float = 15.0,
53
+ transport: httpx.AsyncBaseTransport | None = None,
54
+ ) -> None:
55
+ self.bot_token = bot_token
56
+ self.chat_id = chat_id
57
+ self.timeout = timeout
58
+ self._transport = transport
59
+
60
+ @classmethod
61
+ def from_settings(cls, settings: Settings) -> "TelegramClient":
62
+ return cls(
63
+ bot_token=settings.telegram_bot_token,
64
+ chat_id=settings.telegram_chat_id,
65
+ )
66
+
67
+ @property
68
+ def enabled(self) -> bool:
69
+ return bool(self.bot_token and self.chat_id)
70
+
71
+ async def send_digest(self, *, thread_id: str, topic: str, digest: str) -> bool:
72
+ """Send the complete digest, with approval buttons on the final part."""
73
+ if not self.enabled:
74
+ logger.info("Telegram is not configured; skipping digest delivery.")
75
+ return False
76
+
77
+ approve = f"approve:{thread_id}"
78
+ reject = f"reject:{thread_id}"
79
+ if max(len(approve), len(reject)) > MAX_CALLBACK_DATA_BYTES:
80
+ logger.error("thread_id %r is too long for Telegram callback_data", thread_id)
81
+ return False
82
+
83
+ body = digest.strip() or "(The compiler did not produce a digest.)"
84
+ text = (
85
+ "📊 loopgate research digest\n"
86
+ f"Topic: {topic}\n"
87
+ f"Thread: {thread_id}\n\n"
88
+ f"{body}"
89
+ )
90
+
91
+ reply_markup = {
92
+ "inline_keyboard": [
93
+ [{"text": "✅ Approve", "callback_data": approve}],
94
+ [{"text": "❌ Reject", "callback_data": reject}],
95
+ ]
96
+ }
97
+ parts = _split_text(text, MAX_MESSAGE_LENGTH)
98
+ for index, part in enumerate(parts):
99
+ delivered = await self.send_message(
100
+ part,
101
+ reply_markup=reply_markup if index == len(parts) - 1 else None,
102
+ )
103
+ if not delivered:
104
+ return False
105
+ return True
106
+
107
+ async def send_message(
108
+ self,
109
+ text: str,
110
+ *,
111
+ chat_id: str | None = None,
112
+ reply_markup: dict[str, Any] | None = None,
113
+ ) -> bool:
114
+ if not self.enabled:
115
+ logger.info("Telegram is not configured; skipping message delivery.")
116
+ return False
117
+
118
+ payload: dict[str, Any] = {
119
+ "chat_id": chat_id or self.chat_id,
120
+ "text": _truncate(text, MAX_MESSAGE_LENGTH),
121
+ "disable_web_page_preview": True,
122
+ }
123
+ if reply_markup is not None:
124
+ payload["reply_markup"] = reply_markup
125
+
126
+ return await self._post("sendMessage", payload)
127
+
128
+ async def answer_callback_query(
129
+ self, callback_query_id: str, *, text: str | None = None
130
+ ) -> bool:
131
+ """Stop the Telegram client-side loading spinner for a button press."""
132
+ if not self.enabled or not callback_query_id:
133
+ return False
134
+ payload: dict[str, Any] = {"callback_query_id": callback_query_id}
135
+ if text:
136
+ payload["text"] = _truncate(text, 200)
137
+ return await self._post("answerCallbackQuery", payload)
138
+
139
+ async def _post(self, method: str, payload: dict[str, Any]) -> bool:
140
+ assert self.bot_token # guarded by ``enabled``
141
+ url = f"{TELEGRAM_API_BASE}/bot{self.bot_token}/{method}"
142
+ try:
143
+ async with httpx.AsyncClient(
144
+ timeout=self.timeout, transport=self._transport
145
+ ) as client:
146
+ response = await client.post(url, json=payload)
147
+ if response.status_code >= 400:
148
+ logger.error(
149
+ "Telegram %s failed (%s): %s",
150
+ method,
151
+ response.status_code,
152
+ response.text[:500],
153
+ )
154
+ return False
155
+ return True
156
+ except httpx.HTTPError:
157
+ logger.exception("Telegram %s request failed", method)
158
+ return False