Skip to content

robotsix_chat.llm.agent

LLM chat agent backed by robotsix-llmio's per-level model factory.

:class:LlmioChatAgent satisfies the chat server's ChatAgent protocol (async def stream(message) -> AsyncIterator[str]). It selects the backend purely from a capability level via :func:robotsix_llmio.config.create_model: the level encodes the combined provider-model identifier (resolved from llmio's tier config), so this package never names a concrete provider class or model.

Levels (1 cheap/frequent, 2 workhorse, 3 frontier) are a pure capability axis. Provider redundancy is llmio's failover axis: every turn runs through :func:robotsix_llmio.core.failover.acall_with_failover, which serves the level on the keyless default slot (Claude SDK via the logged-in claude CLI) and retries the SAME level on the keyed OpenRouter fallback slot when the default fails in a provider-shaped way — arming a sticky failover window after repeated failures.

Responses are returned as a single block (not token-streamed): llmio's Claude SDK model does not support incremental streaming through pydantic-ai, so each stream call yields the full reply once. The chat server still frames it as a normal SSE token + done sequence.

The provider dependencies are obtained through robotsix-llmio's own extras — robotsix-llmio[claude-sdk] and robotsix-llmio[openrouter] — wired via this package's claude-sdk / openrouter extras.

LlmioChatAgent

Stream LLM responses via robotsix-llmio, selected by capability level.

Each stream call builds a fresh llmio agent handle (deterministically closed). When a :class:~robotsix_chat.memory.ChatMemory is supplied, the agent gains continuity across calls: it recalls relevant memory before replying and persists the exchange afterwards (the write runs in the background so it never adds latency). With the default :class:NullMemory it stays fully stateless.

