Spaces:
Running on Zero

Pawan2605's picture
Deploy ControlPlane.ai
5e0b6f8 verified
Raw History Blame Contribute Delete
6.98 kB
"""
One chat turn as a stream of (event, data) tuples - the HTTP-free core of the
API's /api/query and /api/resume endpoints.
Mirrors what the Streamlit app's `_run` did: creates the thread on first use,
persists the user's message, forwards every `stream_run` event, and persists
the assistant's answer (or the HITL question) with the same payload shape
(`verdict`, `badges`, `meta`) so a thread reloads identically in either UI.
Events (data is always a dict):
meta {"thread_id"}
node {"node"}
answer_start {}
token {"token"}
reset {}
answer_done {"answer"}
interrupt the interrupt payload (+ "graph_thread")
final {"state"} state without private "_" keys
done {}
Errors raised BEFORE the first event (so the HTTP layer can map them):
PermissionError - thread not owned by this user
LookupError - resume requested but the HITL checkpoint is gone
RuntimeError - "rate_limited"
PermissionError - also when `graph_thread` was paused by a different user
"""
from __future__ import annotations
import time
import traceback
from collections import OrderedDict
from typing import Any, Dict, Iterator, Optional, Tuple
from controlplane.app import store
from controlplane.app.runner import has_checkpoint, stream_run
from controlplane.state import Stage
Event = Tuple[str, Dict[str, Any]]
# graph_thread (a paused HITL run) -> user id that owns it. The checkpoint itself
# holds the original user's state, so a resume must come from the same user -
# never trust the id in the request body alone. Bounded; entries are dropped on
# resume or when the checkpoint turns out to be gone.
_GRAPH_OWNERS: "OrderedDict[str, str]" = OrderedDict()
_OWNERS_MAX = 2000
def remember_graph_owner(graph_thread: str, user_id: str) -> None:
_GRAPH_OWNERS[graph_thread] = user_id
_GRAPH_OWNERS.move_to_end(graph_thread)
while len(_GRAPH_OWNERS) > _OWNERS_MAX:
_GRAPH_OWNERS.popitem(last=False)
def graph_owner(graph_thread: Optional[str]) -> Optional[str]:
return _GRAPH_OWNERS.get(graph_thread or "")
def forget_graph_owner(graph_thread: Optional[str]) -> None:
_GRAPH_OWNERS.pop(graph_thread or "", None)
def rate_limited(user_id: str, hourly_limit: int) -> bool:
"""True when the user has reached the per-hour question limit. 0 or a negative
limit means unlimited (same meaning as the Streamlit app and DEPLOYMENT.md)."""
if hourly_limit <= 0:
return False
return store.count_user_queries_since(user_id, time.time() - 3600) >= hourly_limit
def _public_state(state: Dict[str, Any]) -> Dict[str, Any]:
return {k: v for k, v in (state or {}).items() if not str(k).startswith("_")}
def run_chat(
user_id: str,
*,
query: Optional[str],
thread_id: Optional[str],
forced_kb: Optional[str],
resume: Optional[str] = None,
graph_thread: Optional[str] = None,
hourly_limit: int = 40,
) -> Iterator[Event]:
if thread_id and not store.owns_thread(user_id, thread_id):
raise PermissionError("thread does not belong to this user")
if resume is not None:
owner = graph_owner(graph_thread)
if owner is not None and owner != user_id:
raise PermissionError("paused run does not belong to this user")
if owner is None or not has_checkpoint(graph_thread):
forget_graph_owner(graph_thread)
raise LookupError("hitl_expired")
forget_graph_owner(graph_thread) # consumed; a new interrupt re-registers it
if rate_limited(user_id, hourly_limit):
raise RuntimeError("rate_limited")
if not thread_id:
title = " ".join((query or "New chat").split())[:60]
thread_id = store.create_thread(user_id, title)
if resume is not None:
store.add_message(user_id, thread_id, "user", f"↳ (clarification) {resume.strip()}")
else:
store.add_message(user_id, thread_id, "user", query or "")
yield ("meta", {"thread_id": thread_id})
t0 = time.time()
tokens: list[str] = []
streamed = ""
final_state: Dict[str, Any] = {}
progress: Dict[str, Any] = {"stage": Stage.START, "visited": []}
try:
for kind, payload in stream_run(query, thread_id, resume=resume, graph_thread=graph_thread,
progress=progress, forced_kb=forced_kb, cache_ns=user_id):
if kind == "node":
yield ("node", {"node": payload, "stage": progress["stage"], "visited": list(progress["visited"])})
elif kind == "answer_start":
yield ("answer_start", {})
elif kind == "reset":
tokens = []
yield ("reset", {})
elif kind == "token":
tokens.append(payload)
yield ("token", {"token": payload})
elif kind == "answer_done":
streamed = payload or "".join(tokens)
yield ("answer_done", {"answer": streamed})
elif kind == "interrupt":
p = dict(payload)
p["graph_thread"] = p.pop("_graph_thread", graph_thread)
q = p.get("question") or "More information is needed."
entry = {"verdict": "HUMAN-IN-THE-LOOP", "badges": ["HUMAN-IN-THE-LOOP"],
"meta": {"route": p.get("selected_kb"), "latency_s": round(time.time() - t0, 2)}}
store.add_message(user_id, thread_id, "assistant", q, payload=entry)
if p.get("graph_thread"):
remember_graph_owner(str(p["graph_thread"]), user_id)
yield ("interrupt", p)
yield ("done", {})
return
elif kind == "final":
final_state = payload or {}
except Exception as exc: # noqa: BLE001 - surface as an event, keep the server alive
traceback.print_exc()
yield ("error", {"code": "internal", "message": f"Something went wrong while answering ({type(exc).__name__}). Please try again."})
yield ("done", {})
return
final = final_state.get("final_answer") or streamed or "".join(tokens) or "(no answer)"
entry = {
"verdict": final_state.get("final_verdict"),
"badges": final_state.get("final_verdict_badges", []),
"meta": {
"decision": final_state.get("final_decision"),
"route": final_state.get("selected_kb"),
"model": (final_state.get("model_used") or "").split("/")[-1],
"latency_s": round(time.time() - t0, 2),
"graph_ms": final_state.get("total_latency_ms"),
},
}
public = _public_state(final_state)
try:
store.add_message(user_id, thread_id, "assistant", final, payload=entry, state=public)
except Exception:
traceback.print_exc()
yield ("final", {"state": public, "answer": final, **entry})
yield ("done", {})