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/graph/state.py ADDED
@@ -0,0 +1,51 @@
1
+ """Shared state schema for the loopgate research graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated, Any, Literal, TypedDict
6
+
7
+ from langchain_core.messages import AnyMessage
8
+ from langgraph.graph.message import add_messages
9
+
10
+ ApprovalStatus = Literal["pending", "approved", "rejected"]
11
+
12
+
13
+ class GraphState(TypedDict, total=False):
14
+ """Runtime ledger that flows between loopgate graph nodes.
15
+
16
+ ``total=False`` is intentional: every node returns only the keys it changes,
17
+ and LangGraph merges those partial updates into the checkpointed state.
18
+ """
19
+
20
+ # Primary query submitted by the operator.
21
+ topic: str
22
+
23
+ # Conversation / execution log. ``add_messages`` appends instead of replacing.
24
+ messages: Annotated[list[AnyMessage], add_messages]
25
+
26
+ # Ordered search queries selected by the planning agent.
27
+ research_plan: list[str]
28
+
29
+ # Number of planned searches already executed.
30
+ research_step: int
31
+
32
+ # Evidence coverage and latest-pass telemetry used by the loop router.
33
+ coverage_report: dict[str, Any]
34
+
35
+ # Normalized, bounded, deduplicated research source records.
36
+ raw_data: list[dict[str, Any]]
37
+
38
+ # Structured metadata derived from the research pass.
39
+ extracted_metrics: dict[str, Any]
40
+
41
+ # Sanitized per-provider request counts, timings, statuses, and token usage.
42
+ provider_telemetry: dict[str, Any]
43
+
44
+ # Model-generated Markdown digest awaiting human review.
45
+ compiled_digest: str
46
+
47
+ # Human-in-the-loop decision: pending -> approved | rejected.
48
+ approval_status: ApprovalStatus
49
+
50
+ # Last node-level failure, if any. Kept in state so callers can inspect it.
51
+ error: str | None
src/main.py ADDED
@@ -0,0 +1,210 @@
1
+ """Command-line entry point for loopgate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import sys
8
+
9
+ from src.config import get_settings
10
+ from src.pipeline import PipelineRunner, PipelineStatus
11
+
12
+
13
+ def _build_parser() -> argparse.ArgumentParser:
14
+ parser = argparse.ArgumentParser(
15
+ prog="loopgate",
16
+ description="Stateful research pipeline with human-in-the-loop approval.",
17
+ )
18
+ subparsers = parser.add_subparsers(dest="command")
19
+
20
+ run_parser = subparsers.add_parser("run", help="Run the pipeline from the terminal.")
21
+ run_parser.add_argument("--topic", "-t", required=True, help="Research topic.")
22
+ run_parser.add_argument("--thread-id", default=None, help="Checkpoint thread id.")
23
+ run_parser.add_argument(
24
+ "--decision",
25
+ choices=("approve", "reject"),
26
+ default=None,
27
+ help="Skip the interactive prompt and apply this decision.",
28
+ )
29
+
30
+ status_parser = subparsers.add_parser(
31
+ "status", help="Inspect a checkpointed pipeline run."
32
+ )
33
+ status_parser.add_argument("thread_id", help="Checkpoint thread id.")
34
+
35
+ resume_parser = subparsers.add_parser(
36
+ "resume", help="Apply a decision to a run awaiting review."
37
+ )
38
+ resume_parser.add_argument("thread_id", help="Checkpoint thread id.")
39
+ resume_parser.add_argument(
40
+ "--decision",
41
+ required=True,
42
+ choices=("approve", "reject"),
43
+ help="Decision to apply at the review gate.",
44
+ )
45
+
46
+ serve_parser = subparsers.add_parser("serve", help="Start the FastAPI gateway.")
47
+ serve_parser.add_argument("--host", default="127.0.0.1")
48
+ serve_parser.add_argument("--port", type=int, default=8000)
49
+ serve_parser.add_argument("--reload", action="store_true")
50
+
51
+ return parser
52
+
53
+
54
+ def _print_status(status: PipelineStatus) -> None:
55
+ print(f"\nThread: {status.thread_id}")
56
+ print(f"Status: {status.to_dict(include_digest=False)['status']}")
57
+ print(f"Approval: {status.approval_status}")
58
+ print(f"Next node(s): {list(status.next) or 'none'}")
59
+ error = status.values.get("error")
60
+ if error:
61
+ print(f"Error: {error}")
62
+
63
+
64
+ def _print_digest(status: PipelineStatus) -> None:
65
+ if status.digest:
66
+ print("\n" + "─" * 72)
67
+ print(status.digest)
68
+ print("─" * 72)
69
+
70
+
71
+ async def _ask_for_decision() -> str:
72
+ while True:
73
+ try:
74
+ answer = await asyncio.to_thread(
75
+ input, "\nDecision [approve/reject]: "
76
+ )
77
+ except EOFError:
78
+ return "reject"
79
+ answer = answer.strip().lower()
80
+ if answer in ("approve", "approved", "reject", "rejected"):
81
+ return answer
82
+ print("Please type 'approve' or 'reject'.")
83
+
84
+
85
+ async def _run(topic: str, thread_id: str | None, decision: str | None) -> int:
86
+ settings = get_settings()
87
+ missing = [
88
+ name
89
+ for name, value in (("TAVILY_API_KEY", settings.tavily_api_key),)
90
+ if not value
91
+ ]
92
+ if missing:
93
+ print(
94
+ "Configuration error: set " + ", ".join(missing) + " in your .env file.",
95
+ file=sys.stderr,
96
+ )
97
+ return 1
98
+ if not settings.openai_api_key:
99
+ if getattr(settings, "ollama_base_url", None) and getattr(
100
+ settings, "ollama_model", None
101
+ ):
102
+ print(
103
+ f"ℹ Using local Ollama model {settings.ollama_model} for synthesis.",
104
+ file=sys.stderr,
105
+ )
106
+ else:
107
+ print(
108
+ "ℹ No model provider configured -- digest will use the no-LLM fallback.",
109
+ file=sys.stderr,
110
+ )
111
+
112
+ runner = PipelineRunner()
113
+ try:
114
+ return await _pipeline_session(runner, topic, thread_id, decision)
115
+ finally:
116
+ await runner.aclose()
117
+
118
+
119
+ async def _pipeline_session(
120
+ runner: PipelineRunner, topic: str, thread_id: str | None, decision: str | None
121
+ ) -> int:
122
+ print(f"🚀 Starting research for: {topic}")
123
+ try:
124
+ status = await runner.start(topic, thread_id=thread_id)
125
+ except Exception as exc:
126
+ print(f"Pipeline failed to start: {exc}", file=sys.stderr)
127
+ return 1
128
+
129
+ _print_status(status)
130
+ _print_digest(status)
131
+
132
+ if not status.is_pending:
133
+ return 0 if not status.values.get("error") else 1
134
+
135
+ print("\n🛑 Graph paused at the human review gate.")
136
+ choice = decision or await _ask_for_decision()
137
+ try:
138
+ status = await runner.resume(status.thread_id, choice)
139
+ except Exception as exc:
140
+ print(f"Failed to resume thread: {exc}", file=sys.stderr)
141
+ return 1
142
+
143
+ _print_status(status)
144
+ return 0
145
+
146
+
147
+ async def _status(thread_id: str) -> int:
148
+ runner = PipelineRunner()
149
+ try:
150
+ try:
151
+ status = await runner.status(thread_id)
152
+ except Exception as exc:
153
+ print(f"Failed to inspect thread: {exc}", file=sys.stderr)
154
+ return 1
155
+ _print_status(status)
156
+ _print_digest(status)
157
+ return 0 if not status.values.get("error") else 1
158
+ finally:
159
+ await runner.aclose()
160
+
161
+
162
+ async def _resume(thread_id: str, decision: str) -> int:
163
+ runner = PipelineRunner()
164
+ try:
165
+ try:
166
+ status = await runner.resume(thread_id, decision)
167
+ except Exception as exc:
168
+ print(f"Failed to resume thread: {exc}", file=sys.stderr)
169
+ return 1
170
+ _print_status(status)
171
+ return 0
172
+ finally:
173
+ await runner.aclose()
174
+
175
+
176
+ def main(argv: list[str] | None = None) -> int:
177
+ parser = _build_parser()
178
+ args = parser.parse_args(argv)
179
+
180
+ if args.command == "serve":
181
+ try:
182
+ import uvicorn
183
+ except ImportError:
184
+ print("uvicorn is not installed.", file=sys.stderr)
185
+ return 1
186
+ uvicorn.run(
187
+ "src.api.main:app",
188
+ host=args.host,
189
+ port=args.port,
190
+ reload=args.reload,
191
+ )
192
+ return 0
193
+
194
+ if args.command in {"run", "status", "resume"}:
195
+ try:
196
+ if args.command == "run":
197
+ return asyncio.run(_run(args.topic, args.thread_id, args.decision))
198
+ if args.command == "status":
199
+ return asyncio.run(_status(args.thread_id))
200
+ return asyncio.run(_resume(args.thread_id, args.decision))
201
+ except KeyboardInterrupt:
202
+ print("\nCancelled.", file=sys.stderr)
203
+ return 130
204
+
205
+ parser.print_help()
206
+ return 1
207
+
208
+
209
+ if __name__ == "__main__":
210
+ raise SystemExit(main())
src/pipeline.py ADDED
@@ -0,0 +1,257 @@
1
+ """Checkpointed pipeline runner used by the CLI and the API gateway."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+ from uuid import uuid4
10
+
11
+ from langchain_core.messages import HumanMessage
12
+ from langgraph.checkpoint.base import BaseCheckpointSaver
13
+
14
+ from src.checkpointing import build_checkpointer
15
+ from src.config import get_settings
16
+ from src.graph.graph import FAILURE_NODE, REVIEW_NODE, build_graph
17
+ from src.graph.state import GraphState
18
+ from src.utils.observability import get_observability
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _APPROVE_ALIASES = {"approve", "approved"}
23
+ _REJECT_ALIASES = {"reject", "rejected"}
24
+
25
+
26
+ class PipelineError(Exception):
27
+ """Base exception for pipeline lifecycle errors."""
28
+
29
+
30
+ class PipelineNotFound(PipelineError):
31
+ """Raised when a thread has no checkpointed state."""
32
+
33
+
34
+ class PipelineConflict(PipelineError):
35
+ """Raised when a new run attempts to reuse an existing thread."""
36
+
37
+
38
+ class PipelineNotAwaitingApproval(PipelineError):
39
+ """Raised when a resume is attempted on a run that is not paused."""
40
+
41
+
42
+ def _message_text(message: Any) -> str:
43
+ if isinstance(message, str):
44
+ return message
45
+ if isinstance(message, dict):
46
+ content = message.get("content")
47
+ return content if isinstance(content, str) else str(content)
48
+ content = getattr(message, "content", None)
49
+ return content if isinstance(content, str) else str(content)
50
+
51
+
52
+ @dataclass(slots=True)
53
+ class PipelineStatus:
54
+ """Immutable snapshot of a pipeline thread."""
55
+
56
+ thread_id: str
57
+ values: dict[str, Any] = field(default_factory=dict)
58
+ next: tuple[str, ...] = ()
59
+
60
+ @property
61
+ def is_pending(self) -> bool:
62
+ """True while the graph is paused at the human review gate."""
63
+ return "review_gate" in self.next
64
+
65
+ @property
66
+ def approval_status(self) -> str:
67
+ return str(self.values.get("approval_status") or "pending")
68
+
69
+ @property
70
+ def digest(self) -> str:
71
+ return str(self.values.get("compiled_digest") or "")
72
+
73
+ def to_dict(
74
+ self, *, include_digest: bool = True, include_messages: bool = True
75
+ ) -> dict[str, Any]:
76
+ if self.values.get("error"):
77
+ state = "failed"
78
+ elif self.is_pending:
79
+ state = "awaiting_approval"
80
+ elif self.next:
81
+ state = "running"
82
+ else:
83
+ state = "completed"
84
+
85
+ payload: dict[str, Any] = {
86
+ "thread_id": self.thread_id,
87
+ "status": state,
88
+ "approval_status": self.approval_status,
89
+ "next": list(self.next),
90
+ "topic": self.values.get("topic"),
91
+ "source_count": len(self.values.get("raw_data") or []),
92
+ "research_step": self.values.get("research_step", 0),
93
+ "coverage": self.values.get("coverage_report") or {},
94
+ "provider_telemetry": self.values.get("provider_telemetry") or {},
95
+ "error": self.values.get("error"),
96
+ }
97
+ if include_digest:
98
+ payload["digest"] = self.digest
99
+ if include_messages:
100
+ payload["messages"] = [
101
+ _message_text(item) for item in (self.values.get("messages") or [])[-5:]
102
+ ]
103
+ return payload
104
+
105
+
106
+ class PipelineRunner:
107
+ """Owns the compiled graph and serializes operations per thread."""
108
+
109
+ def __init__(
110
+ self,
111
+ *,
112
+ checkpointer: BaseCheckpointSaver | None = None,
113
+ graph: Any | None = None,
114
+ ) -> None:
115
+ self.checkpointer = checkpointer or build_checkpointer()
116
+ self.graph = graph or build_graph(self.checkpointer)
117
+ self._locks: dict[str, asyncio.Lock] = {}
118
+
119
+ @staticmethod
120
+ def _config(thread_id: str) -> dict[str, Any]:
121
+ return {"configurable": {"thread_id": thread_id}}
122
+
123
+ def _lock(self, thread_id: str) -> asyncio.Lock:
124
+ return self._locks.setdefault(thread_id, asyncio.Lock())
125
+
126
+ async def aclose(self) -> None:
127
+ """Release the checkpointer's connection, if it owns one.
128
+
129
+ aiosqlite runs a non-daemon helper thread, so forgetting to close the
130
+ durable checkpointer keeps the process alive at exit.
131
+ """
132
+ conn = getattr(self.checkpointer, "conn", None)
133
+ if conn is not None:
134
+ try:
135
+ await conn.close()
136
+ logger.debug("Checkpointer connection closed")
137
+ except Exception:
138
+ logger.debug("Checkpointer close skipped", exc_info=True)
139
+ await asyncio.to_thread(get_observability().flush)
140
+
141
+ async def _drain(self, input_state: GraphState | None, thread_id: str) -> None:
142
+ async for _ in self.graph.astream(
143
+ input_state,
144
+ config=self._config(thread_id),
145
+ stream_mode="values",
146
+ ):
147
+ pass
148
+
149
+ async def start(
150
+ self, topic: str, *, thread_id: str | None = None
151
+ ) -> PipelineStatus:
152
+ """Execute until review or terminal failure under the configured deadline."""
153
+ topic = topic.strip()
154
+ if not topic:
155
+ raise ValueError("topic must not be empty")
156
+
157
+ thread_id = thread_id or uuid4().hex
158
+ initial: GraphState = {
159
+ "topic": topic,
160
+ "messages": [HumanMessage(content=f"Research request: {topic}")],
161
+ "research_plan": [],
162
+ "research_step": 0,
163
+ "coverage_report": {},
164
+ "raw_data": [],
165
+ "extracted_metrics": {},
166
+ "provider_telemetry": {},
167
+ "compiled_digest": "",
168
+ "approval_status": "pending",
169
+ "error": None,
170
+ }
171
+
172
+ with get_observability().observation(
173
+ name="loopgate.research",
174
+ input={"topic": topic},
175
+ metadata={"thread_id": thread_id},
176
+ ) as observation:
177
+ async with self._lock(thread_id):
178
+ snapshot = await self.graph.aget_state(self._config(thread_id))
179
+ if snapshot.values:
180
+ raise PipelineConflict(f"Thread already exists: {thread_id}")
181
+ try:
182
+ async with asyncio.timeout(get_settings().run_deadline_seconds):
183
+ await self._drain(initial, thread_id)
184
+ except TimeoutError:
185
+ logger.error("Research run exceeded the overall deadline: %s", thread_id)
186
+ await self.graph.aupdate_state(
187
+ self._config(thread_id),
188
+ {
189
+ "compiled_digest": "",
190
+ "approval_status": "pending",
191
+ "error": "Research run exceeded the overall deadline.",
192
+ },
193
+ as_node=FAILURE_NODE,
194
+ )
195
+
196
+ status = await self.status(thread_id)
197
+ observation.update(
198
+ output={
199
+ "status": status.to_dict(
200
+ include_digest=False, include_messages=False
201
+ )["status"],
202
+ "source_count": len(status.values.get("raw_data") or []),
203
+ "error": status.values.get("error"),
204
+ }
205
+ )
206
+ return status
207
+
208
+ async def resume(self, thread_id: str, action: str) -> PipelineStatus:
209
+ """Apply a human decision and continue the graph to completion."""
210
+ normalized = action.strip().lower()
211
+ if normalized in _APPROVE_ALIASES:
212
+ decision = "approved"
213
+ elif normalized in _REJECT_ALIASES:
214
+ decision = "rejected"
215
+ else:
216
+ raise ValueError("action must be 'approve' or 'reject'")
217
+
218
+ with get_observability().observation(
219
+ name="loopgate.review",
220
+ input={"thread_id": thread_id, "decision": decision},
221
+ metadata={"thread_id": thread_id},
222
+ ) as observation:
223
+ async with self._lock(thread_id):
224
+ snapshot = await self.graph.aget_state(self._config(thread_id))
225
+ if not snapshot.values:
226
+ raise PipelineNotFound(f"Unknown thread: {thread_id}")
227
+ if snapshot.values.get("error") or tuple(snapshot.next) != (REVIEW_NODE,):
228
+ raise PipelineNotAwaitingApproval(
229
+ f"Thread {thread_id} is not waiting for approval."
230
+ )
231
+
232
+ await self.graph.aupdate_state(
233
+ self._config(thread_id), {"approval_status": decision}
234
+ )
235
+ await self._drain(None, thread_id)
236
+
237
+ status = await self.status(thread_id)
238
+ observation.update(
239
+ output={
240
+ "status": status.to_dict(
241
+ include_digest=False, include_messages=False
242
+ )["status"],
243
+ "approval_status": status.approval_status,
244
+ }
245
+ )
246
+ return status
247
+
248
+ async def status(self, thread_id: str) -> PipelineStatus:
249
+ """Return the current checkpoint snapshot for ``thread_id``."""
250
+ snapshot = await self.graph.aget_state(self._config(thread_id))
251
+ if not snapshot.values:
252
+ raise PipelineNotFound(f"Unknown thread: {thread_id}")
253
+ return PipelineStatus(
254
+ thread_id=thread_id,
255
+ values=dict(snapshot.values),
256
+ next=tuple(snapshot.next),
257
+ )
src/utils/__init__.py ADDED
File without changes
@@ -0,0 +1,151 @@
1
+ """Optional, failure-isolated Langfuse tracing for graph and provider execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+ from collections.abc import Awaitable, Callable, Iterator
8
+ from contextlib import contextmanager
9
+ from dataclasses import dataclass
10
+ from functools import lru_cache, wraps
11
+ from importlib import import_module
12
+ from typing import Any
13
+
14
+ from src.config import get_settings
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @dataclass(slots=True)
20
+ class _SafeObservation:
21
+ observation: Any = None
22
+
23
+ def update(self, **kwargs: Any) -> None:
24
+ if self.observation is None:
25
+ return
26
+ try:
27
+ self.observation.update(**kwargs)
28
+ except Exception:
29
+ logger.debug("Langfuse observation update failed", exc_info=True)
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class Observability:
34
+ """Small no-op-compatible wrapper around the optional Langfuse SDK."""
35
+
36
+ client: Any = None
37
+
38
+ @contextmanager
39
+ def observation(
40
+ self,
41
+ *,
42
+ name: str,
43
+ as_type: str = "span",
44
+ input: dict[str, Any] | None = None,
45
+ metadata: dict[str, Any] | None = None,
46
+ model: str | None = None,
47
+ ) -> Iterator[_SafeObservation]:
48
+ """Create one observation, or yield a no-op when tracing is disabled."""
49
+ if self.client is None:
50
+ yield _SafeObservation()
51
+ return
52
+ kwargs: dict[str, Any] = {"name": name, "as_type": as_type}
53
+ if input is not None:
54
+ kwargs["input"] = input
55
+ if metadata is not None:
56
+ kwargs["metadata"] = metadata
57
+ if model is not None:
58
+ kwargs["model"] = model
59
+ try:
60
+ manager = self.client.start_as_current_observation(**kwargs)
61
+ observation = manager.__enter__()
62
+ except Exception:
63
+ logger.warning("Langfuse observation failed; continuing untraced", exc_info=True)
64
+ yield _SafeObservation()
65
+ return
66
+ try:
67
+ yield _SafeObservation(observation)
68
+ except BaseException:
69
+ try:
70
+ manager.__exit__(*sys.exc_info())
71
+ except Exception:
72
+ logger.debug("Langfuse observation close failed", exc_info=True)
73
+ raise
74
+ else:
75
+ try:
76
+ manager.__exit__(None, None, None)
77
+ except Exception:
78
+ logger.debug("Langfuse observation close failed", exc_info=True)
79
+
80
+ def flush(self) -> None:
81
+ """Flush queued traces during CLI/API shutdown without failing cleanup."""
82
+ if self.client is None:
83
+ return
84
+ try:
85
+ self.client.flush()
86
+ except Exception:
87
+ logger.warning("Langfuse flush failed during shutdown", exc_info=True)
88
+
89
+
90
+ @lru_cache(maxsize=1)
91
+ def get_observability() -> Observability:
92
+ """Build the optional client lazily from centralized settings."""
93
+ settings = get_settings()
94
+ if not settings.langfuse_public_key or not settings.langfuse_secret_key:
95
+ return Observability()
96
+ try:
97
+ module = import_module("langfuse")
98
+ client = module.Langfuse(
99
+ public_key=settings.langfuse_public_key,
100
+ secret_key=settings.langfuse_secret_key,
101
+ base_url=settings.langfuse_host,
102
+ )
103
+ except ImportError:
104
+ logger.warning("Langfuse is configured but the 'observability' extra is not installed")
105
+ return Observability()
106
+ except Exception:
107
+ logger.exception("Langfuse initialization failed; continuing untraced")
108
+ return Observability()
109
+ return Observability(client=client)
110
+
111
+
112
+ def _node_output(result: dict[str, Any]) -> dict[str, Any]:
113
+ coverage = result.get("coverage_report") or {}
114
+ metrics = result.get("extracted_metrics") or {}
115
+ return {
116
+ "research_step": result.get("research_step"),
117
+ "planned_queries": len(result.get("research_plan") or []),
118
+ "source_count": len(result.get("raw_data") or []),
119
+ "coverage_status": coverage.get("status"),
120
+ "planning_mode": coverage.get("planning_mode"),
121
+ "approval_status": result.get("approval_status"),
122
+ "model_provider": metrics.get("model_provider"),
123
+ "fallback_reason": metrics.get("fallback_reason"),
124
+ "error": result.get("error"),
125
+ }
126
+
127
+
128
+ def traced_node(
129
+ name: str,
130
+ ) -> Callable[
131
+ [Callable[[dict[str, Any]], Awaitable[dict[str, Any]]]],
132
+ Callable[[dict[str, Any]], Awaitable[dict[str, Any]]],
133
+ ]:
134
+ """Trace a graph node using only sanitized execution metadata."""
135
+
136
+ def decorator(
137
+ function: Callable[[dict[str, Any]], Awaitable[dict[str, Any]]],
138
+ ) -> Callable[[dict[str, Any]], Awaitable[dict[str, Any]]]:
139
+ @wraps(function)
140
+ async def wrapper(state: dict[str, Any]) -> dict[str, Any]:
141
+ with get_observability().observation(
142
+ name=f"loopgate.node.{name}",
143
+ input={"research_step": state.get("research_step", 0)},
144
+ ) as observation:
145
+ result = await function(state)
146
+ observation.update(output=_node_output(result))
147
+ return result
148
+
149
+ return wrapper
150
+
151
+ return decorator