Source code in src/robotsix_chat/llm/agent.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
class LlmioChatAgent:
    """Stream LLM responses via robotsix-llmio, selected by capability level.

    Each ``stream`` call builds a fresh llmio agent handle (deterministically
    closed). When a :class:`~robotsix_chat.memory.ChatMemory` is supplied, the
    agent gains continuity across calls: it recalls relevant memory before
    replying and persists the exchange afterwards (the write runs in the
    background so it never adds latency). With the default :class:`NullMemory`
    it stays fully stateless.
    """

    def __init__(
        self,
        *,
        model_level: int,
        instruction: str,
        api_key: str = "",
        anthropic_api_key: str = "",
        memory: ChatMemory | None = None,
        tools: list[Any] | None = None,
        request_tools_factory: Callable[[str], list[Any]] | None = None,
        event_sink: EventSink | None = None,
        failover_window_seconds: float | None = None,
        tier_overrides: dict[str, Any] | None = None,
    ) -> None:
        """Store the agent configuration for later ``stream`` calls.

        *api_key* is the configured OpenRouter key, if any. It is forwarded
        only to keyed (OpenRouter) slot attempts — holding it is what lets
        llmio's provider failover reach the keyed fallback slot when the
        shared Claude credential or subscription quota is the thing that
        failed.

        *anthropic_api_key* is the configured Anthropic API key, if any. It
        is forwarded only to slots served by the direct Anthropic Messages
        API provider (``anthropic``). When empty, llmio's provider falls
        back to the ``ANTHROPIC_API_KEY`` environment variable.

        *failover_window_seconds*, when set, overrides how long llmio routes
        calls straight to the fallback (OpenRouter) slot after the default
        (Claude) slot fails repeatedly, before automatically returning to
        the default. ``None`` keeps llmio's baked policy (15 minutes).

        *request_tools_factory* is called once per ``stream`` invocation with
        the request's *client_id* to produce per-request tools (e.g. the
        subsession tools whose closures capture that session id).  It keeps
        the module dependency acyclic: those tools are built fresh per
        request inside ``stream``, not baked into the shared agent.

        *event_sink*, when given, receives an ``activity`` frame (see
        :func:`robotsix_chat.chat.events.activity_frame`) for every tool
        call, tool result, thinking block, or intermediate assistant text
        the claudeSDK backend streams during a turn — live feedback on what
        the agent is doing while the final reply is still pending. A
        non-claudeSDK level (e.g. an OpenRouter tier) simply never triggers
        it: ``robotsix_llmio.claude_sdk.activity_events()`` is a no-op unless
        the resolved transport is the Claude Agent SDK.
        """
        self._model_level = model_level
        self._instruction = instruction
        self._api_key = api_key
        self._anthropic_api_key = anthropic_api_key
        self._memory: ChatMemory = memory if memory is not None else NullMemory()
        # Tools the underlying agent may call (e.g. the mill consult tool). When
        # non-empty, llmio runs a real tool loop; the final reply is still
        # returned as one block.
        self._tools = list(tools) if tools is not None else None
        self._request_tools_factory = request_tools_factory
        self._event_sink = event_sink
        # The two-slot tier config every turn resolves against; its failover
        # section is adopted by llmio's process-wide tracker on each call.
        # Binding overrides come from the llmio_tier_overrides setting; the
        # raw dict stays readable (create_app mirrors it onto app.state for
        # the /models display, following the model_level pattern).
        self.tier_overrides: dict[str, Any] = dict(tier_overrides or {})
        self._tier_config = load_tier_config(
            _merge_tier_overrides(self.tier_overrides, failover_window_seconds)
        )
        # Hold references to in-flight background writes so they aren't GC'd.
        self._write_tasks: set[asyncio.Task[None]] = set()

    @property
    def memory(self) -> ChatMemory:
        """The agent's memory backend (for health reporting / recovery wiring)."""
        return self._memory

    def _slot_kwargs(self, tlc: TierLevelConfig) -> dict[str, Any]:
        """Build the provider-constructor kwargs for the slot binding *tlc*.

        Starts from the slot's own ``provider_kwargs`` + ``max_tokens`` (a
        real per-response cap on OpenRouter). Forwards the configured
        api_key only to keyed slots — keyless providers reject it. The
        direct Anthropic slot gets the Anthropic key (an empty one is
        omitted so llmio falls back to ``ANTHROPIC_API_KEY``); every other
        keyed slot gets the OpenRouter key.
        """
        kwargs: dict[str, Any] = dict(tlc.provider_kwargs)
        if tlc.max_tokens is not None:
            kwargs.setdefault("max_tokens", tlc.max_tokens)
        if tlc.provider == _ANTHROPIC_PROVIDER:
            if self._anthropic_api_key:
                kwargs["api_key"] = self._anthropic_api_key
        elif slot_needs_api_key(tlc) and self._api_key:
            kwargs["api_key"] = self._api_key
        return kwargs

    def _activity_callback(
        self, session_id: str | None
    ) -> Callable[[ClaudeSDKActivityEvent], None] | None:
        """Build the ``on_event`` callback for :func:`activity_events`.

        Bound to *session_id*.  The callback does two things: publishes an
        activity frame to the event sink (when one is configured and there
        is a session to scope it to), and records ``tool_call`` /
        ``tool_result`` pairs into the caller's actions collector (see
        :func:`robotsix_chat.chat.actions.collect_actions`) when one is
        active.  Returns ``None`` when neither applies so the caller can
        skip wrapping the run in a no-op context.
        """
        sink = self._event_sink if session_id else None
        actions = current_actions()
        if sink is None and actions is None:
            return None

        # A tool_call event carries the name + args; the matching tool_result
        # arrives as a separate event without the name.  Record the call
        # immediately and patch its entry when the result shows up so a call
        # that never returns (turn aborted) still leaves a trace.
        pending: list[tuple[int, str, str]] = []

        def _record(event: ClaudeSDKActivityEvent) -> None:
            if actions is None:
                return
            if event.kind == "tool_call" and event.tool_name:
                before = len(actions)
                record_action(event.tool_name, event.detail, entries=actions)
                if len(actions) > before:
                    pending.append((before, event.tool_name, event.detail))
            elif event.kind == "tool_result" and pending:
                idx, name, args = pending.pop(0)
                actions[idx] = format_action(
                    name, args, event.detail, is_error=event.is_error
                )

        def _on_activity(event: ClaudeSDKActivityEvent) -> None:
            _record(event)
            if sink is not None and session_id:
                sink.publish(
                    session_id,
                    activity_frame(
                        event.kind,
                        event.turn,
                        tool_name=event.tool_name,
                        detail=event.detail,
                        is_error=event.is_error,
                    ),
                )

        return _on_activity

    @staticmethod
    def _record_actions_from_result(result: Any) -> None:
        """Fill the active actions collector from a run result's messages.

        The keyed (pydantic-ai) tiers report tool calls only through
        ``result.all_messages()`` — no activity events fire for them.  When
        the collector is still empty after the run, extract the
        ``ToolCallPart`` / ``ToolReturnPart`` pairs from there.  A collector
        already populated by activity events is left as is (the SDK tiers
        would otherwise double-count).  Never raises.
        """
        actions = current_actions()
        if actions is None or actions or result is None:
            return
        all_messages = getattr(result, "all_messages", None)
        if not callable(all_messages):
            return
        try:
            messages = all_messages()
        except Exception:
            return
        actions.extend(actions_from_messages(messages))

    def _publish_synthetic_activity(
        self,
        session_id: str | None,
        kind: str,
        *,
        tool_name: str | None = None,
        detail: str = "",
        is_error: bool = False,
    ) -> None:
        """Publish an activity frame for a preliminary step outside the SDK run.

        E.g. memory recall — so the UI shows something during phases the
        Claude SDK's own activity events don't cover — otherwise the typing
        indicator sits blank for as long as that step takes, which can be
        the majority of the wall-clock time for a turn (memory recall alone
        has been observed taking 90+ seconds).

        A no-op when there is nowhere to publish to (no sink, no session).
        """
        if self._event_sink is None or not session_id:
            return
        self._event_sink.publish(
            session_id,
            activity_frame(
                kind, 0, tool_name=tool_name, detail=detail, is_error=is_error
            ),
        )

    @property
    def model_level(self) -> int:
        """The level this agent was configured with.

        Read-only: a session's escalated level is passed per turn via
        ``stream(model_level=...)`` rather than mutating the shared agent.
        """
        return self._model_level

    @property
    def has_api_key(self) -> bool:
        """Whether a non-empty API key is configured for keyed levels.

        Keyless (claudeSDK) levels never need it; keyed (OpenRouter) levels
        cannot serve a turn without it. Surfaced so the UI can mark keyed
        model levels unavailable when no key is present.
        """
        return bool(self._api_key)

    async def stream(
        self,
        message: str,
        *,
        history: list[Turn] | None = None,
        session_id: str | None = None,
        client_id: str | None = None,
        images: list[tuple[str, bytes]] | None = None,
        trace_metadata: dict[str, str] | None = None,
        trace_name: str | None = None,
        model_level: int | None = None,
        skip_recall: bool = False,
    ) -> AsyncIterator[str]:
        """Yield the assistant's reply to *message* as a single block.

        *skip_recall* suppresses the automatic long-term memory recall for
        this turn. It is set by callers whose turn input is machine-generated
        boilerplate rather than an operator utterance — chiefly event-driven
        and periodic monitor wakes, whose prompts are self-contained by
        design and whose fixed instruction text recalls near-random,
        noise-only matches while hammering the memory component on every
        wake. Interactive operator turns leave it ``False`` and keep full
        recall.

        *history* is the prior ``(user, assistant)`` turns of the current
        conversation, replayed to the agent so it has multi-turn context.
        *session_id* groups this run's trace spans under one conversation in
        Langfuse (a fresh id starts a new trace). *client_id* identifies the
        owning browser — it is forwarded to the per-request tools factory so
        delegation tools can tag spawned tasks correctly.  *images* is an
        optional list of ``(media_type, raw_bytes)`` pairs (e.g.
        ``[("image/png", b"...")]``) — attachments are handed to llmio's
        ``build_agent(images=...)`` seam: the Claude transport reads them
        natively, while text-only OpenRouter models get an ``ask_image``
        tool (answered by the tier config's vision binding) instead. Images
        belong to the turn they arrive with only — replayed history is
        text-only by construction, so an old attachment can never poison a
        later turn.
        *trace_name* is an optional human-readable label for the Langfuse
        trace (e.g. ``"chat-turn"``, ``"subsession-turn"``) so cost can be
        attributed by function.  When ``None`` the trace inherits whatever
        name the calling context set (if any); this keeps the feedback
        runner's ``feedback-<type>`` trace name from being overwritten.
        All keyword arguments are optional — with none, the agent behaves as a
        single stateless query.

        *trace_metadata* is stamped as span attributes for observability
        (parent/owner lineage, subsession ids, etc.).

        *model_level* overrides the agent's configured level for this turn
        only.  The chat server passes a session's escalated level here, so one
        shared agent instance can serve sessions running at different tiers
        without rebuilding it.

        Transient upstream errors (OpenRouter provider failures, 5xx,
        network blips) are retried locally per slot attempt. Provider-shaped
        failures that outlive those retries (usage exhaustion, a dead
        credential, an outage) are handed to llmio's provider failover,
        which retries the SAME level on the other provider slot and arms a
        sticky failover window on repeated default-slot failures. Only when
        both slots fail does the error surface — the chat server turns that
        into an SSE ``error`` frame.
        """
        # Recall relevant memory and prepend it to the current user turn.
        # recall() never raises (it degrades to "" on any backend failure).
        # The block must NOT go into the system prompt: recall text changes
        # with every message, and the system prompt is the head of the
        # provider's cacheable prefix — mutating it there invalidates the
        # prompt cache for the whole request on every turn. Prepending to the
        # newest user turn keeps the instruction, tools, and replayed
        # transcript byte-stable and cache-servable.
        recalled = ""
        if not skip_recall:
            self._publish_synthetic_activity(
                session_id, "tool_call", tool_name="recall_memory"
            )
            # A periodic session's first message starts with fixed scheduler
            # scaffolding (the preamble plus the injected current-date/time
            # block) and a user_chat subsession's first turn starts with the
            # side-chat system note; recalling on either retrieves chunks
            # about the boilerplate instead of the actual task, so strip the
            # scaffolding from the recall query (the agent still gets the
            # full message).
            recall_query = strip_recall_scaffolding(message)
            recalled = await self._memory.recall(recall_query, session_id=session_id)
            self._publish_synthetic_activity(
                session_id,
                "tool_result",
                detail=(
                    f"found {len(recalled)} chars of prior context"
                    if recalled
                    else "no relevant memory found"
                ),
            )
        system_prompt = self._instruction
        llm_message = message
        if recalled:
            llm_message = (
                f"{_MEMORY_PROMPT_HEADER}{recalled}{_MEMORY_PROMPT_FOOTER}\n{message}"
            )

        # The per-call override wins; the slot factory and the trace
        # metadata below close over this local, so nothing else has to be
        # threaded. Which provider serves the level is llmio's business:
        # every turn goes through acall_with_failover, which resolves the
        # active slot (and retries the other slot on provider failure).
        level = self._model_level if model_level is None else model_level
        message_history = _build_message_history(history)

        # Compute effective tools once: static tools + per-request tools from
        # the factory (which captures client_id lexically so delegation works
        # even across the claude_sdk/MCP execution-context boundary).
        effective_tools: list[Any] = list(self._tools) if self._tools else []
        if self._request_tools_factory and client_id:
            effective_tools.extend(self._request_tools_factory(client_id))
        tools_arg = effective_tools or None

        # The prompt is ALWAYS plain text. Attachments travel through
        # llmio's ``build_agent(images=...)`` seam instead of being embedded
        # as ``BinaryContent`` parts: the claude_sdk transport passes them as
        # native SDK image blocks (Claude models read images directly), and
        # text-only OpenRouter models get an injected ``ask_image`` tool
        # answered by the tier config's vision binding. Embedding binary
        # parts here 404'd every DeepSeek-served turn ("No endpoints found
        # that support image input", live incident 2026-09-01).
        prompt = llm_message

        on_activity = self._activity_callback(session_id)

        # Stamp model_level as trace metadata so by-model cost breakdowns
        # are usable in Langfuse — the trace_metadata dict from the caller
        # (if any) is merged in so caller keys win on collision.
        effective_trace_metadata: dict[str, str] = {
            "model_level": str(level),
        }
        if trace_metadata:
            effective_trace_metadata.update(trace_metadata)

        # One factory per provider slot: llmio's failover loop calls it with
        # the slot's TierLevelConfig for THIS level (the level never changes
        # across attempts — only the provider slot does). Each slot attempt
        # runs under its own bounded transient retry; a provider-shaped
        # failure that outlives the retries bubbles to the failover loop,
        # which records it and retries the same level on the other slot.
        def _fn_factory(tlc: TierLevelConfig) -> Callable[[], Any]:
            async def _attempt() -> Any:
                provider = get_provider_for_identifier(
                    tlc.model, **self._slot_kwargs(tlc)
                )
                slot_system_prompt = system_prompt
                effective_history = message_history
                if slot_needs_api_key(tlc):
                    # A keyed (OpenRouter) slot does not share the Claude
                    # SDK resume session — tell it plainly it is
                    # mid-conversation, and cap the replayed history to the
                    # slot's token window.
                    if message_history:
                        slot_system_prompt = (
                            f"{system_prompt}\n\n{_FALLBACK_CONTINUATION_NOTE}"
                        )
                    if history and tlc.max_tokens:
                        capped = _cap_history_for_keyed_tier(history, tlc.max_tokens)
                        effective_history = _build_message_history(capped)
                handle = provider.build_agent(
                    level=level,
                    model=tlc.model_name,
                    # Only the images/vision path reads tier_config here —
                    # the explicit ``model=`` override bypasses level
                    # resolution — so passing it wires the configured vision
                    # binding without touching slot routing.
                    tier_config=self._tier_config,
                    system_prompt=slot_system_prompt,
                    tools=tools_arg,
                    images=images or None,
                    vision_api_key=self._api_key or None,
                    builtin_tools=False,
                    # Read-only web access. The filesystem and shell stay
                    # denied; these two only fetch. Without them a research
                    # subsession cannot look anything up, and — because a
                    # refused tool call is indistinguishable from an empty
                    # result — it reports "sources fetched, all empty"
                    # rather than "I cannot search".
                    web_tools=True,
                )
                # Stateless turn: history + one fresh memory block travel in
                # the prompt; no CLI session is resumed (see the module note
                # above).
                # Stamp the slot's image capability for tools that run inside
                # this attempt: keyed OpenRouter slots (DeepSeek/mimo) are
                # text-only, so image-returning tools degrade to text instead
                # of 404ing the whole turn ("No endpoints found that support
                # image input"). The Claude transports (Claude SDK and the
                # direct Anthropic API) read images natively.
                capability_token = set_model_supports_images(
                    not slot_needs_api_key(tlc) or tlc.provider == _ANTHROPIC_PROVIDER
                )
                try:
                    with _activity_context(on_activity):
                        limits = _keyed_usage_limits(tlc)
                        if limits is not None:
                            return await handle.run(
                                prompt,
                                message_history=effective_history,
                                usage_limits=limits,
                            )
                        return await handle.run(
                            prompt, message_history=effective_history
                        )
                finally:
                    reset_model_supports_images(capability_token)
                    handle.close()

            async def _run_slot() -> Any:
                try:
                    return await acall_with_retry(
                        _attempt,
                        config=RetryConfig(
                            backoff_base=0.5,
                            backoff_cap=1.0,
                            max_retries=2,
                            jitter_factor=0.0,
                        ),
                        is_transient_fn=_is_chat_turn_transient,
                        what=f"chat turn ({tlc.provider})",
                    )
                except Exception as exc:
                    # A dead Claude credential takes the whole default slot
                    # with it (every claudeSDK level drives the same CLI and
                    # .credentials.json), but llmio's failover classifier
                    # has no auth category — wrap it as a provider-wide
                    # exhaustion so the loop arms failover immediately and
                    # retries this level on the keyed slot. Usage exhaustion
                    # needs no wrapping: llmio detects it in the
                    # cause/context chain even when the CLI launders it.
                    root = _chained_claude_unavailability(exc)
                    if isinstance(root, ClaudeSDKAuthError):
                        raise ProviderExhaustedError(
                            f"claude credential unusable: {root}"
                        ) from exc
                    raise

            return _run_slot

        # The named trace wraps the WHOLE failover loop so the turn (not an
        # llmio-internal ``llmio.failover.attempt`` span) is the Langfuse trace
        # root. Opening it inside each slot attempt made every chat trace
        # surface as "llmio.failover.attempt" (2026-09-07: the fleet cost
        # review read that name as paid-backup failover spend and spawned an
        # investigation of a provider degradation that never happened).
        with _trace_session(
            session_id,
            effective_trace_metadata,
            trace_name=trace_name,
            function=trace_name,
        ):
            result = await acall_with_failover(
                _fn_factory,
                tier_config=self._tier_config,
                level=level,
                what="chat turn",
            )

        self._record_actions_from_result(result)
        text = result.output
        # Persist the exchange in the background so memory consolidation never
        # blocks the reply. The task is tracked to avoid premature GC.
        if text:
            self._schedule_remember(message, text, session_id)
            yield text

    def _schedule_remember(
        self, message: str, reply: str, session_id: str | None
    ) -> None:
        """Fire-and-forget the memory write for a completed exchange."""
        try:
            task = asyncio.create_task(
                self._memory.remember(message, reply, session_id=session_id)
            )
        except RuntimeError:
            # No running loop (shouldn't happen in the ASGI path) — skip silently.
            return
        self._write_tasks.add(task)
        task.add_done_callback(self._write_tasks.discard)

