Generative AI is transforming the tech landscape. If you are a developer or a UPSC aspirant with a Science & Tech focus, understanding how to build AI tools is a massive advantage. In this guide, we will use Python to create a functional AI assistant.
Introduction to Gen AI Development
Before diving into code, it is essential to understand why Python is the leading language for Artificial Intelligence. Python’s simplicity allows you to focus on AI logic rather than complex syntax.
Why Choose Python for AI?
- Extensive Libraries: Tools like
OpenAI,LangChain, andPyTorch. - Community Support: Thousands of pre-built scripts are available online.
- Scalability: Easy to move from a simple script to a full-stack web app.
Setting Up Your Development Environment
To begin, you need to prepare your machine. Follow these steps to ensure your environment is ready for AI integration.
Installing Required Python Libraries
Open your terminal or command prompt and run:
Bash
pip install openai python-dotenv
Securing Your OpenAI API Key
- Visit the OpenAI Dashboard.
- Create a new Secret Key.
- Store it in a
.envfile to keep your credentials safe from hackers.
Writing the Chatbot Code
Now, let’s write the actual script. This code uses the latest OpenAI v1.0+ syntax.
The Python Script Implementation
Create a file named ai_bot.py and paste the following:
Python
import os
from openai import OpenAI
from dotenv import load_dotenv
# Initialize Environment
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def generate_response(prompt):
completion = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
return completion.choices[0].message.content
# Main Chat Loop
print("AI: System Online. How can I help you today?")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
break
print(f"AI: {generate_response(user_input)}")