Building Command-Line Agent Interfaces
argparse, click, and Typer for agent CLI argument handling.
Building Command-Line Agent Interfaces is a free AI Agents lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Build a CLI for Your Agent?
A command-line interface (CLI) makes your agent accessible from a terminal, scriptable in pipelines, and easy to test without a web UI. Many production agents are deployed as CLI tools.
Python has three excellent libraries for building CLIs: argparse (standard library), Typer, and Click.
argparse: The Standard Library Option
argparse is built into Python — no installation required. Use ArgumentParser() to define your interface, add_argument() to declare parameters, and parse_args() to process them.
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?'])Running argparse CLI and Auto-Generated Help
argparse automatically generates a --help message from your argument definitions. Run python agent_cli.py --help to see it. Required arguments that are missing produce helpful error messages automatically.
# 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: Modern CLI with Type Hints
Typer builds CLIs from Python type hints — less boilerplate than argparse. Install with pip install typer. Function parameters become CLI arguments automatically.
# 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: Decorator-Based CLI Framework
Click uses decorators to define CLI commands and options. Install with pip install click. It offers rich features like command groups, prompts, and progress bars.
# 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()Adding Subcommands
As your agent grows, organize functionality into subcommands like agent ask, agent search, and agent history. Both Click and Typer support subcommand groups natively.
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 5Reading from stdin for Piped Input
A CLI agent that reads from stdin can be used in Unix pipelines. Use sys.stdin or Click's stdin argument type to accept piped content.
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()Progress Indicators for Long Tasks
Agent tasks can take several seconds. Show a spinner or progress message so users know the agent is working. Typer has built-in progress support via the rich library.
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()Output Formatting: JSON vs. Plain Text
Allow users to choose between human-readable and machine-readable output formats. A --json flag is useful for piping agent output into other tools.
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()Error Handling in CLI Agents
Exit with a non-zero code on errors so calling scripts can detect failures. Use typer.echo(..., err=True) or click.echo(..., err=True) to write error messages to 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()Making Your Agent an Installable CLI Tool
Use a pyproject.toml entry point to make your agent available as a system command. After pip install -e ., users can run myagent ask 'question' directly from any directory.
# 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')Knowledge Check: CLI Agent Interfaces
Test your understanding of building CLI interfaces for agents.
Recap: Building CLI Agent Interfaces
You can now build professional CLI interfaces for your agents:
- Use
argparsefor zero-dependency CLIs (standard library) - Use
typerfor clean, type-hint-driven CLIs - Use
clickfor feature-rich decorator-based CLIs - Organize large agents with subcommands
- Support stdin for pipeline integration
- Use
--jsonflags for machine-readable output - Exit with non-zero codes on errors for shell script compatibility
Frequently asked questions
Is the “Building Command-Line Agent Interfaces” lesson free?
Yes — the full text of “Building Command-Line Agent Interfaces” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Building Command-Line Agent Interfaces”?
argparse, click, and Typer for agent CLI argument handling. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Building Command-Line Agent Interfaces” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Building Command-Line Agent Interfaces
- Interactive REPL-Style Agents
- Argument Parsing and Help Text
- Streaming Output in CLI Agents