Build a GPT-Powered Chatbot That Runs in Your CMD — No Frameworks Needed
A clean, colorful AI chatbot using pure Python and OpenRouter's free API — works on Windows, Mac, and Linux right inside your terminal.
What are we building?
A fully working AI chatbot that lives in your terminal. You type, it thinks, it responds — just like ChatGPT, but running from your command prompt using 100% pure Python. No pip installs, no virtual environments, no frameworks. Just Python and a free API key.
It has colored output, multi-turn memory (it remembers what you said earlier in the chat), and clean error handling. Perfect for beginners who want to see how AI APIs actually work under the hood.
Prerequisites
- 01Python 3.6 or above — check by running python --version in your terminal. Download from python.org if you don't have it.
- 02A free OpenRouter account — sign up at openrouter.ai, go to your dashboard, and create an API key. It's free and takes 2 minutes.
- 03Any text editor — Notepad, VS Code, whatever you prefer. Save the file as chatbot.py.
The full code
Copy the entire script below. This is the only file you need.
import os, json, urllib.request, urllib.error
API_KEY = "sk-or-v1-xxx" # replace with your key
MODEL = "openai/gpt-3.5-turbo"
API_URL = "https://openrouter.ai/api/v1/chat/completions"
COLORS = {
"cyan": "\033[96m", "green": "\033[92m",
"yellow": "\033[93m", "red": "\033[91m",
"bold": "\033[1m", "reset": "\033[0m",
}
def color(text, *names):
codes = "".join(COLORS[n] for n in names)
return f"{codes}{text}{COLORS['reset']}"
def ask(messages):
payload = json.dumps({
"model": MODEL, "messages": messages,
}).encode("utf-8")
req = urllib.request.Request(API_URL, data=payload,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
"HTTP-Referer": "https://localhost",
"X-Title": "ChatGPT-CMD",
}, method="POST")
with urllib.request.urlopen(req) as resp:
data = json.loads(resp.read().decode("utf-8"))
return data["choices"][0]["message"]["content"]
def main():
conversation = [
{"role": "system", "content": "You are a helpful AI assistant."}
]
while True:
try:
user_input = input(color("You > ", "green", "bold")).strip()
except (KeyboardInterrupt, EOFError):
print(color("\nBye!", "cyan")); break
if not user_input: continue
if user_input.lower() in ("quit", "exit"):
print(color("Goodbye!", "cyan")); break
if user_input.lower() == "clear":
conversation = [conversation[0]]
print(color("Conversation cleared.", "yellow")); continue
conversation.append({"role": "user", "content": user_input})
print(color("AI > ", "cyan", "bold"), end="", flush=True)
try:
reply = ask(conversation)
except urllib.error.HTTPError as e:
print(color(f"HTTP Error {e.code}: {e.read().decode()}", "red"))
conversation.pop(); continue
except Exception as e:
print(color(f"Error: {e}", "red")); conversation.pop(); continue
print(reply); print()
conversation.append({"role": "assistant", "content": reply})
if __name__ == "__main__":
main()
How to run it
- 01Open the file and replace "sk-or-v1-xxx" with your actual OpenRouter API key.
- 02Save the file as chatbot.py anywhere on your computer — Desktop is fine.
- 03Open Command Prompt (Windows) or Terminal (Mac/Linux). Navigate to where you saved the file using cd Desktop.
- 04Run the command below. You should see the You > prompt appear in green.
# Windows python chatbot.py # Mac / Linux python3 chatbot.py
On Windows, if python is not recognized, try py chatbot.py instead. Make sure Python was added to your PATH during installation.
Commands you can use
| Command | What it does |
|---|---|
| clear | Wipes the conversation history and starts fresh — the AI forgets everything you said. |
| exit / quit | Gracefully exits the chatbot. |
| Ctrl + C | Emergency exit — works even if the AI is mid-response. |
How the code works — quickly
The conversation list is the heart of the script. Every message you send and every reply the AI gives gets appended to it. When you ask a new question, the entire history is sent to the API — that is how the AI "remembers" what you talked about earlier.
The ask() function packages that list into a JSON payload and fires it at OpenRouter's API endpoint using Python's built-in urllib — no third-party libraries needed at all.
The COLORS dictionary uses ANSI escape codes — special character sequences that most terminals understand. That is what makes the You prompt appear green and the AI prompt appear cyan.
Want to customise it?
- ⚙Change the AI's personality — edit the "system" message at the top of main(). Try "You are a sarcastic coding assistant" or "You only respond in haiku."
- ⚙Switch the model — change the MODEL variable. OpenRouter supports Mistral, LLaMA, Claude, Gemini and more. Check their free models at openrouter.ai/models.
- ⚙Change the colors — swap the ANSI codes in the COLORS dict. \033[95m is magenta, \033[94m is blue, \033[33m is orange.
Comments
Post a Comment