Build Your Own Chatbot Using Python and OpenAI API

 

Build Your Own Chatbot Using Python and OpenAI API

Artificial Intelligence has made chatbots one of the most powerful tools for businesses and developers. With just a few lines of Python code, you can build your own AI-powered chatbot using the OpenAI API. This chatbot can answer questions, provide recommendations, and even integrate into websites or applications.

In this guide, I’ll show you how to build a fully functional chatbot in Python.


🛠 Requirements

  • Python 3.8 or newer

  • An OpenAI API key (get it from platform.openai.com)

  • Install the OpenAI Python package

Run this in your terminal to install dependencies:

pip install openai

💻 Full Python Code

import openai
# ضع مفتاح OpenAI API الخاص بك هنا
openai.api_key = "YOUR_OPENAI_API_KEY"
def chatbot_response(user_input):
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # يمكنك تغييره إلى "gpt-4" إذا متاح عندك
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_input}
]
)
reply = response['choices'][0]['message']['content']
return reply
except Exception as e:
return f"Error: {e}"
def run_chatbot():
print("🤖 Chatbot is ready! Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() in ["quit", "exit"]:
print("Chatbot: Goodbye! 👋")
break
reply = chatbot_response(user_input)
print(f"Chatbot: {reply}")
if __name__ == "__main__":
run_chatbot()

🚀 How it Works

  1. You enter your message.

  2. The Python script sends it to the OpenAI API.

  3. The API responds with an AI-generated reply.

  4. The chatbot prints the reply back to you.


🔗 Next Steps

  • Connect it with Telegram API or Discord API.

  • Create a web app using Flask or Streamlit.

  • Add memory so the bot remembers past conversations.


Post a Comment

0 Comments