Creating AI chatbots similar ChatGPT in Python? Is it Possible?

I’ve been learning Python basics for a while now and know this is a stretch, but…

Can you make a AI chatbot in Python?
I have already got some down:

user = input(“Username: “)
formated = f”{user.capitalize()}:”
message = “Answer
print(“GPT: Welcome to BisonGPT”, user.capitalize(), “How can I help you today?”)
input(formated)

def GPTresp():
print("GPT: ", message)
GPTresp()


Output:

Username: Your Username
GPT: Welcome to BisonGPT your username How can I help you today?
your username:


How can I make a real ai in Python? Not just a chatbot that looks for certain keywords and a predetermined output- real ai. Is it possible?


Link to my code: Online Python Compiler (Interpreter) - Programiz

You just made a program that prints out several formatted strings. There’s going to be a big leap forward in the code you must write in generating AI responses.

You are on the OpenAI developer forum. OpenAI offers AI services. The first thing is to go to platform.openai.com and set up an API account. To actually make API calls, you have to pre-purchase credits to pay for the usage, and generate an API key that your calls over the network to OpenAI will use to authenticate.

But yes, one can create a chatbot with Python. ChatGPT is a product with millions of users and billions in annual billings, so it already has massive development costs behind all the features, but I can show Python code that:

  1. gives a function to make an API call to the OpenAI AI services;
  2. uses that function and a growing history of your chat sent back to the AI to create a conversational context AI.

Here’s that basic demo code that I’ve worked up for just this occasion…

import os, httpx

def send_chat_request(conversation_messages):
    # Set your API key in OPENAI_API_KEY env variable (never hard-code it).
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("Set OPENAI_API_KEY environment variable!")
    api_url = "https://api.openai.com/v1/chat/completions"
    headers = {"Authorization": f"Bearer {api_key}"}
    payload = {"model": "gpt-4o-mini", "messages": conversation_messages,
               "max_completion_tokens": 1999}
    try:
        response = httpx.post(api_url, headers=headers, json=payload, timeout=180.0)
        response.raise_for_status()
    except Exception as error:
        print("API error:", error)
        return None
    return response

system = [{"role": "developer", "content":
                         "You are a helpful AI assistant."}]
conversation_history = []
while True:
    user_input = input("prompt> ")
    if user_input.strip().lower() == "exit":
        break
    conversation_history.append({"role": "user", "content": user_input})
    messages_to_send = system + conversation_history[-20:]
    resp = send_chat_request(messages_to_send)
    assistant_response = resp.json()["choices"][0]["message"]["content"]
    if assistant_response is None:
        print("Error retrieving API response.")
        continue
    print("assistant>", assistant_response)
    conversation_history.append({"role": "assistant", "content": assistant_response})

You’ll need to understand the API reference and documentation, both linked on the sidebar of this forum, to develop the API call technique more, and advanced Python programming to have this be the backend of a web page or app with user accounts and chat session memory. But that’s enough code to talk to an AI:

1 Like

Welcome to the dev forum @PrintedBison

I wrote a tutorial on it a while ago when chat models were launched. Hope this helps.

1 Like

You can ask Chat to help create an avatar and then start loading it with a personality, it will do your homework to. If you want it to be local off line you will need LLM to you can streamline it to fit by removing what you don’t want.