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:

import tkinter as tk
from tkinter import ttk
from datetime import datetime
import openai
import json
import requestshistory = []
# 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 historyopenai.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.contentchunk = 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 resultsdef 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 historymessage = 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? ? ? ? 我解決了我自己提出的問題

import tkinter as tk
from datetime import datetime
import openaihistory = []# 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 historyopenai.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 = Falsewhile True:chunk = next(stream)chunk = chunk.choices[0].delta.contentchunk = str(chunk)if chunk != "None":buffer += chunkif "**" in buffer:while "**" in buffer:pre, _, post = buffer.partition("**")append_to_chat_log(message=pre, bold=bold)bold = not boldbuffer = postif "###" in buffer:while "###" in buffer:pre, _, post = buffer.partition("###")append_to_chat_log(message=pre, bold=heading)heading = not headingbuffer = postelse: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 historymessage = 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()

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/42914.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/42914.shtml
英文地址,請注明出處:http://en.pswp.cn/web/42914.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python數據分析-天氣類型預測分析

一、研究背景 近年來&#xff0c;隨著全球氣候變化的加劇&#xff0c;天氣預報和氣象預測變得越來越重要。準確的天氣預測不僅能夠幫助人們做好日常生活的安排&#xff0c;還能在農業生產、防災減災等方面起到關鍵作用。隨著大數據技術和機器學習算法的快速發展&#xff0c;利…

科普文:深入理解負載均衡(四層負載均衡、七層負載均衡)

概敘 網絡模型&#xff1a;OSI七層模型、TCP/IP四層模型、現實的五層模型 應用層&#xff1a;對軟件提供接口以使程序能使用網絡服務&#xff0c;如事務處理程序、文件傳送協議和網絡管理等。&#xff08;HTTP、Telnet、FTP、SMTP&#xff09; 表示層&#xff1a;程序和網絡之…

基于vue的地圖特效(飛線和標注)

這段代碼的主要功能是在頁面加載完成后&#xff0c;初始化一個 echarts 地圖圖表&#xff0c;并配置了相關的地理數據、散點數據、線條數據以及樣式效果&#xff0c;最后在指定的 div 元素中進行展示。 需要再vue中的框架實現&#xff0c;不能單獨直接運行。 標注 type: effe…

Python30 使用Gensim庫實現Word2Vec對文本進行處理

1.Word2Vec Word2Vec 是一種將詞語表示為向量的技術&#xff0c;能夠捕捉詞語之間的語義關系。它由 Google 的 Tomas Mikolov 等人在 2013 年提出&#xff0c;廣泛應用于自然語言處理任務中。其核心概念主要包括&#xff1a; 詞嵌入&#xff08;Word Embeddings&#xff09; …

使用昇騰芯片進行多卡訓推時使用hccl_tools.py為npu分配ip報錯問題解決辦法

目錄 問題描述問題產生原因解決辦法最終執行并驗證參考網站命令擴展 問題描述 昇騰芯片&#xff08;910b/310p等&#xff09;進行多卡訓練或者推理時需要先獲取并配置每張npu的ip信息&#xff0c;因此需要執行類似下面問題&#xff1a; python mindformers/tools/hccl_tools.…

[AI 大模型] Meta LLaMA-2

文章目錄 [AI 大模型] Meta LLaMA-2簡介模型架構發展新技術和優勢示例 [AI 大模型] Meta LLaMA-2 簡介 Meta LLaMA-2 是 Meta 推出的第二代開源大型語言模型&#xff08;LLM&#xff09;&#xff0c;旨在為研究和商業應用提供強大的自然語言處理能力。 LLaMA-2 系列模型包括從…

Python實現串口通信(Python+Stm32)詳解

Python實現串口通信&#xff08;PythonStm32&#xff09;詳解 引言 在現代的嵌入式系統開發和自動化控制中&#xff0c;串口通信是一種非常常見的通信方式。Python作為一種易于學習且功能強大的編程語言&#xff0c;結合Stm32微控制器&#xff0c;能夠實現高效、靈活的串口通…

Python29 Tensorflow的基本知識和使用

1. TensorFlow TensorFlow 是一個開源的機器學習框架&#xff0c;由 Google Brain 團隊開發。它用于數據流圖的計算&#xff0c;尤其擅長深度學習任務。在 TensorFlow 中&#xff0c;數據流圖&#xff08;Data Flow Graph&#xff09;是其核心概念之一&#xff0c;它定義了計算…

Blackbox AI : 全新的人工智能編碼助手 您的高效AI開發全能助手