has_api_key property

Whether a non-empty API key is configured for keyed levels.

Keyless (claudeSDK) levels never need it; keyed (OpenRouter) levels cannot serve a turn without it. Surfaced so the UI can mark keyed model levels unavailable when no key is present.

memory property

The agent's memory backend (for health reporting / recovery wiring).

model_level property

The level this agent was configured with.

Read-only: a session's escalated level is passed per turn via stream(model_level=...) rather than mutating the shared agent.

__init__(*, model_level, instruction, api_key='', anthropic_api_key='', memory=None, tools=None, request_tools_factory=None, event_sink=None, failover_window_seconds=None, tier_overrides=None)

Store the agent configuration for later stream calls.

api_key is the configured OpenRouter key, if any. It is forwarded only to keyed (OpenRouter) slot attempts — holding it is what lets llmio's provider failover reach the keyed fallback slot when the shared Claude credential or subscription quota is the thing that failed.

anthropic_api_key is the configured Anthropic API key, if any. It is forwarded only to slots served by the direct Anthropic Messages API provider (anthropic). When empty, llmio's provider falls back to the ANTHROPIC_API_KEY environment variable.

failover_window_seconds, when set, overrides how long llmio routes calls straight to the fallback (OpenRouter) slot after the default (Claude) slot fails repeatedly, before automatically returning to the default. None keeps llmio's baked policy (15 minutes).

