• HINDI
  •    
  • Saturday, 17-Jan-26 04:39:36 IST
Tech Trending :
* ๐Ÿค–How OpenAI + MCP Servers Can Power the Next Generation of AI Agents for Automation * ๐Ÿ“š Book Recommendation System Using OpenAI Embeddings And Nomic Atlas Visualization

๐Ÿง  Building Your Own ChatGPT Clone in Python using OpenAI API

Contents

Table of Contents

    Contents
    ๐Ÿง  Building Your Own ChatGPT Clone in Python using OpenAI API

    ๐Ÿง  Building Your Own ChatGPT Clone in Python using OpenAI API

    ๐Ÿš€ Introduction

    Have you ever wondered how ChatGPT actually works under the hood?
    What if you could build your own ChatGPT-like chatbot โ€” fully customizable, interactive, and smart enough to carry out conversations in real-time?

    In this guide, weโ€™ll walk you through building a ChatGPT clone using Python and the OpenAI API.
    By the end, youโ€™ll have your own interactive chatbot that can:

    • Accept custom system prompts (change the assistantโ€™s behavior)

    • Maintain chat history

    • Switch personality mid-conversation

    • Exit gracefully when youโ€™re done

    Letโ€™s get started! ๐Ÿ’ฌ


    ๐Ÿงฉ Prerequisites

    Before you start, make sure you have:

    • ๐Ÿ Python 3.8+

    • ๐Ÿ”‘ An OpenAI API key (you can get it from OpenAI Dashboard)

    • ๐Ÿ“ฆ Required Python libraries:

      pip install openai streamlit

    ๐Ÿ’ก Project Overview

    Weโ€™ll build a terminal-based ChatGPT clone that uses OpenAIโ€™s gpt-3.5-turbo model.
    This app will:

    1. Accept a system prompt to define the assistantโ€™s behavior.

    2. Allow you to chat interactively.

    3. Let you update the system prompt dynamically.

    4. Gracefully exit on โ€œbyeโ€, โ€œexitโ€, or โ€œquitโ€.

    Later, you can easily adapt this to a Streamlit-based web interface.


    ๐Ÿง  Step 1: Import Dependencies

    Letโ€™s begin by importing the required libraries:

    import streamlit as st from openai import OpenAI import os import time
    • openai โ†’ To access GPT models

    • os โ†’ To handle environment variables (for API keys)

    • time โ†’ To add small response delays

    • streamlit โ†’ Optional, for building a web interface later


    ๐Ÿค– Step 2: Define a Simple Chat Function

    This function sends a single prompt to the GPT model and returns the response:

    def gpt_chat(prompt): client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY')) messages = list() system_prompt = "Answer as concisely as possible" messages.append({"role": "system", "content": system_prompt}) messages.append({"role": "user", "content": prompt}) response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, temperature=0.7, max_tokens=300 ) current_response = response.choices[0].message.content return current_response

    ๐Ÿ’ก Tip:
    You can modify the system_prompt to change the chatbotโ€™s personality โ€”
    for example, โ€œYou are a sarcastic assistantโ€ or โ€œYou are a helpful teacherโ€.


    ๐Ÿ’ฌ Step 3: Building the Interactive Chat Loop

    This is where the magic happens โ€” we maintain a message history and allow users to chat freely.

    def interactive_chat(): client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY')) questions = list() bot_responses = list() messages = list() # Get system prompt from user print("Enter system prompt (or press Enter for default):") try: system_prompt = input("System: ").strip() if not system_prompt: system_prompt = "Answer as concisely as possible" print(f"Using system prompt: '{system_prompt}'") except EOFError: system_prompt = "Answer as concisely as possible" print(f"Using default system prompt: '{system_prompt}'") messages.append({"role": "system", "content": system_prompt}) print("-" * 50) try: while True: current_question = input("Me: ") if current_question.lower() in ["exit", "quit", "bye"]: print("Bot: Bye!") time.sleep(2) break # Allow changing system prompt mid-chat if current_question.lower() in ["/system", "/prompt"]: print("Enter new system prompt:") try: new_prompt = input("System: ").strip() if new_prompt: system_prompt = new_prompt messages[0] = {"role": "system", "content": system_prompt} print(f"System prompt updated to: '{system_prompt}'") else: print("System prompt unchanged.") except EOFError: print("System prompt unchanged.") print("-" * 50) continue if current_question == '': continue messages.append({"role": "user", "content": current_question}) response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, temperature=0.7, max_tokens=300 ) current_response = response.choices[0].message.content print(f"Bot: {current_response}") bot_responses.append(current_response) messages.append({"role": "assistant", "content": current_response}) questions.append(current_question) print('\n' + '-' * 50 + '\n') except EOFError: print("\nInteractive chat ended (EOF detected).") except KeyboardInterrupt: print("\n\nChat ended by user (Ctrl+C).")

    โœจ Highlights:

    • /system or /prompt allows you to update the system prompt anytime.

    • Conversation context is preserved with messages history.

    • Clean exit with bye, exit, or quit.


    ๐Ÿ” Step 4: Running the Chat

    To kickstart your chatbot, add the following:

    if __name__ == "__main__": # Set API key os.environ['OPENAI_API_KEY'] = 'your-openai-api-key-here' print("Welcome to ChatGPT Clone!") print("Features:") print("- Set custom system prompt at startup") print("- Change system prompt during chat with '/system' or '/prompt'") print("- Type 'exit', 'quit', or 'bye' to end the conversation") print("- Press Ctrl+C for emergency exit") print("=" * 50) interactive_chat()

    Run it in your terminal:

    python chatgpt_clone.py

    ๐Ÿงญ Example Conversation

    Welcome to ChatGPT Clone! Features: - Set custom system prompt at startup - Change system prompt during chat with '/system' or '/prompt' ================================================== Enter system prompt (or press Enter for default): System: You are a witty assistant who gives humorous answers Using system prompt: 'You are a witty assistant who gives humorous answers' -------------------------------------------------- Me: What's the weather today? Bot: Iโ€™m not a weatherman, but it feels like โ€œstay indoors with coffeeโ€ kind of day! โ˜• -------------------------------------------------- Me: /system Enter new system prompt: System: You are a professional software mentor System prompt updated to: 'You are a professional software mentor' -------------------------------------------------- Me: Explain Python decorators Bot: Decorators in Python are functions that modify the behavior of another function without changing its code. Theyโ€™re often used for logging, access control, or measuring execution time. -------------------------------------------------- Me: bye Bot: Bye!

    ๐ŸŒ Bonus: Streamlit Web Interface (Optional)

    You can easily turn this into a web-based chatbot using Streamlit.
    Hereโ€™s a mini version:

    import streamlit as st st.title("๐Ÿ’ฌ ChatGPT Clone") if "messages" not in st.session_state: st.session_state.messages = [{"role": "system", "content": "Answer concisely"}] user_input = st.text_input("You:") if user_input: st.session_state.messages.append({"role": "user", "content": user_input}) response = gpt_chat(user_input) st.session_state.messages.append({"role": "assistant", "content": response}) st.write(f"**Bot:** {response}")

    Run it with:

    streamlit run app.py

    ๐Ÿ Conclusion

    ๐ŸŽ‰ Congratulations! Youโ€™ve just built your own ChatGPT clone using Python and OpenAIโ€™s API.
    You now understand:

    • How to manage chat history

    • How to use system prompts to alter behavior

    • How to extend the terminal chatbot into a web app

    This setup forms the backbone of AI-driven assistants, customer support bots, and educational tutors โ€” all powered by GPT.