构建命令行代理界面
使用 argparse、click 和 Typer 处理代理 CLI 参数。
构建命令行代理界面 是 CoddyKit 上的免费 AI Agents 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 代理中的错误处理
发生错误时以非零代码退出,这样调用脚本就能检测到失败。使用 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 接口:
- 使用
argparse构建零依赖 CLI(标准库) - 使用
typer构建简洁、由类型提示驱动的 CLI - 使用
click构建功能丰富、基于装饰器的 CLI - 使用子命令组织大型代理
- 支持标准输入,以便集成到管道中
- 使用
--json标志生成机器可读的输出 - 发生错误时以非零代码退出,以兼容 Shell 脚本
常见问题解答
「构建命令行代理界面」课时是免费的吗?
是的 — 「构建命令行代理界面」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「构建命令行代理界面」这节课中我会学到什么?
使用 argparse、click 和 Typer 处理代理 CLI 参数。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「构建命令行代理界面」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 构建命令行代理界面
- 交互式 REPL 风格代理
- 参数解析与帮助文本
- CLI 代理中的流式输出