0Pricing
AI Agents · 강의

명령줄 에이전트 인터페이스 만들기

에이전트 CLI 인수 처리를 위해 argparse, click, Typer를 사용합니다.

명령줄 에이전트 인터페이스 만들기은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

에이전트용 CLI를 만드는 이유

명령줄 인터페이스(CLI)를 사용하면 터미널에서 에이전트에 접근하고, 처리 흐름에서 스크립트로 실행하며, 웹 사용자 인터페이스 없이 쉽게 검사할 수 있습니다. 많은 운영 에이전트가 CLI 도구로 배포됩니다.

Python에는 CLI를 만드는 데 유용한 세 가지 라이브러리가 있습니다. argparse(표준 라이브러리), Typer, Click입니다.

argparse: 표준 라이브러리 방식

argparse는 Python에 내장되어 있으므로 설치할 필요가 없습니다. ArgumentParser()로 인터페이스를 정의하고, add_argument()로 매개변수를 선언하며, parse_args()로 매개변수를 처리하십시오.

import argparse

def main(argv=None):
    parser = argparse.ArgumentParser(
        description='AI Agent CLI — ask questions and get answers'
    )
    parser.add_argument('--query', type=str, required=True, help='The question to ask the agent')
    parser.add_argument('--model', type=str, default='gpt-4o-mini', help='OpenAI model to use (default: gpt-4o-mini)')
    args = parser.parse_args(argv)

    print(f'Querying agent with: {args.query}')
    print(f'Using model: {args.model}')

if __name__ == '__main__':
    main(['--query', 'What is the weather today?'])

argparse CLI 실행 및 자동 생성 도움말

argparse는 인수 정의를 바탕으로 --help 메시지를 자동으로 생성합니다. python agent_cli.py --help를 실행하여 확인하십시오. 누락된 필수 인수가 있으면 유용한 오류 메시지가 자동으로 표시됩니다.

# How users invoke the CLI:
# python agent_cli.py --query 'What is the weather in Paris?'
# python agent_cli.py --query 'Summarize this' --model gpt-4o
# python agent_cli.py --help

# Auto-generated help output:
# usage: agent_cli.py [-h] --query QUERY [--model MODEL]
#
# AI Agent CLI -- ask questions and get answers
#
# options:
#   -h, --help     show this help message and exit
#   --query QUERY  The question to ask the agent
#   --model MODEL  OpenAI model to use (default: gpt-4o-mini)

print('argparse generates help text automatically from your definitions')

Typer: 형식 힌트를 사용하는 현대적인 CLI

Typer는 Python 형식 힌트로 CLI를 구성하므로 argparse보다 반복적인 상용구 코드가 적습니다. pip install typer로 설치합니다. 함수 매개변수는 자동으로 CLI 인수가 됩니다.

# pip install typer
import typer

app = typer.Typer(help='AI Agent CLI')

@app.command()
def ask(
    query: str = typer.Option(..., '--query', '-q', help='Question for the agent'),
    model: str = typer.Option('gpt-4o-mini', '--model', '-m', help='Model to use'),
    verbose: bool = typer.Option(False, '--verbose', '-v', help='Show reasoning steps')
):
    typer.echo(f'Query: {query}')
    typer.echo(f'Model: {model}')
    if verbose:
        typer.echo('Verbose mode enabled')
    # result = run_agent(query, model=model, verbose=verbose)

if __name__ == '__main__':
    app()

Click: 데코레이터 기반 CLI 프레임워크

Click은 데코레이터를 사용해 CLI 명령과 옵션을 정의합니다. pip install click으로 설치합니다. 명령 그룹, 프롬프트, 진행률 표시줄과 같은 다양한 기능을 제공합니다.

# pip install click
import click

@click.command()
@click.option('--query', '-q', required=True, help='Question for the agent')
@click.option('--model', '-m', default='gpt-4o-mini', help='LLM model to use')
@click.option('--output', '-o', type=click.Path(), help='Save output to file')
def ask(query: str, model: str, output: str):
    click.echo(f'Sending: {query}')
    # result = run_agent(query, model=model)
    # click.echo(result['answer'])

    if output:
        with open(output, 'w') as f:
            f.write('result["answer"]')
        click.echo(f'Saved to {output}')

if __name__ == '__main__':
    ask()

하위 명령 추가

에이전트가 성장하면 기능을 agent ask, agent search, agent history와 같은 하위 명령으로 구성해 보십시오. Click과 Typer는 모두 하위 명령 그룹을 기본적으로 지원합니다.

import typer

app = typer.Typer(help='AI Research Agent')

@app.command()
def ask(query: str = typer.Argument(..., help='Question to ask')):
    'Ask the agent a question'
    typer.echo(f'Asking: {query}')

@app.command()
def search(topic: str = typer.Argument(..., help='Topic to research')):
    'Search and summarize a topic'
    typer.echo(f'Researching: {topic}')

@app.command()
def history(limit: int = typer.Option(10, help='Number of past queries to show')):
    'Show recent query history'
    typer.echo(f'Showing last {limit} queries')

if __name__ == '__main__':
    app()

# Usage: python agent.py ask 'What is AI?'
#        python agent.py search 'Python async'
#        python agent.py history --limit 5

파이프로 전달되는 입력을 위한 표준 입력 읽기

표준 입력을 읽는 CLI 에이전트는 Unix 파이프라인에서 사용할 수 있습니다. 파이프로 전달된 내용을 받으려면 sys.stdin 또는 Click의 stdin 인수 형식을 사용하십시오.

import sys
import click

