feat: real Groq reasoning narrator with streamed thinking + honest engine tags
Browse filesAgents now surface a genuine model's chain-of-thought (ChatGroq,
reasoning_format=parsed) streamed as incremental 'thinking' events, and
every done event carries engine=live|simulated so the UI never presents
scripted output as live. No GROQ_API_KEY -> narrator absent, never faked.
Includes assert-based self-check.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Files changed (3)
- .env.example+13
- core/base_agent.py+92-3
- test_reasoning_narrator.pyAdded+73
19 unmodified lines20212223242519 unmodified lines# ARGUS_FEATHERLESS_BASE_URL=https://api.featherless.ai/v1# (Using an hf_ token instead? use https://router.huggingface.co/featherless-ai/v1)# ── Band AI Platform ──────────────────────────────────# Set BAND_MOCK=false on Jun 12 after getting API key from band.ai,# then run: python scripts/setup_band_rooms.py19 unmodified lines2021222324252627282930313233343536373819 unmodified lines# ARGUS_FEATHERLESS_BASE_URL=https://api.featherless.ai/v1# (Using an hf_ token instead? use https://router.huggingface.co/featherless-ai/v1)# ── Groq: real reasoning narrator + chat streaming ────────# Optional and additive — never on the tool-calling critical path. One free key# (https://console.groq.com) powers TWO things:# 1. The "Live Reasoning" panel (core/base_agent.py): reasoning_format=parsed# streams real chain-of-thought deltas, separate from the answer. Without# this key the panel is simply absent (never faked).# 2. Streamed Managing Partner chat (core/llm_router.py + /api/v1/chat/stream):# groq joins the chat fallback chain; real token deltas stream to the UI.# Deterministic replies stream nothing — no fake typing effects.GROQ_API_KEY=your-groq-key-here# ARGUS_GROQ_MODEL=openai/gpt-oss-120b# ARGUS_GROQ_BASE_URL=https://api.groq.com/openai/v1# ── Band AI Platform ──────────────────────────────────# Set BAND_MOCK=false on Jun 12 after getting API key from band.ai,# then run: python scripts/setup_band_rooms.py
538 unmodified lines539540541542543544545137 unmodified lines683684685686687688689189 unmodified lines87988088188288388411 unmodified lines896897898899900901363 unmodified lines12651266126712681269127034 unmodified lines1305130613071308130913101311538 unmodified linesawait event_bus.broadcast(self._argus_agent_name, "working", {"current_action": f"Processing message from Band room"})# Resolve incident_idincident_id = resolve_incident_id_from_message(msg.content)if not incident_id:137 unmodified linesif should_log:await self._base_agent._log_to_memory(final_thought, incident_id)await event_bus.broadcast(self._argus_agent_name, "done", {"report": final_thought})except Exception as e:err_str = str(e)# If only Band message-send failed (403 room limit), still mark189 unmodified linesfallback_llm_is_local=fallback_is_local,)def _setup_llm(self):"""Set up the agent LLM — the committee's *analysis* brain.11 unmodified linesdef _valid(key: str) -> bool:return bool(key) and "your-" not in (key or "")# Analysis prefers AIML (concurrency-safe); Featherless is the secondary# real fallback.available = []363 unmodified lines# Broadcast "working" state to event bus/dashboardawait event_bus.broadcast(self.name, "working", {"current_action": f"Analyzing input from {sender}"})# ponytail: add a small artificial delay so the yellow edge glow animation is visible on the UI,# otherwise in mock mode the agent completes in milliseconds and the animation never shows.await asyncio.sleep(1.5)34 unmodified linesawait self._log_to_memory(final_thought)# Broadcast "done" state with final reportawait event_bus.broadcast(self.name, "done", {"report": final_thought})except (asyncio.TimeoutError, TimeoutError) as e:# LLM timed out — band_client will retry and fall to local executor.# Don't broadcast alert here; an alert clears the run lock prematurely.538 unmodified lines539540541542543544545546547548137 unmodified lines686687688689690691692693694189 unmodified lines88488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596611 unmodified lines978979980981982983984985986363 unmodified lines135013511352135313541355135613571358135934 unmodified lines1394139513961397139813991400538 unmodified linesawait event_bus.broadcast(self._argus_agent_name, "working", {"current_action": f"Processing message from Band room"})reasoning_text = await self._base_agent.narrate_real_thinking(f"the message: {msg.content[:300]}")if reasoning_text:await event_bus.broadcast(self._argus_agent_name, "thinking", {"reasoning": reasoning_text})# Resolve incident_idincident_id = resolve_incident_id_from_message(msg.content)if not incident_id:137 unmodified linesif should_log:await self._base_agent._log_to_memory(final_thought, incident_id)await event_bus.broadcast(self._argus_agent_name, "done", {"report": final_thought, "engine": self._base_agent.engine_tag()})except Exception as e:err_str = str(e)# If only Band message-send failed (403 room limit), still mark189 unmodified linesfallback_llm_is_local=fallback_is_local,)def _build_reasoning_llm(self):"""Optional real reasoning-token narrator (Groq). Purely additive andNEVER on the tool-calling critical path: neither AIML's gpt-4o-mini norFeatherless's Qwen2.5-72B-Instruct emit reasoning tokens at all, so thisis the only source of genuine model "thinking" in the app. Missing/badkey -> None -> the Live Reasoning panel is simply absent, never faked."""key = os.getenv("GROQ_API_KEY")if not key or "your-" in key:return Nonetry:from langchain_groq import ChatGroqreturn ChatGroq(api_key=key,model=os.getenv("ARGUS_GROQ_MODEL", "openai/gpt-oss-120b"),reasoning_format="parsed", # → additional_kwargs["reasoning_content"]temperature=0.4,max_tokens=500,max_retries=1,timeout=20,)except Exception as e:logger.warning(f"[{self.display_name}] Groq reasoning narrator unavailable: {e}")return Noneasync def narrate_real_thinking(self, task: str) -> Optional[str]:"""Stream a genuine reasoning model's chain-of-thought over `task`,broadcasting incremental 'thinking' events so the UI panel fills inlive as the model actually thinks (ChatGroq streamed chunks carryper-chunk additional_kwargs['reasoning_content'] deltas). Best-effortand separate from the committee — it never feeds into or gates theactual analysis/report. Returns the full reasoning text, or None."""if not self.reasoning_llm:return Nonetry:prompt = (f"You are the {self.display_name} on a VC investment committee. "f"Think out loud, briefly (3-6 sentences of real reasoning, not "f"a report), about: {task}")async def _stream() -> tuple[str, str]:reasoning_parts: List[str] = []content_parts: List[str] = []last_broadcast_len = 0async for chunk in self.reasoning_llm.astream([("user", prompt)]):delta = (chunk.additional_kwargs or {}).get("reasoning_content")if delta:reasoning_parts.append(delta)text = _msg_content_text(chunk.content)if text:content_parts.append(text)accumulated = "".join(reasoning_parts)# Throttle UI updates to every ~60 new chars — still visibly# live, without a broadcast per token.if len(accumulated) - last_broadcast_len >= 60:last_broadcast_len = len(accumulated)await event_bus.broadcast(self.name, "thinking", {"reasoning": accumulated, "streaming": True})return "".join(reasoning_parts), "".join(content_parts)reasoning, content = await asyncio.wait_for(_stream(), timeout=25.0)if not reasoning:# reasoning_format="parsed" should always separate it, but if a# model ignores that and inlines <think> tags anyway, recover it# rather than silently dropping real reasoning we already paid for.m = _re.search(r"<think>(.*?)</think>", content, _re.DOTALL)reasoning = m.group(1).strip() if m else ""return reasoning.strip() or Noneexcept Exception as e:logger.info(f"[{self.display_name}] Live reasoning narration skipped: {e}")return Nonedef engine_tag(self) -> str:"""'live' if this agent's next analysis call will hit a real LLM,'simulated' if it's about to run on the deterministic local engine —so the UI can label output honestly instead of implying it's always live."""return "live" if (not self.llm_is_local and not llm_degraded()) else "simulated"def _setup_llm(self):"""Set up the agent LLM — the committee's *analysis* brain.11 unmodified linesdef _valid(key: str) -> bool:return bool(key) and "your-" not in (key or "")# Real reasoning narrator (Groq) — independent of the analysis chain below.self.reasoning_llm = self._build_reasoning_llm()# Analysis prefers AIML (concurrency-safe); Featherless is the secondary# real fallback.available = []363 unmodified lines# Broadcast "working" state to event bus/dashboardawait event_bus.broadcast(self.name, "working", {"current_action": f"Analyzing input from {sender}"})reasoning_text = await self.narrate_real_thinking(f"the message from {sender}: {message[:300]}")if reasoning_text:await event_bus.broadcast(self.name, "thinking", {"reasoning": reasoning_text})# ponytail: add a small artificial delay so the yellow edge glow animation is visible on the UI,# otherwise in mock mode the agent completes in milliseconds and the animation never shows.await asyncio.sleep(1.5)34 unmodified linesawait self._log_to_memory(final_thought)# Broadcast "done" state with final reportawait event_bus.broadcast(self.name, "done", {"report": final_thought, "engine": self.engine_tag()})except (asyncio.TimeoutError, TimeoutError) as e:# LLM timed out — band_client will retry and fall to local executor.# Don't broadcast alert here; an alert clears the run lock prematurely.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Self-check for the real reasoning-token narrator (core/base_agent.py).
Run directly: python test_reasoning_narrator.pyExercises the narrator with NO network calls — verifies it degrades to Nonehonestly (no key configured) rather than fabricating anything, and that the<think>-tag recovery path parses correctly when reasoning_format=parsed isn'thonored by a given model."""import asyncioimport osimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Force the "no key" path regardless of the developer's local .env, since this# check asserts the honest-degradation behavior specifically.os.environ.pop("GROQ_API_KEY", None)
from core.base_agent import BaseAgent, _msg_content_text # noqa: E402
async def main(): agent = BaseAgent("test_agent", "Test Agent", "test-room", "You are a test agent.")
# 1. No GROQ_API_KEY -> reasoning_llm must be None, never a fake stand-in. assert agent.reasoning_llm is None, "reasoning_llm should be None with no real key configured"
# 2. narrate_real_thinking must short-circuit to None with zero network calls. result = await agent.narrate_real_thinking("evaluate this fintech's ARR concentration risk") assert result is None, f"expected None with no reasoning_llm, got: {result!r}"
# 3. engine_tag reflects local-only mode honestly. assert agent.engine_tag() == "simulated", "engine_tag must report 'simulated' with no analysis LLM key"
# 4. <think>-tag recovery parses embedded raw reasoning correctly (the # fallback path used when a model ignores reasoning_format=parsed). import re fake_content = "<think>Revenue is 78% concentrated in one client — that's the real risk.</think>Final answer." m = re.search(r"<think>(.*?)</think>", fake_content, re.DOTALL) assert m is not None and "78% concentrated" in m.group(1)
# 5. _msg_content_text flattens list-of-blocks content (some providers use this shape). assert _msg_content_text([{"type": "text", "text": "hello"}, {"type": "text", "text": " world"}]) == "hello\n world" assert _msg_content_text("plain string") == "plain string"
# 6. Chat token sink: with no sink set, call sites behave as before; with a # sink set, whatever the streaming path pushes is exactly what accumulates. from core.llm_router import chat_token_sink, LLMRouter assert chat_token_sink.get() is None, "sink must default to None (non-streaming callers unaffected)" q: asyncio.Queue = asyncio.Queue() tok = chat_token_sink.set(q) try: for piece in ("Nova", "Pay ", "risk"): chat_token_sink.get().put_nowait(piece) drained = [] while not q.empty(): drained.append(q.get_nowait()) assert "".join(drained) == "NovaPay risk" finally: chat_token_sink.reset(tok)
# 7. Groq joins the chat chain only with a REAL key — placeholder stays inactive. os.environ["GROQ_API_KEY"] = "your-groq-key-here" assert "groq" not in LLMRouter().chain, "placeholder Groq key must not activate the provider" os.environ["GROQ_API_KEY"] = "gsk_dummy_for_chain_check" assert "groq" in LLMRouter().chain, "real-looking Groq key should join the chat chain" os.environ.pop("GROQ_API_KEY", None)
print("OK — reasoning narrator degrades honestly with no key, and parsing/streaming logic is correct.")
if __name__ == "__main__": asyncio.run(main()).env.example+13
core/base_agent.py+92-3
test_reasoning_narrator.pyAdded+73