Skip to content

docs: document graceful BudgetExceededError CLI handling (from PraisonAI PR #1645) #341

@MervinPraison

Description

@MervinPraison

Context

PraisonAI PR #1645 ("fix(cli): graceful BudgetExceededError — wrapper-only, no Agent param bloat") merged into main on 2026-05-09 (head SHA f29326a66b3d26dc071091ce30e4a00c0b184783, base b2611e5d618afe23745624e2c63d71f491b2b9cb).

It adds a CLI-side graceful error handler so that when an agent run exceeds its budget under the praisonai CLI, the user sees a single-line, actionable error message and exit-code 1 instead of a raw Python traceback.

This is a CLI UX change in the praisonai/ wrapper (no SDK changes). The canonical SDK API for budgets — Agent(execution=ExecutionConfig(max_budget=1.00)) — is unchanged and is what the new CLI error message points users to.

Closes upstream issue #1627. The original PR #1635 was reverted because it added a top-level max_budget= param on Agent.__init__ (violates AGENTS.md §5.3 Parameter Consolidation) — PR #1645 is the wrapper-only re-implementation.


SDK-First Verification (per AGENTS.md §1.2)

Verified against source in this repo (synced from upstream daily):

src/praisonai/praisonai/cli/main.py — new helper (lines ~4068–4090)

def _execute_agent_with_budget_handling(self, agent, method_name, *args, **kwargs):
    """Run agent.<method_name>(*args, **kwargs) with a graceful
    BudgetExceededError handler.

    Wrapper-only fix (no core SDK changes). Users configure budgets via
    execution=ExecutionConfig(max_budget=...) on the Agent — per
    AGENTS.md §5.3 there is NO top-level max_budget= parameter on
    Agent.__init__ (avoids parameter bloat).
    """
    from praisonaiagents.errors import BudgetExceededError
    try:
        return getattr(agent, method_name)(*args, **kwargs)
    except BudgetExceededError as e:
        from rich import print as rich_print
        rich_print(
            f"[red]Budget limit exceeded: {e!s}. "
            "Hint: set budget via "
            "execution=ExecutionConfig(max_budget=1.00) on your Agent.[/red]"
        )
        sys.exit(1)

All 17 agent.start(prompt) / agent.chat(prompt) / auto_rag.chat(prompt) call-sites in the CLI's direct-prompt dispatch now route through this helper. Every display mode is covered: silent, quiet, verbose, debug, jsonl, json, flow, editor, default.

praisonaiagents/errors.py — BudgetExceededError

The exception is praisonaiagents.errors.BudgetExceededError (subclass of PraisonAIError, error_category="budget", is_retryable=False). Public attributes (verified in source):

Attribute Type Description
agent_name str Agent that exceeded the budget (legacy alias of agent_id)
total_cost float USD spent at the moment the limit triggered (legacy alias of used)
max_budget float Configured cap (legacy alias of limit)
budget_type str "cost" (default for legacy ctor) or "tokens"
limit float New-style cap
used float New-style usage
is_retryable bool Always False for budget errors

praisonaiagents/config/feature_configs.py — ExecutionConfig.max_budget

Already the canonical home for budget config — unchanged by PR #1645.


What needs to be documented

This is new user-facing behavior in the praisonai CLI that is not covered anywhere in the docs today. Search results confirm:

  • docs/concepts/budget.mdx exists and covers the SDK-side API (ExecutionConfig(max_budget=...), on_budget_exceeded, total_cost, cost_summary). It says nothing about CLI behavior.
  • No file in docs/features/, docs/guides/, or anywhere else mentions the CLI's graceful budget handling.
  • BudgetExceededError only appears in the existing docs/concepts/budget.mdx SDK example — there is no CLI-context example.

⚠️ Folder placement (per AGENTS.md §1.8)

docs/concepts/ is HUMAN-APPROVED ONLY — AI agents must NOT modify docs/concepts/budget.mdx. New content must live in docs/features/.


Proposed action: create new page docs/features/cli-budget-handling.mdx

The page should be agent-centric and user-focused (non-developers), per the documentation principles in the agent instructions. It should explain:

  1. What happens when a praisonai CLI run hits a budget cap (graceful exit, clean message, exit-code 1).
  2. How to set the budget (link to the canonical SDK pattern).
  3. What the error message looks like and how to act on it.
  4. How to use the exit code in shell scripts / CI.
  5. Cross-link to the existing docs/concepts/budget.mdx for the full SDK API.

Also: add the new page to docs.json under the "Features" group (NOT "Concepts"), per AGENTS.md §1.8.

Suggested page skeleton

---
title: "CLI Budget Handling"
sidebarTitle: "CLI Budget"
description: "Stop praisonai CLI runs cleanly when an agent hits its budget cap"
icon: "wallet"
---

When a `praisonai` CLI run goes over its budget, you get a clean error message and exit-code `1` — no Python traceback.

{/* Hero diagram: CLI → Agent → BudgetExceededError → graceful message + exit 1 */}

## Quick Start

<Steps>
<Step title="Set a budget on your agent">
```python
from praisonaiagents import Agent, ExecutionConfig

agent = Agent(
    name="Researcher",
    instructions="Research the topic the user asks about",
    execution=ExecutionConfig(max_budget=1.00),  # USD cap
)

agent.start()  # or run via the praisonai CLI
```bash praisonai "Research the history of AI" ```

If the run goes over $1.00, the CLI prints (in red):

Budget limit exceeded: Agent 'Researcher' exceeded budget: $1.0042 >= $1.0000.
Hint: set budget via execution=ExecutionConfig(max_budget=1.00) on your Agent.

…and exits with code 1.


How It Works

{/* sequenceDiagram showing CLI → Agent → LLM loop → BudgetExceededError caught by CLI wrapper → rich-print + sys.exit(1) */}

The praisonai CLI wraps every agent.start(...) / agent.chat(...) call in a budget handler. When the agent raises BudgetExceededError, the CLI:

  1. Prints a single-line, red, rich-formatted message including the actionable hint.
  2. Exits with code 1 so shell scripts and CI can detect the failure.

This works across every CLI display mode: silent (-qq), quiet (-q), verbose (-v), debug (-vv), --output jsonl, --output json, --output flow, --output editor, and default.


Using the Exit Code in CI / Scripts

if ! praisonai "Research AI trends"; then
    echo "Run failed (likely over budget)"
    exit 1
fi

Exit code reference:

Exit code Meaning
0 Success
1 BudgetExceededError (or other handled fatal error)

Why isn't there a max_budget= shortcut on Agent?

By design. Per AGENTS.md §5.3 (Parameter Consolidation), execution-related knobs live on ExecutionConfig, not as new top-level Agent.__init__ parameters. This keeps the Agent constructor small and discoverable. The CLI's error message points users to the one correct place to set a budget:

Agent(execution=ExecutionConfig(max_budget=1.00))

Catching the error in your own code

If you embed praisonaiagents directly (not via the CLI), you can catch the same exception:

from praisonaiagents import Agent, ExecutionConfig
from praisonaiagents.errors import BudgetExceededError

agent = Agent(
    name="Writer",
    instructions="Write articles",
    execution=ExecutionConfig(max_budget=0.50),
)

try:
    agent.start("Write about climate change")
except BudgetExceededError as e:
    print(f"{e.agent_name} spent ${e.total_cost:.4f} (cap: ${e.max_budget:.4f})")

Best Practices

Without `max_budget`, a runaway agent can rack up costs unbounded. Pick a cap based on a few un-budgeted dev runs. The graceful exit means CI detects the failure cleanly — no need to grep tracebacks. There isn't one. Use `execution=ExecutionConfig(max_budget=...)` — that's the only supported pattern.

Related

Full SDK API for budgets, cost tracking, and `on_budget_exceeded` actions `silent`, `quiet`, `verbose`, `jsonl`, etc. ```

Constraints for the implementing agent (READ FIRST)

Per AGENTS.md rules:

  1. DO NOT modify docs/concepts/budget.mdx — that folder is human-only.
  2. ✅ Create the new page at docs/features/cli-budget-handling.mdx (suggested; pick the closest existing folder if there's a better fit under docs/features/).
  3. ✅ Add the page to docs.json under the "Features" group, NOT "Concepts".
  4. Read the SDK source first (verify the import path, attribute names, and exact wording of the error message against src/praisonai/praisonai/cli/main.py and praisonaiagents/errors.py in this repo's praisonaiagents/ mirror).
  5. ✅ Use the standard Mermaid color scheme (#8B0000, #189AB4, #10B981, #F59E0B, #6366F1, white text, #7C90A0 strokes).
  6. ✅ Include a hero Mermaid diagram at the top.
  7. ✅ Use Mintlify components: <Steps>, <AccordionGroup>, <CardGroup>, <Card>.
  8. ✅ Cross-link to /concepts/budget (the existing SDK doc) — do NOT duplicate its content.
  9. ✅ Keep tone friendly and beginner-focused — non-developers should feel "is it really this easy?".
  10. ✅ Verify docs.json is valid JSON after editing.
  11. ✅ Submit as a draft PR on a feature branch (never commit to main).

Acceptance criteria

  • New page at docs/features/cli-budget-handling.mdx exists and renders.
  • Hero Mermaid diagram present, follows standard color scheme.
  • Quick Start uses <Steps> with one Python+CLI example.
  • Page documents the exact CLI error message string from main.py ("Budget limit exceeded: ... Hint: set budget via execution=ExecutionConfig(max_budget=1.00) on your Agent.").
  • Page mentions exit-code 1 and shows a CI/shell snippet.
  • Page explicitly states there is no top-level max_budget= param on Agent and points to ExecutionConfig.
  • Page covers all 9 CLI display modes the helper touches (silent / quiet / verbose / debug / jsonl / json / flow / editor / default) — at least listed.
  • docs.json updated under "Features" group.
  • Cross-link to /concepts/budget for the full SDK API.
  • No edits to docs/concepts/.
  • PR is a draft and references this issue and PraisonAI PR #1645.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingclaudeTrigger Claude Code analysisclidocumentationImprovements or additions to documentationfeature

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions