initial commit: retrieval + agent artifacts

This commit is contained in:
Danil Poliakov
2026-10-28 20:44:23 +07:00
commit 17e4fab0d2
13 changed files with 630 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
__pycache__/
runs.db
results/
.venv/
+60
View File
@@ -0,0 +1,60 @@
# agent-graph
A small agent loop built on LangGraph, with a checkpointer, retrieval tools and acceptance
that is checked by rules instead of a second model.
## Loop
```
plan -> retrieve (search_docs) -> answer -> verify
^ |
+-- retry <--+ (max 2 attempts)
```
- **plan** — the model returns a validated `Plan` (1-4 steps, each with a tool and a query).
- **retrieve** — one tool, `search_docs`, calling the rag-lab HTTP API.
- **answer** — must answer strictly from retrieved chunks and cite them as `[chunk-id]`.
- **verify** — pure rules: answer is not empty, every citation exists in the retrieved set,
a citation to a document that was not retrieved is rejected, and the required fact must be
present verbatim. Retry carries the rejection reasons back into the state.
## Why rules for acceptance
An LLM judge approving its own answer is the same problem as an agent writing its own report:
both reward confidence. Deterministic checks are boring and reproducible, and they fail for the
right reason.
## Checkpointer
SQLite-backed (`langgraph-checkpoint-sqlite`), one thread id per task: after a run the whole
state can be replayed with `graph.get_state(config)`.
## Run
```bash
pip install -e ".[dev]"
python scripts/build_tasks.py # 12 tasks from BEIR test qrels
python scripts/run_tasks.py # needs rag-lab API on 127.0.0.1:8088
pytest -q
```
Environment: `AGENT_GATE_URL` (OpenAI-compatible endpoint), `AGENT_MODEL`, `AGENT_GATE_KEY_FILE`.
## Results
12 tasks built from BEIR test qrels (real query, gold document, a verbatim span from that document):
| metric | value |
|--------|-------|
| accepted | 12 / 12 |
| gold document in top-8 | 12 / 12 |
| p50 end-to-end | 6.8 s |
| p95 end-to-end | 29.6 s |
Earlier run with top-5 chunks passed 10 / 12: the document was retrieved but the chunk holding
the required span was not, and the verifier rejected the answer for a missing fact. Retrieving
8 chunks fixed both tasks. That failure is the point of a rules-based verifier: it fails for a
specific, inspectable reason.
Model: deepseek-v4.1-flash through a local OpenAI-compatible gateway, temperature 0. Run log and
per-task verdicts: `results/runs.json`, checkpoints: `runs.db` (one thread per task).
+12
View File
@@ -0,0 +1,12 @@
{"id": "t001", "question": "Lack of clpC does not affect sporulation efficiency in Bacillus subtilis cells.", "gold_doc": "4942718", "required_fact": "Several mutants had novel sporulation phenotypes", "source": "beir-scifact:684"}
{"id": "t002", "question": "Commelina yellow mottle virus' (ComYMV) genome consists of 7489 baise pairs.", "gold_doc": "14376683", "required_fact": "We have demonstrated that a construct containing 1", "source": "beir-scifact:279"}
{"id": "t003", "question": "NF2 (Merlin) causes phosphorylation and subsequent cytoplasmic sequestration of YAP in Drosophila by activating LATS1/2 kinases.", "gold_doc": "1897324", "required_fact": "To identify components of this pathway, we performed an RNAi-based kinome screen in human cells", "source": "beir-scifact:830"}
{"id": "t004", "question": "Women with a higher birth weight are more likely to develop breast cancer later in life.", "gold_doc": "23557241", "required_fact": "26]) or maternal diethylstilbestrol treatment (1", "source": "beir-scifact:1379"}
{"id": "t005", "question": "Antibiotic induced alterations in the gut microbiome reduce resistance against Clostridium difficile", "gold_doc": "6372244", "required_fact": "In vitro and ex vivo analyses demonstrate that C", "source": "beir-scifact:118"}
{"id": "t006", "question": "Auditory entrainment is strengthened when people see congruent visual and auditory information.", "gold_doc": "6955746", "required_fact": "One provocative hypothesis deriving from neurophysiology suggests that there exists early and direct cross-modal phase modulation", "source": "beir-scifact:141"}
{"id": "t007", "question": "The DdrB protein from Deinococcus radiodurans is an alternative SSB.", "gold_doc": "15305881", "required_fact": "that is crucial for recovery following DNA damage", "source": "beir-scifact:1163"}
{"id": "t008", "question": "Birth-weight is positively associated with breast cancer.", "gold_doc": "17450673", "required_fact": "18] for > or =3,000 g relative to <3,000 g)", "source": "beir-scifact:179"}
{"id": "t009", "question": "Metastatic colorectal cancer treated with a single agent fluoropyrimidines resulted in reduced efficacy and lower quality of life when compared with oxaliplatin-based chemotherapy in elderly patients.", "gold_doc": "15476777", "required_fact": "This study is registered, number ISRCTN21221452", "source": "beir-scifact:770"}
{"id": "t010", "question": "The repair of Cas9-induced double strand breaks in human DNA is error-prone.", "gold_doc": "44172171", "required_fact": "Furthermore, repair of the DSBs tends to be error prone", "source": "beir-scifact:1262"}
{"id": "t011", "question": "Articles published in open access format are more likely to be cited than traditional journals.", "gold_doc": "27768226", "required_fact": "It is therefore fitting that we publish such a paper", "source": "beir-scifact:130"}
{"id": "t012", "question": "Smc5/6 engagment drives the activation of SUMO E3 ligase Mms21 by ATP-dependent remolding.", "gold_doc": "17628888", "required_fact": "Yet how the activity of the SUMO ligase is controlled remains unknown", "source": "beir-scifact:1089"}
+29
View File
@@ -0,0 +1,29 @@
[project]
name = "agent-graph"
version = "0.1.0"
description = "A small agent loop on LangGraph with a checkpointer, MCP-style tools and rule-based acceptance"
requires-python = ">=3.11"
dependencies = [
"langgraph>=0.2",
"langgraph-checkpoint-sqlite>=2",
"langchain-openai>=0.2",
"httpx>=0.27",
]
[project.optional-dependencies]
dev = ["pytest>=8", "ruff>=0.6"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/agentgraph"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
[tool.ruff]
line-length = 120
target-version = "py311"
+107
View File
@@ -0,0 +1,107 @@
{
"summary": {
"tasks": 12,
"accepted": 12,
"retrieved_gold": 12,
"p50_ms": 6845.3,
"p95_ms": 29572.2
},
"runs": [
{
"task": "t001",
"verdict": "pass",
"attempts": 2,
"gold_retrieved": true,
"took_ms": 29977.9,
"reasons": []
},
{
"task": "t002",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 5578.3,
"reasons": []
},
{
"task": "t003",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 12707.1,
"reasons": []
},
{
"task": "t004",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 7719.7,
"reasons": []
},
{
"task": "t005",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 6291.3,
"reasons": []
},
{
"task": "t006",
"verdict": "pass",
"attempts": 2,
"gold_retrieved": true,
"took_ms": 29572.2,
"reasons": []
},
{
"task": "t007",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 6340.6,
"reasons": []
},
{
"task": "t008",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 5450.9,
"reasons": []
},
{
"task": "t009",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 17323.9,
"reasons": []
},
{
"task": "t010",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 2708.0,
"reasons": []
},
{
"task": "t011",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 3409.9,
"reasons": []
},
{
"task": "t012",
"verdict": "pass",
"attempts": 1,
"gold_retrieved": true,
"took_ms": 7350.0,
"reasons": []
}
]
}
+13
View File
@@ -0,0 +1,13 @@
{"task": "t001", "verdict": "pass", "attempts": 2, "gold_retrieved": true, "took_ms": 29977.9, "reasons": []}
{"task": "t002", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 5578.3, "reasons": []}
{"task": "t003", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 12707.1, "reasons": []}
{"task": "t004", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 7719.7, "reasons": []}
{"task": "t005", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 6291.3, "reasons": []}
{"task": "t006", "verdict": "pass", "attempts": 2, "gold_retrieved": true, "took_ms": 29572.2, "reasons": []}
{"task": "t007", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 6340.6, "reasons": []}
{"task": "t008", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 5450.9, "reasons": []}
{"task": "t009", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 17323.9, "reasons": []}
{"task": "t010", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 2708.0, "reasons": []}
{"task": "t011", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 3409.9, "reasons": []}
{"task": "t012", "verdict": "pass", "attempts": 1, "gold_retrieved": true, "took_ms": 7350.0, "reasons": []}
{"tasks": 12, "accepted": 12, "retrieved_gold": 12, "p50_ms": 6845.3, "p95_ms": 29572.2}
+66
View File
@@ -0,0 +1,66 @@
"""Build evaluation tasks from BEIR qrels: real queries, real gold documents.
The required fact is a short verbatim span from the gold document, so the
verifier can reject an answer that paraphrased it away or cited the wrong chunk.
"""
from __future__ import annotations
import argparse
import json
import random
import sys
from pathlib import Path
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--data", default="../rag-lab/data/scifact")
parser.add_argument("--count", type=int, default=12)
parser.add_argument("--out", default="data/tasks.jsonl")
parser.add_argument("--seed", type=int, default=7)
args = parser.parse_args()
root = Path(args.data)
queries = {row["_id"]: row["text"] for row in map(json.loads, (root / "queries.jsonl").read_text(encoding="utf-8").splitlines()) if row}
corpus = {row["_id"]: row for row in map(json.loads, (root / "corpus.jsonl").read_text(encoding="utf-8").splitlines()) if row}
pairs = []
for line in (root / "qrels" / "test.tsv").read_text(encoding="utf-8").splitlines()[1:]:
if not line.strip():
continue
qid, did, score = line.split("\t")
if int(score) >= 1 and qid in queries and did in corpus:
pairs.append((qid, did))
rng = random.Random(args.seed)
chosen: list[tuple[str, str]] = []
seen_docs: set[str] = set()
for pair in rng.sample(pairs, len(pairs)):
if pair[1] in seen_docs:
continue
chosen.append(pair)
seen_docs.add(pair[1])
if len(chosen) >= args.count:
break
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
with out.open("w", encoding="utf-8") as handle:
for index, (qid, did) in enumerate(chosen, start=1):
doc = corpus[did]
sentences = [s.strip().replace("\n", " ") for s in doc.get("text", ". ").split(".")
if 40 < len(s.strip()) < 220]
span = min(sentences, key=len) if sentences else ""
handle.write(json.dumps({
"id": f"t{index:03d}",
"question": queries[qid],
"gold_doc": did,
"required_fact": span,
"source": f"beir-scifact:{qid}",
}, ensure_ascii=False) + "\n")
print(f"tasks={len(chosen)} -> {out}")
return 0
if __name__ == "__main__":
sys.exit(main())
+63
View File
@@ -0,0 +1,63 @@
"""Run the agent over tasks and report acceptance, not vibes."""
from __future__ import annotations
import argparse
import json
import statistics
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from langgraph.checkpoint.sqlite import SqliteSaver # noqa: E402
from agentgraph.graph import build_graph # noqa: E402
from agentgraph.state import initial_state # noqa: E402
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--tasks", default="data/tasks.jsonl")
parser.add_argument("--out", default="results/runs.json")
parser.add_argument("--limit", type=int, default=0)
args = parser.parse_args()
tasks = [json.loads(line) for line in Path(args.tasks).read_text(encoding="utf-8").splitlines() if line]
if args.limit:
tasks = tasks[: args.limit]
rows = []
with SqliteSaver.from_conn_string("runs.db") as checkpointer:
graph = build_graph(checkpointer=checkpointer)
for task in tasks:
started = time.perf_counter()
state = graph.invoke(initial_state(task), {"configurable": {"thread_id": task["id"]}})
took = (time.perf_counter() - started) * 1000
retrieved_gold = any(d["doc_id"] == task["gold_doc"] for d in state["docs"])
rows.append({
"task": task["id"],
"verdict": state["verdict"].get("status"),
"attempts": state["attempts"],
"gold_retrieved": retrieved_gold,
"took_ms": round(took, 1),
"reasons": state["verdict"].get("reasons", []),
})
print(json.dumps(rows[-1], ensure_ascii=False))
summary = {
"tasks": len(rows),
"accepted": sum(r["verdict"] == "pass" for r in rows),
"retrieved_gold": sum(r["gold_retrieved"] for r in rows),
"p50_ms": statistics.median([r["took_ms"] for r in rows]) if rows else 0,
"p95_ms": sorted([r["took_ms"] for r in rows])[int(len(rows) * 0.95) - 1] if rows else 0,
}
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps({"summary": summary, "runs": rows}, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(summary, ensure_ascii=False))
return 0
if __name__ == "__main__":
sys.exit(main())
+98
View File
@@ -0,0 +1,98 @@
"""Agent loop: plan -> retrieve -> answer -> verify.
The verifier is rules, not another model: a claim that cannot be tied to a
retrieved chunk is rejected, and the retry carries the reason back into state.
"""
from __future__ import annotations
import re
from . import llm
from .state import Plan, State, Verdict, initial_state
from .tools import search_docs
def plan_node(state: State) -> dict:
task = state["task"]
plan: Plan = llm.structured(
"You plan retrieval steps. Reply with JSON.",
f"Task: {task['question']}\nRequired fact to find: {task.get('required_fact','')}\n"
"One or two steps: each has intent, tool (search_docs or none) and a query.",
Plan,
)
return {"plan": [step.model_dump() for step in plan.steps]}
def retrieve_node(state: State) -> dict:
steps = [s for s in state["plan"] if s["tool"] == "search_docs"]
query = steps[0]["query"] if steps else state["task"]["question"]
docs = search_docs(query, k=8)
return {"search_query": query, "docs": docs}
def answer_node(state: State) -> dict:
task = state["task"]
context = "\n\n".join(f"[{d['id']}] {d['title']}\n{d['text']}" for d in state["docs"])
retry = ""
if state.get("verdict", {}).get("status") == "retry":
retry = "\nPrevious attempt rejected:\n" + "; ".join(state["verdict"].get("reasons", []))
required = task.get("required_fact") or ""
answer = llm.plain(
"Answer strictly from the context. "
"Quote the required wording verbatim when it appears, then cite the chunk as [chunk-id] "
"using the id from the context. "
"If the context has no answer, write exactly: NOT FOUND",
f"Question: {task['question']}\n"
f"Required wording to quote: {required}\n\n"
f"Context:\n{context}\n{retry}",
)
# The retry counter belongs to answer attempts: verifying alone must not
# extend the loop.
return {"answer": answer, "attempts": state["attempts"] + 1}
def verify_node(state: State) -> dict:
task = state["task"]
answer = state["answer"]
known = {d["id"] for d in state["docs"]}
reasons: list[str] = []
if answer == "NOT FOUND" or not answer:
reasons.append("empty answer")
cites = re.findall(r"\[([A-Za-z0-9_.-]+:[0-9a-f]{6,64})\]", answer)
unknown = [c for c in cites if ":" in c and c not in known]
if cites and unknown:
reasons.append(f"cite not in retrieved set: {unknown[0]}")
if not cites:
reasons.append("no citation")
fact = task.get("required_fact") or ""
if fact and fact.lower() not in answer.lower():
reasons.append("required fact missing")
status = "pass" if not reasons else ("retry" if state["attempts"] < 2 else "fail")
verdict = Verdict(status=status, reasons=reasons).model_dump()
return {"verdict": verdict, "cites": cites}
def build_graph(checkpointer=None):
from langgraph.graph import END, START, StateGraph
builder = StateGraph(State)
builder.add_node("plan", plan_node)
builder.add_node("retrieve", retrieve_node)
builder.add_node("answer", answer_node)
builder.add_node("verify", verify_node)
builder.add_edge(START, "plan")
builder.add_edge("plan", "retrieve")
builder.add_edge("retrieve", "answer")
builder.add_edge("answer", "verify")
builder.add_conditional_edges(
"verify",
lambda state: "answer" if state["verdict"]["status"] == "retry" else END,
{"answer": "answer", END: END},
)
return builder.compile(checkpointer=checkpointer)
def run(task: dict, config: dict | None = None) -> dict:
graph = build_graph()
final = graph.invoke(initial_state(task), config or {"configurable": {"thread_id": task["id"]}})
return final
+77
View File
@@ -0,0 +1,77 @@
"""Thin chat helper over an OpenAI-compatible gateway.
No prompt templating, no chains: the caller owns the prompt and the output shape.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import time
from langchain_openai import ChatOpenAI
def default_key_path() -> str:
return os.getenv("AGENT_GATE_KEY_FILE", str(Path.home() / ".kodlo" / "lgagent_gate_key.txt"))
def model() -> ChatOpenAI:
key = Path(default_key_path()).read_text(encoding="utf-8").strip()
return ChatOpenAI(
model=os.getenv("AGENT_MODEL", "deepseek-v4.1-flash"),
base_url=os.getenv("AGENT_GATE_URL", "http://192.168.0.195:8790/v1"),
api_key=key,
temperature=0,
timeout=120,
)
def _extract_json(text: str) -> str:
text = text.strip()
if text.startswith("```"):
text = text.strip("`")
text = text[text.find("{"):]
start, end = text.find("{"), text.rfind("}")
if start == -1 or end <= start:
raise ValueError(f"no JSON object in reply: {text[:160]}")
return text[start : end + 1]
def _invoke(messages: list[dict], attempts: int = 4):
"""Invoke with backoff on 429: the gateway enforces a per-key request budget."""
client = model()
last: Exception | None = None
for attempt in range(attempts):
try:
return client.invoke(messages)
except Exception as exc: # noqa: BLE001
if "429" not in str(exc) and "RateLimit" not in type(exc).__name__:
raise
last = exc
time.sleep(45)
raise last
def structured(system: str, user: str, schema, attempts: int = 2) -> object:
"""JSON in the reply, parsed and validated against the schema.
Forced tool_choice is not used: the gateway model runs in thinking mode and
rejects it. One corrective retry, then fail with the validation error.
"""
prompt = f"{system}\nReturn ONE JSON object only. No prose.\n\n{user}"
last: Exception | None = None
for attempt in range(attempts):
reply = str(_invoke([{"role": "user", "content": prompt}]).content)
try:
return schema.model_validate_json(_extract_json(reply))
except Exception as exc: # noqa: BLE001 - one retry with the error text
last = exc
prompt += f"\n\nYour previous reply was rejected: {exc}. Return corrected JSON."
raise ValueError(f"structured output failed: {last}")
def plain(system: str, user: str) -> str:
reply = _invoke([{"role": "system", "content": system}, {"role": "user", "content": user}])
return str(reply.content).strip()
+49
View File
@@ -0,0 +1,49 @@
"""Graph state. Everything the agent may carry forward lives here, nothing else."""
from __future__ import annotations
from typing import Annotated, Literal, Sequence
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
class PlanStep(BaseModel):
intent: str = Field(min_length=3, max_length=200)
tool: Literal["search_docs", "none"] = "none"
query: str = ""
class Plan(BaseModel):
steps: list[PlanStep] = Field(min_length=1, max_length=4)
class Verdict(BaseModel):
status: Literal["pass", "retry", "fail"]
reasons: list[str] = []
class State(TypedDict):
task: dict
plan: list[dict]
search_query: str
docs: Annotated[
list[dict],
lambda a, b: list({**{d["id"]: d for d in a}, **{d["id"]: d for d in b}}.values()),
]
answer: str
cites: Annotated[Sequence[str], lambda a, b: list(dict.fromkeys([*a, *b]))]
verdict: dict
attempts: int
def initial_state(task: dict) -> State:
return {
"task": task,
"plan": [],
"search_query": "",
"docs": [],
"answer": "",
"cites": [],
"verdict": {},
"attempts": 0,
}
+18
View File
@@ -0,0 +1,18 @@
"""Tools: the search tool calls the rag-lab HTTP API, nothing else."""
from __future__ import annotations
import os
import httpx
RAG_URL = os.getenv("RAG_URL", "http://127.0.0.1:8088")
def search_docs(query: str, k: int = 8) -> list[dict]:
response = httpx.get(f"{RAG_URL}/search", params={"q": query, "mode": "hybrid", "k": k}, timeout=60)
response.raise_for_status()
payload = response.json()
return [
{"id": hit["id"], "doc_id": hit["doc_id"], "title": hit["title"], "text": hit["text"], "score": hit["score"]}
for hit in payload["hits"]
]
+34
View File
@@ -0,0 +1,34 @@
from agentgraph.state import initial_state
from agentgraph.graph import verify_node
def state_for(answer, docs, attempts=1, required=None):
state = initial_state({"id": "t1", "question": "q", "required_fact": required})
state["docs"] = docs
state["answer"] = answer
state["attempts"] = attempts
return state
DOC = {"id": "d1:a1b2c3d4e5f6", "doc_id": "d1", "title": "T", "text": "text", "score": 1.0}
def test_pass_needs_citation_and_fact():
out = verify_node(state_for("Answer [d1:a1b2c3d4e5f6] with fact-42", [DOC], required="fact-42"))
assert out["verdict"]["status"] == "pass"
def test_unknown_citation_is_rejected():
out = verify_node(state_for("Answer [zz:000000000000] fact-42", [DOC], required="fact-42"))
assert out["verdict"]["status"] == "retry"
assert "not in retrieved set" in out["verdict"]["reasons"][0]
def test_missing_fact_is_rejected():
out = verify_node(state_for("Answer [d1:a1b2c3d4e5f6]", [DOC], required="fact-42"))
assert out["verdict"]["status"] == "retry"
def test_retry_becomes_fail_on_second_attempt():
out = verify_node(state_for("NOT FOUND", [DOC], attempts=2, required="fact-42"))
assert out["verdict"]["status"] == "fail"