コマンドラインエージェントインターフェースの構築
argparse、click、TyperでエージェントCLIの引数処理を実装します。
「コマンドラインエージェントインターフェースの構築」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。
エージェント用のCLIを構築する理由
コマンドラインインターフェース(CLI)を使うと、エージェントにターミナルからアクセスでき、パイプラインでスクリプトとして実行でき、Web UIなしで簡単にテストできます。本番環境のエージェントの多くはCLIツールとしてデプロイされています。
Pythonには、CLI構築用の優れたライブラリが3つあります。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パイプ入力のstdinからの読み取り
stdinから読み取る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)を使うと、エラーメッセージを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インターフェースを構築できるようになりました。
- 依存関係なしのCLIには
argparse(標準ライブラリ)を使用します - 型ヒントを活用したすっきりしたCLIには
typerを使用します - 機能が豊富なデコレータベースのCLIには
clickを使用します - 大規模なエージェントはサブコマンドで整理します
- パイプライン連携のためにstdinをサポートします
- 機械が読み取れる出力には
--jsonフラグを使用します - シェルスクリプトとの互換性のため、エラー時は0以外の終了コードで終了します
よくある質問
「コマンドラインエージェントインターフェースの構築」レッスンは無料ですか?
はい。「コマンドラインエージェントインターフェースの構築」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。
「コマンドラインエージェントインターフェースの構築」で何を学びますか?
argparse、click、TyperでエージェントCLIの引数処理を実装します。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Agentsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「コマンドラインエージェントインターフェースの構築」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Agentsレッスンでコードを書いて実行できますか?
はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- コマンドラインエージェントインターフェースの構築
- 対話型REPLスタイルエージェント
- 引数解析とヘルプテキスト
- CLIエージェントでのストリーミング出力