本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

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

网络教程 app 1℃

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

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

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

为什么使用 click 和 markdown?

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

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

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

构建互动聊天系统1. 设置基本聊天命令

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

import osimport clickimport shlexfrom rich.console import consolefrom rich.markdown import markdownconsole = console()@click.mand()@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 mand execution execute_cli_mand(user_input)

. 自省以发现和执行命令

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

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

import inspectimport your_project_cmd # replace with your actual module containing mandsmand_modules = {"project": your_project_cmd} # list your mand modules heredef execute_cli_mand(user_input): """ function to execute cli mands 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] mand_name = parts[1].replace("-", "_") # replace hyphens with underscores mand_args = parts[2:] # keep the rest of the arguments as a list # check if the module exists in mand_modules if module_name in mand_modules:module = mand_modules[module_name]# introspection: get the function by nameif hasattr(module, mand_name): cmd_func = getattr(module, mand_name) # check if it’s a click mand 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 mand from module: [bold]{module_name}[/bold]" ) # directly call the function with the argument list cmd_func(*mand_args) else: console.print(f"[bold red]'{mand_name}’ is not a valid mand[/bold red]" )else: console.print( f"[bold red]mand ‘{mand_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 mand: {str(e)}[/bold red]")

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

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

@click.group()def project(): """project management cli.""" pass@project.mand()def init(): """initialize a new project.""" console.print("[bold green]project initialized![/bold green]")@project.mand()@click.argument("name")def create(name): """create a new ponent in the project.""" console.print(f"[bold cyan]ponent {name} created.[/bold cyan]")@project.mand()def status(): """check the project status.""" console.print("[bold yellow]all systems operational.[/bold yellow]")

执行聊天界面

运行交互式聊天系统:

    确保您的模块(如项目)已在 mand_modules 中列出。运行命令:

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

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

you: project init you: project create "homepage"

输出将使用 rich markdown 以格式良好的方式显示:

[bold green]Project initialized![/bold green] [bold cyan]Component Homepage created.[/bold cyan]

结论

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

主要亮点:

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

以上就是如何使用内省、单击和丰富格式为 Python CLI 构建交互式聊天的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » 如何使用内省、单击和丰富格式为PythonCLI构建交互式聊天

喜欢 (0)