One of the most rewarding milestones for software engineers venturing into applied artificial intelligence is constructing an interactive terminal chatbot. Through this foundational project, you gain immediate, hands-on experience with how large language models handle conversational memory, how message roles collaborate, and how token consumption scales over time.
In this tutorial, we will build a production-grade CLI chatbot in Python using the standard openai library configured to connect to TOP AI's unified gateway. We will harness deepseek-v4-pro (deepseek-v4-pro)—a high-reasoning model renowned for rapid execution and exceptional cost efficiency.

The Fundamental Rule: AI APIs Are Strictly Stateless
The most critical architectural reality every developer must grasp is that AI endpoints hold zero internal memory. Every HTTP POST invocation is treated as an isolated, standalone computational event.
If you want the model to recall your name or reference an error code discussed two exchanges ago, your application code is responsible for collecting the ongoing dialogue history and resubmitting it within an ordered array of message objects.
Without this client-side state maintenance, the model will treat follow-up questions (such as "can you refactor the function you just suggested?") with complete incomprehension, as it possesses no memory of previous completions.
Step 1: Environment Setup and Tooling
Ensure that your development workstation has Python 3.8 or higher installed. Open your command terminal and install the official OpenAI client library:
pip install openaiNext, export your TOP AI developer credential (which includes your 5,000 TP welcome grant) into your shell environment:
export TOPAI_API_KEY="tp-live-xxxxxxxxxxxxxxxxxxxxxxxx"Step 2: Full Implementation of the Terminal Chatbot
Create a file named chatbot.py and insert the following complete script:
# language: Python, file: chatbot.py, runtime: Python 3.10+
import os
import sys
from openai import OpenAI
# 1. Instantiate the Custom Gateway Client
API_KEY = os.getenv("TOPAI_API_KEY", "tp-live-xxxxxxxxxxxxxxxxxxxxxxxx")
client = OpenAI(
base_url="https://topai.id/v1",
api_key=API_KEY
)
# 2. Establish Foundational System Directives
system_prompt = {
"role": "system",
"content": "You are a concise, pragmatic, and helpful senior coding assistant. Provide concrete code snippets."
}
# 3. Dynamic Conversational Context Array
conversation_history = [system_prompt]
print("=" * 60)
print("🤖 TOP AI Terminal Assistant Online (Type 'exit' or 'quit' to end)")
print("=" * 60)
while True:
try:
user_input = input("
You: ").strip()
# Handle Clean Termination
if user_input.lower() in ["exit", "quit", "q"]:
print("
Session concluded cleanly. Goodbye!")
sys.exit(0)
if not user_input:
continue
# Ingest User Input into Historical Context
conversation_history.append({"role": "user", "content": user_input})
# Apply Sliding Window to Cap Context (Retain System + Last 10 Turns)
if len(conversation_history) > 11:
conversation_history = [conversation_history[0]] + conversation_history[-10:]
# 4. Dispatch Completion Request to Gateway
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=conversation_history,
temperature=0.7
)
assistant_reply = response.choices[0].message.content
tokens_used = response.usage.total_tokens
# Persist Model Response to Ground Subsequent Inquiries
conversation_history.append({"role": "assistant", "content": assistant_reply})
print(f"
AI: {assistant_reply}")
print(f"
[Telemetry: {tokens_used} tokens ingested & generated]")
except KeyboardInterrupt:
print("
Session aborted via SIGINT.")
sys.exit(0)
except Exception as err:
print(f"
Runtime Exception encountered: {err}")
Breakdown of Message Roles
Live TOP AI API Pricing for Models Mentioned
Frequently Asked Questions
Why must the client maintain the full message history across turns?+
AI inference endpoints are strictly stateless. To maintain contextual continuity across multi-turn dialogues, the client application must resubmit prior exchanges in the messages array.
How can I prevent runaway token costs as the conversation lengthens?+
Implement a sliding context window that preserves the original system instruction while slicing only the most recent 6 to 10 dialogue turns.
Is this Python script compatible with modern Python 3.11+ virtual environments?+
Yes. The implementation relies on standard libraries and the official openai package, making it fully compatible with Python 3.8 through 3.12+.
What is the expected operating cost for running this terminal bot for 15 minutes?+
When querying cost-effective models like deepseek-v4-pro via TOP AI, a 15-minute dialogue typically consumes between 10 to 50 TP (approximately $0.0006 to $0.003).





