WolfStack icon indicating copy to clipboard operation
WolfStack copied to clipboard

Collapse 3 provider-specific tool loops in wolfagents::agent_loop.rs into one that calls ai_gateway (~1,083-line refactor)

Open tonytouch opened this issue 5 months ago • 2 comments

Problem

src/wolfagents/agent_loop.rs (1,238 lines) contains three near-duplicate provider-specific tool loops:

Loop Start line Span (lines) Talks to
openai_tool_loop 148 148–376 (≈229) OpenAI / OpenRouter / local
gemini_tool_loop 377 377–790 (≈414) Google Gemini
claude_tool_loop 791 791–≈1,230 (≈440) Anthropic Claude
Total ≈1,083 lines of duplication

A single dispatch site in the same file (≈L98–118) picks one of the three at runtime based on which provider AiConfig is configured for. The duplication shows up in: system-prompt assembly, request body encoding (3 different shapes), tool-call extraction (3 different parsers), the actual dispatch::dispatch(agent, …) call (identical in all three), and error reporting / budget enforcement.

Why now

The Phase-0 scaffold of the new ai_gateway module just landed. ai_gateway is the unified LLM caller that replaces mod ai::simple_chat as the call site and collapses the three tool loops into one. Once Phase 1 of the design doc lands concrete Provider impls (openai-compat, anthropic, gemini), this refactor becomes a tractable drop-in.

Refactor target

  • Delete openai_tool_loop (L148–376), gemini_tool_loop (L377–790), claude_tool_loop (L791–≈1,230) — ≈1,083 lines
  • Replace the dispatch site (≈L98–118) with a single call to the new ai_gateway::chat_unified
  • agent_loop.rs shrinks from 1,238 → ≈155 lines (≈87% reduction)
  • src/ai/mod.rs (4,493 lines) — simple_chat at L2406, chat at L825, AiConfig at L92 — can shrink to ≈500 lines once the gateway is the only LLM call site

Approach (3 phases)

A. Side-by-side — ai_gateway::chat_unified added; dispatch picks between old and new based on a feature flag (default: new). Both code paths live and run in production; results must match.

B. Cutover — flag flips to new-only after 1–2 weeks of parity confirmation; the three legacy loops are deleted.

C. Clean up — ai/mod.rs audited for non-LLM helpers (prompt templating, config loading); moved into ai_gateway/ or a smaller ai_core/; simple_chat and chat deleted.

Acceptance criteria

  • [ ] src/wolfagents/agent_loop.rs is ≤200 lines (down from 1,238)
  • [ ] The three *_tool_loop functions are deleted; no callers reference them
  • [ ] src/ai/mod.rs is ≤1,000 lines (down from 4,493)
  • [ ] ai_gateway::chat_unified is the only LLM call site used by wolfagents::dispatch
  • [ ] Discord / Telegram / WhatsApp agent bindings work end-to-end against all three providers
  • [ ] cargo check --bin wolfstack clean (0 warnings, 0 errors)
  • [ ] No behavioural regressions

Dependencies

Blocked on Phase 1 of the design doc (concrete Provider impls + chat_unified). Unblocked work: drop-in OpenAI SDK surface for external clients, virtual keys + per-key budgets, fallback chain.

Canonical tracking doc

Full design + refactor plan + decision log lives in the tonysplace mirror at docs/issues/rust-ai-gateway-collapse-tool-loops.md (cross-linked from docs/rust-ai-gateway.md). This GitHub issue is the mirror for wolfstack maintainer visibility.

tonytouch avatar Jun 15 '26 00:06 tonytouch

Phase 0 — done ✅

The ai_gateway scaffold shipped in this session:

  • src/ai_gateway/ — 5 files, 523 lines, cargo check --bin wolfstack clean
  • 3 deps added to Cargo.toml (per §3 of the design doc): usearch (HNSW vector store, Phase 4), ort + all-MiniLM-L6-v2 ONNX asset (local embedding, Phase 4), redb (pure-Rust embedded ledger — now required, since installer/ does not bootstrap a DB and the gateway cannot assume one)
  • AiConfig refactored — load() split from the chat-time accessor (the cluster_secret pattern in main.rs), so the gateway can re-read keys per-request for rotation without breaking the existing call sites
  • api::AppState slots reserved — ai_gateway_providers, ai_gateway_keys_ledger, ai_gateway_cache (added to the same AppState, not a second one)
  • tracing structured fields wired — target: "wolfstack::ai_gateway", fields: provider, model, status, latency_ms
  • CLI subcommand --ai-gateway-validate — parity with --wolfrouter-recover / --leave-cluster; runs one test call per configured provider and exits with a result table

Design doc is at rev 5 (2026-06-15): docs/rust-ai-gateway.md in the in-repo mirror. Freellmapi-bridge relationship is REPLACE with co-exist migration (see §4 of the doc); the bridge's 22-platform catalog in backend/freellmapi-bridge/ts/catalog.ts becomes the input to ai_gateway::providers concrete impls.


Open dependency chain (Phase 0 → 2)

