Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:416rehman DeepZero CLIAgentBackend

From Leeroopedia
Knowledge Sources
Domains LLM_Backend, Extensibility
Last Updated 2026-10-27 00:00 GMT

Overview

Abstract base class providing reusable subprocess plumbing for LLM backends that shell out to a locally installed agent CLI, with binary discovery, prompt flattening, error classification, and env sanitization.

Description

The CLIAgentBackend class is the base for backends that drive a locally installed coding-agent CLI (e.g., Claude Code, Codex, Gemini CLI). It handles all the subprocess plumbing so subclasses only declare what to run and how to read the output.

Inherited functionality:

  • Binary discovery: find_binary() searches PATH and extra_search_paths() for the declared binary_names. Raises BackendNotFoundError if missing.
  • Prompt flattening: split_messages() converts a chat message list into (system_prompt, user_prompt). Agent CLIs are single-shot, so prior turns are rendered inline.
  • Subprocess execution: raw_complete() runs the CLI as a subprocess with stdin input, timeout, env sanitization, and cwd control.
  • Error classification: classify_error() maps return codes (401/403/429/5xx) and error substrings to the generic taxonomy (BackendAuthError, BackendRateLimitError, BackendContextWindowError, BackendError).
  • Env sanitization: build_env() optionally strips env vars (e.g., API keys) so the CLI uses its own login rather than a metered key in .env.
  • Pre-flight checks: validate_model() checks binary presence; check_auth() sends a minimal prompt to verify authentication.

Subclasses implement two abstract methods:

  • build_argv(system): returns (argv, inline_system). The argv list for the subprocess; system text to route via stdin if too long for argv.
  • parse_output(returncode, stdout, stderr): extracts response text from the CLI's output, or raises a BackendError subclass.

Usage

  • Adding a new CLI backend: subclass CLIAgentBackend, set scheme/binary_names/display_name, implement build_argv and parse_output, and register with register_backend.
  • The reference implementation is ClaudeCodeBackend.

Code Reference

Source Location

  • Repository: DeepZero
  • File: src/deepzero/engine/backends/base.py

Signature

class LLMBackend(ABC):
    scheme: ClassVar[str] = ""
    aliases: ClassVar[tuple[str, ...]] = ()
    rate_limit_error: ClassVar[type[BaseException]] = BackendRateLimitError
    context_window_error: ClassVar[type[BaseException]] = BackendContextWindowError
    non_retryable_errors: ClassVar[tuple[type[BaseException], ...]] = (BackendAuthError,)
    retryable_errors: ClassVar[tuple[type[BaseException], ...]] = (BackendError, OSError)

    @abstractmethod
    def raw_complete(self, messages: list[dict[str, str]], **kwargs: Any) -> str: ...

class CLIAgentBackend(LLMBackend):
    binary_names: ClassVar[tuple[str, ...]] = ()
    install_hint: ClassVar[str] = ""
    default_timeout: ClassVar[int] = 900
    max_argv_text: ClassVar[int] = 8000
    subscription_auth_env_blocklist: ClassVar[tuple[str, ...]] = ()

    @abstractmethod
    def build_argv(self, system: str) -> tuple[list[str], str]: ...

    @abstractmethod
    def parse_output(self, returncode: int, stdout: str, stderr: str) -> str: ...

    def classify_error(self, detail: str, status: Any = None) -> BackendError: ...
    def raw_complete(self, messages: list[dict[str, str]], **kwargs: Any) -> str: ...
    def check_auth(self) -> str | None: ...

Import

from deepzero.engine.backends.base import CLIAgentBackend, LLMBackend, BackendError

I/O Contract

Inputs

Name Type Required Description
model str Yes Model string (scheme/alias)
messages list[dict] Yes (raw_complete) Chat messages
timeout int No (kwargs) Per-call timeout (default 900)
system str Yes (build_argv) Flattened system prompt
returncode int Yes (parse_output) Subprocess exit code
stdout str Yes (parse_output) Subprocess stdout
stderr str Yes (parse_output) Subprocess stderr

Outputs

Name Type Description
raw_complete() returns str LLM response text
build_argv() returns tuple[list[str], str] (argv, inline_system)
parse_output() returns str Response text

Usage Examples

Subclassing CLIAgentBackend

from deepzero.engine.backends.base import CLIAgentBackend, BackendError
from deepzero.engine.backends.registry import register_backend

@register_backend
class MyAgentBackend(CLIAgentBackend):
    scheme = "my-agent"
    display_name = "My Agent"
    binary_names = ("my-agent",)
    install_hint = "install from https://example.com"

    def build_argv(self, system: str) -> tuple[list[str], str]:
        argv = [str(self._binary), "--json", "--model", self.alias]
        inline = ""
        if system:
            if len(system) <= self.max_argv_text:
                argv += ["--system", system]
            else:
                inline = system
        return argv, inline

    def parse_output(self, returncode: int, stdout: str, stderr: str) -> str:
        import json
        payload = json.loads(stdout)
        if payload.get("error"):
            raise self.classify_error(payload["error"])
        return payload["response"]

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment