首页  >  文章  >  后端开发  >  如何使用内省、单击和丰富格式为 Python CLI 构建交互式聊天

如何使用内省、单击和丰富格式为 Python CLI 构建交互式聊天

Barbara Streisand
Barbara Streisand原创
2024-10-26 11:00:29812浏览

How to Build an Interactive Chat for Your Python CLI Using Introspection, Click, and Rich Formatting

如果您曾经想让您的 CLI 更具交互性和动态性,构建实时命令交互系统可能是答案。通过利用 Python 的自省功能、用于管理命令的 Click 以及用于格式化输出的 Rich,您可以创建一个强大、灵活的 CLI,以智能地响应用户输入。您的 CLI 可以自动发现并执行命令,而不是手动硬编码每个命令,从而使用户体验更流畅、更具吸引力。

丰富多彩的控制台混乱:点击命令与丰富的输出相遇 - 因为即使是终端也喜欢炫耀风格!

为什么使用 Click 和 Markdown?

Click 简化了命令管理、参数解析和帮助生成。它还允许轻松的命令结构和选项处理。

Rich 使您能够直接在终端中输出格式精美的 Markdown,使结果不仅实用,而且具有视觉吸引力。

通过将这两个库与 Python 自省相结合,您可以构建交互式聊天功能,该功能可以动态发现和执行命令,同时以丰富、可读的格式显示输出。 有关实际示例,请了解 StoryCraftr 如何使用类似的方法来简化 AI 驱动的写作工作流程: https://storycraftr.app。

构建互动聊天系统

1. 设置基本聊天命令

聊天命令初始化会话,允许用户与 CLI 交互。在这里,我们捕获用户输入,这些输入将动态映射到适当的 Click 命令。

import os
import click
import shlex
from rich.console import Console
from rich.markdown import Markdown

console = Console()

@click.command()
@click.option("--project-path", type=click.Path(), help="Path to the project directory")
def chat(project_path=None):
    """
    Start a chat session with the assistant for the given project.
    """
    if not project_path:
        project_path = os.getcwd()

    console.print(
        f"Starting chat for [bold]{project_path}[/bold]. Type [bold green]exit()[/bold green] to quit."
    )

    # Start the interactive session
    while True:
        user_input = console.input("[bold blue]You:[/bold blue] ")

        # Handle exit
        if user_input.lower() == "exit()":
            console.print("[bold red]Exiting chat...[/bold red]")
            break

        # Call the function to handle command execution
        execute_cli_command(user_input)

2. 自省以发现和执行命令

使用Python内省,我们动态地发现可用的命令并执行它们。这里的一个关键部分是 Click 命令是修饰函数。为了执行实际的逻辑,我们需要调用未修饰的函数(即回调)。

以下是如何使用内省动态执行命令并处理 Click 的装饰器:

import os
import click
import shlex
from rich.console import Console
from rich.markdown import Markdown

console = Console()

@click.command()
@click.option("--project-path", type=click.Path(), help="Path to the project directory")
def chat(project_path=None):
    """
    Start a chat session with the assistant for the given project.
    """
    if not project_path:
        project_path = os.getcwd()

    console.print(
        f"Starting chat for [bold]{project_path}[/bold]. Type [bold green]exit()[/bold green] to quit."
    )

    # Start the interactive session
    while True:
        user_input = console.input("[bold blue]You:[/bold blue] ")

        # Handle exit
        if user_input.lower() == "exit()":
            console.print("[bold red]Exiting chat...[/bold red]")
            break

        # Call the function to handle command execution
        execute_cli_command(user_input)

这是如何运作的?

  • 输入解析:我们使用 shlex.split 来处理命令行参数等输入。这可确保正确处理带引号的字符串和特殊字符。
  • 模块和命令查找:输入分为 module_name 和 command_name。命令名称经过处理,将连字符替换为下划线,以匹配 Python 函数名称。
  • 内省:我们使用 getattr() 从模块动态获取命令函数。如果是 Click 命令(即具有回调属性),我们通过剥离 Click 装饰器来访问实际的函数逻辑。
  • 命令执行:一旦我们检索到未修饰的函数,我们就传递参数并调用它,就像直接调用 Python 函数一样。

3. CLI 命令示例

让我们考虑项目模块中的一些示例命令,用户可以通过聊天交互调用这些命令:

import inspect
import your_project_cmd  # Replace with your actual module containing commands

command_modules = {"project": your_project_cmd}  # List your command modules here

def execute_cli_command(user_input):
    """
    Function to execute CLI commands dynamically based on the available modules,
    calling the undecorated function directly.
    """
    try:
        # Use shlex.split to handle quotes and separate arguments correctly
        parts = shlex.split(user_input)
        module_name = parts[0]
        command_name = parts[1].replace("-", "_")  # Replace hyphens with underscores
        command_args = parts[2:]  # Keep the rest of the arguments as a list

        # Check if the module exists in command_modules
        if module_name in command_modules:
            module = command_modules[module_name]

            # Introspection: Get the function by name
            if hasattr(module, command_name):
                cmd_func = getattr(module, command_name)

                # Check if it's a Click command and strip the decorator
                if hasattr(cmd_func, "callback"):
                    # Call the underlying undecorated function
                    cmd_func = cmd_func.callback

                # Check if it's a callable (function)
                if callable(cmd_func):
                    console.print(
                        f"Executing command from module: [bold]{module_name}[/bold]"
                    )

                    # Directly call the function with the argument list
                    cmd_func(*command_args)
                else:
                    console.print(
                        f"[bold red]'{command_name}' is not a valid command[/bold red]"
                    )
            else:
                console.print(
                    f"[bold red]Command '{command_name}' not found in {module_name}[/bold red]"
                )
        else:
            console.print(f"[bold red]Module {module_name} not found[/bold red]")
    except Exception as e:
        console.print(f"[bold red]Error executing command: {str(e)}[/bold red]")

执行聊天界面

运行交互式聊天系统:

  1. 确保您的模块(如项目)已在 command_modules 中列出。
  2. 运行命令:
@click.group()
def project():
    """Project management CLI."""
    pass

@project.command()
def init():
    """Initialize a new project."""
    console.print("[bold green]Project initialized![/bold green]")

@project.command()
@click.argument("name")
def create(name):
    """Create a new component in the project."""
    console.print(f"[bold cyan]Component {name} created.[/bold cyan]")

@project.command()
def status():
    """Check the project status."""
    console.print("[bold yellow]All systems operational.[/bold yellow]")

会话开始后,用户可以输入以下命令:

python your_cli.py chat --project-path /path/to/project

输出将使用 Rich Markdown 以格式良好的方式显示:

You: project init You: project create "Homepage"

结论

通过结合 Click 命令管理、Rich for Markdown 格式和 Python 自省,我们可以为 CLI 构建一个强大的交互式聊天系统。这种方法允许您动态发现和执行命令,同时以优雅、可读的格式呈现输出。

主要亮点:

  • 动态命令执行:内省使您能够发现和运行命令,而无需对其进行硬编码。
  • 丰富的输出:使用 Rich Markdown 可确保输出易于阅读且具有视觉吸引力。
  • 灵活性:此设置允许命令结构和执行的灵活性。

以上是如何使用内省、单击和丰富格式为 Python CLI 构建交互式聊天的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn