Argument Parsing and Help Text
Required vs optional args, type validation, and auto-generated help.
Argument Parsing and Help Text is a free AI Agents lesson on CoddyKit — lesson 3 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.
Good CLI Design Starts with Good Arguments
A well-designed CLI agent argument interface means users can figure out how to use the tool from --help alone. Every argument should have a clear name, type, default value, and description.
Poorly named or undocumented arguments make tools frustrating to use and hard to maintain.
Required vs. Optional Arguments
Required arguments must be provided — the CLI exits with an error if they are missing. Optional arguments have a default= value and can be omitted. Deciding which is which shapes your tool's UX.
import argparse
parser = argparse.ArgumentParser(description='AI Agent CLI')
# Required: no default, must be provided
parser.add_argument(
'--query', '-q',
type=str,
required=True,
help='Question to send to the agent'
)
# Optional: has a default, can be omitted
parser.add_argument(
'--model', '-m',
type=str,
default='gpt-4o-mini',
help='Model name (default: gpt-4o-mini)'
)
parser.add_argument(
'--max-tokens',
type=int,
default=1000,
help='Maximum tokens in response (default: 1000)'
)
args = parser.parse_args(['--query', 'test'])
print(args.query, args.model, args.max_tokens)Type Validation
The type= parameter automatically converts the string input and validates it. Use built-in types like int, float, bool, or a custom function for more complex validation.
import argparse
def positive_int(value: str) -> int:
n = int(value)
if n <= 0:
raise argparse.ArgumentTypeError(f'{value} must be a positive integer')
return n
parser = argparse.ArgumentParser()
parser.add_argument('--temperature', type=float, help='LLM temperature 0.0-2.0')
parser.add_argument('--max-results', type=positive_int, default=5,
help='Number of results to return (must be > 0)')
parser.add_argument('--timeout', type=float, default=30.0,
help='Request timeout in seconds')
# These would be rejected with helpful error messages:
# --temperature abc -> invalid float value
# --max-results -1 -> must be positive integer
args = parser.parse_args(['--temperature', '0.7', '--max-results', '3'])
print(args.temperature, args.max_results)Choices: Restricting Valid Values
The choices=[...] parameter restricts the argument to a fixed set of allowed values. argparse validates this automatically and lists the options in the help text.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--format',
choices=['json', 'text', 'markdown'],
default='text',
help='Output format: json, text, or markdown'
)
parser.add_argument(
'--model',
choices=['gpt-4o', 'gpt-4o-mini', 'claude-3-5-sonnet', 'gemini-1.5-flash'],
default='gpt-4o-mini',
help='Model to use'
)
# Error if invalid value given:
# python agent.py --format xml
# agent.py: error: argument --format: invalid choice: 'xml'
# (choose from 'json', 'text', 'markdown')
args = parser.parse_args(['--format', 'json'])
print(args.format) # 'json'Boolean Flags with store_true
Boolean flags are presence/absence toggles — no value is provided. Use action='store_true' to set a flag to True when present and False when absent.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Enable verbose output showing agent reasoning steps'
)
parser.add_argument(
'--no-cache',
action='store_true',
help='Disable response caching'
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Parse arguments but do not run the agent'
)
# Usage: python agent.py --query 'test' --verbose
args = parser.parse_args(['--verbose'])
print(f'verbose={args.verbose}') # True
print(f'no_cache={args.no_cache}') # False
print(f'dry_run={args.dry_run}') # Falsemetavar: Controlling Help Text Display
By default, argparse shows the argument name in uppercase in help text: --query QUERY. Use metavar= to display a more informative placeholder like QUESTION or URL.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--query',
type=str,
metavar='QUESTION', # shown in help as: --query QUESTION
required=True,
help='Natural language question for the agent'
)
parser.add_argument(
'--url',
type=str,
metavar='URL', # shown in help as: --url URL
help='URL to scrape and summarize'
)
parser.add_argument(
'--temperature',
type=float,
metavar='0.0-2.0', # shown in help as: --temperature 0.0-2.0
default=0.7
)
# Help output:
# --query QUESTION Natural language question for the agent
# --url URL URL to scrape and summarize
print('metavar makes help text more informative')Multiple Values with nargs
Use nargs='+' to accept one or more values, or nargs='*' for zero or more. This is useful for passing lists of URLs, tags, or file paths to the agent.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--urls',
nargs='+', # one or more URLs
metavar='URL',
help='URLs to analyze (space-separated)'
)
parser.add_argument(
'--tags',
nargs='*', # zero or more tags
default=[],
help='Optional tags for filtering results'
)
# Usage: python agent.py --urls https://a.com https://b.com --tags ai research
args = parser.parse_args(
['--urls', 'https://a.com', 'https://b.com', '--tags', 'ai']
)
print(args.urls) # ['https://a.com', 'https://b.com']
print(args.tags) # ['ai']Subcommands with add_subparsers()
Subcommands (like git commit, git push) give each command its own argument set. Use add_subparsers() to define them in argparse.
import argparse
parser = argparse.ArgumentParser(description='AI Agent CLI')
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# 'ask' subcommand
ask_parser = subparsers.add_parser('ask', help='Ask the agent a question')
ask_parser.add_argument('question', type=str, help='Question to ask')
ask_parser.add_argument('--model', default='gpt-4o-mini')
# 'search' subcommand
search_parser = subparsers.add_parser('search', help='Research a topic')
search_parser.add_argument('topic', type=str, help='Topic to research')
search_parser.add_argument('--depth', type=int, default=3, choices=[1, 2, 3])
args = parser.parse_args(['ask', 'What is Python?', '--model', 'gpt-4o'])
print(args.command) # 'ask'
print(args.question) # 'What is Python?'
print(args.model) # 'gpt-4o'Writing Good Help Text
Good help text answers three questions: what does this argument do, what values are valid, and what is the default? Write help text from the user's perspective, not the implementer's.
import argparse
parser = argparse.ArgumentParser(
description='AI Research Agent — answers questions using web search and LLMs.',
epilog='Example: python agent.py --query "What is quantum computing?" --format json'
)
# Bad help text:
parser.add_argument('--t', type=float, help='t value') # cryptic
# Good help text:
parser.add_argument(
'--temperature',
type=float,
default=0.7,
metavar='0.0-2.0',
help='Sampling temperature for the LLM. Lower = more focused, higher = more creative. (default: 0.7)'
)
print('Good help text explains what, how, and default value')Argument Groups for Complex CLIs
When a CLI has many arguments, group them by topic using add_argument_group(). This makes the --help output much easier to read.
import argparse
parser = argparse.ArgumentParser(description='AI Agent CLI')
# Group 1: required inputs
required_group = parser.add_argument_group('Required')
required_group.add_argument('--query', required=True, help='Question to ask')
# Group 2: LLM settings
llm_group = parser.add_argument_group('LLM Settings')
llm_group.add_argument('--model', default='gpt-4o-mini', help='Model name')
llm_group.add_argument('--temperature', type=float, default=0.7)
llm_group.add_argument('--max-tokens', type=int, default=1000)
# Group 3: output settings
output_group = parser.add_argument_group('Output')
output_group.add_argument('--format', choices=['text', 'json'], default='text')
output_group.add_argument('--verbose', action='store_true')
print('Argument groups organize --help output by category')Environment Variable Fallbacks
Allow arguments to fall back to environment variables when not provided. This lets users set defaults in their shell profile without typing them every time.
import argparse
import os
os.environ['OPENAI_API_KEY'] = 'sk-proj-demo-key'
parser = argparse.ArgumentParser()
parser.add_argument(
'--api-key',
type=str,
default=os.environ.get('OPENAI_API_KEY'),
help='OpenAI API key (default: $OPENAI_API_KEY env var)'
)
parser.add_argument(
'--model',
type=str,
default=os.environ.get('AGENT_MODEL', 'gpt-4o-mini'),
help='Model to use (default: $AGENT_MODEL or gpt-4o-mini)'
)
args = parser.parse_args([])
if not args.api_key:
parser.error('--api-key is required (or set OPENAI_API_KEY environment variable)')
print(f'Model: {args.model}')Knowledge Check: Argument Parsing
Test your understanding of CLI argument parsing techniques.
Recap: Argument Parsing and Help Text
You now know how to build a complete, user-friendly CLI argument interface:
- Use
required=Truefor mandatory arguments,default=for optional ones - Validate input types with
type=and custom validator functions - Restrict values with
choices=[...] - Use
action='store_true'for boolean flags - Improve help readability with
metavar=and clearhelp=strings - Accept multiple values with
nargs='+' - Use subcommands and argument groups for complex CLIs
- Fall back to environment variables for common settings
Frequently asked questions
Is the “Argument Parsing and Help Text” lesson free?
Yes — the full text of “Argument Parsing and Help Text” 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 “Argument Parsing and Help Text”?
Required vs optional args, type validation, and auto-generated help. 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 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Argument Parsing and Help Text” 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