request_tools_factory is called once per stream invocation with the request's client_id to produce per-request tools (e.g. the subsession tools whose closures capture that session id). It keeps the module dependency acyclic: those tools are built fresh per request inside stream, not baked into the shared agent.

event_sink, when given, receives an activity frame (see :func:robotsix_chat.chat.events.activity_frame) for every tool call, tool result, thinking block, or intermediate assistant text the claudeSDK backend streams during a turn — live feedback on what the agent is doing while the final reply is still pending. A non-claudeSDK level (e.g. an OpenRouter tier) simply never triggers it: robotsix_llmio.claude_sdk.activity_events() is a no-op unless the resolved transport is the Claude Agent SDK.

Source code in src/robotsix_chat/llm/agent.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
def __init__(
    self,
    *,
    model_level: int,
    instruction: str,
    api_key: str = "",
    anthropic_api_key: str = "",
    memory: ChatMemory | None = None,
    tools: list[Any] | None = None,
    request_tools_factory: Callable[[str], list[Any]] | None = None,
    event_sink: EventSink | None = None,
    failover_window_seconds: float | None = None,
    tier_overrides: dict[str, Any] | None = None,
) -> None:
    """Store the agent configuration for later ``stream`` calls.

    *api_key* is the configured OpenRouter key, if any. It is forwarded
    only to keyed (OpenRouter) slot attempts — holding it is what lets
    llmio's provider failover reach the keyed fallback slot when the
    shared Claude credential or subscription quota is the thing that
    failed.

    *anthropic_api_key* is the configured Anthropic API key, if any. It
    is forwarded only to slots served by the direct Anthropic Messages
    API provider (``anthropic``). When empty, llmio's provider falls
    back to the ``ANTHROPIC_API_KEY`` environment variable.

    *failover_window_seconds*, when set, overrides how long llmio routes
    calls straight to the fallback (OpenRouter) slot after the default
    (Claude) slot fails repeatedly, before automatically returning to
    the default. ``None`` keeps llmio's baked policy (15 minutes).

    *request_tools_factory* is called once per ``stream`` invocation with
    the request's *client_id* to produce per-request tools (e.g. the
    subsession tools whose closures capture that session id).  It keeps
    the module dependency acyclic: those tools are built fresh per
    request inside ``stream``, not baked into the shared agent.

    *event_sink*, when given, receives an ``activity`` frame (see
    :func:`robotsix_chat.chat.events.activity_frame`) for every tool
    call, tool result, thinking block, or intermediate assistant text
    the claudeSDK backend streams during a turn — live feedback on what
    the agent is doing while the final reply is still pending. A
    non-claudeSDK level (e.g. an OpenRouter tier) simply never triggers
    it: ``robotsix_llmio.claude_sdk.activity_events()`` is a no-op unless
    the resolved transport is the Claude Agent SDK.
    """
    self._model_level = model_level
    self._instruction = instruction
    self._api_key = api_key
    self._anthropic_api_key = anthropic_api_key
    self._memory: ChatMemory = memory if memory is not None else NullMemory()
    # Tools the underlying agent may call (e.g. the mill consult tool). When
    # non-empty, llmio runs a real tool loop; the final reply is still
    # returned as one block.
    self._tools = list(tools) if tools is not None else None
    self._request_tools_factory = request_tools_factory
    self._event_sink = event_sink
    # The two-slot tier config every turn resolves against; its failover
    # section is adopted by llmio's process-wide tracker on each call.
    # Binding overrides come from the llmio_tier_overrides setting; the
    # raw dict stays readable (create_app mirrors it onto app.state for
    # the /models display, following the model_level pattern).
    self.tier_overrides: dict[str, Any] = dict(tier_overrides or {})
    self._tier_config = load_tier_config(
        _merge_tier_overrides(self.tier_overrides, failover_window_seconds)
    )
    # Hold references to in-flight background writes so they aren't GC'd.
    self._write_tasks: set[asyncio.Task[None]] = set()