&#x1f3ac; 鴿芷咕&#xff1a;個人主頁 &#x1f525; 個人專欄: 《C干貨基地》《粉絲福利》 ??生活的理想&#xff0c;就是為了理想的生活! 引入 提起AI 智能編碼助手&#xff0c;相信到了如今大家都不陌生。其對我們開發的代碼時的效率有顯著的提升&#xff0c;可以說…

效果驚人!LivePortrait開源數字人技術,讓靜態照片生動起來

不得了了,快手已經不是眾人所知的那個短視頻娛樂平臺了。 可靈AI視頻的風口尚未過去,又推出了LivePortrait--開源的數字人項目。LivePortrait讓你的照片動起來,合成逼真的動態人像視頻,阿里通義EMO不再是唯一選擇。 讓圖像動起來 LivePortrait 主要提供了對眼睛和嘴唇動作的…

Mattermost:一個強大的開源協作平臺

Mattermost是一個強大的開源協作平臺&#xff0c;基于云原生架構&#xff0c;為企業級用戶提供安全、可擴展且自托管的消息傳遞解決方案。 一、平臺特點 開源與定制性&#xff1a;Mattermost是一個開源項目&#xff0c;用戶可以根據自身需求定制界面、添加功能或擴展其功能&am…

[大師C語言(第四十一篇)]C語言指針數組與數組指針技術詳解

C語言中的指針和數組是兩個核心概念&#xff0c;它們在許多高級編程任務中扮演著重要角色。本文將深入探討C語言中的指針數組與數組指針&#xff0c;包括它們的基本概念、使用場景和技術細節。我們將通過詳細的解釋和實用的代碼案例來展示如何有效地使用這些技術。 第一部分&a…

matlab 卷積和多項式乘法

目錄 一、算法原理1、原理概述2、主要函數二、代碼實現1、通過卷積計算多項式乘法2、向量卷積3、卷積的中心部分三、參考鏈接一、算法原理 1、原理概述 兩個向量 u u u和 v v v的卷積,表示

大屏自適應容器組件 v-scale-screen

在vue中&#xff0c;v-scale-screen可用于大屏項目開發&#xff0c;實現屏幕自適應&#xff0c;可根據寬度自適應&#xff0c;高度自適應&#xff0c;和寬高等比例自適應&#xff0c;全屏自適應。 倉庫地址&#xff1a;github國內地址&#xff1a;gitee 一、安裝 npm instal…

qr 獲取當前路徑

qDebug() 函數在 Qt 應用程序中用于輸出調試信息。這些信息通常被發送到標準輸出&#xff08;stdout&#xff09;或標準錯誤&#xff08;stderr&#xff09;&#xff0c;具體取決于你的應用程序是如何配置的。在大多數開發環境中&#xff0c;你可以通過以下方式查看 qDebug() 輸…

React setState

老生常談之setState 是同步的還是異步的&#xff1f; 設想setState是同步的&#xff0c;那也就是每次調用setState都要進行新舊虛擬DOM的對比&#xff0c;然后將差異化的dom更新到頁面上&#xff0c;性能損耗很大 所以react把setState設置為了異步&#xff0c;當狀態更新時不…

【Unity2D 2022:Audio】添加游戲音樂和音效

一、添加背景音樂 1. 創建空的游戲物體&#xff0c;名為BackgroundMusic 2. 為音頻播放器添加音頻源&#xff08;Audio Source&#xff09;組件 3. 將背景音樂音頻賦值到AudioClip&#xff08;紅色&#xff09; 4. 設置循環播放&#xff08;藍色&#xff09; 二、添加草莓拾取…

springboot封裝請求參數json的源碼解析

源碼位置&#xff1a; org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver#readWithMessageConverters(org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type…

解答 | http和https的區別,誰更好用

TTP&#xff08;超文本傳輸協議&#xff09;和HTTPS&#xff08;安全超文本傳輸協議&#xff09;的主要區別在于安全性和數據傳輸的方式。 一、區別 1、協議安全性&#xff1a; HTTP&#xff1a;使用明文形式傳輸數據&#xff0c;不提供數據加密功能&#xff0c;數據在傳輸過…

coze搭建工作流和Agent

coze搭建工作流和Agent Agent LLM 記憶感知規劃使用工具 LLM是大語言模型&#xff0c;prompt提示詞影響LLM的輸出質量 描述需求——>背景——>解決思路&#xff0c;提示詞文檔。 當有明確的需求和實現需求的路徑時&#xff0c;可以通過搭建工作流來完成標準化任務為…