How to Build a Custom CLI Tool with AI in 10 Minutes

Want to build your own AI command-line tool in the next ten minutes? You can.

You don’t need a framework, boilerplate generator, or even much experience with OpenAI. With a few lines of Python, a good idea, and an API key, you can create something useful and personalized that actually saves you time.

We’ll build a minimal CLI tool that takes a user query and returns a GPT-4 powered response. You’ll finish with a working prototype that can be extended into anything from a documentation explainer to a Bash assistant.

Prerequisites

Before you begin, you’ll need:

Step 1: Set up the CLI wrapper

Start by creating a new Python file:

mkdir ai-cli-tool && cd ai-cli-tool
touch ai.py

Now open ai.py in your editor and add:

import argparse

def main():
    parser = argparse.ArgumentParser(description="Ask GPT-4 anything.")
    parser.add_argument("query", type=str, help="Your question or command in quotes.")
    args = parser.parse_args()
    print("You asked:", args.query)

if __name__ == "__main__":
    main()

This is a simple wrapper that lets you run commands like:

python ai.py "summarize this paragraph"

Step 2: Add AI integration

Install the OpenAI SDK:

pip install openai

Then update your ai.py script:

import openai
import os

openai.api_key = os.getenv("OPENAI_API_KEY")

def ask_gpt(prompt):
    response = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.7
    )
    return response['choices'][0]['message']['content'].strip()

Integrate it into the CLI flow:

if __name__ == "__main__":
    main()
    print("Thinking...")
    answer = ask_gpt(args.query)
    print("\n" + answer)

Set your API key:

export OPENAI_API_KEY="sk-..."

Now your CLI tool can talk to GPT-4.

Step 3: Polish the UX

You can improve user feedback with optional libraries like termcolor or halo:

pip install halo termcolor

Then update the script:

from halo import Halo
from termcolor import cprint

with Halo(text='Thinking...', spinner='dots'):
    answer = ask_gpt(args.query)

cprint("\n" + answer, "green")

This gives you visual feedback while the API processes your request.

Step 4: Make it portable

Add a shebang to the top of ai.py:

#!/usr/bin/env python3

Make it executable:

chmod +x ai.py

Add a symlink to a directory in your $PATH, like:

ln -s $(pwd)/ai.py ~/.local/bin/ai

Now you can run your tool from anywhere:

ai "explain SSH tunneling in simple terms"

Example Use Cases

Here are a few real-world ideas:

You’re All Set

You now have a working GPT-4 CLI tool in under 10 minutes.

To extend it: - Add file input support - Build multiple subcommands with argparse - Cache or log results - Customize system prompts per use case

Built on UTC: 2025-04-09 10:36:15