stream(message, *, history=None, session_id=None, client_id=None, images=None, trace_metadata=None, trace_name=None, model_level=None, skip_recall=False) async

Yield the assistant's reply to message as a single block.

skip_recall suppresses the automatic long-term memory recall for this turn. It is set by callers whose turn input is machine-generated boilerplate rather than an operator utterance — chiefly event-driven and periodic monitor wakes, whose prompts are self-contained by design and whose fixed instruction text recalls near-random, noise-only matches while hammering the memory component on every wake. Interactive operator turns leave it False and keep full recall.

history is the prior (user, assistant) turns of the current conversation, replayed to the agent so it has multi-turn context. session_id groups this run's trace spans under one conversation in Langfuse (a fresh id starts a new trace). client_id identifies the owning browser — it is forwarded to the per-request tools factory so delegation tools can tag spawned tasks correctly. images is an optional list of (media_type, raw_bytes) pairs (e.g. [("image/png", b"...")]) — attachments are handed to llmio's build_agent(images=...) seam: the Claude transport reads them natively, while text-only OpenRouter models get an ask_image tool (answered by the tier config's vision binding) instead. Images belong to the turn they arrive with only — replayed history is text-only by construction, so an old attachment can never poison a later turn. trace_name is an optional human-readable label for the Langfuse trace (e.g. "chat-turn", "subsession-turn") so cost can be attributed by function. When None the trace inherits whatever name the calling context set (if any); this keeps the feedback runner's feedback-<type> trace name from being overwritten. All keyword arguments are optional — with none, the agent behaves as a single stateless query.

trace_metadata is stamped as span attributes for observability (parent/owner lineage, subsession ids, etc.).

model_level overrides the agent's configured level for this turn only. The chat server passes a session's escalated level here, so one shared agent instance can serve sessions running at different tiers without rebuilding it.

Transient upstream errors (OpenRouter provider failures, 5xx, network blips) are retried locally per slot attempt. Provider-shaped failures that outlive those retries (usage exhaustion, a dead credential, an outage) are handed to llmio's provider failover, which retries the SAME level on the other provider slot and arms a sticky failover window on repeated default-slot failures. Only when both slots fail does the error surface — the chat server turns that into an SSE error frame.

Source code in src/robotsix_chat/llm/agent.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
async def stream(
    self,
    message: str,
    *,
    history: list[Turn] | None = None,
    session_id: str | None = None,
    client_id: str | None = None,
    images: list[tuple[str, bytes]] | None = None,
    trace_metadata: dict[str, str] | None = None,
    trace_name: str | None = None,
    model_level: int | None = None,
    skip_recall: bool = False,
) -> AsyncIterator[str]:
    """Yield the assistant's reply to *message* as a single block.

    *skip_recall* suppresses the automatic long-term memory recall for
    this turn. It is set by callers whose turn input is machine-generated
    boilerplate rather than an operator utterance — chiefly event-driven
    and periodic monitor wakes, whose prompts are self-contained by
    design and whose fixed instruction text recalls near-random,
    noise-only matches while hammering the memory component on every
    wake. Interactive operator turns leave it ``False`` and keep full
    recall.

    *history* is the prior ``(user, assistant)`` turns of the current
    conversation, replayed to the agent so it has multi-turn context.
    *session_id* groups this run's trace spans under one conversation in
    Langfuse (a fresh id starts a new trace). *client_id* identifies the
    owning browser — it is forwarded to the per-request tools factory so
    delegation tools can tag spawned tasks correctly.  *images* is an
    optional list of ``(media_type, raw_bytes)`` pairs (e.g.
    ``[("image/png", b"...")]``) — attachments are handed to llmio's
    ``build_agent(images=...)`` seam: the Claude transport reads them
    natively, while text-only OpenRouter models get an ``ask_image``
    tool (answered by the tier config's vision binding) instead. Images
    belong to the turn they arrive with only — replayed history is
    text-only by construction, so an old attachment can never poison a
    later turn.
    *trace_name* is an optional human-readable label for the Langfuse
    trace (e.g. ``"chat-turn"``, ``"subsession-turn"``) so cost can be
    attributed by function.  When ``None`` the trace inherits whatever
    name the calling context set (if any); this keeps the feedback
    runner's ``feedback-<type>`` trace name from being overwritten.
    All keyword arguments are optional — with none, the agent behaves as a
    single stateless query.

    *trace_metadata* is stamped as span attributes for observability
    (parent/owner lineage, subsession ids, etc.).

    *model_level* overrides the agent's configured level for this turn
    only.  The chat server passes a session's escalated level here, so one
    shared agent instance can serve sessions running at different tiers
    without rebuilding it.

    Transient upstream errors (OpenRouter provider failures, 5xx,
    network blips) are retried locally per slot attempt. Provider-shaped
    failures that outlive those retries (usage exhaustion, a dead
    credential, an outage) are handed to llmio's provider failover,
    which retries the SAME level on the other provider slot and arms a
    sticky failover window on repeated default-slot failures. Only when
    both slots fail does the error surface — the chat server turns that
    into an SSE ``error`` frame.
    """
    # Recall relevant memory and prepend it to the current user turn.
    # recall() never raises (it degrades to "" on any backend failure).
    # The block must NOT go into the system prompt: recall text changes
    # with every message, and the system prompt is the head of the
    # provider's cacheable prefix — mutating it there invalidates the
    # prompt cache for the whole request on every turn. Prepending to the
    # newest user turn keeps the instruction, tools, and replayed
    # transcript byte-stable and cache-servable.
    recalled = ""
    if not skip_recall:
        self._publish_synthetic_activity(
            session_id, "tool_call", tool_name="recall_memory"
        )
        # A periodic session's first message starts with fixed scheduler
        # scaffolding (the preamble plus the injected current-date/time
        # block) and a user_chat subsession's first turn starts with the
        # side-chat system note; recalling on either retrieves chunks
        # about the boilerplate instead of the actual task, so strip the
        # scaffolding from the recall query (the agent still gets the
        # full message).
        recall_query = strip_recall_scaffolding(message)
        recalled = await self._memory.recall(recall_query, session_id=session_id)
        self._publish_synthetic_activity(
            session_id,
            "tool_result",
            detail=(
                f"found {len(recalled)} chars of prior context"
                if recalled
                else "no relevant memory found"
            ),
        )
    system_prompt = self._instruction
    llm_message = message
    if recalled:
        llm_message = (
            f"{_MEMORY_PROMPT_HEADER}{recalled}{_MEMORY_PROMPT_FOOTER}\n{message}"
        )

    # The per-call override wins; the slot factory and the trace
    # metadata below close over this local, so nothing else has to be
    # threaded. Which provider serves the level is llmio's business:
    # every turn goes through acall_with_failover, which resolves the
    # active slot (and retries the other slot on provider failure).
    level = self._model_level if model_level is None else model_level
    message_history = _build_message_history(history)

    # Compute effective tools once: static tools + per-request tools from
    # the factory (which captures client_id lexically so delegation works
    # even across the claude_sdk/MCP execution-context boundary).
    effective_tools: list[Any] = list(self._tools) if self._tools else []
    if self._request_tools_factory and client_id:
        effective_tools.extend(self._request_tools_factory(client_id))
    tools_arg = effective_tools or None

    # The prompt is ALWAYS plain text. Attachments travel through
    # llmio's ``build_agent(images=...)`` seam instead of being embedded
    # as ``BinaryContent`` parts: the claude_sdk transport passes them as
    # native SDK image blocks (Claude models read images directly), and
    # text-only OpenRouter models get an injected ``ask_image`` tool
    # answered by the tier config's vision binding. Embedding binary
    # parts here 404'd every DeepSeek-served turn ("No endpoints found
    # that support image input", live incident 2026-09-01).
    prompt = llm_message

    on_activity = self._activity_callback(session_id)

    # Stamp model_level as trace metadata so by-model cost breakdowns
    # are usable in Langfuse — the trace_metadata dict from the caller
    # (if any) is merged in so caller keys win on collision.
    effective_trace_metadata: dict[str, str] = {
        "model_level": str(level),
    }
    if trace_metadata:
        effective_trace_metadata.update(trace_metadata)

    # One factory per provider slot: llmio's failover loop calls it with
    # the slot's TierLevelConfig for THIS level (the level never changes
    # across attempts — only the provider slot does). Each slot attempt
    # runs under its own bounded transient retry; a provider-shaped
    # failure that outlives the retries bubbles to the failover loop,
    # which records it and retries the same level on the other slot.
    def _fn_factory(tlc: TierLevelConfig) -> Callable[[], Any]:
        async def _attempt() -> Any:
            provider = get_provider_for_identifier(
                tlc.model, **self._slot_kwargs(tlc)
            )
            slot_system_prompt = system_prompt
            effective_history = message_history
            if slot_needs_api_key(tlc):
                # A keyed (OpenRouter) slot does not share the Claude
                # SDK resume session — tell it plainly it is
                # mid-conversation, and cap the replayed history to the
                # slot's token window.
                if message_history:
                    slot_system_prompt = (
                        f"{system_prompt}\n\n{_FALLBACK_CONTINUATION_NOTE}"
                    )
                if history and tlc.max_tokens:
                    capped = _cap_history_for_keyed_tier(history, tlc.max_tokens)
                    effective_history = _build_message_history(capped)
            handle = provider.build_agent(
                level=level,
                model=tlc.model_name,
                # Only the images/vision path reads tier_config here —
                # the explicit ``model=`` override bypasses level
                # resolution — so passing it wires the configured vision
                # binding without touching slot routing.
                tier_config=self._tier_config,
                system_prompt=slot_system_prompt,
                tools=tools_arg,
                images=images or None,
                vision_api_key=self._api_key or None,
                builtin_tools=False,
                # Read-only web access. The filesystem and shell stay
                # denied; these two only fetch. Without them a research
                # subsession cannot look anything up, and — because a
                # refused tool call is indistinguishable from an empty
                # result — it reports "sources fetched, all empty"
                # rather than "I cannot search".
                web_tools=True,
            )
            # Stateless turn: history + one fresh memory block travel in
            # the prompt; no CLI session is resumed (see the module note
            # above).
            # Stamp the slot's image capability for tools that run inside
            # this attempt: keyed OpenRouter slots (DeepSeek/mimo) are
            # text-only, so image-returning tools degrade to text instead
            # of 404ing the whole turn ("No endpoints found that support
            # image input"). The Claude transports (Claude SDK and the
            # direct Anthropic API) read images natively.
            capability_token = set_model_supports_images(
                not slot_needs_api_key(tlc) or tlc.provider == _ANTHROPIC_PROVIDER
            )
            try:
                with _activity_context(on_activity):
                    limits = _keyed_usage_limits(tlc)
                    if limits is not None:
                        return await handle.run(
                            prompt,
                            message_history=effective_history,
                            usage_limits=limits,
                        )
                    return await handle.run(
                        prompt, message_history=effective_history
                    )
            finally:
                reset_model_supports_images(capability_token)
                handle.close()

        async def _run_slot() -> Any:
            try:
                return await acall_with_retry(
                    _attempt,
                    config=RetryConfig(
                        backoff_base=0.5,
                        backoff_cap=1.0,
                        max_retries=2,
                        jitter_factor=0.0,
                    ),
                    is_transient_fn=_is_chat_turn_transient,
                    what=f"chat turn ({tlc.provider})",
                )
            except Exception as exc:
                # A dead Claude credential takes the whole default slot
                # with it (every claudeSDK level drives the same CLI and
                # .credentials.json), but llmio's failover classifier
                # has no auth category — wrap it as a provider-wide
                # exhaustion so the loop arms failover immediately and
                # retries this level on the keyed slot. Usage exhaustion
                # needs no wrapping: llmio detects it in the
                # cause/context chain even when the CLI launders it.
                root = _chained_claude_unavailability(exc)
                if isinstance(root, ClaudeSDKAuthError):
                    raise ProviderExhaustedError(
                        f"claude credential unusable: {root}"
                    ) from exc
                raise

        return _run_slot

    # The named trace wraps the WHOLE failover loop so the turn (not an
    # llmio-internal ``llmio.failover.attempt`` span) is the Langfuse trace
    # root. Opening it inside each slot attempt made every chat trace
    # surface as "llmio.failover.attempt" (2026-09-07: the fleet cost
    # review read that name as paid-backup failover spend and spawned an
    # investigation of a provider degradation that never happened).
    with _trace_session(
        session_id,
        effective_trace_metadata,
        trace_name=trace_name,
        function=trace_name,
    ):
        result = await acall_with_failover(
            _fn_factory,
            tier_config=self._tier_config,
            level=level,
            what="chat turn",
        )

    self._record_actions_from_result(result)
    text = result.output
    # Persist the exchange in the background so memory consolidation never
    # blocks the reply. The task is tracked to avoid premature GC.
    if text:
        self._schedule_remember(message, text, session_id)
        yield text