@click.command()
@click.argument('input', default='-', type=click.File('r'))
@click.option('--task', default='summarize', help='Task: summarize, translate, or analyze')
def process(input, task: str):
    text = input.read().strip()
    if not text:
        click.echo('Error: no input provided', err=True)
        raise SystemExit(1)

    click.echo(f'Task: {task}')
    click.echo(f'Input length: {len(text)} chars')
    # result = agent.run(task=task, content=text)
    # click.echo(result)

# Usage:
# echo 'Hello world' | python agent_cli.py --task translate
# cat article.txt | python agent_cli.py --task summarize
if __name__ == '__main__':
    process()

긴 작업을 위한 진행률 표시

에이전트 작업에는 몇 초가 걸릴 수 있습니다. 사용자가 에이전트가 작업 중임을 알 수 있도록 스피너나 진행 메시지를 표시하십시오. Typer는 rich 라이브러리를 통해 진행률 표시를 기본적으로 지원합니다.

import typer
from time import sleep

app = typer.Typer()

@app.command()
def research(topic: str = typer.Argument(...)):
    typer.echo(f'Researching: {topic}')

    with typer.progressbar(range(5), label='Gathering sources') as progress:
        for i in progress:
            sleep(0.5)  # simulate work

    typer.echo('Done!')
    typer.echo('Result: [mocked research result]')

# Or with a spinner from rich:
# from rich.console import Console
# console = Console()
# with console.status('Thinking...'):
#     result = agent.run(topic)
# console.print(result)

if __name__ == '__main__':
    app()

출력 형식: JSON과 일반 텍스트 비교

사용자가 사람이 읽기 쉬운 출력 형식과 기계가 읽을 수 있는 출력 형식 중에서 선택할 수 있도록 하십시오. 에이전트 출력을 다른 도구로 파이프 처리할 때는 --json 플래그가 유용합니다.

import json
import typer

app = typer.Typer()

@app.command()
def ask(
    query: str = typer.Argument(...),
    as_json: bool = typer.Option(False, '--json', help='Output as JSON')
):
    result = {
        'query': query,
        'answer': 'Paris is the capital of France.',
        'confidence': 0.98,
        'sources': ['https://wikipedia.org/France']
    }

    if as_json:
        typer.echo(json.dumps(result, indent=2))
    else:
        typer.echo(f'Answer: {result["answer"]}')
        typer.echo(f'Sources: {', '.join(result["sources"])}')

if __name__ == '__main__':
    app()

CLI 에이전트의 오류 처리

오류가 발생하면 0이 아닌 종료 코드로 종료하여 호출한 스크립트가 실패를 감지할 수 있도록 하십시오. typer.echo(..., err=True) 또는 click.echo(..., err=True)를 사용해 오류 메시지를 표준 오류 스트림에 기록하십시오.

import sys
import typer

app = typer.Typer()

@app.command()
def ask(query: str = typer.Argument(...)):
    try:
        # result = agent.run(query)
        result = {'status': 'ok', 'answer': 'Result here'}

        if result['status'] != 'ok':
            typer.echo(f'Agent error: {result.get("error")}', err=True)
            raise typer.Exit(code=1)

        typer.echo(result['answer'])

    except Exception as e:
        typer.echo(f'Unexpected error: {e}', err=True)
        raise typer.Exit(code=2)

# Exit codes: 0 = success, 1 = agent error, 2 = unexpected error
# These allow shell scripts to handle failures:
# python agent.py 'query' || echo 'Agent failed'
if __name__ == '__main__':
    app()

에이전트를 설치 가능한 CLI 도구로 만들기

pyproject.toml 진입점을 사용하면 에이전트를 시스템 명령으로 사용할 수 있습니다. pip install -e .을 실행한 후에는 사용자가 어느 디렉터리에서든 myagent ask 'question'을 직접 실행할 수 있습니다.

# pyproject.toml
# [project]
# name = 'myagent'
# version = '0.1.0'
# dependencies = ['typer', 'openai', 'httpx']
#
# [project.scripts]
# myagent = 'myagent.cli:app'

# After pip install -e .:
# myagent ask 'What is AI?'
# myagent search 'Python tutorials'
# myagent --help

# This is how production CLI agents like 'gh', 'poetry', and 'ruff' work
print('Entry points turn your Python module into a system CLI command')

학습 확인: CLI 에이전트 인터페이스

에이전트용 CLI 인터페이스 구축에 대한 이해도를 확인해 보십시오.

복습: CLI 에이전트 인터페이스 구축

이제 에이전트를 위한 전문적인 CLI 인터페이스를 구축할 수 있습니다:

  • 종속성 없는 CLI에는 argparse를 사용하십시오(표준 라이브러리)
  • 깔끔하고 형식 힌트 중심의 CLI에는 typer를 사용하십시오
  • 기능이 풍부한 데코레이터 기반 CLI에는 click을 사용하십시오
  • 대규모 에이전트는 하위 명령으로 구성하십시오
  • 파이프라인 통합을 위해 표준 입력을 지원하십시오
  • 기계가 읽을 수 있는 출력에는 --json 플래그를 사용하십시오
  • 셸 스크립트와 호환되도록 오류 발생 시 0이 아닌 코드로 종료하십시오

자주 묻는 질문

“명령줄 에이전트 인터페이스 만들기” 강의는 무료인가요?

네 — “명령줄 에이전트 인터페이스 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

“명령줄 에이전트 인터페이스 만들기”에서 뭘 배우나요?

에이전트 CLI 인수 처리를 위해 argparse, click, Typer를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Agents을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“명령줄 에이전트 인터페이스 만들기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 명령줄 에이전트 인터페이스 만들기
  2. 대화형 REPL 스타일 에이전트
  3. 인수 파싱 및 도움말 텍스트
  4. CLI 에이전트의 스트리밍 출력
← AI Agents(으)로 돌아가기