Skip to content

fix(showcase/langroid): route A2UI planner through langroid LLM abstraction - #4098

Merged
jpr5 merged 5 commits into
mainfrom
fix/langroid-a2ui-provider-agnostic
Apr 19, 2026
Merged

jpr5 merged 5 commits into
mainfrom
fix/langroid-a2ui-provider-agnostic

Conversation

@jpr5

@jpr5 jpr5 commented Apr 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

langroid is provider-agnostic by design — operators pick a chat model via LANGROID_MODEL. But GenerateA2UITool hardcoded openai.OpenAI() + gpt-4.1, forcing non-OpenAI users to keep an OPENAI_API_KEY around just for the A2UI dashboard demo.

This PR routes the A2UI planner through lm.OpenAIGPT (langroid's universal LLM abstraction) and hardens the deploy/boot path around it.

Core fix

  • Provider-agnostic A2UI planner. GenerateA2UITool now uses lm.OpenAIGPT keyed on A2UI_MODEL (override) → LANGROID_MODEL (inherit) → gpt-4.1 (default, bare name — openai/ prefix is NOT langroid-native and silently breaks at request time).
  • Structured error surface. _A2uiError TypedDict with _A2uiErrorKind enum (values pinned to sibling adapters), _a2ui_error factory with non-empty-string validation at construction, runtime ValueError (not assert) so python -O can't strip it.
  • _ARGS_MISSING sentinel distinguishes "no tool call" from "tool call with degraded shape" — different remediations for the frontend.
  • Narrow re-raise tuple propagates programmer errors (AttributeError, TypeError, NameError, ImportError, ModuleNotFoundError, AssertionError, NotImplementedError, pydantic.ValidationError) while wrapping recoverable SDK errors into a2ui_llm_error.
  • Backend tool handlers now wrap impls in try/except → _tool_error(kind: _ToolErrorKind, ...) JSON surfaces, preventing unhandled exceptions from escaping to langroid's tool machinery.
  • Boundary validation after build_a2ui_operations_from_tool_call return.

Deploy / entrypoint hardening

  • Provider-aware credential guard. Detects LANGROID_MODEL prefix (openai/ → warns it's not routable, gemini/ → GEMINI_API_KEY, litellm/anthropic/ → ANTHROPIC_API_KEY, ollama//local//vllm//llamacpp/ → no-key-required, langdb//litellm-proxy//litellm/<other>/ → config-resolved) and fails fast under REQUIRE_LANGROID_API_KEY=1 only when credentials are genuinely missing.
  • Real PID capture for uvicorn + Next.js via process substitution (prior | sed pattern captured the sed PID, masking crash diagnostics).
  • Graceful shutdown: trap cleanup with set +e safety + 5s SIGTERM→SIGKILL grace window, survivor-kill with EPERM diagnostics.
  • Package Dockerfile now runs as non-root with ENV PORT=10000 / ENV HOSTNAME=0.0.0.0 parity with starter.

Generator + CI

  • entrypointOverride mechanism in generate-starters.ts so the langroid starter's provider-aware entrypoint survives regeneration. Reads canonical from STARTERS_DIR/<slug>/ (not outDir) so --check mode doesn't false-flag drift.
  • Fail-loud on missing required inputs (agent_server.py, extraFiles, PIN_OVERRIDES stale deps, missing override file) instead of silent warn+skip.
  • Regression test pins the entrypointOverride preservation behavior.
  • .gitattributes enforces LF on .sh for Windows contributor safety.

Review

5 full CR rounds (7 agents each) + 6 fix rounds. Load-bearing bugs converged:

  • Round 1: R1 → 47 findings, most resolved
  • Round 2: R2 → 30+ findings, critical (lru_cache keying, build_a2ui wrapper, starter parity, _A2uiError hardening)
  • Round 3: R3 → sed-PID bug (production-blocking), --check drift, file mode, entrypointOverride hard-error, saw_modern_call logic gap
  • Round 4: R4 → google/* FATAL, bare-prefix FATAL, RecursionError test naming, caplog ambiguity, ClassDef walker, _ToolErrorKind enum
  • Round 5: R5 → openai/gpt-4.1 default empirically broken (langroid doesn't strip the prefix → OpenAI SDK rejects), fail-fast refusing ollama/local/vllm/llamacpp, missing regression test for entrypointOverride, rootful package Dockerfile
  • Round 6: R6 → langdb//litellm-proxy//litellm/<non-anthropic>/ refused under fail-fast, starter wait -n pid quoting, cleanup trap set -e safety

Deferred as design-scope follow-ups (not load-bearing, current code is correct):

  • _A2uiError TypedDict → frozen dataclass / pydantic model (stronger encapsulation, cross-sibling alignment required)
  • _ARGS_MISSING: object → named sentinel class (cleaner narrowing)
  • list[dict] tool fields → TypedDict / pydantic models for schema enforcement at ingestion
  • Comment rot around "Identical TypedDicts live in siblings" (sibling adapters diverged on the Literal)
  • Frontend-tool handle() server-side regression path returns benign string (explicit UX tradeoff)

Tests

  • 109 passed, 1 skipped (integration test gated by LANGROID_INTEGRATION_TESTS=1)
  • Module-import hygiene via subprocess isolation (no more stale importlib.reload state)
  • AST walker catches top-level + try/except import openai (including ClassDef bodies)
  • LRU eviction pinned at maxsize=4
  • Forced-function-call kwargs + stream=False planner assertion
  • Parametrized error propagation (both re-raise and wrap tuples)
  • Backend tool handle happy + error paths across all 6 tools
  • create_agent factory: stream=True + enable_message(ALL_TOOLS)

Test plan

  • pytest showcase/packages/langroid/tests/python/ — 109 pass, 1 skipped
  • npx tsx showcase/scripts/generate-starters.ts --check — no langroid drift
  • bash -n clean on both entrypoints
  • Manual: REQUIRE_LANGROID_API_KEY=1 + various LANGROID_MODEL values — bare anthropic/ FATALs, langdb/litellm-proxy/litellm-non-anthropic INFO-pass, ollama/local no-key-required INFO-pass
  • CI green (watching)
  • Railway deploy of showcase-langroid once merged

🤖 Generated with Claude Code

@vercel

vercel Bot commented Apr 19, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
chat-with-your-data Ready Ready Preview, Comment Apr 19, 2026 6:44pm
docs Ready Ready Preview, Comment Apr 19, 2026 6:44pm
form-filling Ready Ready Preview, Comment Apr 19, 2026 6:44pm
research-canvas Ready Ready Preview, Comment Apr 19, 2026 6:44pm
travel Ready Ready Preview, Comment Apr 19, 2026 6:44pm

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

📣 Social Copy Generator

Generate social media copies (Twitter/X, LinkedIn, Blog Post) for this PR using Claude.

  • Generate social media copies

jpr5 added a commit that referenced this pull request Apr 19, 2026
…ntics in A2UI planner

Addresses Python source CR findings in PR #4098 — the _A2uiError contract
was runtime-unenforced and the planner's structural-error propagate-set
was too broad, catching recoverable transport conditions.

Type safety + contract enforcement:
- _A2uiError.error narrowed from `str` to
  `Literal["a2ui_llm_error", "a2ui_no_tool_call", "a2ui_invalid_arguments"]`
  so type-checkers flag unknown error codes.
- _a2ui_error factory signature changed to accept `error: _A2uiErrorKind`
  enum directly; the factory extracts `.value` internally. Call sites pass
  the enum — no more scattered `.value` suffixes that could drift.
- Factory now rejects non-string `message` / `remediation` values at
  runtime (not only empty). Previously `if not err.get(k)` accepted lists
  or dicts silently.
- Module-level frontend-tool-name canary switched from `assert` to
  `if ... raise RuntimeError`. `python -O` strips asserts — the canary
  must fire in production too (same rationale as the adjacent _a2ui_error
  ValueError).

Re-raise tuple narrowed:
- Dropped KeyError, IndexError, LookupError, RecursionError, MemoryError
  from the propagate-set. Provider SDK / adapter internals raise these on
  malformed payloads as recoverable conditions; swallowing them into the
  structured `a2ui_llm_error` surface gives callers the correct
  "retry / check provider" remediation rather than an uncaught 500.
- Added `pydantic.ValidationError` — a schema-validation failure from
  langroid is a programmer error, not a transport failure.
- Dropped the now-stale SyntaxError comment (never was in the tuple).

Defense-in-depth:
- Validate `build_a2ui_operations_from_tool_call` return shape at runtime.
  The success branch previously returned the helper's value verbatim;
  an upstream regression (None, dict without `a2ui_operations`, non-list
  value) would bypass `_A2uiSuccess` and break the frontend renderer
  silently. Now wrapped in a cast after an isinstance check.
- `_extract_tool_call_arguments` falls through to the legacy
  `function_call` slot not only when `.function` is None but also when
  `.function.arguments` is None. The two degraded-shape paths were
  asymmetric before — modern-slot-empty skipped the legacy fallback and
  converted silently into `a2ui_no_tool_call`.
- JSON-parse failure message truncated to 200 chars, matching the
  LLM-error path. Prevents multi-KB raw LLM payloads leaking into the
  structured error surface.
- `GenerateA2UITool.handle` json.dumps except widened to include
  OverflowError (NaN/inf) and RecursionError (cyclic) — neither is a
  TypeError / ValueError subclass but both are raised by json.dumps.

Documentation drift:
- `_get_a2ui_llm` docstring/comment now match `maxsize=4` and document
  LRU eviction semantics briefly (5th distinct model evicts LRU).
- Removed the "as of this writing" time-bounded claim around SDK
  exception messages; framed as a defensive invariant instead.

Starter (`showcase/starters/langroid/agent/agent.py`) mirrors every
source change plus:
- `.tools` / `tools` fallback narrowed from bare `ImportError` to
  `ModuleNotFoundError`. The broader catch masked real in-module import
  failures (e.g. missing third-party dep inside `tools.py`) by silently
  rerunning with a bare `tools` import that could pick up an unrelated
  module on sys.path.
- Header DRIFT note updated to describe the actual starter import
  fallback (was describing the old generator-rewrite behavior).

Tests will be updated by the tests agent in a follow-up commit to match
the narrower re-raise tuple and enum-based factory signature.
jpr5 added a commit that referenced this pull request Apr 19, 2026
…e contract

Addresses Python test CR findings in PR #4098 — several assertions were
shape-only and wouldn't catch a regression in error-kind dispatch, the
module-reload test polluted module state across test runs, and the AST
import-hygiene walker missed imports inside top-level try/except blocks.

Test-module state safety:
- test_agent_module_imports_cleanly_without_openai_env no longer uses
  importlib.reload(). That rebinds module-level function identities
  (_get_a2ui_llm and friends), which breaks the autouse _reset_llm_cache
  fixture for subsequent tests in the same run — the fixture clears the
  OLD function's cache while generate_a2ui_via_llm now holds the NEW one.
  Replaced with a subprocess import so the parent interpreter's state is
  never perturbed. Runs from tmp_path to avoid auto-loading a stray .env.

Error-kind dispatch pinning:
- Every error-branch test now asserts result["error"] against the exact
  _A2uiErrorKind value, not just _assert_full_error_shape. A regression
  that swapped a2ui_llm_error ↔ a2ui_invalid_arguments would previously
  pass with only shape assertions.
- Added test_a2ui_error_kind_values_pinned — locks the three enum .values
  as the cross-sibling contract (google-adk / strands share this surface).

Remediation content + truncation:
- test_generate_a2ui_llm_exception: ConnectionError test now asserts BOTH
  "ConnectionError" AND "backend unreachable" (was `or`), pins
  LANGROID_MODEL + A2UI_MODEL substrings in remediation. The whole point
  of the provider-agnostic fix is that the remediation no longer mentions
  OpenAI-specific env vars.
- Added test_generate_a2ui_llm_exception_message_is_truncated_to_200_chars
  — raises ConnectionError("X" * 5000) and asserts the exception-detail
  portion of message is ≤200 chars.

caplog message substrings:
- Multi-tool-call WARN now matched on "2 tool calls" in rec.getMessage().
- Degraded-shape (arguments None) WARN matched on "arguments is None".
- No-tool-call WARN matched on "did not emit". Any unrelated future WARN
  from agents.agent no longer silently satisfies these assertions.

Round-trip assertions on success paths:
- test_generate_a2ui_legacy_function_call_path and the JSON-string happy
  path now assert a2ui_operations[0]["surfaceId"] matches the input, so
  the test fails if the consumed args came from the wrong slot.

New source-contract tests:
- test_generate_a2ui_propagates_pydantic_validation_error — added since
  ValidationError is now in the re-raise tuple.
- test_generate_a2ui_wraps_recoverable_errors_into_llm_error (KeyError /
  IndexError / LookupError / RecursionError / MemoryError) — these USED
  to propagate; the narrowed re-raise tuple now lets them flow into the
  structured a2ui_llm_error surface. Previous test parametrized them as
  propagating; moved to a separate parametrize that asserts the wrap.
- test_a2ui_error_rejects_non_string_message — _a2ui_error factory now
  rejects non-str message/remediation at runtime.
- test_build_a2ui_operations_boundary_validates_return_shape — if the
  shared builder ever returns a dict without "a2ui_operations", the
  planner surfaces a2ui_invalid_arguments rather than passing it through.
- test_tool_call_with_function_arguments_none_falls_through_to_legacy_path
  — symmetric with the existing function=None fallthrough test; guards
  the new branch in _extract_tool_call_arguments where the modern slot
  has no args but a legacy function_call is present.

AST import-hygiene walker now covers top-level try/except:
- Previous walker only inspected tree.body. A regression like
  `try: import openai; except: pass` at module level would slip through.
  New _module_level_ancestors helper walks the full AST and flags any
  import whose ancestor chain does NOT pass through a FunctionDef /
  AsyncFunctionDef / ClassDef body — so top-level Try / If / With
  blocks are correctly treated as module-load-time code.

Integration-test gating:
- test_construction_succeeds_without_openai_env_real_openaigpt gated
  behind LANGROID_INTEGRATION_TESTS=1 so it doesn't flake in default unit
  runs (langroid's OpenAIGPT construction has historically flirted with
  network / provider init). The model-string routing test remains always-
  on as the unit-level line of defense.

Minor hygiene:
- Removed unused `field` / `datetime` / `importlib` imports.
- Normalized annotations to `X | None` (from __future__ import annotations
  is already in effect).
- Removed the dead `fake_llm = MagicMock()` in the A2UI_MODEL-override
  test (the actual fake was the class-level _FakeLLM patched in).
- Replaced `datetime.utcnow()` (deprecated in 3.12) with `{1, 2, 3}` (a
  set) in the json.dumps failure test — simpler, unambiguously non-
  serializable, and no deprecation noise.
jpr5 added a commit that referenced this pull request Apr 19, 2026
…kind routing

Address CR findings on PR #4098 across the canonical package source and
the generated starter copy. Edits are applied to both files so they stay
in lockstep until ``generate-starters.ts`` is re-run.

Type design
- Synthesize ``_A2uiError.error`` Literal from ``_A2uiErrorKind`` via
  ``Literal[*tuple(k.value for k in _A2uiErrorKind)]`` (Python 3.11+).
  Removes the hand-synced duplicate closed-set of strings and enum
  values — add/remove an enum member and the TypedDict follows.
- Annotate ``BACKEND_TOOLS`` / ``FRONTEND_TOOLS`` / ``ALL_TOOLS`` as
  ``tuple[type[ToolMessage], ...]``; annotate ``FRONTEND_TOOL_NAMES``
  as ``frozenset[str]``. Previously inferred; explicit types lock the
  public contract for consumers and static checkers.
- Replace the ``response: Any`` parameter on
  ``_extract_tool_call_arguments`` with a ``_LLMResponseLike`` Protocol
  documenting the two attributes actually read. Return type tightened
  from ``dict | None | str`` to ``dict[str, Any] | str | None | object``
  (parameterized; ``object`` covers the new sentinel — see below).

Error-kind routing correctness
- Distinguish "tool-call slot present but ``arguments`` is None" from
  "no tool call at all." The former is now surfaced as
  ``a2ui_invalid_arguments`` via an ``_ARGS_MISSING`` sentinel; the
  latter remains ``a2ui_no_tool_call``. Previously both collapsed to
  NO_TOOL_CALL with the wrong remediation ("verify the planner
  supports forced function-calling") for the degraded-shape case.
  Applies symmetrically to the modern ``oai_tool_calls`` path and the
  legacy ``function_call`` path — both now emit a WARN and return the
  sentinel rather than silently return None.
- Widen the ``json.loads`` except clause to include ``MemoryError`` and
  ``RecursionError`` for pathological payloads (multi-MB JSON, cyclic
  structures). Parity with ``GenerateA2UITool.handle`` which already
  catches these for ``json.dumps``.

Diagnostics
- ``_A2uiSuccess`` shape-validation log now includes
  ``sorted(result.keys())[:20]`` when result is a dict. Type name
  alone cannot tell "wrong key name" (planner emitted ``operations``
  instead of ``a2ui_operations``) from "wrong type."
- ``ChangeBackgroundTool.handle`` / ``GenerateHaikuTool.handle``
  emit a ``logger.error`` when fired server-side. If the AG-UI adapter
  dispatch regresses, the agent used to silently return "Background
  changed to ..." / "Haiku generated!" even though no client-side
  render happened. We preserve the benign string return (non-breaking
  for starters) but now log loudly.

Cleanup
- Drop redundant docstrings on all 9 ToolMessage subclasses — ``purpose``
  is the single source of truth (langroid consumes it for the LLM).
- Trim the ``_get_a2ui_llm`` lru_cache commentary from ~20 lines to 6.
- Sync the package header comment with the starter header comment so
  both mention the ``.tools`` / ``tools`` fallback rewrite performed
  by the generator.

Verified locally: ``python -m pytest tests/python/ -x`` is 78 pass /
1 skip / 1 fail. The one failure is in the tests file (asserts the
old NO_TOOL_CALL routing for the modern-slot missing-arguments case);
the tests agent is aligning that in a separate commit.
…action

The secondary GenerateA2UITool previously hardcoded openai.OpenAI() + gpt-4.1,
forcing non-OpenAI users to keep an OPENAI_API_KEY around just for the A2UI
dashboard demo even when LANGROID_MODEL pointed at another provider.

Route the planner through lm.OpenAIGPT (langroid's universal LLM abstraction)
keyed on A2UI_MODEL (override) → LANGROID_MODEL (inherit) → gpt-4.1 (default).
Default uses the bare model name because `openai/` is NOT a langroid-native
prefix — langroid passes it literally to the OpenAI SDK which rejects it.

Additional hardening:
- _A2uiError TypedDict with _A2uiErrorKind enum, factory with non-empty-string
  validation that raises ValueError (not assert, so python -O can't strip it)
- _ARGS_MISSING sentinel distinguishes "no tool call" from "degraded shape"
  so the frontend gets correct remediation
- Narrow re-raise tuple propagates programmer errors (AttributeError, TypeError,
  NameError, ImportError, ModuleNotFoundError, AssertionError, NotImplementedError,
  pydantic.ValidationError) while wrapping recoverable SDK errors into _a2ui_error
- _ToolErrorKind enum for backend tool error codes — typo-safe parity with _A2uiErrorKind
- Boundary validation after build_a2ui_operations_from_tool_call return
- Backend tool handlers wrap impls in try/except so exceptions don't escape
  to langroid's tool machinery
- @lru_cache(maxsize=4) on _get_a2ui_llm keyed on resolved model string
- FRONTEND_TOOL_NAMES canary raises RuntimeError at import time on drift
- No top-level import of openai (AST walker test pins this contract)

Covered by 109 tests (integration test gated by LANGROID_INTEGRATION_TESTS=1).
…graceful shutdown

Replace the OPENAI_API_KEY-hardcoded credential guard with a provider-aware
_check_key that inspects LANGROID_MODEL's prefix and probes the correct env
var for that provider:

- openai/ → WARN (not a langroid-native prefix; use bare model names)
- anthropic/ → WARN (not routable; suggest litellm/anthropic/<model>)
- litellm/anthropic/ → ANTHROPIC_API_KEY
- gemini/ → GEMINI_API_KEY
- openrouter/, groq/, cerebras/, glhf/, minimax/, portkey/, deepseek/ → dedicated keys
- ollama/, local/, vllm/, llamacpp/ → NO_KEY_REQUIRED (local inference)
- langdb/, litellm-proxy/, litellm/<non-anthropic>/ → NO_KEY_REQUIRED_* (credentials
  resolved via config, not env)

Under REQUIRE_LANGROID_API_KEY=1 a missing credential FATALs the boot; the
default is warn-and-continue so dev containers boot cleanly.

Process lifecycle hardening:
- Use process substitution `> >(sed ...)` instead of pipelines so $! captures
  the real python/next PID (not sed's) — prior pipeline pattern would mask
  uvicorn crashes behind sed's exit code
- Trap cleanup with `set +e` at entry (trap may fire from FATAL `exit 1` path
  where set -e would otherwise abort the cleanup loop)
- 5s SIGTERM→SIGKILL grace window on the surviving child
- Extended exit-code case statement (0, 1, 2, 126, 127, 130, 137, 139, 143, 255)
- Survivor-kill diagnostics distinguish EPERM from ESRCH
- wait -n with explicit positional PIDs so unrelated subshell reaps can't
  satisfy the wait

.env.example updates document the multi-provider options so operators
discover them from the file itself, not entrypoint.sh.

.gitattributes enforces LF on *.sh so Windows contributors regenerating
the starter don't silently ship CRLF entrypoints.
jpr5 added 3 commits April 19, 2026 11:38
Package Dockerfile:
- Create unprivileged app:app user (UID/GID 1001) matching starter Dockerfile
- USER app drop with --chown=app:app on COPY for security parity
- ENV PORT=10000 / ENV HOSTNAME=0.0.0.0 so child processes inherit defaults
- Preserves PYTHONPATH=/app/shared/python for shared-tools imports

requirements.txt (package + starter): pin httpx, pydantic, openai directly
rather than relying on transitive resolution from langroid / fastapi.
agui_adapter.py imports these symbols directly — the module's contract
shouldn't depend on upstream pin discipline we don't control.
…ssing inputs

generate-starters.ts:
- Add entrypointOverride?: boolean to FrameworkDef so slugs whose boot sequence
  diverges from the shared template (e.g. langroid's provider-aware credential
  guard) can preserve their committed entrypoint.sh through regeneration.
- Snapshot the override from STARTERS_DIR/<slug>/entrypoint.sh (canonical
  committed path), NOT outDir — so --check mode (which passes a temp outDir)
  doesn't false-flag the override as drift.
- Force mode: 0o755 on the restored file regardless of source mode so editors
  that strip the executable bit can't silently ship a broken starter.
- Throw (not warn) when an entrypointOverride slug is missing the override
  file, when declared extraFiles / agent_server.py / Dockerfile are missing,
  and when PIN_OVERRIDES references a stale dep. These are repo-integrity
  failures — silent-warn-and-continue ships broken starters.
- Strip unused `import sys` after sys.path.insert removal (pair with the
  existing osUsed detection).

Opt langroid in via entrypointOverride: true.

Also adds a regression test in __tests__/generate-starters.test.ts that
calls generateStarterToDir against a tmp dir and asserts the emitted
entrypoint.sh byte-equals the committed langroid starter entrypoint,
plus a negative test that a non-override slug does NOT preserve its file.
@jpr5
jpr5 force-pushed the fix/langroid-a2ui-provider-agnostic branch from 62b40ef to ede34da Compare April 19, 2026 18:40
@jpr5
jpr5 merged commit 09d08b1 into main Apr 19, 2026
9 of 13 checks passed
@jpr5
jpr5 deleted the fix/langroid-a2ui-provider-agnostic branch April 19, 2026 18:40
jpr5 added a commit that referenced this pull request Apr 19, 2026
#4098 landed two generator-level changes that affect every starter slug but only
langroid was regenerated in that PR:

1. rewritePythonImports now strips `import sys` when sys.path.insert is removed
   and no other `sys` reference survives in the file (paired with existing
   osUsed detection).
2. starters/template/entrypoint.template.sh switched from pipeline
   (`2>&1 | sed 's/^/[agent] /'`) to process substitution
   (`&> >(awk '{print "[agent] " $0; fflush()}')`) so $! captures the real
   agent PID, not sed's — prior pattern masked uvicorn crashes behind sed's
   exit code.

Regenerate the remaining 16 starters so drift-check passes on main.

No source logic change.
jpr5 added a commit that referenced this pull request Apr 19, 2026
## Summary

Hotfix for drift-check on main after #4098 merged.

#4098 landed two generator-level changes that affect every starter slug:
1. `rewritePythonImports` now strips `import sys` when the
`sys.path.insert` block is removed and no other `sys` reference
survives.
2. `starters/template/entrypoint.template.sh` switched from
pipeline-with-sed to process substitution so `$!` captures the real
agent PID, not sed's.

Only langroid was regenerated in #4098. This PR regenerates the other 16
starters so drift-check passes.

No source logic change.

## Test plan
- [x] `npx tsx showcase/scripts/generate-starters.ts` — clean regen
- [x] `npx tsx showcase/scripts/generate-starters.ts --check` — no drift
- [ ] CI drift-check green

🤖 Generated with [Claude Code](https://claude.com/claude-code)
ataibarkai added a commit that referenced this pull request Apr 19, 2026
…n merge

Re-ran generate-registry + validate-pins after merging main (which brought
in PR #4098 langroid + #4100/#4101/#4102 starter regens) and the non-root
+ PID-capture column sweep. FAIL count unchanged at 110; hash drifts
because the FAIL set is the same strands entries but ordering normalized.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
…action (CopilotKit#4098)

## Summary

langroid is provider-agnostic by design — operators pick a chat model
via `LANGROID_MODEL`. But `GenerateA2UITool` hardcoded `openai.OpenAI()`
+ `gpt-4.1`, forcing non-OpenAI users to keep an `OPENAI_API_KEY` around
just for the A2UI dashboard demo.

This PR routes the A2UI planner through `lm.OpenAIGPT` (langroid's
universal LLM abstraction) and hardens the deploy/boot path around it.

## Core fix

- **Provider-agnostic A2UI planner.** `GenerateA2UITool` now uses
`lm.OpenAIGPT` keyed on `A2UI_MODEL` (override) → `LANGROID_MODEL`
(inherit) → `gpt-4.1` (default, bare name — `openai/` prefix is NOT
langroid-native and silently breaks at request time).
- **Structured error surface.** `_A2uiError` TypedDict with
`_A2uiErrorKind` enum (values pinned to sibling adapters), `_a2ui_error`
factory with non-empty-string validation at construction, runtime
`ValueError` (not `assert`) so `python -O` can't strip it.
- **`_ARGS_MISSING` sentinel** distinguishes "no tool call" from "tool
call with degraded shape" — different remediations for the frontend.
- **Narrow re-raise tuple** propagates programmer errors
(`AttributeError`, `TypeError`, `NameError`, `ImportError`,
`ModuleNotFoundError`, `AssertionError`, `NotImplementedError`,
`pydantic.ValidationError`) while wrapping recoverable SDK errors into
`a2ui_llm_error`.
- **Backend tool handlers** now wrap impls in try/except →
`_tool_error(kind: _ToolErrorKind, ...)` JSON surfaces, preventing
unhandled exceptions from escaping to langroid's tool machinery.
- **Boundary validation** after `build_a2ui_operations_from_tool_call`
return.

## Deploy / entrypoint hardening

- **Provider-aware credential guard.** Detects `LANGROID_MODEL` prefix
(`openai/` → warns it's not routable, `gemini/` → `GEMINI_API_KEY`,
`litellm/anthropic/` → `ANTHROPIC_API_KEY`,
`ollama/`/`local/`/`vllm/`/`llamacpp/` → no-key-required,
`langdb/`/`litellm-proxy/`/`litellm/<other>/` → config-resolved) and
fails fast under `REQUIRE_LANGROID_API_KEY=1` only when credentials are
genuinely missing.
- **Real PID capture** for uvicorn + Next.js via process substitution
(prior `| sed` pattern captured the sed PID, masking crash diagnostics).
- **Graceful shutdown:** trap cleanup with `set +e` safety + 5s
SIGTERM→SIGKILL grace window, survivor-kill with EPERM diagnostics.
- **Package Dockerfile** now runs as non-root with `ENV PORT=10000` /
`ENV HOSTNAME=0.0.0.0` parity with starter.

## Generator + CI

- **`entrypointOverride`** mechanism in `generate-starters.ts` so the
langroid starter's provider-aware entrypoint survives regeneration.
Reads canonical from `STARTERS_DIR/<slug>/` (not `outDir`) so `--check`
mode doesn't false-flag drift.
- **Fail-loud** on missing required inputs (agent_server.py, extraFiles,
PIN_OVERRIDES stale deps, missing override file) instead of silent
warn+skip.
- **Regression test** pins the `entrypointOverride` preservation
behavior.
- **`.gitattributes`** enforces LF on `.sh` for Windows contributor
safety.

## Review

5 full CR rounds (7 agents each) + 6 fix rounds. Load-bearing bugs
converged:
- Round 1: R1 → 47 findings, most resolved
- Round 2: R2 → 30+ findings, critical (lru_cache keying, build_a2ui
wrapper, starter parity, `_A2uiError` hardening)
- Round 3: R3 → sed-PID bug (production-blocking), `--check` drift, file
mode, `entrypointOverride` hard-error, `saw_modern_call` logic gap
- Round 4: R4 → `google/*` FATAL, bare-prefix FATAL, RecursionError test
naming, caplog ambiguity, ClassDef walker, `_ToolErrorKind` enum
- Round 5: R5 → **`openai/gpt-4.1` default empirically broken**
(langroid doesn't strip the prefix → OpenAI SDK rejects), fail-fast
refusing ollama/local/vllm/llamacpp, missing regression test for
entrypointOverride, rootful package Dockerfile
- Round 6: R6 → `langdb/`/`litellm-proxy/`/`litellm/<non-anthropic>/`
refused under fail-fast, starter `wait -n` pid quoting, cleanup trap
`set -e` safety

Deferred as design-scope follow-ups (not load-bearing, current code is
correct):
- `_A2uiError` TypedDict → frozen dataclass / pydantic model (stronger
encapsulation, cross-sibling alignment required)
- `_ARGS_MISSING: object` → named sentinel class (cleaner narrowing)
- `list[dict]` tool fields → TypedDict / pydantic models for schema
enforcement at ingestion
- Comment rot around "Identical TypedDicts live in siblings" (sibling
adapters diverged on the Literal)
- Frontend-tool `handle()` server-side regression path returns benign
string (explicit UX tradeoff)

## Tests

- 109 passed, 1 skipped (integration test gated by
`LANGROID_INTEGRATION_TESTS=1`)
- Module-import hygiene via subprocess isolation (no more stale
`importlib.reload` state)
- AST walker catches top-level + `try/except` `import openai` (including
ClassDef bodies)
- LRU eviction pinned at `maxsize=4`
- Forced-function-call kwargs + `stream=False` planner assertion
- Parametrized error propagation (both re-raise and wrap tuples)
- Backend tool handle happy + error paths across all 6 tools
- `create_agent` factory: stream=True + enable_message(ALL_TOOLS)

## Test plan
- [x] `pytest showcase/packages/langroid/tests/python/` — 109 pass, 1
skipped
- [x] `npx tsx showcase/scripts/generate-starters.ts --check` — no
langroid drift
- [x] `bash -n` clean on both entrypoints
- [x] Manual: `REQUIRE_LANGROID_API_KEY=1` + various `LANGROID_MODEL`
values — bare anthropic/ FATALs,
langdb/litellm-proxy/litellm-non-anthropic INFO-pass, ollama/local
no-key-required INFO-pass
- [ ] CI green (watching)
- [ ] Railway deploy of showcase-langroid once merged

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
CopilotKit#4098 landed two generator-level changes that affect every starter slug but only
langroid was regenerated in that PR:

1. rewritePythonImports now strips `import sys` when sys.path.insert is removed
   and no other `sys` reference survives in the file (paired with existing
   osUsed detection).
2. starters/template/entrypoint.template.sh switched from pipeline
   (`2>&1 | sed 's/^/[agent] /'`) to process substitution
   (`&> >(awk '{print "[agent] " $0; fflush()}')`) so $! captures the real
   agent PID, not sed's — prior pattern masked uvicorn crashes behind sed's
   exit code.

Regenerate the remaining 16 starters so drift-check passes on main.

No source logic change.
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
… (CopilotKit#4100)

## Summary

Hotfix for drift-check on main after CopilotKit#4098 merged.

CopilotKit#4098 landed two generator-level changes that affect every starter slug:
1. `rewritePythonImports` now strips `import sys` when the
`sys.path.insert` block is removed and no other `sys` reference
survives.
2. `starters/template/entrypoint.template.sh` switched from
pipeline-with-sed to process substitution so `$!` captures the real
agent PID, not sed's.

Only langroid was regenerated in CopilotKit#4098. This PR regenerates the other 16
starters so drift-check passes.

No source logic change.

## Test plan
- [x] `npx tsx showcase/scripts/generate-starters.ts` — clean regen
- [x] `npx tsx showcase/scripts/generate-starters.ts --check` — no drift
- [ ] CI drift-check green

🤖 Generated with [Claude Code](https://claude.com/claude-code)

This branch was successfully deployed

5 active deployments
Preview – research-canvas — ede34dab Deployed Apr 19, 2026 by vercel[bot]
Preview – travel — ede34dab Deployed Apr 19, 2026 by vercel[bot]
Preview – docs — ede34dab Deployed Apr 19, 2026 by vercel[bot]
Preview – form-filling — ede34dab Deployed Apr 19, 2026 by vercel[bot]
Preview – chat-with-your-data — ede34dab Deployed Apr 19, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant