Make Your First AI in 5 Minutes with Python

Create Your AI Assistant Using Python

How to Create Your Own AI Assistant Using Python

Creating your own AI assistant can seem like a daunting task, but with Python and OpenAI’s API, it’s surprisingly simple. This tutorial will guide you through building an AI-powered Q&A assistant with a graphical user interface (GUI) using Tkinter and OpenAI’s GPT-3.5-Turbo model.

Features

  • Interactive Chat Interface: Communicate with the AI assistant in a conversational manner.
  • Customizable Settings: Control the creativity of the AI responses using the temperature parameter.
  • User-Friendly GUI: Built using Tkinter, the interface is clean and easy to use.

Code Explanation

Here’s a step-by-step breakdown of the code:

1. Setting Up the OpenAI API

import openai
openai.api_key = ""

  • Replace the "" with your actual OpenAI API key. This key is required to access the GPT-3.5-Turbo model.
  • You can obtain an API key by creating an account at OpenAI.

2. Function to Send Prompts to OpenAI

def ask_chatgpt(prompt, temperature=0.1, max_tokens=100):
    ...
    response = openai.ChatCompletion.create(...)
    return response['choices'][0]['message']['content'].strip()

  • prompt: The user’s input/question.
  • temperature: Controls the creativity of the response (lower values make responses more focused).
  • max_tokens: Limits the response length.

This function communicates with the OpenAI API and returns the AI’s response.

3. GUI with Tkinter

Creating the Main Window

root = tk.Tk()
root.title("AI-Powered Q&A Assistant")

  • Creates the main application window with a title.

Chat Display Area

chat_window = scrolledtext.ScrolledText(frame, wrap=tk.WORD, width=60, height=20, state='disabled')

  • A scrollable text widget displays the conversation history.

User Input and Action Button

entry = tk.Entry(root, width=50)
ask_button = tk.Button(root, text="Ask", command=on_ask)

  • Entry Widget: Allows users to type their questions.
  • Button: Triggers the on_ask() function to process the input and get a response.

Handling User Input

def on_ask():
    user_input = entry.get()
    ...
    response = ask_chatgpt(user_input, temperature=0.5, max_tokens=200)
    ...
    entry.delete(0, tk.END)

  • Retrieves the user’s question, sends it to the AI, displays the response in the chat window, and clears the input field.

4. Running the Application

root.mainloop()

  • Starts the Tkinter event loop, keeping the application window open for interaction.


image-20-1024x492 Create Your AI Assistant Using Python
Own AI Assistant Using Python






import openai
import tkinter as tk
from tkinter import scrolledtext

# Set your OpenAI API key
openai.api_key = ""
def ask_chatgpt(prompt, temperature=0.1, max_tokens=100):
    """
    Sends a prompt to the OpenAI API and returns the response.
    Parameters:
    - prompt (str): The user input combined with context.
    - temperature (float): Controls creativity of the response.
    - max_tokens (int): Controls the length of the response.
    """
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful AI specialized in programming."},
                {"role": "user", "content": prompt},
            ],
            temperature=temperature,
            max_tokens=max_tokens,
        )
        return response['choices'][0]['message']['content'].strip()
    except Exception as e:
        return f"Error: {e}"

# Function to handle the "Ask" button click
def on_ask():
    user_input = entry.get()
    if user_input.strip() == "":
        return
    
    # Display user input in the chat window
    chat_window.config(state='normal')
    chat_window.insert(tk.END, f"You: {user_input}\n")
    chat_window.yview(tk.END)
    
    # Call the API and get the response
    response = ask_chatgpt(user_input, temperature=0.5, max_tokens=200)
    
    # Display AI response in the chat window
    chat_window.insert(tk.END, f"AI: {response}\n\n")
    chat_window.yview(tk.END)
    
    # Clear the entry widget
    entry.delete(0, tk.END)

# Create the main window
root = tk.Tk()
root.title("AI-Powered Q&A Assistant")

# Create a frame for the chat window
frame = tk.Frame(root)
frame.pack(padx=10, pady=10)

# Create a scrollable text widget for the chat window
chat_window = scrolledtext.ScrolledText(frame, wrap=tk.WORD, width=60, height=20, state='disabled')
chat_window.pack()

# Create an entry widget for user input
entry = tk.Entry(root, width=50)
entry.pack(pady=5)

# Create a button to trigger the "ask" function
ask_button = tk.Button(root, text="Ask", command=on_ask)
ask_button.pack(pady=5)

# Run the main loop to display the GUI
root.mainloop()

How to Run This Project

  1. Set Up the Environment:
    • Install the required Python packages: pip install openai
  2. Add Your OpenAI API Key:
    • Replace the placeholder in the code with your OpenAI API key.
  3. Run the Code:
    • Save the script to a .py file and execute it: python your_script_name.py
  4. Interact with the Assistant:
    • Type your questions into the input box, click the “Ask” button, and see the AI’s response in the chat window.

Download New Real Time Projects :-Click here

Post Comment