loopgate-research 0.2.1__tar.gz
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.
- loopgate_research-0.2.1/.env.example +39 -0
- loopgate_research-0.2.1/LICENSE +21 -0
- loopgate_research-0.2.1/MANIFEST.in +3 -0
- loopgate_research-0.2.1/PKG-INFO +359 -0
- loopgate_research-0.2.1/README.md +328 -0
- loopgate_research-0.2.1/constraints.txt +75 -0
- loopgate_research-0.2.1/loopgate_research.egg-info/PKG-INFO +359 -0
- loopgate_research-0.2.1/loopgate_research.egg-info/SOURCES.txt +43 -0
- loopgate_research-0.2.1/loopgate_research.egg-info/dependency_links.txt +1 -0
- loopgate_research-0.2.1/loopgate_research.egg-info/entry_points.txt +2 -0
- loopgate_research-0.2.1/loopgate_research.egg-info/requires.txt +24 -0
- loopgate_research-0.2.1/loopgate_research.egg-info/top_level.txt +1 -0
- loopgate_research-0.2.1/pyproject.toml +49 -0
- loopgate_research-0.2.1/setup.cfg +4 -0
- loopgate_research-0.2.1/src/__init__.py +0 -0
- loopgate_research-0.2.1/src/agents/__init__.py +0 -0
- loopgate_research-0.2.1/src/api/__init__.py +0 -0
- loopgate_research-0.2.1/src/api/main.py +429 -0
- loopgate_research-0.2.1/src/checkpointing.py +51 -0
- loopgate_research-0.2.1/src/config.py +125 -0
- loopgate_research-0.2.1/src/evaluation.py +281 -0
- loopgate_research-0.2.1/src/graph/__init__.py +6 -0
- loopgate_research-0.2.1/src/graph/graph.py +90 -0
- loopgate_research-0.2.1/src/graph/nodes.py +813 -0
- loopgate_research-0.2.1/src/graph/state.py +51 -0
- loopgate_research-0.2.1/src/main.py +210 -0
- loopgate_research-0.2.1/src/pipeline.py +257 -0
- loopgate_research-0.2.1/src/utils/__init__.py +0 -0
- loopgate_research-0.2.1/src/utils/observability.py +151 -0
- loopgate_research-0.2.1/src/utils/ollama.py +63 -0
- loopgate_research-0.2.1/src/utils/ranking.py +52 -0
- loopgate_research-0.2.1/src/utils/telegram.py +158 -0
- loopgate_research-0.2.1/tests/test_api.py +514 -0
- loopgate_research-0.2.1/tests/test_checkpointing.py +167 -0
- loopgate_research-0.2.1/tests/test_cli.py +102 -0
- loopgate_research-0.2.1/tests/test_config.py +110 -0
- loopgate_research-0.2.1/tests/test_evaluation.py +56 -0
- loopgate_research-0.2.1/tests/test_failures.py +165 -0
- loopgate_research-0.2.1/tests/test_local_ranking.py +173 -0
- loopgate_research-0.2.1/tests/test_observability.py +177 -0
- loopgate_research-0.2.1/tests/test_ollama.py +203 -0
- loopgate_research-0.2.1/tests/test_orchestration.py +208 -0
- loopgate_research-0.2.1/tests/test_pipeline.py +285 -0
- loopgate_research-0.2.1/tests/test_research_quality.py +210 -0
- loopgate_research-0.2.1/tests/test_telegram.py +121 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# ==============================================================================
|
|
2
|
+
# loopgate environment configuration
|
|
3
|
+
# Copy this file to .env and replace every placeholder before running.
|
|
4
|
+
# ==============================================================================
|
|
5
|
+
|
|
6
|
+
# Core pipeline providers
|
|
7
|
+
OPENAI_API_KEY=your_openai_api_key_here
|
|
8
|
+
OPENAI_MODEL=gpt-4o-mini
|
|
9
|
+
# Optional local model provider, used only when OPENAI_API_KEY is not configured.
|
|
10
|
+
# Both values are required; install/start Ollama and pull the model separately.
|
|
11
|
+
# OLLAMA_BASE_URL=http://127.0.0.1:11434
|
|
12
|
+
# OLLAMA_MODEL=qwen3:4b
|
|
13
|
+
TAVILY_API_KEY=your_tavily_search_api_key_here
|
|
14
|
+
# Maximum Tavily searches per run, including follow-up evidence gathering (1-5).
|
|
15
|
+
LOOPGATE_MAX_RESEARCH_STEPS=2
|
|
16
|
+
# Overall graph-execution deadline in seconds; excludes time waiting for review.
|
|
17
|
+
LOOPGATE_RUN_DEADLINE_SECONDS=300
|
|
18
|
+
# Optional local source ranking; requires: pip install -e ".[local-ranking]"
|
|
19
|
+
LOOPGATE_LOCAL_RANKING=false
|
|
20
|
+
|
|
21
|
+
# API security. Production requires both LOOPGATE_API_KEY and a webhook secret.
|
|
22
|
+
LOOPGATE_ENV=development
|
|
23
|
+
# LOOPGATE_API_KEY=your_random_api_key_here
|
|
24
|
+
|
|
25
|
+
# Human-in-the-loop gateway (Telegram)
|
|
26
|
+
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
|
|
27
|
+
TELEGRAM_CHAT_ID=your_private_telegram_chat_id_here
|
|
28
|
+
# Passed to Telegram's setWebhook call as secret_token; checked on every update.
|
|
29
|
+
TELEGRAM_WEBHOOK_SECRET=your_random_webhook_secret_here
|
|
30
|
+
|
|
31
|
+
# Optional Langfuse tracing; requires: pip install -e ".[observability]"
|
|
32
|
+
# Both keys are required. Tracing remains disabled when either is absent.
|
|
33
|
+
LANGFUSE_PUBLIC_KEY=your_langfuse_public_key_here
|
|
34
|
+
LANGFUSE_SECRET_KEY=your_langfuse_secret_key_here
|
|
35
|
+
LANGFUSE_HOST=https://cloud.langfuse.com
|
|
36
|
+
|
|
37
|
+
# Durable checkpoints (production): point at a SQLite file so paused runs
|
|
38
|
+
# survive restarts. Requires: pip install -e ".[sqlite-checkpointer]"
|
|
39
|
+
# LOOPGATE_CHECKPOINT_DB=./data/loopgate-checkpoints.sqlite
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aashirwad Mishra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loopgate-research
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Stateful multi-agent research pipeline featuring LangGraph interrupt checkpoints and Telegram webhook validation.
|
|
5
|
+
Project-URL: Repository, https://github.com/aash-aashirwad/loopgate
|
|
6
|
+
Project-URL: Issues, https://github.com/aash-aashirwad/loopgate/issues
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: langgraph<2.0,>=0.1.0
|
|
11
|
+
Requires-Dist: langchain-core<2.0,>=0.2.0
|
|
12
|
+
Requires-Dist: langchain-openai<2.0,>=0.1.0
|
|
13
|
+
Requires-Dist: tavily-python<1.0,>=0.3.0
|
|
14
|
+
Requires-Dist: fastapi<1.0,>=0.110.0
|
|
15
|
+
Requires-Dist: uvicorn<1.0,>=0.28.0
|
|
16
|
+
Requires-Dist: httpx<1.0,>=0.27.0
|
|
17
|
+
Requires-Dist: python-dotenv<2.0,>=1.0.1
|
|
18
|
+
Requires-Dist: pydantic<3.0,>=2.6.0
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: build<2.0,>=1.0; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest<10.0,>=8.0; extra == "dev"
|
|
22
|
+
Requires-Dist: pytest-asyncio<2.0,>=0.23; extra == "dev"
|
|
23
|
+
Provides-Extra: sqlite-checkpointer
|
|
24
|
+
Requires-Dist: langgraph-checkpoint-sqlite<4.0,>=3.0.0; extra == "sqlite-checkpointer"
|
|
25
|
+
Requires-Dist: aiosqlite<1.0,>=0.20.0; extra == "sqlite-checkpointer"
|
|
26
|
+
Provides-Extra: local-ranking
|
|
27
|
+
Requires-Dist: torch<3.0,>=2.2; extra == "local-ranking"
|
|
28
|
+
Provides-Extra: observability
|
|
29
|
+
Requires-Dist: langfuse<6.0,>=4.0; extra == "observability"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# loopgate
|
|
33
|
+
|
|
34
|
+
A stateful multi-agent research pipeline built on [LangGraph](https://www.langchain.com/langgraph)
|
|
35
|
+
that pauses at a human-in-the-loop checkpoint, waits for approval via Telegram, and resumes
|
|
36
|
+
the graph from a persisted state.
|
|
37
|
+
|
|
38
|
+
## Architecture
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
START -> planner -> researcher -> evidence_review -> compiler
|
|
42
|
+
^ │ │
|
|
43
|
+
└───────────────┘ ├──> [INTERRUPT before review_gate]
|
|
44
|
+
bounded follow-up │ approve/reject
|
|
45
|
+
│ review_gate
|
|
46
|
+
│ │
|
|
47
|
+
└──> failure ──> END finalize
|
|
48
|
+
│
|
|
49
|
+
END
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- **State** – `GraphState` tracks the topic, messages, research plan and progress,
|
|
53
|
+
evidence coverage, normalized sources, compiled digest, `approval_status`
|
|
54
|
+
(`pending` | `approved` | `rejected`), and any provider error. Public run states are
|
|
55
|
+
`running`, `awaiting_approval`, `completed`, and `failed`; status also exposes
|
|
56
|
+
`research_step`, coverage metadata, and sanitized per-provider request telemetry.
|
|
57
|
+
- **Checkpoints** – in-process `MemorySaver` by default; set `LOOPGATE_CHECKPOINT_DB`
|
|
58
|
+
to a SQLite file path and every `PipelineRunner` (CLI and API) uses a durable
|
|
59
|
+
`AsyncSqliteSaver` persisted across restarts (`pip install -e ".[sqlite-checkpointer]"`;
|
|
60
|
+
the parent directory is created automatically).
|
|
61
|
+
- **Nodes** – `research_planner_node` uses OpenAI or local Ollama to select
|
|
62
|
+
complementary queries when configured, or a deterministic heuristic plan otherwise. `research_node` executes one
|
|
63
|
+
Tavily query at a time. `evidence_review_node` checks source count and domain diversity,
|
|
64
|
+
then loops back for another planned search or advances to `digest_compiler_node`.
|
|
65
|
+
The loop stops at `LOOPGATE_MAX_RESEARCH_STEPS` (default 2, maximum 5), when evidence
|
|
66
|
+
is sufficient, or when a follow-up adds no new sources. A failed follow-up retains
|
|
67
|
+
earlier usable sources; an initial research failure or absence of usable sources remains
|
|
68
|
+
fatal. The compiler, review gate, and finalizer preserve the existing approval lifecycle.
|
|
69
|
+
- **Run deadline** – graph execution is bounded by `LOOPGATE_RUN_DEADLINE_SECONDS`
|
|
70
|
+
(default 300 seconds). Expiry creates a terminal `failed` checkpoint with no digest
|
|
71
|
+
or approval prompt. Time spent waiting for a human decision is not part of this deadline.
|
|
72
|
+
- **API** – FastAPI gateway exposes `POST /research` (background execution + optional
|
|
73
|
+
Telegram delivery), `GET /research/{thread_id}`, `GET /health/ready`, and
|
|
74
|
+
`POST /webhook/telegram`. `LOOPGATE_API_KEY` protects research/status with `X-API-Key`;
|
|
75
|
+
Telegram webhooks validate their secret and configured chat.
|
|
76
|
+
- **CLI** – `run`, `status`, and `resume` share the same checkpointed runner. `--decision approve`
|
|
77
|
+
is useful for scripted/testing flows.
|
|
78
|
+
|
|
79
|
+
## Setup
|
|
80
|
+
|
|
81
|
+
Python 3.11 or newer is required. Install the published distribution with:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
pip install loopgate-research
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The PyPI distribution is named `loopgate-research`; the CLI command remains `loopgate`.
|
|
88
|
+
For local development, clone the repository and install it with test and SQLite support:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
python -m venv venv
|
|
92
|
+
source venv/bin/activate
|
|
93
|
+
pip install -e ".[dev,sqlite-checkpointer]"
|
|
94
|
+
cp .env.example .env
|
|
95
|
+
# Add TAVILY_API_KEY and optionally OpenAI/Ollama, API-security, and Telegram keys.
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Optional local Ollama models
|
|
99
|
+
|
|
100
|
+
Model provider precedence is **OpenAI → Ollama → heuristic planning/source excerpts**.
|
|
101
|
+
OpenAI remains backward-compatible and takes precedence whenever its key is configured.
|
|
102
|
+
To use Ollama, leave OpenAI unconfigured, install and start Ollama separately, pull a
|
|
103
|
+
local model, and set both values:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
ollama pull qwen3:4b
|
|
107
|
+
# .env:
|
|
108
|
+
# OLLAMA_BASE_URL=http://127.0.0.1:11434
|
|
109
|
+
# OLLAMA_MODEL=qwen3:4b
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Loopgate calls Ollama's non-streaming `/api/chat` endpoint through HTTPX; it does not
|
|
113
|
+
install Ollama or download models. Planning and synthesis retain the same 60-second
|
|
114
|
+
timeout, output bounds, citation validation, telemetry, and graceful fallbacks as OpenAI.
|
|
115
|
+
See the [Ollama API documentation](https://docs.ollama.com/api/introduction).
|
|
116
|
+
|
|
117
|
+
PyTorch is not part of the default runtime. To enable optional local source ranking:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
pip install -c constraints.txt -e ".[local-ranking]" \
|
|
121
|
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
|
122
|
+
# Then set LOOPGATE_LOCAL_RANKING=true in .env
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The constraints pin the CPU builds verified on Python 3.11, 3.12, and 3.14. The test
|
|
126
|
+
environment used approximately 1.1 GB on disk and 366 MiB peak resident memory.
|
|
127
|
+
|
|
128
|
+
The ranker hashes lexical features locally and uses PyTorch cosine similarity to order
|
|
129
|
+
up to ten candidates before selecting five. It downloads no model and sends no source
|
|
130
|
+
text to another service. If PyTorch is unavailable or ranking fails, loopgate retains
|
|
131
|
+
provider ordering and continues research.
|
|
132
|
+
|
|
133
|
+
For a runtime installation using the verified dependency versions:
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
pip install -c constraints.txt ".[sqlite-checkpointer]"
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Usage
|
|
140
|
+
|
|
141
|
+
### CLI (local, with human prompt)
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
python -m src.main run -t "Arch Linux system telemetry automation workflows"
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
The CLI prints the digest in the terminal and pauses until you type `approve` or
|
|
148
|
+
`reject` (or pass `--decision approve`). Telegram delivery is handled by the API path.
|
|
149
|
+
With `LOOPGATE_CHECKPOINT_DB` configured, inspect or resume a run after restarting:
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
loopgate status <thread_id>
|
|
153
|
+
loopgate resume <thread_id> --decision approve
|
|
154
|
+
loopgate resume <thread_id> --decision reject
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
If neither OpenAI nor Ollama is configured, planning uses deterministic query templates
|
|
158
|
+
and the compiler assembles the digest from bounded source excerpts. The same compiler
|
|
159
|
+
fallback is used after the selected model provider fails, times out, or returns invalid
|
|
160
|
+
output, with the reason recorded in the digest and run metadata. Planning failures
|
|
161
|
+
likewise fall back to heuristic queries without failing research.
|
|
162
|
+
|
|
163
|
+
Tavily results are normalized, limited to five HTTP(S) sources, deduplicated by URL,
|
|
164
|
+
and bounded to 4,000 content characters per source. Model output must contain the
|
|
165
|
+
required sections and valid inline citations. Every reviewable digest ends with an
|
|
166
|
+
application-generated `### Sources` manifest mapping citation numbers to source URLs.
|
|
167
|
+
|
|
168
|
+
### Run deadlines and provider telemetry
|
|
169
|
+
|
|
170
|
+
`LOOPGATE_RUN_DEADLINE_SECONDS` bounds each research execution from planning through
|
|
171
|
+
compilation (default 300 seconds; positive finite values only). A run that exceeds the
|
|
172
|
+
deadline ends as `failed`, cannot be resumed, and does not send a Telegram approval
|
|
173
|
+
request. Existing provider timeouts and fallback behavior still apply within this limit.
|
|
174
|
+
|
|
175
|
+
Checkpointed state and `GET /research/{thread_id}` expose a `provider_telemetry` object
|
|
176
|
+
keyed by `tavily` and the selected model provider (`openai` or `ollama`). Each provider entry contains:
|
|
177
|
+
|
|
178
|
+
- `request_count`, `total_latency_ms`, `last_operation`, and `last_status`.
|
|
179
|
+
- A bounded `requests` history with per-call operation, `latency_ms`, and status.
|
|
180
|
+
- Aggregated `token_usage` (`input_tokens`, `output_tokens`, and `total_tokens`) when
|
|
181
|
+
OpenAI or Ollama supplies usage; individual model request entries include the same data.
|
|
182
|
+
|
|
183
|
+
Telemetry contains no prompts, source content, credentials, or provider exception text.
|
|
184
|
+
It is preserved in SQLite checkpoints and remains available after approval or rejection.
|
|
185
|
+
|
|
186
|
+
### Optional Langfuse tracing
|
|
187
|
+
|
|
188
|
+
Install the separate observability extra and configure both Langfuse keys:
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
pip install -e ".[observability]"
|
|
192
|
+
# Set LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and optionally LANGFUSE_HOST.
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Research/review runs then create nested node and provider observations with model names,
|
|
196
|
+
token usage, latency, coverage, fallback, and terminal status. Traces exclude source
|
|
197
|
+
excerpts, full digests, credentials, and provider exception details. Missing packages,
|
|
198
|
+
initialization failures, and export failures leave research behavior unchanged. CLI/API
|
|
199
|
+
shutdown flushes queued traces. See the [Langfuse Python SDK documentation](https://langfuse.com/docs/sdk/python/sdk-v3).
|
|
200
|
+
|
|
201
|
+
### FastAPI server
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
python -m src.main serve --host 127.0.0.1 --port 8000
|
|
205
|
+
# or: uvicorn src.api.main:app --reload
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
`/health` is a liveness check. `/health/ready` returns HTTP 503 until `TAVILY_API_KEY`
|
|
209
|
+
is configured; research submissions are also rejected with 503 in that state.
|
|
210
|
+
|
|
211
|
+
For production, set `LOOPGATE_ENV=production`, `LOOPGATE_API_KEY`, and
|
|
212
|
+
`TELEGRAM_WEBHOOK_SECRET`. Startup fails if either secret is missing, and unsigned
|
|
213
|
+
non-Telegram approval payloads are disabled. Use one Uvicorn worker with a persistent
|
|
214
|
+
SQLite path. Accepted submissions, per-thread locks, and in-memory checkpoints are
|
|
215
|
+
process-local; SQLite does not make multiple workers safe or queue accepted work
|
|
216
|
+
across restarts. Deploy behind HTTPS with appropriate database backups and permissions.
|
|
217
|
+
A production-like process launch is:
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
uvicorn src.api.main:app --host 0.0.0.0 --port 8000 --workers 1
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Only expose that process through the HTTPS reverse proxy, then register the Telegram
|
|
224
|
+
webhook below. The repository does not include a hosted deployment or public hostname.
|
|
225
|
+
|
|
226
|
+
Start a run:
|
|
227
|
+
|
|
228
|
+
```bash
|
|
229
|
+
curl -X POST http://localhost:8000/research \
|
|
230
|
+
-H "Content-Type: application/json" \
|
|
231
|
+
-H "X-API-Key: $LOOPGATE_API_KEY" \
|
|
232
|
+
-d '{"topic": "LangGraph human-in-the-loop patterns"}'
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Topics are trimmed before execution. Thread IDs are create-only: submitting an existing
|
|
236
|
+
or currently accepted ID returns HTTP 409 instead of rerunning research or replacing its
|
|
237
|
+
review state. Immediate polls return `running` before the first checkpoint; failures
|
|
238
|
+
before checkpoint creation remain visible as `failed` in the running process.
|
|
239
|
+
|
|
240
|
+
Check status / digest:
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
curl -H "X-API-Key: $LOOPGATE_API_KEY" http://localhost:8000/research/<thread_id>
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Failed or empty runs do not produce Telegram approval prompts. Only a run paused at
|
|
247
|
+
`review_gate` can be resumed. Digests longer than Telegram's 4,096-character message
|
|
248
|
+
limit are delivered as ordered parts without truncation; approval buttons appear only
|
|
249
|
+
on the final part.
|
|
250
|
+
|
|
251
|
+
Resume from Telegram or a test webhook:
|
|
252
|
+
|
|
253
|
+
```bash
|
|
254
|
+
curl -X POST http://localhost:8000/webhook/telegram \
|
|
255
|
+
-H "Content-Type: application/json" \
|
|
256
|
+
-H "X-Telegram-Bot-Api-Secret-Token: $TELEGRAM_WEBHOOK_SECRET" \
|
|
257
|
+
-d '{"callback_query":{"id":"cq_1","data":"approve:<thread_id>","message":{"chat":{"id":<telegram_chat_id>}}}}'
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
In development, you can also POST `{"thread_id": "...", "action": "approve"}` for local
|
|
261
|
+
testing. Real callbacks must originate from the configured `TELEGRAM_CHAT_ID` when set.
|
|
262
|
+
Duplicate or already-decided callbacks remain harmless; transient resume failures return
|
|
263
|
+
HTTP 503 so Telegram can retry instead of acknowledging a decision that was not applied.
|
|
264
|
+
|
|
265
|
+
### Telegram webhook registration
|
|
266
|
+
|
|
267
|
+
```bash
|
|
268
|
+
curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \
|
|
269
|
+
-d "url=https://your-host/webhook/telegram" \
|
|
270
|
+
-d "secret_token=$TELEGRAM_WEBHOOK_SECRET"
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Telegram delivers `callback_data` as `approve:<thread_id>` or `reject:<thread_id>`.
|
|
274
|
+
Thread ids are limited to 48 characters so callback data stays under Telegram's
|
|
275
|
+
64-byte limit.
|
|
276
|
+
|
|
277
|
+
## Testing
|
|
278
|
+
|
|
279
|
+
```bash
|
|
280
|
+
python -m unittest discover -s tests -v
|
|
281
|
+
# or, if you installed the dev extra:
|
|
282
|
+
pytest -q
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Tests cover graph planning and bounded evidence loops, overall deadlines, provider
|
|
286
|
+
telemetry, interrupt/resume, CLI lifecycle, API authorization/readiness, submission
|
|
287
|
+
tracking, source normalization, citation validation, optional local ranking and its
|
|
288
|
+
fallbacks, provider failure routing, webhook validation/retries, SQLite persistence,
|
|
289
|
+
and complete multipart Telegram delivery without making live API calls.
|
|
290
|
+
|
|
291
|
+
### Research-quality evaluation
|
|
292
|
+
|
|
293
|
+
Run the repeatable offline evaluation with:
|
|
294
|
+
|
|
295
|
+
```bash
|
|
296
|
+
python -m src.evaluation
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Four labeled fixtures exercise valid synthesis, invalid-citation fallback, provider-error
|
|
300
|
+
fallback, and unconfigured-model fallback through the real graph. The JSON report scores
|
|
301
|
+
citation accuracy, source/domain coverage, factual consistency of labeled source-backed
|
|
302
|
+
claims, and fallback quality. It also includes provider telemetry and an overall score.
|
|
303
|
+
These fixtures validate pipeline behavior deterministically; they do not prove that every
|
|
304
|
+
live model statement is true. Live provider quality still needs separate labeled review.
|
|
305
|
+
|
|
306
|
+
Build and smoke-test the distributions with:
|
|
307
|
+
|
|
308
|
+
```bash
|
|
309
|
+
python -m build
|
|
310
|
+
pip install --force-reinstall --no-deps dist/*.whl
|
|
311
|
+
loopgate --help
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
GitHub Actions runs the suite on Python 3.11 and 3.12 and builds/installs the wheel.
|
|
315
|
+
Publishing a GitHub release builds its distributions and publishes them to PyPI as
|
|
316
|
+
`loopgate-research` using a trusted publisher; no PyPI API token is stored in GitHub.
|
|
317
|
+
|
|
318
|
+
## Environment variables
|
|
319
|
+
|
|
320
|
+
See [`.env.example`](.env.example) for the full list:
|
|
321
|
+
|
|
322
|
+
| Variable | Purpose |
|
|
323
|
+
| --- | --- |
|
|
324
|
+
| `OPENAI_API_KEY` | OpenAI key for research planning and digest synthesis; takes precedence over Ollama |
|
|
325
|
+
| `OPENAI_MODEL` | Model name (default `gpt-4o-mini`) |
|
|
326
|
+
| `OLLAMA_BASE_URL`, `OLLAMA_MODEL` | Optional local model endpoint and model; both required when OpenAI is absent |
|
|
327
|
+
| `TAVILY_API_KEY` | Tavily key for web research and API readiness |
|
|
328
|
+
| `LOOPGATE_MAX_RESEARCH_STEPS` | Maximum planned searches per run; default 2, clamped to 1–5 |
|
|
329
|
+
| `LOOPGATE_RUN_DEADLINE_SECONDS` | Overall planning-through-compilation deadline; default 300 seconds |
|
|
330
|
+
| `LOOPGATE_LOCAL_RANKING` | Opt-in PyTorch query-relevance ranking; default `false` |
|
|
331
|
+
| `LOOPGATE_ENV` | `development` by default; `production` enforces security configuration |
|
|
332
|
+
| `LOOPGATE_API_KEY` | `X-API-Key` required for research/status when configured; required in production |
|
|
333
|
+
| `TELEGRAM_BOT_TOKEN` | Bot that delivers approval prompts |
|
|
334
|
+
| `TELEGRAM_CHAT_ID` | Chat that receives digests and is authorized to approve them |
|
|
335
|
+
| `TELEGRAM_WEBHOOK_SECRET` | Shared secret checked on every webhook call |
|
|
336
|
+
| `LOOPGATE_CHECKPOINT_DB` | Optional SQLite path for durable checkpoints (extras required) |
|
|
337
|
+
| `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY` | Enable sanitized tracing when both are set and the `observability` extra is installed |
|
|
338
|
+
| `LANGFUSE_HOST` | Langfuse cloud/self-hosted base URL; default `https://cloud.langfuse.com` |
|
|
339
|
+
|
|
340
|
+
## Layout
|
|
341
|
+
|
|
342
|
+
```text
|
|
343
|
+
src/
|
|
344
|
+
api/main.py FastAPI app factory + webhook validation
|
|
345
|
+
graph/state.py GraphState TypedDict
|
|
346
|
+
graph/nodes.py planner / researcher / evidence review / compiler / review / finalize
|
|
347
|
+
graph/graph.py bounded research loop with the review interrupt
|
|
348
|
+
pipeline.py PipelineRunner: start, resume, status
|
|
349
|
+
evaluation.py Repeatable offline research-quality JSON evaluation
|
|
350
|
+
utils/ollama.py Optional local Ollama chat client
|
|
351
|
+
utils/observability.py Lazy optional Langfuse tracing
|
|
352
|
+
utils/ranking.py Lazy optional PyTorch source ranking
|
|
353
|
+
utils/telegram.py Telegram Bot API client
|
|
354
|
+
config.py env-backed Settings
|
|
355
|
+
main.py CLI (run / status / resume / serve)
|
|
356
|
+
tests/ unit + integration tests with fakes
|
|
357
|
+
constraints.txt Verified core and optional CPU-ranking constraints
|
|
358
|
+
.github/workflows/ Test, build, and wheel-install CI
|
|
359
|
+
```
|