In this tutorial, you’ll walk through creating your first AI-powered Command Line Interface (CLI) tool using OpenAI’s API. You’ll build a tool named Text Summarizer CLI, which takes some text and returns a concise summary. Although this guide focuses on text summarization, the same approach can be applied to a wide range of AI-driven tasks—such as translation, sentiment analysis, code generation, and more.
Why build a CLI AI tool? Because it streamlines workflows, automates repetitive tasks, and provides simple terminal-based access to advanced capabilities—allowing you to seamlessly integrate AI into your development process or everyday workflows.
This knowledge will also help you apply OpenAI to any other tool eg an idea for a mobile app
What You Will Learn
- How to set up a Node.js project
- How to configure your CLI tool to work with OpenAI’s API
- How to securely store and manage your API key locally
- How to interact with the OpenAI API using HTTP requests
- How to implement a user-friendly CLI interface
By the end, you’ll have a working CLI tool that you can run from your terminal.
Prerequisites
- Node.js and npm: Make sure you have Node.js installed. Check by running:
node -v
npm -v
If not installed, visit https://nodejs.org and follow the instructions to install the stable version, LTS.
Keep this API key private. You will provide it to your CLI tool once, and it will store it locally on your machine for future use.
Project Setup
Let’s create a new project for our CLI tool:
mkdir ai-cli-tool
cd ai-cli-tool
npm init -y
This creates a package.json
file with default settings.
Installing Dependencies
We’ll need a few packages:
- axios: For making HTTP requests to the OpenAI API.
- commander: For handling CLI commands and arguments.
- fs and os: Core Node.js modules for file system operations and user directory handling (no need to install, they come with Node.js).
Install the external dependencies:
npm install axios commander
Storing the API Key Securely
Instead of using environment variables, we’ll store the API key in a configuration file located in the user’s home directory. The configuration file approach allows portability without requiring environment variable setup for every terminal session. However, you should ensure that .ai-cli-tool-config.json is not shared publicly or included in version control systems to protect your API key. This way, you don’t have to rely on a .env file, and the key remains local and private.
Our approach:
- When the user first sets their API key using a CLI command (e.g.,
ai-cli-tool set-key <your-api-key>
), you’ll store it in a file~/.ai-cli-tool-config.json
. - Each time the tool runs, it will read from this file to retrieve the saved key.
Implementing the CLI Tool
Create a file named index.js
:
touch index.js
Add the following code in index.js
:
#!/usr/bin/env node
// The line at the top is a shebang. It tells the operating system which interpreter to use to execute the file. This is especially useful for scripts that need to be run as standalone executable programs.
const { Command } = require('commander');
const axios = require('axios');
const fs = require('fs');
const os = require('os');
const path = require('path');
const program = new Command();
// Path to the config file in the user's home directory
const configPath = path.join(os.homedir(), '.ai-cli-tool-config.json');
// Load the API key from the config file (if it exists)
function loadApiKey() {
if (fs.existsSync(configPath)) {
const configData = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
return configData.apiKey;
}
return null;
}
// Save the API key to the config file
function saveApiKey(key) {
const configData = { apiKey: key };
fs.writeFileSync(configPath, JSON.stringify(configData, null, 2), 'utf-8');
}
// Command to set the API key
program
.command('set-key <key>')
.description('Set your OpenAI API key')
.action((key) => {
saveApiKey(key);
console.log('API key has been saved successfully!');
});
// Command to summarize text
program
.command('summarize <text>')
.description('Summarize the provided text using OpenAI')
.action(async (text) => {
try {
const summary = await summarizeText(text);
console.log('\n\nSummary:', summary);
} catch (error) {
if (error.response) {
console.error('Error from OpenAI API:', error.response.data.error.message);
} else {
console.error('Error:', error.message);
}
}
});
async function summarizeText(inputText) {
const apiKey = loadApiKey();
if (!apiKey) {
throw new Error("API key not set. Run `ai-cli-tool set-key <your-api-key>` first.");
}
const apiUrl = "https://api.openai.com/v1/chat/completions";
const data = {
model: "gpt-4o-mini", // Model used for completion
messages: [
{ role: "system", content: "You are a helpful assistant that summarizes text, make it very easy to understand and make it concise." },
{ role: "user", content: `Please summarize the following text: ${inputText}` }
],
temperature: 0.7 // Controls creativity; lower values are more deterministic
};
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
};
const response = await axios.post(apiUrl, data, { headers });
return response.data.choices[0].message.content.trim();
}
program.parse(process.argv);
What’s Happening Here?
- Storing the API Key: We created two helper functions,
loadApiKey()
andsaveApiKey()
, to read and write the API key from a JSON file in the user’s home directory. - Setting the API Key: The
set-key
command allows the user to input their API key once. The tool saves it locally, so you don’t need to pass the key every time. - Summarize Command: The
summarize
command sends the user’s input to the OpenAI API and returns a summary. It reads the previously stored API key so you don’t have to repeat it.
Making the Tool Executable
Update your package.json
to include a bin
field:
{
"name": "ai-cli-tool",
"version": "1.0.0",
"main": "index.js",
"bin": {
"ai-cli-tool": "./index.js"
},
"dependencies": {
"axios": "^1.0.0",
"commander": "^9.0.0"
}
}
Then, link the package so you can run ai-cli-tool
from your terminal:
npm link
Using the CLI Tool
- Remember the API key you got from OpenAI; use this command to set the API Key (once per machine or whenever you need to update it):
ai-cli-tool set-key YOUR_OPENAI_API_KEY
- Summarize Some Text:
ai-cli-tool summarize "In recent years, the global economy has experienced significant fluctuations, driven by a variety of factors such as technological advancements, changes in trade policies, and the ongoing challenges of the COVID-19 pandemic. As businesses adapt to new conditions, many have shifted toward digital platforms, automating processes to increase efficiency and streamline operations. This transformation has also led to the rise of e-commerce, with online shopping becoming more prevalent than ever. While these changes have opened up new opportunities, they have also presented challenges related to cybersecurity, privacy, and the need for continuous innovation. Moving forward, companies must remain agile, staying ahead of trends and evolving customer expectations to maintain a competitive edge in the market."
You should see a concise summary of the provided text printed to your terminal.
You can extend this approach for other tasks by changing the system and user messages sent to the OpenAI API:
- Translation: Instruct the model to translate text to another language.
ai-cli-tool translate "Bonjour tout le monde" --to en
- Sentiment Analysis: Ask the model to determine the sentiment of the input text.
ai-cli-tool analyze-sentiment "I love learning new things!"
- Code Generation: Prompt the model to generate or refactor code snippets.
By modifying the prompt and possibly adding new commands, you can create an entire suite of AI-powered CLI tools.
Adapting This Knowledge Beyond the CLI
The approach you’ve learned here—integrating OpenAI’s API, managing API keys securely, and interpreting responses—goes far beyond building a CLI tool. For example:
Web Applications: You can use the same logic within a Node.js backend for a web application. Your server endpoints could accept text data from a frontend, summarize it using the OpenAI API, and return the results to be displayed in the browser.
Mobile Apps: If you’re building a mobile app (either native or using frameworks like React Native or Flutter), you can set up a backend service powered by Node.js. Your mobile app would send requests to the server’s API, which would then leverage the OpenAI API to process data and return insights or summaries directly to the user’s phone.
Desktop Clients: The same code could also serve as the core logic for a desktop app. For example, an Electron-based application could offer text summarization directly on the user’s desktop without needing to open a browser or terminal.
In essence, the fundamental principles—obtaining an API key, sending requests to OpenAI’s endpoints, and handling responses—apply across various environments. Whether it’s a CLI tool, a web service, a mobile app, or a desktop client, you can integrate AI functionalities anywhere you need them.
Additional Tips
-
Experiment with Parameters: Adjust
temperature
andmodel
to control the style and creativity of responses. - Version Control Your Code (But Not Your Key): While you can commit your code to a repository, remember that the API key should stored locally on each user’s machine and not committed to Git.
- Publishing to npm: If you want to share your CLI tool with others, you can publish it to npm. Check out the npm documentation on publishing packages.
Conclusion
You’ve now built a simple AI-powered CLI tool and learned how to securely store your API key without relying on environment variables. You can run the tool from anywhere on your system and easily adapt it for a variety of AI-driven use cases.
Whether you’re summarizing text, translating languages, or performing sentiment analysis, you now have a strong foundation for building and sharing your AI-powered command-line utilities.
Feel free to experiment, iterate, and create the AI-powered tools you’ve always envisioned!
Top comments (2)
Very insightful, thank you for this article!
Thanks for going through