0Pricing
AI Agents · บทเรียน

การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน

argparse, click และ Typer สำหรับจัดการอาร์กิวเมนต์ CLI ของตัวแทน

การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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?'])

การเรียกใช้ CLI ของ argparse และความช่วยเหลือที่สร้างขึ้นโดยอัตโนมัติ

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 สร้างอินเทอร์เฟซ CLI จากคำใบ้ชนิดข้อมูลของ Python โดยมีโค้ดประกอบน้อยกว่า 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 หรือชนิดอาร์กิวเมนต์ stdin ของ Click เพื่อรับเนื้อหาที่ส่งผ่านไปป์ไลน์

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

ออกจากโปรแกรมด้วยรหัสที่ไม่ใช่ศูนย์เมื่อเกิดข้อผิดพลาด เพื่อให้สคริปต์ที่เรียกใช้สามารถตรวจพบความล้มเหลวได้ ใช้ typer.echo(..., err=True) หรือ click.echo(..., err=True) เพื่อเขียนข้อความแสดงข้อผิดพลาดไปยัง stderr

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 ระดับมืออาชีพสำหรับเอเจนต์ของคุณได้แล้ว:

  • ใช้ argparse สำหรับ CLI ที่ไม่มีการพึ่งพาไลบรารีภายนอก (ไลบรารีมาตรฐาน)
  • ใช้ typer สำหรับ CLI ที่กระชับและขับเคลื่อนด้วยคำใบ้ชนิดข้อมูล
  • ใช้ click สำหรับ CLI ที่ใช้ตัวตกแต่งและมีความสามารถหลากหลาย
  • จัดระเบียบเอเจนต์ขนาดใหญ่ด้วยคำสั่งย่อย
  • รองรับอินพุตมาตรฐานเพื่อเชื่อมต่อกับไปป์ไลน์
  • ใช้แฟล็ก --json สำหรับเอาต์พุตที่เครื่องอ่านได้
  • ออกจากโปรแกรมด้วยรหัสที่ไม่ใช่ศูนย์เมื่อเกิดข้อผิดพลาด เพื่อให้เข้ากันได้กับสคริปต์เชลล์

คำถามที่พบบ่อย

บทเรียน “การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน”

argparse, click และ Typer สำหรับจัดการอาร์กิวเมนต์ CLI ของตัวแทน คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน
  2. ตัวแทนรูปแบบ REPL แบบโต้ตอบ
  3. การแยกวิเคราะห์อาร์กิวเมนต์และข้อความช่วยเหลือ
  4. การส่งข้อมูลออกแบบสตรีมในตัวแทน CLI
← กลับไปที่ AI Agents