Source code for reli.agent

"""The ReLI agent: one conversational session with one robot."""

from __future__ import annotations

import itertools
import json
import logging
import threading
import time
from collections import deque
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path

import numpy as np

from .actions import Catalog, expand, is_motion
from .config import ReLIConfig
from .consent import ConsentClassifier, normalise
from .executor import ExecutionReport, Executor, Reporter, fmt
from .interaction_log import InteractionLog
from .llm import ChatMessage, LLMError, LLMProvider
from .localization import Localizer
from .perception import Grounder
from .planner import Plan, Planner, PlanningContext
from .prompts import Prompts, render
from .robot.base import Robot
from .safety import SafetyGuard, SafetyReport
from .types import Action, Event

log = logging.getLogger(__name__)


[docs] @dataclass class TurnResult: turn_id: int text: str language: str plan: Plan | None = None primitives: list[Action] = field(default_factory=list) safety: SafetyReport | None = None outcome: str = "" # replied | executing | awaiting_consent | cancelled | rejected | error responses: list[str] = field(default_factory=list)
@dataclass class _Pending: turn_id: int plan: Plan actions: list[Action] language: str created: float = field(default_factory=time.monotonic)
[docs] class ReLIAgent: def __init__( self, cfg: ReLIConfig, robot: Robot, provider: LLMProvider, grounder: Grounder | None = None, on_event: Callable[[Event], None] = lambda e: None, log_dir: str | None = None, ): self.cfg = cfg self.robot = robot self.provider = provider self.grounder = grounder self.on_event = on_event self.prompts = Prompts.load(cfg.resolve(cfg.prompts_file) if cfg.prompts_file else None) run_dir = Path(log_dir or cfg.logging.dir).expanduser() # relative to the CWD self.catalog = Catalog( {"camera"} if grounder is not None else set(), list(cfg.destinations), cfg.safety.allowed_actions, ) self.planner = Planner(cfg, provider, self.prompts, self.catalog) self.localizer = Localizer( provider, self.prompts, run_dir / "translations.json" if cfg.logging.cache_translations else None, ) self.consent = ConsentClassifier(cfg.consent, provider, self.prompts) self.guard = SafetyGuard(cfg) self.executor = Executor(cfg, robot, grounder, self.guard) self.journal = InteractionLog(run_dir) self.language = cfg.language.fixed or cfg.language.default self.history: deque[ChatMessage] = deque(maxlen=2 * cfg.llm.history_turns) self._stop_phrases = {normalise(p) for p in cfg.safety.stop_phrases} self._pending: _Pending | None = None self._turn_lock = threading.Lock() self._ids = itertools.count(1) self._current: TurnResult | None = None self._first_response: float | None = None
[docs] def handle(self, text: str, language: str | None = None) -> TurnResult: """Process one user utterance synchronously. ``language`` (BCP-47) fixes the language for this turn, as when the user selects it in the interface.""" text = (text or "").strip() with self._turn_lock: fixed = language or self.cfg.language.fixed turn = TurnResult(next(self._ids), text, fixed or self.language) self._current, self._first_response = turn, None t0 = time.time() try: if text: self._turn(turn, fixed) except Exception as exc: # never kill the caller's thread log.exception("Turn %d failed", turn.turn_id) turn.outcome = "error" self._respond(self.localizer.message("rephrase", self.language)) turn.responses.append(f"[internal error: {exc}]") finally: self._journal(turn, t0) self._current = None return turn
[docs] def emergency_stop(self) -> None: """Stop immediately, cancel the running plan and any plan awaiting consent.""" self._pending = None self.executor.emergency_stop() self._respond(self.localizer.message("stopped", self.language))
@property def awaiting_consent(self) -> bool: return self._pending is not None def close(self) -> None: self.executor.cancel_motion() self.robot.close() def _turn(self, turn: TurnResult, fixed: str | None) -> None: if normalise(turn.text) in self._stop_phrases: turn.outcome = "stopped" self.emergency_stop() return pending, self._pending = self._pending, None if pending is not None and time.monotonic() - pending.created > self.cfg.consent.timeout_s: log.info("Plan of turn %d expired without consent.", pending.turn_id) pending = None if pending is not None: decision = self.consent.classify(turn.text) turn.language = pending.language if decision == "yes": # The robot may have moved since the plan was checked: check it again. report = self.guard.review(pending.actions, self.robot.pose()) turn.plan, turn.primitives, turn.safety = pending.plan, pending.actions, report self._remember(turn.text, {"consent": "yes"}) if not report.ok: turn.outcome = "rejected" self._respond( self.localizer.message( "safety_rejected", pending.language, reasons="; ".join(report.violations), ) ) return turn.outcome = "executing" self._execute(pending.turn_id, report.actions, pending.language) return if decision == "no": turn.outcome = "cancelled" self._remember(turn.text, {"consent": "no"}) self._respond(self.localizer.message("plan_cancelled", pending.language)) return log.info("Reply to the consent question is a new instruction; dropping the plan.") ctx = PlanningContext( pose=self.robot.pose(), language=self.language, fixed_language=fixed, scene=self._scene_lines(), image_jpeg=self._planning_image(), has_navigation=self.robot.has_navigation_stack, ) try: plan = self.planner.plan(turn.text, ctx, list(self.history)) except LLMError: log.exception("Planner unavailable") turn.outcome = "error" self._respond(self.localizer.message("service_unavailable", self.language)) return turn.plan = plan self.language = turn.language = plan.language self._remember( turn.text, { "intent": plan.intent, "reply": plan.reply, "actions": [a.to_dict() for a in plan.actions], }, ) if not plan.usable: turn.outcome = "error" self._respond(self.localizer.message("rephrase", plan.language)) return if plan.intent != "execute": turn.outcome = "replied" self._respond(plan.reply) return primitives = expand(plan.actions) turn.primitives = primitives if primitives and primitives[0].name == "STOP": self.executor.emergency_stop() # do not wait for the model's later steps report = self.guard.review(primitives, self.robot.pose()) turn.safety = report self._emit( Event( "plan", language=plan.language, turn_id=turn.turn_id, data={ "intent": plan.intent, "actions": [a.to_dict() for a in plan.actions], "primitives": [a.to_dict() for a in report.actions or primitives], "violations": report.violations, "predicted_end": report.rollout.end.to_dict() if report.rollout else None, }, ) ) if not report.ok: turn.outcome = "rejected" self._respond( self.localizer.message( "safety_rejected", plan.language, reasons="; ".join(report.violations) ) ) return if report.adjustments: self._respond( self.localizer.message( "safety_adjusted", plan.language, notes="; ".join(report.adjustments) ) ) if plan.reply: self._respond(plan.reply) if self._needs_consent(plan.actions, report.actions): self._pending = _Pending(turn.turn_id, plan, report.actions, plan.language) turn.outcome = "awaiting_consent" r = report.rollout if r is not None and not r.unmodelled: question = self.localizer.message( "confirm_plan", plan.language, x=fmt(r.end.x), y=fmt(r.end.y), yaw=fmt(r.end.yaw_deg, 0), ) else: question = self.localizer.message("confirm_plan_unmodelled", plan.language) self._respond(question) return turn.outcome = "executing" self._execute(turn.turn_id, report.actions, plan.language) def _needs_consent(self, steps: list[Action], primitives: list[Action]) -> bool: policy = self.cfg.consent.policy if policy == "never" or not primitives or primitives[0].name == "STOP": return False if policy == "always": return True if policy == "motion": return is_motion(primitives) return len(steps) > 1 and is_motion(primitives) def _execute(self, turn_id: int, actions: list[Action], language: str) -> None: def done(report: ExecutionReport) -> None: self.journal.write( { "turn": turn_id, "type": "execution", "success": report.success, "cancelled": report.cancelled, "steps": [vars(s) for s in report.steps], "start_pose": report.start_pose.to_dict(), "end_pose": report.end_pose.to_dict() if report.end_pose else None, "duration_s": (report.finished or report.started) - report.started, } ) self._emit( Event( "status", turn_id=turn_id, data={"done": True, "success": report.success, "cancelled": report.cancelled}, ) ) self.executor.submit(actions, _PlanReporter(self, language, turn_id), done) def _respond(self, text: str) -> None: if not text: return turn = self._current if turn is not None: turn.responses.append(text) if self._first_response is None: self._first_response = time.time() self._emit( Event( "response", text=text, language=self._language_of(turn), turn_id=turn.turn_id if turn else None, ) ) def _language_of(self, turn: TurnResult | None) -> str: return turn.language if turn is not None else self.language def _emit(self, event: Event) -> None: try: self.on_event(event) except Exception: # a broken event sink must not stop the robot log.exception("Event sink failed") def _scene_lines(self) -> list[str]: if self.grounder is None: return [] lines = [] for o in self.grounder.remembered()[:15]: if o.position is not None: lines.append( f"- {o.label} at ({o.position[0]:.2f}, {o.position[1]:.2f}), " f"seen {o.age_s:.0f} s ago" ) return lines def _planning_image(self) -> bytes | None: if not self.cfg.llm.attach_image or self.grounder is None: return None frame = self.grounder.frame() return _jpeg(frame) if frame is not None else None def _remember(self, user_text: str, assistant: dict) -> None: if self.history.maxlen == 0: return self.history.append(ChatMessage("user", user_text)) self.history.append(ChatMessage("assistant", json.dumps(assistant, ensure_ascii=False))) def _journal(self, turn: TurnResult, t0: float) -> None: plan = turn.plan self.journal.write( { "turn": turn.turn_id, "type": "turn", "time": t0, "input": turn.text, "language": turn.language, "outcome": turn.outcome, "response_time_s": (self._first_response - t0) if self._first_response else None, "intent": plan.intent if plan else None, "reply": plan.reply if plan else None, "actions": [a.to_dict() for a in plan.actions] if plan else [], "primitives": [a.to_dict() for a in turn.primitives], "errors": plan.errors if plan else [], "repaired": plan.repaired if plan else False, "planner_latency_s": plan.latency_s if plan else None, "safety": { "violations": turn.safety.violations, "adjustments": turn.safety.adjustments, } if turn.safety else None, "responses": turn.responses, "raw": plan.raw if plan else None, } )
class _PlanReporter(Reporter): """Reports one plan's progress in the language of the turn that started it.""" def __init__(self, agent: ReLIAgent, language: str, turn_id: int): self.agent = agent self.language = language self.turn_id = turn_id def _event(self, kind: str, text: str = "", data=None) -> None: self.agent._emit(Event(kind, text, self.language, data, self.turn_id)) def say(self, key: str, **values) -> None: a = self.agent try: text = a.localizer.message(key, self.language, **values) except Exception: # never lose a status message over a rendering problem log.exception("Could not render message %s", key) text = render(a.prompts.messages.get(key, key), **values) self._event("response", text) def speak(self, text: str) -> None: self._event("response", text) def image(self, image: np.ndarray) -> None: self._event("image", data=image) def status(self, data: dict) -> None: self._event("status", data=data) def narrate(self, evidence: list[str], image: np.ndarray | None) -> str | None: a = self.agent prompt = render( a.prompts["describe_scene"], language=self.language, evidence="Detected objects:\n" + ("\n".join(evidence) or "(none)"), ) images = [] if image is not None and a.cfg.llm.attach_image: jpeg = _jpeg(image) if jpeg: images.append(jpeg) try: return a.provider.complete( "You describe scenes for a robot.", [ChatMessage("user", prompt, images)] ).strip() except LLMError: log.exception("Scene narration failed") return None def _jpeg(image: np.ndarray, quality: int = 85) -> bytes | None: try: import cv2 except ImportError: log.warning("opencv is needed to send images to the language model") return None ok, buf = cv2.imencode(".jpg", image, [cv2.IMWRITE_JPEG_QUALITY, quality]) return buf.tobytes() if ok else None