Phase 1 — Vertical slice (blocks this refactor's Phase A)

  • /api/llm/v1/chat/completions route appended to src/api/mod.rs::configure (L34615) — either inline or via a configure_ai_gateway(cfg) sub-fn matching the configure_statuspage_only precedent
  • serde models for ChatCompletionRequest / ChatCompletionResponse (snake_case to match the rest of the API surface)
  • SSE streaming via reqwest (already in Cargo.toml 0.12 with stream + json features)
  • ai_gateway::providers::{OpenaiCompat, Anthropic, Gemini} — the three concrete impls that encapsulate the per-provider request/response translation that today lives in agent_loop.rs:148/377/791
  • ai_gateway::chat::chat_unified(req) -> Result<UnifiedResponse> — the single entry point
  • Auth / cache / budget interceptors as no-op stubs so Phase 1 is testable in isolation
  • One provider (cerebras) + one fallback (openai) for the first end-to-end test with the openai Python SDK against http://localhost:8553/api/llm/v1

Acceptance gate: openai Python SDK round-trips a chat completion through /api/llm/v1/ and a simulated upstream 5xx triggers fallback without client-side errors.

Phase 2 — Auth + budget (blocks this refactor's Phase B flag flip)

  • Authorization: Bearer <virtual_key> interceptor — validate at startup, cache the result, re-validate on 401/403 from upstream (not per-request)
  • In-memory Arc<RwLock<HashMap<String, AtomicU64>>> for hot-path spend; write-behind flush to redb ledger (or to existing MySQL/Postgres if the operator has it; installer/ does not bootstrap a DB)
  • Budget rejection before upstream call; atomic CAS to avoid the check-then-act race
  • Real provider keys stay env-var-only (read at request time, never logged, never persisted — same contract as freellmapi-bridge/ts/catalog.ts)

Acceptance gate: load test with virtual keys + budget caps shows the latency win is preserved (no SQLite-style single-writer lock); 401/403 from upstream triggers re-validation.

Phase 3 — Observability + rollout (parallel, not strictly blocking)

  • tracing structured fields per the §2.5 table (provider, model, status, latency_ms, fallback_used)
  • Per-consumer migration runbook for the 4 existing AI surfaces:
    1. Python ProviderManager (backend/agent-os/providers/manager.py)
    2. TS freellmapi-bridge (backend/freellmapi-bridge/ts/catalog.ts)
    3. TS codebuff-bridge (backend/node/codebuff-bridge/server.ts)
    4. Internal wolfagents::agent_loop (this issue)
  • Decide AiConfig (6 hardcoded providers, single-active-at-a-time) vs ai_gateway.json (per-provider, per-model) — option 2 from §2.2 #6 of the design doc is the recommended path

Phase 4 — Semantic cache (not blocking, can land later)

  • usearch index persisted to /var/lib/wolfstack/ai_gateway/index.usearch on every N inserts
  • ort embedding of incoming prompts (≤1ms on CPU for short prompts)
  • Cosine-similarity threshold tuning against an eval set (TBD)
  • Defer until 1–3 are stable in prod; if it doesn't pan out, the gateway is still useful without it

Refactor sequencing for this issue (#21)

Step Phase Action Gate
A. Side-by-side Phase 1 agent_loop::dispatch adds a chat_unified path alongside the three *_tool_loop calls; both run; results must match Phase 1 parity-complete
B. Flag flip + cutover Phase 2 WOLFSTACK_USE_AI_GATEWAY=1 (default ON); run 1–2 weeks in prod; then delete openai_tool_loop / gemini_tool_loop / claude_tool_loop (~1,083 lines) Phase 1 parity + Phase 2 budget tracking live
C. Clean up ai/mod.rs Phase 2 simple_chat (L2406) and chat (L825) become thin wrappers or get deleted; non-LLM helpers (config loading, prompt templating) move to ai_gateway/ or ai_core/; ai/mod.rs shrinks 4,493 → ~500 lines Phase B cutover complete

File shrink targets (acceptance criteria, from the issue body): agent_loop.rs 1,238 → ≤200 lines, ai/mod.rs 4,493 → ≤1,000 lines, the three *_tool_loop functions deleted, ai_gateway::chat_unified is the only LLM call site used by wolfagents::dispatch, cargo check and cargo clippy clean, Discord/Telegram/WhatsApp bindings work end-to-end against all three providers.


Project board suggestion

I'd suggest one parent issue (#21, this one) + three child issues (one per phase: 1, 2, 3). Use the standard "blocked by" relationship to wire the chain:

  • #21 (this) — Blocked by → Phase 1 child
  • Phase 1 child — Blocks → #21 Phase A and Phase 3 child
  • Phase 2 child — Blocks → #21 Phase B flag flip
  • Phase 3 child — Parallel to Phase 1 + 2 (observability can land alongside)

That way the dependency chain is explicit on the board, a maintainer can sequence without re-reading the design doc, and the refactor doesn't get closed prematurely.


Posted from the in-repo mirror at docs/issues/rust-ai-gateway-collapse-tool-loops.md (the canonical artifact). The local mirror will be updated to reference this comment.

tonytouch avatar Jun 15 '26 01:06 tonytouch

Closing — WolfStack's public issue tracker is now limited to maintainers; we are not accepting external feature or design proposals through the public tracker. Thanks.

intelligentwolf avatar Jun 15 '26 06:06 intelligentwolf