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
+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"]
]