pythontkinteropenai-apitkinter-entrytkinter-layout

How do I make the text bold and have space in between in tkinter python?


enter image description here

In my code, I only want to make the sender name bold. This means I only want to make "User" and "Gpt-3.5-turbo" bold. For some reason, messages sent by "User" is always bold. Additionally, there is no new line between "User" and "Gpt-3.5-turbo" as seen in the image I've attached, although there is space in between the very first message by "User" and "Gpt-3.5-turbo". I've tried many commands to fix this issue but no luck. Can someone help me out in fixing these 2 issues? Below is my code:

import tkinter as tk
from tkinter import ttk
from datetime import datetime
import openai
import json
import requests

history = []

# Create a function to use ChatGPT 3.5 turbo to answer a question based on the prompt
def get_answer_from_chatgpt(prompt, history):
    openai.api_key = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    print("Trying")

    messages = [
            {"role": "system", "content": "You are a helpful assistant."}
        ]

    for sender, message in history:
            messages.append({"role": sender, "content": message})

    try:
        stream = openai.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            stream=True,
            
        )
        append_to_chat_log("Gpt-3.5-turbo")
        for chunk in stream:
            if chunk.choices[0].delta.content is not None:
               chunk = chunk.choices[0].delta.content
               append_to_chat_log(message=chunk) 
               #history.append(("assistant", chunk))
        append_to_chat_log(message="\n")
        
        #chat_log.insert("end",'\n\n')
        
        print("Streamig complete")        
    except Exception as e:
        print(e)
        return "Sorry, an error occurred while processing your request."


def append_to_chat_log(sender=None, message=None):
   
    chat_log.config(state=tk.NORMAL)
    if sender:
        chat_log.insert("end", f"{sender}\n\n", "sender")
        
        #chat_log.insert("end",'\n\n')
    if message:
        chat_log.insert("end", message)
    chat_log.tag_config("sender", font=('Arial', 12, 'bold'))
    chat_log.config(state=tk.DISABLED)
    chat_log.see("end")
    chat_log.update()


def send_message(event=None):
    global history
    message = message_entry.get(1.0, "end-1c") 
    message = message.strip()
    message_entry.delete(1.0, tk.END)
    message_entry.update()
    
    if not message:
        pass 
    else:
        append_to_chat_log("User")
        append_to_chat_log(message)
        history.append(("user", message))
        if len(history) >4:
            history = history[-4:]

        get_answer_from_chatgpt(message, history)
        print(history)

root = tk.Tk()

root.title("Chat")

# Maximize the window
root.attributes('-zoomed', True)

chat_frame = tk.Frame(root)
chat_frame.pack(expand=True, fill=tk.BOTH)

chat_log = tk.Text(chat_frame, state='disabled', wrap='word', width=70, height=30, font=('Arial', 12), highlightthickness=0, borderwidth=0)
chat_log.pack(side=tk.LEFT, padx=(500,0), pady=10)


message_entry = tk.Text(root, padx=17, insertbackground='white', width=70, height=1, spacing1=20, spacing3=20, font=('Open Sans', 14))
message_entry.pack(side=tk.LEFT, padx=(500, 0), pady=(0, 70))  # Adjust pady to move it slightly above the bottom
#message_entry.insert(0, "Ask me anything...")
message_entry.insert(1.0, "Ask me anything...")
message_entry.mark_set("insert", "%d.%d" % (0,0))
message_entry.bind("<Return>", send_message)
#message_entry.bind("<Button-1>", click)

root.mainloop()

I've tried using commands like chat_log.insert("end",'\n\n') and append_to_chat_log(message="\n") in def get_answer_from_chatgpt(prompt, history): function but none seem to work.


Solution

  • The message from user is bold because you call append_to_chat_log() wrong on message and you need to use message option as below:

    def send_message(event=None):
        ...
        else:
            append_to_chat_log("User")  # log the sender
            append_to_chat_log(message=message)  # log the message
            ...
    

    To add newlines between messages, you can add newlines messages before and after GPT response:

    def get_answer_from_chatgpt(message, history):
        ...
        try:
            ...
            # add newlines before response
            append_to_chat_log(message="\n\n")
            append_to_chat_log("Gpt-3.5-turbo")
            for chunk in stream:
                ...
            # add newlines after response
            append_to_chat_log(message="\n\n")
            ...
        ...