How do I format markdown chatgpt response in tkinter frame python?

题意:怎样在Tkinter框架中使用Python来格式化Markdown格式的ChatGPT响应?

问题背景:

Chatgpt sometimes responds in markdown language. Sometimes the respond contains ** ** which means the text in between should be bold and ### text ### which means that text is a heading. I want to format this correctly and display it properly in tkinter. If it's bold or a heading, it should be formatted to bold or to a heading in tkintter. How to do this?

ChatGPT有时会以Markdown语言回应。有时回应中包含** **,这表示中间的文本应该是粗体的;而### text ###则表示该文本是一个标题。我想在Tkinter中正确地格式化并显示这些文本。如果它是粗体或标题,则应该在Tkinter中以粗体或标题的形式显示。如何做到这一点?

My code:

python 复制代码
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, historyxx):
    global history

    openai.api_key = "xxxxxxx"
    append_to_chat_log(message="\n\n\n")
    append_to_chat_log("Chatgpt")

    print("Trying")

    messages = [
            {"role": "user", "content": prompt}
        ]

    try:
        stream = openai.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            stream=True,
            
        )
        
        for chunk in stream:
            chunk = chunk.choices[0].delta.content
            chunk = str(chunk)
            if chunk != "None":
                append_to_chat_log(message=chunk)
        
        
        append_to_chat_log(message="\n\n\n")
        print("Streaming complete")
               
    except Exception as e:
        print(e)
        return "Sorry, an error occurred while processing your request."

# Create a function to use OpenAI to answer a question based on the search results

def append_to_chat_log(sender=None, message=None):
    chat_log.config(state="normal")
    if sender:
        chat_log.insert("end", f"{sender}:\n", "sender")
    if message:
        chat_log.insert("end", message)
    chat_log.config(state="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", message)
        history.append(("user", message))
        if len(history) >4:
            history = history[-4:]
        print(message)
        response = get_answer_from_chatgpt(message, history)
        
        history.append(("assistant", response))

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.mark_set("insert", "%d.%d" % (0,0))
message_entry.bind("<Return>", send_message)

root.mainloop()

问题解决:

I solved my own question 我解决了我自己提出的问题

python 复制代码
import tkinter as tk
from datetime import datetime
import openai

history = []

# Create a function to use ChatGPT 3.5 turbo to answer a question based on the prompt
def get_answer_from_chatgpt(prompt, historyxx):
    global history

    openai.api_key = "xxxx"
    append_to_chat_log(message="\n\n\n")
    append_to_chat_log("Chatgpt")

    print("Trying")

    messages = [
            {"role": "user", "content": prompt}
        ]

    try:
        stream = openai.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            stream=True,
        )
        
        buffer = ""
        heading =  ""
        bold = False
        while True:
            chunk = next(stream)
            chunk = chunk.choices[0].delta.content
            chunk = str(chunk)
            if chunk != "None":
                buffer += chunk
                if "**" in buffer:
                    while "**" in buffer:
                        pre, _, post = buffer.partition("**")
                        append_to_chat_log(message=pre, bold=bold)
                        bold = not bold
                        buffer = post
                if "###" in buffer:
                    while "###" in buffer:
                        pre, _, post = buffer.partition("###")
                        append_to_chat_log(message=pre, bold=heading)
                        heading = not heading
                        buffer = post
                else:
                    append_to_chat_log(message=buffer, bold=bold)
                    buffer = ""
        
        append_to_chat_log(message="\n\n\n")
        print("Streaming 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, bold=False, heading=False):
    chat_log.config(state="normal")
    if sender:
        chat_log.insert("end", f"{sender}:\n", "sender")
    if message:
        if bold:
            chat_log.insert("end", message, "bold")
        if heading:
            chat_log.insert("end", message, "heading")
        else:
            chat_log.insert("end", message)
    chat_log.config(state="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", message)
        history.append(("user", message))
        if len(history) > 4:
            history = history[-4:]
        print(message)
        response = get_answer_from_chatgpt(message, history)
        history.append(("assistant", response))

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.tag_configure("sender", font=('Arial', 12, 'bold'))
chat_log.tag_configure("bold", font=('Arial', 12, 'bold'))
chat_log.tag_configure("heading", font=('Arial', 16, 'bold'))
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.mark_set("insert", "%d.%d" % (0,0))
message_entry.bind("<Return>", send_message)

root.mainloop()
相关推荐
Narutolxy21 分钟前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
Amo Xiang44 分钟前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
liangbm31 小时前
数学建模笔记——动态规划
笔记·python·算法·数学建模·动态规划·背包问题·优化问题
B站计算机毕业设计超人1 小时前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
羊小猪~~1 小时前
深度学习基础案例5--VGG16人脸识别(体验学习的痛苦与乐趣)
人工智能·python·深度学习·学习·算法·机器学习·cnn
waterHBO3 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AI大模型知识分享4 小时前
Prompt最佳实践|如何用参考文本让ChatGPT答案更精准?
人工智能·深度学习·机器学习·chatgpt·prompt·gpt-3
草莓屁屁我不吃6 小时前
Siri因ChatGPT-4o升级:我们的个人信息还安全吗?
人工智能·安全·chatgpt·chatgpt-4o
AIAdvocate6 小时前
Pandas_数据结构详解
数据结构·python·pandas