← Volver
Comunicación con ChatGPT usando Python
Publicado el 23 de abril de 2025
Python
En este post se realiza la conexión con la API de OpenAI con ChatGPT en Python.
Necesitaremos una API KEY que debemos solicitar en la página web: https://platform.openai.com/api-keys
Archivo main.py
from dotenv import load_dotenv
from ChatGPT import ChatGPT
import tkinter as tk
from tkinter import scrolledtext
import os
import pygame
def center_window(window, width, height):
window_width = window.winfo_screenwidth()
window_height = window.winfo_screenheight()
pos_x = int((window_width - width) / 2)
pos_y = int((window_height - height) /2)
window.geometry(f'{width}x{height}+{pos_x}+{pos_y}')
pygame.mixer.init()
pygame.mixer.music.load("./success.mp3")
load_dotenv()
api_key = os.getenv("API_KEY")
chat = ChatGPT(api_key)
root = tk.Tk()
root.title("ChatGPT")
center_window(root,800,600)
def send_message():
text_response.configure(state='normal')
text_question = input_text.get()
response = chat.askChatGPT(text_question)
text_response.insert(tk.END, f"{response} \n\n")
text_response.configure(state='disabled')
pygame.mixer.music.play()
label_question = tk.Label(root, text="Escribe tu consulta a ChatGPT", font=("Helvetica", 20), wraplength=750, justify="left", fg="black")
label_question.pack(fill="x", padx=20, pady=20)
input_text = tk.Entry(root, width=40)
input_text.pack(fill="x", padx=20, pady=20)
send_button = tk.Button(root, text="Enviar", command=send_message)
send_button.pack(fill="x", padx=20, pady=20)
text_response = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=90, height=15, font=("Helvetica", 18))
text_response.pack(fill="both", expand=True, padx=20, pady=20)
root.mainloop()Creamos el cliente con la API KEY en el constructor y definimos el método askChatGPT pasándole como argumento el mensaje. Este nos devolverá un mensaje con la respuesta.
Clase ChatGPT
from openai import OpenAI
class ChatGPT:
def __init__(self, api_key):
self.client = OpenAI(api_key=api_key)
def askChatGPT(self, message):
completion = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "developer",
"content": "Eres un asistente útil para código de programación"
},
{
"role": "user",
"content": message
}
],
)
print(completion.choices[0].message.content)
return completion.choices[0].message.content