Skip to content

Add retry logic for AGI commands#775

Merged
Bryan-Roe merged 3 commits intomainfrom
codex/implement-retry-logic-for-agi-commands
Aug 6, 2025
Merged

Add retry logic for AGI commands#775
Bryan-Roe merged 3 commits intomainfrom
codex/implement-retry-logic-for-agi-commands

Conversation

@Bryan-Roe
Copy link
Collaborator

@Bryan-Roe Bryan-Roe commented Jul 27, 2025

Summary

  • improve agi_cli command execution with retry support

Testing

  • python -m py_compile agi_cli.py
  • pytest -k "" -q (fails: SystemExit 1)

https://chatgpt.com/codex/tasks/task_e_6886a6eb30548322a9496ade2b8f5543

Summary by Sourcery

Introduce retry mechanisms to the AGI CLI command executor to improve resilience against transient failures.

New Features:

  • Add max_retries and retry_delay parameters to run_command for configurable retry behavior.
  • Implement retry loop with delay and logging of failed attempts before final error.

Copilot AI review requested due to automatic review settings July 27, 2025 22:43
@sourcery-ai
Copy link

sourcery-ai bot commented Jul 27, 2025

Reviewer's Guide

The PR enhances the run_command function in agi_cli.py by adding configurable retry logic: it updates the function signature, wraps the existing command dispatch in a retry loop, and improves error and retry messaging with delays between attempts.

File-Level Changes

Change Details Files
Extend run_command signature for retry parameters
  • Added max_retries and retry_delay parameters with defaults
  • Updated docstring to reflect retry support
agi_cli.py
Wrap command execution in a retry loop
  • Introduced for-loop over attempts up to max_retries
  • Moved command dispatch and invoke calls inside the loop
  • Retained existing command branches (reason, file, code, plan, help)
agi_cli.py
Enhance error handling and messaging
  • On exception, print attempt-specific warning and delay before retry
  • After final attempt, print a consolidated error and return False
  • Use asyncio.sleep for retry delays
agi_cli.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds retry logic to the AGI command execution functionality to improve reliability when commands fail due to temporary issues.

  • Added retry parameters (max_retries and retry_delay) to the run_command function
  • Implemented a retry loop that attempts command execution up to the specified maximum number of times
  • Enhanced error handling to differentiate between retry attempts and final failures
Comments suppressed due to low confidence (4)

agi_cli.py:136

  • The indentation is inconsistent. This line should be aligned with the 'except' statement above it, not indented further.
            if attempt == max_retries:

agi_cli.py:137

  • The indentation is inconsistent. This line should be aligned properly within the if block.
                print(f"❌ Error executing command after {max_retries} attempts: {e}")

agi_cli.py:138

  • The indentation is inconsistent. This line should be aligned properly within the if block.
                return False

agi_cli.py:139

  • The indentation is inconsistent. This line should be aligned with the 'if' statement above it.
            print(f"⚠️  Attempt {attempt} failed: {e}. Retrying in {retry_delay} seconds...")

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Bryan-Roe - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `agi_cli.py:88` </location>
<code_context>
-
-        elif command == "help":
-            result = """
+    for attempt in range(1, max_retries + 1):
+        try:
+            if command == "reason":
</code_context>

<issue_to_address>
Retry logic will always retry on any Exception, including KeyboardInterrupt.

Consider catching only specific exceptions or re-raising critical ones like KeyboardInterrupt and SystemExit to avoid suppressing important signals.
</issue_to_address>

### Comment 2
<location> `agi_cli.py:79` </location>
<code_context>

-async def run_command(command: str, *args):
-    """Run an AGI command"""
+async def run_command(
+    command: str,
+    *args,
</code_context>

<issue_to_address>
Consider refactoring by extracting retry logic into a decorator, moving help text to a constant, and using a command handler map to simplify dispatch.

```suggestion
# 1) Move the help text to a module‐level constant
HELP_TEXT = """
🤖 AGI Command Line Interface
Available commands:
  reason <query>              - Perform AGI reasoning on a query
  file <filename> [operation] - Process file (analyze, optimize, transform, summarize)
  code <language> <description> - Generate code in specified language
  plan <goal>                 - Create and execute a plan for a goal
  help                        - Show this help message
Examples:
  python agi_cli.py reason "How does machine learning work?"
  python agi_cli.py file myfile.txt analyze
  python agi_cli.py code python "Create a web scraper"
  python agi_cli.py plan "Build a recommendation system"
"""

# 2) Extract retry logic into a decorator
def retry_async(max_retries: int = 3, retry_delay: float = 1.0):
    def decorator(fn):
        async def wrapper(*args, **kwargs):
            for attempt in range(1, max_retries + 1):
                try:
                    return await fn(*args, **kwargs)
                except Exception as e:
                    if attempt == max_retries:
                        print(f"❌ Error after {max_retries} attempts: {e}")
                        return False
                    print(f"⚠️  Attempt {attempt} failed: {e}. Retrying in {retry_delay} seconds…")
                    await asyncio.sleep(retry_delay)
        return wrapper
    return decorator

# 3) Define per‐command handlers, then dispatch via a map
async def _handle_reason(agi, args):
    query = " ".join(args) if args else "What is artificial general intelligence?"
    fn = agi.kernel.get_function("agi_cli", "reason")
    return await fn.invoke(agi.kernel, query=query)

# … similarly define _handle_file, _handle_code, _handle_plan …

COMMAND_HANDLERS = {
    "reason": _handle_reason,
    "file":   _handle_file,
    "code":   _handle_code,
    "plan":   _handle_plan,
    "help":   lambda agi, args: HELP_TEXT,
}

# 4) Simplify run_command
@retry_async()
async def run_command(command: str, *args) -> bool:
    agi = AGICommandLine()
    handler = COMMAND_HANDLERS.get(command)
    if not handler:
        print(f"❌ Unknown command: {command}. Use 'help' for available commands.")
        return False

    result = await handler(agi, args)
    print(result)
    return True
```

This keeps the same retry behavior, removes the nested if/elif chain, and relocates help text to a constant for clarity.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Bryan-Roe and others added 2 commits August 6, 2025 09:10
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: Bryan <74067792+Bryan-Roe@users.noreply.github.com>
@Bryan-Roe Bryan-Roe merged commit 1aadb01 into main Aug 6, 2025
7 of 11 checks passed
@Bryan-Roe Bryan-Roe deleted the codex/implement-retry-logic-for-agi-commands branch August 6, 2025 16:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant