Introspection, 클릭 및 다양한 형식을 사용하여 Python CLI용 대화형 채팅을 구축하는 방법

Barbara Streisand
풀어 주다: 2024-10-26 11:00:29
원래의
831명이 탐색했습니다.

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

CLI를 더욱 대화형이고 동적으로 만들고 싶다면 실시간 명령 상호 작용 시스템을 구축하는 것이 답이 될 수 있습니다. Python의 내부 검사 기능, 명령 관리를 위한 Click, 출력 형식 지정을 위한 Rich를 활용하여 사용자 입력에 지능적으로 응답하는 강력하고 유연한 CLI를 만들 수 있습니다. 각 명령을 수동으로 하드코딩하는 대신 CLI가 자동으로 명령을 검색하고 실행할 수 있으므로 사용자 경험이 더욱 원활하고 매력적으로 만들어집니다.

다채로운 콘솔 혼돈: 클릭 명령과 풍부한 출력이 만나는 곳 — 터미널도 스타일을 과시하기를 좋아하기 때문입니다!

클릭과 마크다운을 사용하는 이유는 무엇입니까?

클릭은 명령 관리, 인수 구문 분석 및 도움말 생성을 단순화합니다. 또한 명령 구조화 및 옵션 처리가 쉽습니다.

Rich를 사용하면 아름다운 형식의 Markdown을 터미널에서 직접 출력할 수 있어 기능적일 뿐만 아니라 시각적으로도 매력적인 결과를 얻을 수 있습니다.

이 두 라이브러리를 Python 내부 검사와 결합하면 출력을 풍부하고 읽기 쉬운 형식으로 표시하는 동시에 명령을 동적으로 검색하고 실행하는 대화형 채팅 기능을 구축할 수 있습니다. 실용적인 예를 보려면 StoryCraftr이 유사한 접근 방식을 사용하여 AI 기반 글쓰기 작업 흐름을 간소화하는 방법을 확인하세요. https://storycraftr.app.

대화형 채팅 시스템 구축

1. 기본 채팅 명령어 설정하기

채팅 명령은 세션을 초기화하여 사용자가 CLI와 상호 작용할 수 있도록 합니다. 여기서는 적절한 클릭 명령에 동적으로 매핑되는 사용자 입력을 캡처합니다.

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의 데코레이터를 처리하는 방법은 다음과 같습니다.

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, Markdown 서식 지정을 위한 Rich, Python 자체 검사를 결합하여 CLI를 위한 강력하고 대화형 채팅 시스템을 구축할 수 있습니다. 이 접근 방식을 사용하면 우아하고 읽기 쉬운 형식으로 출력을 표시하면서 명령을 동적으로 검색하고 실행할 수 있습니다.

주요 하이라이트:

  • 동적 명령 실행: Introspection을 사용하면 명령을 하드코딩하지 않고도 검색하고 실행할 수 있습니다.
  • 리치 출력: 리치 마크다운을 사용하면 출력이 읽기 쉽고 시각적으로 매력적입니다.
  • 유연성: 이 설정은 명령 구조와 실행에 유연성을 제공합니다.

위 내용은 Introspection, 클릭 및 다양한 형식을 사용하여 Python CLI용 대화형 채팅을 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!