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/api/main.py ADDED
@@ -0,0 +1,429 @@
1
+ """FastAPI gateway for starting runs and resuming them from Telegram."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import secrets
8
+ from contextlib import asynccontextmanager
9
+ from dataclasses import dataclass
10
+ from typing import Any, Literal
11
+ from uuid import uuid4
12
+
13
+ from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, Request, Response
14
+ from pydantic import BaseModel, Field, field_validator
15
+
16
+ from src.config import Settings, get_settings
17
+ from src.pipeline import (
18
+ PipelineConflict,
19
+ PipelineNotFound,
20
+ PipelineNotAwaitingApproval,
21
+ PipelineRunner,
22
+ PipelineStatus,
23
+ )
24
+ from src.utils.telegram import TelegramClient
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ _APPROVE_ALIASES = {"approve", "approved"}
29
+ _REJECT_ALIASES = {"reject", "rejected"}
30
+
31
+
32
+ class ResearchRequest(BaseModel):
33
+ topic: str = Field(min_length=3, max_length=500)
34
+ thread_id: str | None = Field(
35
+ default=None,
36
+ min_length=1,
37
+ max_length=48,
38
+ pattern=r"^[A-Za-z0-9_-]+$",
39
+ )
40
+
41
+ @field_validator("topic")
42
+ @classmethod
43
+ def normalize_topic(cls, value: str) -> str:
44
+ normalized = value.strip()
45
+ if len(normalized) < 3:
46
+ raise ValueError("topic must contain at least 3 non-whitespace characters")
47
+ return normalized
48
+
49
+
50
+ @dataclass(slots=True)
51
+ class WebhookAction:
52
+ action: Literal["approve", "reject"]
53
+ thread_id: str
54
+ callback_query_id: str | None = None
55
+
56
+
57
+ def parse_webhook_update(update: dict[str, Any]) -> WebhookAction | None:
58
+ """Extract an approval action from a Telegram update or a dev payload."""
59
+ callback_query = update.get("callback_query")
60
+ if isinstance(callback_query, dict):
61
+ raw_data = str(callback_query.get("data") or "")
62
+ action, separator, thread_id = raw_data.partition(":")
63
+ if not separator or not thread_id:
64
+ return None
65
+ normalized = _normalize_action(action)
66
+ if normalized is None:
67
+ return None
68
+ callback_id = callback_query.get("id")
69
+ return WebhookAction(
70
+ action=normalized,
71
+ thread_id=thread_id,
72
+ callback_query_id=str(callback_id) if callback_id else None,
73
+ )
74
+
75
+ # Convenience payload for local testing / non-Telegram callers.
76
+ thread_id = update.get("thread_id")
77
+ normalized = _normalize_action(update.get("action"))
78
+ if not thread_id or normalized is None:
79
+ return None
80
+ return WebhookAction(action=normalized, thread_id=str(thread_id))
81
+
82
+
83
+ def _normalize_action(value: Any) -> Literal["approve", "reject"] | None:
84
+ if not isinstance(value, str):
85
+ return None
86
+ normalized = value.strip().lower()
87
+ if normalized in _APPROVE_ALIASES:
88
+ return "approve"
89
+ if normalized in _REJECT_ALIASES:
90
+ return "reject"
91
+ return None
92
+
93
+
94
+ def _is_valid_secret(request: Request, settings: Settings) -> bool:
95
+ expected = settings.telegram_webhook_secret
96
+ if not expected:
97
+ return True
98
+ supplied = request.headers.get("x-telegram-bot-api-secret-token", "")
99
+ return secrets.compare_digest(supplied, expected)
100
+
101
+
102
+ def _is_valid_api_key(request: Request, settings: Settings) -> bool:
103
+ if not settings.api_key:
104
+ return True
105
+ supplied = request.headers.get("x-api-key", "")
106
+ return secrets.compare_digest(supplied, settings.api_key)
107
+
108
+
109
+ def _is_authorized_telegram_chat(update: dict[str, Any], settings: Settings) -> bool:
110
+ expected = settings.telegram_chat_id
111
+ if not expected:
112
+ return True
113
+ callback = update.get("callback_query")
114
+ message = callback.get("message") if isinstance(callback, dict) else None
115
+ chat = message.get("chat") if isinstance(message, dict) else None
116
+ supplied = str(chat.get("id") or "") if isinstance(chat, dict) else ""
117
+ return bool(supplied) and secrets.compare_digest(supplied, expected)
118
+
119
+
120
+ def _validate_security_settings(settings: Settings) -> None:
121
+ if not settings.is_production:
122
+ return
123
+ missing = [
124
+ name
125
+ for name, value in (
126
+ ("LOOPGATE_API_KEY", settings.api_key),
127
+ ("TELEGRAM_WEBHOOK_SECRET", settings.telegram_webhook_secret),
128
+ )
129
+ if not value
130
+ ]
131
+ if missing:
132
+ raise ValueError(
133
+ "Production security configuration is incomplete: set "
134
+ + ", ".join(missing)
135
+ )
136
+
137
+
138
+ def create_app(
139
+ *,
140
+ runner: PipelineRunner | None = None,
141
+ telegram: TelegramClient | None = None,
142
+ settings: Settings | None = None,
143
+ ) -> FastAPI:
144
+ """Application factory so tests can inject fake collaborators."""
145
+ settings = settings or get_settings()
146
+ _validate_security_settings(settings)
147
+ telegram = telegram or TelegramClient.from_settings(settings)
148
+
149
+ if not settings.telegram_webhook_secret:
150
+ logger.warning(
151
+ "TELEGRAM_WEBHOOK_SECRET is not set; the webhook accepts unsigned calls."
152
+ )
153
+
154
+ async def _run_research(thread_id: str, topic: str) -> None:
155
+ try:
156
+ status = await app.state.runner.start(topic, thread_id=thread_id)
157
+ except PipelineConflict:
158
+ app.state.submissions.pop(thread_id, None)
159
+ logger.warning("Research thread already exists: %s", thread_id)
160
+ return
161
+ except Exception:
162
+ submission = app.state.submissions.get(thread_id)
163
+ if submission is not None:
164
+ submission.update(
165
+ status="failed",
166
+ next=[],
167
+ error="Research failed before a checkpoint was created.",
168
+ )
169
+ logger.exception("Research run failed for thread %s", thread_id)
170
+ return
171
+
172
+ app.state.submissions.pop(thread_id, None)
173
+ if status.values.get("error") or not status.is_pending:
174
+ logger.warning(
175
+ "Thread %s stopped before the review gate: %s",
176
+ thread_id,
177
+ status.values.get("error"),
178
+ )
179
+ return
180
+ if not status.digest:
181
+ logger.warning("Thread %s has no digest to review", thread_id)
182
+ return
183
+
184
+ delivered = await telegram.send_digest(
185
+ thread_id=thread_id,
186
+ topic=str(status.values.get("topic") or topic),
187
+ digest=status.digest,
188
+ )
189
+ if not delivered:
190
+ logger.warning("Digest for thread %s was not delivered to Telegram", thread_id)
191
+
192
+ async def _apply_decision(action: WebhookAction) -> dict[str, Any]:
193
+ try:
194
+ status = await app.state.runner.resume(action.thread_id, action.action)
195
+ except PipelineNotFound:
196
+ return {
197
+ "ok": True,
198
+ "handled": False,
199
+ "error": "unknown_thread",
200
+ "thread_id": action.thread_id,
201
+ }
202
+ except PipelineNotAwaitingApproval:
203
+ return {
204
+ "ok": True,
205
+ "handled": False,
206
+ "error": "not_awaiting_approval",
207
+ "thread_id": action.thread_id,
208
+ }
209
+ except Exception:
210
+ logger.exception("Failed to resume thread %s", action.thread_id)
211
+ return {
212
+ "ok": False,
213
+ "handled": False,
214
+ "error": "resume_failed",
215
+ "thread_id": action.thread_id,
216
+ }
217
+
218
+ return {
219
+ "ok": True,
220
+ "handled": True,
221
+ "thread_id": action.thread_id,
222
+ "action": action.action,
223
+ "status": status.to_dict(include_digest=False, include_messages=False),
224
+ }
225
+
226
+ @asynccontextmanager
227
+ async def lifespan(_: FastAPI):
228
+ app.state.submission_lock = asyncio.Lock()
229
+ # Built here, inside a running loop, so LOOPGATE_CHECKPOINT_DB can select
230
+ # the durable AsyncSqliteSaver (which requires an event loop at init).
231
+ built_here = app.state.runner is None
232
+ if built_here:
233
+ app.state.runner = PipelineRunner()
234
+ logger.info(
235
+ "loopgate API ready (telegram=%s, webhook_secret=%s, checkpoints=%s)",
236
+ "enabled" if telegram.enabled else "disabled",
237
+ "set" if settings.telegram_webhook_secret else "unset",
238
+ settings.checkpoint_db or "in-memory",
239
+ )
240
+ yield
241
+ if built_here:
242
+ await app.state.runner.aclose()
243
+
244
+ app = FastAPI(
245
+ title="loopgate API Gateway",
246
+ description=(
247
+ "Stateful research pipeline with a LangGraph interrupt gate and "
248
+ "Telegram webhook approvals."
249
+ ),
250
+ version="0.2.1",
251
+ lifespan=lifespan,
252
+ )
253
+ app.state.settings = settings
254
+ app.state.runner = runner
255
+ app.state.telegram = telegram
256
+ app.state.submissions = {}
257
+
258
+ @app.get("/")
259
+ async def root() -> dict[str, Any]:
260
+ return {
261
+ "service": "loopgate",
262
+ "endpoints": [
263
+ "/health",
264
+ "/health/ready",
265
+ "/research",
266
+ "/research/{thread_id}",
267
+ "/webhook/telegram",
268
+ ],
269
+ }
270
+
271
+ @app.get("/health")
272
+ async def health_check() -> dict[str, Any]:
273
+ return {
274
+ "status": "operational",
275
+ "service": "loopgate-backend",
276
+ "telegram_enabled": telegram.enabled,
277
+ }
278
+
279
+ @app.get("/health/ready")
280
+ async def readiness_check(response: Response) -> dict[str, Any]:
281
+ ready = bool(settings.tavily_api_key)
282
+ response.status_code = 200 if ready else 503
283
+ return {
284
+ "status": "ready" if ready else "unavailable",
285
+ "service": "loopgate-backend",
286
+ "tavily_configured": ready,
287
+ "telegram_enabled": telegram.enabled,
288
+ }
289
+
290
+ @app.post("/research", status_code=202)
291
+ async def start_research(
292
+ payload: ResearchRequest, background_tasks: BackgroundTasks, request: Request
293
+ ) -> dict[str, Any]:
294
+ if not _is_valid_api_key(request, settings):
295
+ raise HTTPException(status_code=401, detail="Invalid API key")
296
+
297
+ if not settings.tavily_api_key:
298
+ raise HTTPException(
299
+ status_code=503, detail="TAVILY_API_KEY is not configured"
300
+ )
301
+
302
+ thread_id = payload.thread_id or uuid4().hex
303
+ async with app.state.submission_lock:
304
+ if thread_id in app.state.submissions:
305
+ raise HTTPException(
306
+ status_code=409, detail=f"Thread already exists: {thread_id}"
307
+ )
308
+ try:
309
+ await app.state.runner.status(thread_id)
310
+ except PipelineNotFound:
311
+ pass
312
+ else:
313
+ raise HTTPException(
314
+ status_code=409, detail=f"Thread already exists: {thread_id}"
315
+ )
316
+
317
+ app.state.submissions[thread_id] = {
318
+ "thread_id": thread_id,
319
+ "status": "running",
320
+ "approval_status": "pending",
321
+ "next": ["planner"],
322
+ "topic": payload.topic,
323
+ "source_count": 0,
324
+ "research_step": 0,
325
+ "coverage": {},
326
+ "provider_telemetry": {},
327
+ "error": None,
328
+ "digest": "",
329
+ "messages": [],
330
+ }
331
+ background_tasks.add_task(_run_research, thread_id, payload.topic)
332
+
333
+ return {
334
+ "thread_id": thread_id,
335
+ "status": "started",
336
+ "status_url": f"/research/{thread_id}",
337
+ }
338
+
339
+ @app.get("/research/{thread_id}")
340
+ async def get_research(
341
+ thread_id: str,
342
+ request: Request,
343
+ include_digest: bool = Query(default=True),
344
+ include_messages: bool = Query(default=True),
345
+ ) -> dict[str, Any]:
346
+ if not _is_valid_api_key(request, settings):
347
+ raise HTTPException(status_code=401, detail="Invalid API key")
348
+
349
+ try:
350
+ status = await app.state.runner.status(thread_id)
351
+ except PipelineNotFound as exc:
352
+ submission = app.state.submissions.get(thread_id)
353
+ if submission is None:
354
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
355
+ payload = dict(submission)
356
+ if not include_digest:
357
+ payload.pop("digest", None)
358
+ if not include_messages:
359
+ payload.pop("messages", None)
360
+ return payload
361
+ return status.to_dict(
362
+ include_digest=include_digest,
363
+ include_messages=include_messages,
364
+ )
365
+
366
+ @app.post("/webhook/telegram")
367
+ async def handle_telegram_callback(request: Request) -> dict[str, Any]:
368
+ if not _is_valid_secret(request, settings):
369
+ raise HTTPException(status_code=401, detail="Invalid webhook secret")
370
+
371
+ try:
372
+ update = await request.json()
373
+ except Exception as exc:
374
+ raise HTTPException(status_code=400, detail="Invalid JSON payload") from exc
375
+ if not isinstance(update, dict):
376
+ raise HTTPException(status_code=400, detail="Update must be a JSON object")
377
+
378
+ action = parse_webhook_update(update)
379
+ callback_query = update.get("callback_query")
380
+ is_telegram = isinstance(callback_query, dict)
381
+ callback_id = (
382
+ str(callback_query.get("id"))
383
+ if is_telegram and callback_query.get("id")
384
+ else None
385
+ )
386
+
387
+ if settings.is_production and not is_telegram:
388
+ raise HTTPException(
389
+ status_code=400, detail="Only Telegram callback updates are allowed"
390
+ )
391
+ if is_telegram and not _is_authorized_telegram_chat(update, settings):
392
+ raise HTTPException(status_code=403, detail="Unauthorized Telegram chat")
393
+
394
+ if action is None:
395
+ if callback_id:
396
+ await telegram.answer_callback_query(
397
+ callback_id, text="Unrecognized approval action."
398
+ )
399
+ return {"ok": True, "handled": False, "error": "unrecognized_action"}
400
+
401
+ result = await _apply_decision(action)
402
+
403
+ if not result.get("ok"):
404
+ if callback_id:
405
+ await telegram.answer_callback_query(
406
+ callback_id,
407
+ text="Temporary failure while applying the decision. Please try again.",
408
+ )
409
+ raise HTTPException(
410
+ status_code=503, detail="Failed to resume the research run; retry later."
411
+ )
412
+
413
+ if callback_id:
414
+ decision = "Approved" if action.action == "approve" else "Rejected"
415
+ note = decision if result.get("handled") else "Thread is no longer awaiting review."
416
+ await telegram.answer_callback_query(callback_id, text=note)
417
+
418
+ if result.get("handled"):
419
+ decision = "✅ approved" if action.action == "approve" else "⛔ rejected"
420
+ await telegram.send_message(
421
+ f"loopgate thread {action.thread_id} was {decision} by an operator."
422
+ )
423
+
424
+ return result
425
+
426
+ return app
427
+
428
+
429
+ app = create_app()
src/checkpointing.py ADDED
@@ -0,0 +1,51 @@
1
+ """Checkpoint storage selection for loopgate.
2
+
3
+ Zero-config default is the in-process ``MemorySaver``. Set
4
+ ``LOOPGATE_CHECKPOINT_DB`` to a SQLite file path (requires the
5
+ ``sqlite-checkpointer`` extra) and every ``PipelineRunner`` — CLI and API —
6
+ persists state so paused runs survive process restarts.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import os
13
+ from pathlib import Path
14
+
15
+ from langgraph.checkpoint.base import BaseCheckpointSaver
16
+ from langgraph.checkpoint.memory import MemorySaver
17
+
18
+ from src.config import Settings, get_settings
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def build_checkpointer(settings: Settings | None = None) -> BaseCheckpointSaver:
24
+ """Return the checkpointer configured for the current runtime."""
25
+ settings = settings or get_settings()
26
+ db_path = os.path.expanduser(settings.checkpoint_db or "")
27
+ if not db_path:
28
+ return MemorySaver()
29
+
30
+ try:
31
+ import aiosqlite
32
+ from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
33
+ except ImportError as exc:
34
+ raise RuntimeError(
35
+ "LOOPGATE_CHECKPOINT_DB is set but the SQLite checkpointer is not "
36
+ 'installed. Add it with: pip install -e ".[sqlite-checkpointer]"'
37
+ ) from exc
38
+
39
+ if db_path != ":memory:":
40
+ # aiosqlite creates the file but not missing parent directories.
41
+ Path(db_path).parent.mkdir(parents=True, exist_ok=True)
42
+
43
+ logger.info("Using durable SQLite checkpoints at %s", db_path)
44
+ try:
45
+ return AsyncSqliteSaver(aiosqlite.connect(db_path))
46
+ except RuntimeError as exc:
47
+ raise RuntimeError(
48
+ "LOOPGATE_CHECKPOINT_DB is configured, but AsyncSqliteSaver can only be "
49
+ "created inside a running event loop. Construct PipelineRunner from "
50
+ "async code (e.g. the FastAPI lifespan or inside asyncio.run())."
51
+ ) from exc
src/config.py ADDED
@@ -0,0 +1,125 @@
1
+ """Environment-backed configuration for loopgate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from functools import lru_cache
8
+ from math import isfinite
9
+
10
+ from dotenv import load_dotenv
11
+
12
+ # Load .env once at import time. Real environment variables still win because
13
+ # python-dotenv does not override existing values by default.
14
+ load_dotenv()
15
+
16
+ _PLACEHOLDER_PREFIXES = ("your_", "changeme", "replace_me")
17
+ _DEFAULT_MAX_RESEARCH_STEPS = 2
18
+ _MAX_RESEARCH_STEPS = 5
19
+ _DEFAULT_RUN_DEADLINE_SECONDS = 300.0
20
+
21
+
22
+ def _clean(value: str | None) -> str | None:
23
+ """Treat empty strings and template placeholders as "not configured"."""
24
+ if value is None:
25
+ return None
26
+ value = value.strip()
27
+ if not value:
28
+ return None
29
+ lowered = value.lower()
30
+ if any(lowered.startswith(prefix) for prefix in _PLACEHOLDER_PREFIXES):
31
+ return None
32
+ return value
33
+
34
+
35
+ def _enabled(value: str | None) -> bool:
36
+ return bool(value and value.strip().lower() in {"1", "true", "yes", "on"})
37
+
38
+
39
+ def _bounded_research_steps(value: str | None) -> int:
40
+ try:
41
+ steps = int(value) if value is not None else _DEFAULT_MAX_RESEARCH_STEPS
42
+ except ValueError:
43
+ return _DEFAULT_MAX_RESEARCH_STEPS
44
+ return min(max(steps, 1), _MAX_RESEARCH_STEPS)
45
+
46
+
47
+ def _run_deadline_seconds(value: str | None) -> float:
48
+ try:
49
+ seconds = float(value) if value is not None else _DEFAULT_RUN_DEADLINE_SECONDS
50
+ except ValueError:
51
+ return _DEFAULT_RUN_DEADLINE_SECONDS
52
+ if not isfinite(seconds) or seconds <= 0:
53
+ return _DEFAULT_RUN_DEADLINE_SECONDS
54
+ return seconds
55
+
56
+
57
+ @dataclass(frozen=True, slots=True)
58
+ class Settings:
59
+ """Typed view over loopgate's environment variables."""
60
+
61
+ openai_api_key: str | None = None
62
+ openai_model: str = "gpt-4o-mini"
63
+ ollama_base_url: str | None = None
64
+ ollama_model: str | None = None
65
+ tavily_api_key: str | None = None
66
+ max_research_steps: int = _DEFAULT_MAX_RESEARCH_STEPS
67
+ run_deadline_seconds: float = _DEFAULT_RUN_DEADLINE_SECONDS
68
+ local_ranking_enabled: bool = False
69
+
70
+ api_key: str | None = None
71
+ environment: str = "development"
72
+ telegram_bot_token: str | None = None
73
+ telegram_chat_id: str | None = None
74
+ telegram_webhook_secret: str | None = None
75
+
76
+ langfuse_public_key: str | None = None
77
+ langfuse_secret_key: str | None = None
78
+ langfuse_host: str = "https://cloud.langfuse.com"
79
+
80
+ # Optional SQLite file path for durable, restart-safe checkpoints.
81
+ checkpoint_db: str | None = None
82
+
83
+ @property
84
+ def telegram_enabled(self) -> bool:
85
+ """True when the bot can actually deliver approval prompts."""
86
+ return bool(self.telegram_bot_token and self.telegram_chat_id)
87
+
88
+ @property
89
+ def is_production(self) -> bool:
90
+ return self.environment.strip().lower() == "production"
91
+
92
+
93
+ def _load_settings() -> Settings:
94
+ return Settings(
95
+ openai_api_key=_clean(os.getenv("OPENAI_API_KEY")),
96
+ openai_model=_clean(os.getenv("OPENAI_MODEL")) or "gpt-4o-mini",
97
+ ollama_base_url=(
98
+ _clean(os.getenv("OLLAMA_BASE_URL")) or ""
99
+ ).rstrip("/")
100
+ or None,
101
+ ollama_model=_clean(os.getenv("OLLAMA_MODEL")),
102
+ tavily_api_key=_clean(os.getenv("TAVILY_API_KEY")),
103
+ max_research_steps=_bounded_research_steps(
104
+ os.getenv("LOOPGATE_MAX_RESEARCH_STEPS")
105
+ ),
106
+ run_deadline_seconds=_run_deadline_seconds(
107
+ os.getenv("LOOPGATE_RUN_DEADLINE_SECONDS")
108
+ ),
109
+ local_ranking_enabled=_enabled(os.getenv("LOOPGATE_LOCAL_RANKING")),
110
+ api_key=_clean(os.getenv("LOOPGATE_API_KEY")),
111
+ environment=_clean(os.getenv("LOOPGATE_ENV")) or "development",
112
+ telegram_bot_token=_clean(os.getenv("TELEGRAM_BOT_TOKEN")),
113
+ telegram_chat_id=_clean(os.getenv("TELEGRAM_CHAT_ID")),
114
+ telegram_webhook_secret=_clean(os.getenv("TELEGRAM_WEBHOOK_SECRET")),
115
+ langfuse_public_key=_clean(os.getenv("LANGFUSE_PUBLIC_KEY")),
116
+ langfuse_secret_key=_clean(os.getenv("LANGFUSE_SECRET_KEY")),
117
+ langfuse_host=os.getenv("LANGFUSE_HOST", "https://cloud.langfuse.com"),
118
+ checkpoint_db=_clean(os.getenv("LOOPGATE_CHECKPOINT_DB")),
119
+ )
120
+
121
+
122
+ @lru_cache(maxsize=1)
123
+ def get_settings() -> Settings:
124
+ """Return cached process settings. Call ``get_settings.cache_clear()`` in tests."""
125
+ return _load_settings()