Introduction
I recently built my first LLM-powered chatbot using the OpenAI API, and it was a truly rewarding experience! In this blog, I’ll walk you through how I set it up, wrote the code, and made the chatbot interactive.
Getting Started
To begin, I set up Python and installed the OpenAI library:
Install Python and OpenAI Library:
pip install openai
2. Get an API Key: I signed up on OpenAI’s platform and generated my API key.
Building the ChatbotThe basic idea was to create a chatbot that could hold a conversation with context. Here’s the essential code I used:
import openai
import os
# Set the API key
openai.api_key = os.getenv("OPENAI_API_KEY")
conversation_history = [
{"role": "system", "content": "You are a helpful assistant."}
]
def chat_with_openai(prompt):
conversation_history.append({"role": "user", "content": prompt})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=conversation_history
)
answer = response.choices[0].message['content'].strip()
conversation_history.append({"role": "assistant", "content": answer})
return answer
print("Chatbot ready! Type 'exit' to end.")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("Goodbye!")
break
print(f"Assistant: {chat_with_openai(user_input)}")
For the full code and more details, check out the GitHub repository.
Here’s a quick example of how the chatbot can assist with a simple task, such as providing a recipe for making a cup of tea:
Conversation Handling: It stores the conversation history to maintain context, allowing for meaningful replies.
Chat Loop: The chatbot runs in a loop, responding to user input until “exit” is typed.
Enhancements
I made a few improvements:
Conversation Context: The chatbot remembers previous messages to maintain a natural flow.
Custom Behavior: By tweaking the initial system message, I experimented with different chatbot personalities.
Lessons Learned
Ease of Integration: The OpenAI API is straightforward and powerful, making it ideal for quick AI projects.
Context Matters: Maintaining conversation history is crucial for coherent responses.
Error Handling: Adding basic error checks helps ensure a smooth experience.
Future Plans
I’m planning to:
Add a GUI: Develop a user-friendly interface using Streamlit to make the chatbot more accessible and visually appealing.
Prompt System Role Changes: Experiment with different system roles (e.g., “math tutor” or “travel guide”) for more specialized and flexible interactions.
Conclusion
Building this LLM powered chatbot was a fantastic introduction to AI development. It’s an accessible project for beginners, and I’m excited to keep improving it!
Call to Action
Give it a try and share your experiences. If you’re new to AI, this project is a great way to start!