Okay, here's a guide on how to overload or monkey-patch the `llm prompt` command in plugins, using the provided `llm` documentation:

**Guide: Overloading the `llm prompt` Command in Plugins**

**Goal:**

Create an LLM plugin that extends the functionality of the existing `llm prompt` command without modifying the core LLM codebase. We want to add a new feature (e.g., `--ground`) while preserving the original command's behavior.

**Approach:**

We'll use a combination of techniques, leveraging the LLM plugin system and potentially Click's (the CLI framework) features:

1. **Plugin Structure:**
    *   Create a new plugin directory (e.g., `llm-grounded-prompt`).
    *   Include the standard `pyproject.toml` file defining the plugin.
    *   Create an `llm_grounded_prompt.py` file for the plugin's logic.

2. **Registering a New Command (Without Overriding):**

    *   **Option A: Subcommand:** The most straightforward way is to create a subcommand under `llm`. For example, you could add `llm grounded-prompt`.
        *   Use the `register_commands(cli)` hook.
        *   Within this hook, create a new `click.Command` or `click.Group` for your command.

    ```python
    # llm_grounded_prompt.py
    import click
    import llm

    @llm.hookimpl
    def register_commands(cli):
        @cli.group()
        def grounded_prompt():
            """Grounded prompt commands."""
            pass

        @grounded_prompt.command()
        @click.argument("prompt")
        @click.option("--ground", is_flag=True, help="Enable grounding")
        @click.pass_context
        def run(ctx, prompt, ground):
            """Run a grounded prompt."""
            ctx.obj = {"ground": ground} # Pass to the original prompt command
            # Reuse the original prompt command logic
            ctx.forward(llm.cli.commands["prompt"].callback)

        @grounded_prompt.command()
        def other_command():
            """Another command."""
            click.echo("Another command.")
    ```

    *   **Option B: Separate CLI Entry Point:** Create a new entry point in your `pyproject.toml`:

    ```toml
    [project.scripts]
    llm-grounded = "llm_grounded_prompt:cli"
    ```

    *   This creates a separate `llm-grounded` command.
    *   This approach is less ideal if you want to keep everything under the `llm` umbrella.

3. **Calling the Original `llm prompt` (Monkey-Patching):**

    *   Since we want to retain the functionality of `llm prompt`, the most robust approach is to find a way to call the original command from your plugin.
    *   To achieve this, you can use `click.Context.forward` to execute the original `prompt` command, passing your modified parameters to it, as demonstrated above.
    *   **Caveat:** This approach depends on the internal structure of LLM's CLI, which could change in future versions.

4. **Adding New Functionality (`--ground`):**

    *   Add a new option (e.g., `--ground`) to your command using `@click.option`.
    *   Retrieve the option's value in your command's function.
    *   Implement the grounding logic:
        *   This might involve fetching external data, modifying the prompt, or post-processing the model's response.

5. **Example Plugin Code (`llm_grounded_prompt.py`):**

```python
import click
import llm
from click.testing import CliRunner

@llm.hookimpl
def register_commands(cli):
    @cli.group()
    def grounded_prompt():
        """Grounded prompt commands."""
        pass

    @grounded_prompt.command()
    @click.argument("prompt")
    @click.option("--ground", is_flag=True, help="Enable grounding")
    @click.pass_context
    def run(ctx, prompt, ground):
        """Run a grounded prompt."""
        if ground:
            # Implement your grounding logic here
            prompt = ground_the_prompt(prompt)

        # Pass the potentially modified prompt to the original command
        ctx.obj = {"ground": ground}
        ctx.forward(llm.cli.commands["prompt"].callback)

    @grounded_prompt.command()
    def other_command():
        """Another command."""
        click.echo("Another command.")

def ground_the_prompt(prompt):
    """Example grounding logic (replace with your actual implementation)."""
    # Fetch relevant information, modify the prompt, etc.
    grounded_prompt = f"Based on my knowledge: {prompt} What are your thoughts?"
    return grounded_prompt
```

**Example `pyproject.toml`:**

```toml
[project]
name = "llm-grounded-prompt"
version = "0.1.0"
description = "Plugin for LLM to add grounding to prompts"
dependencies = [
    "llm",
    "click",
]

[project.entry-points.llm]
grounded_prompt = "llm_grounded_prompt"
```

**Installation:**

```bash
llm install -e .
```

**Usage:**

```bash
llm grounded-prompt run "What is the capital of France?" --ground
llm grounded-prompt other-command
```

**Important Considerations:**

*   **Error Handling:**  Add error handling to your grounding logic to gracefully handle cases where external data is unavailable or the model's response is unexpected.
*   **Flexibility:** Consider making your grounding logic configurable through options or a configuration file to allow users to customize it.
*   **Testing:** Thoroughly test your plugin to ensure it works as expected and doesn't break the original `llm prompt` functionality. Use `click.testing.CliRunner` to simulate CLI interactions in your tests, and pass the options to the original command using `ctx.forward`.

This guide provides a solid starting point for overloading the `llm prompt` command. You can adapt and extend these techniques to create powerful plugins that enhance LLM's capabilities while maintaining the core functionality of the original tool.

