当前位置:   article > 正文

2023.12.12最新源码及资源:使用Python构建与百度大模型(包括文心一言在内的18个语言模型)的交互式界面!!_python大模型 微调 界面

python大模型 微调 界面

#ps:12.12修复bug,部分模型不能回应的问题,资源已更新!

    在当前人工智能领域,通过与机器进行智能对话的能力变得越来越重要。本文将介绍如何使用Python编程语言和Tkinter库构建一个交互式界面,使用户能够与百度大模型进行智能对话,展示了人机交互的潜力与未来发展。

与百度API通信过程

通过百度的API,代码可以获取访问令牌,并将用户输入的消息发送给百度大模型。模型返回的结果通过JSON格式解析,最终在界面上显示。

用户界面构建

使用Tkinter库构建了一个简单但功能完善的用户界面,其中包括输入API密钥的文本框、模型选择的下拉菜单、参数设置的输入框以及聊天历史记录的显示。

聊天功能实现细节

用户可以在输入框中键入消息,通过“发送消息”按钮发送给百度大模型。模型返回的消息将会显示在界面上,并且整个对话历史都会保留在界面上。同时,添加了保存对话消息的功能,让用户随时保存他们感兴趣的对话记录。

效果如图:

加载和保存配置文件功能

利用config.json文件,实现了用户配置参数的读取和保存。这确保了用户下次启动应用时能够继续使用先前的参数,如图:

如上软件集成了百度大模型的18个模型,其中有5个模型正在限时免费使用,快去注册登录获取属于自己的API密钥开启对话吧!!!

步骤如下:百度智能云千帆大模型平台

 

 

软件资源:

已更新!百度大模型软件大小9.3MB,百度网盘下载地址如下,永久有效:

百度大模型​icon-default.png?t=N7T8https://pan.baidu.com/share/init?surl=Ojs0W00E0L5pteGqPPpecw&pwd=6666

代码功能概述:

代码实现了以下主要功能:

  • 加载和保存配置文件: 提供了一种方法,使用户可以保存他们的API密钥和其他参数,以便于下次使用。
  • 与百度API通信: 通过百度的API,代码能够将用户的输入发送给百度大模型,并获取模型的回复。
  • 构建用户界面: 使用Tkinter库,创建了一个简单的用户界面,包括API密钥输入、模型选择、参数设置和聊天历史记录显示和清除等功能。
  • 实现聊天功能: 用户可以在界面上输入文本消息并发送给模型,模型将生成回复并显示在界面上。同时,还添加了保存对话消息的功能。

源码如下,可以根据注释和需求自行改进:

  1. import datetime
  2. import threading
  3. import tkinter as tk
  4. from tkinter.scrolledtext import ScrolledText
  5. from tkinter import ttk
  6. import requests
  7. import json
  8. import os
  9. CONFIG_FILE = "config.json"
  10. BACKGROUND_COLOR = "#D0E0F0"
  11. TEXT_COLOR = "#000000"
  12. BUTTON_COLOR = "#AEC6CF"
  13. ENTRY_BG = "#F0F8FF"
  14. FONT = ("Arial", 10)
  15. # 加载配置文件
  16. def load_config():
  17. default_config = {
  18. "API_KEY": "",
  19. "SECRET_KEY": "",
  20. "temperature": 0.9,
  21. "top_p": 0.7,
  22. "penalty_score": 1.0,
  23. "system": "You are a helpful assistant",
  24. "selected_model": "ERNIE-Bot-turbo"
  25. }
  26. if os.path.exists(CONFIG_FILE):
  27. with open(CONFIG_FILE, "r") as file:
  28. config = json.load(file)
  29. default_config.update(config)
  30. return default_config
  31. else:
  32. return default_config
  33. # 保存所有配置
  34. def save_config(api_key, secret_key, selected_model, temperature, top_p, penalty_score, system):
  35. with open(CONFIG_FILE, "w") as file:
  36. config = {
  37. "API_KEY": api_key,
  38. "SECRET_KEY": secret_key,
  39. "selected_model": selected_model,
  40. "temperature": temperature,
  41. "top_p": top_p,
  42. "penalty_score": penalty_score,
  43. "system": system
  44. }
  45. json.dump(config, file)
  46. def get_access_token(api_key, secret_key):
  47. url = "https://aip.baidubce.com/oauth/2.0/token"
  48. params = {"grant_type": "client_credentials", "client_id": api_key, "client_secret": secret_key}
  49. return str(requests.post(url, params=params).json().get("access_token"))
  50. # 在 chat_with_bot 函数中添加参数,从配置文件读取相应的值
  51. def chat_with_bot(prompt, api_key, secret_key, model_url, temperature, top_p, penalty_score, system):
  52. access_token = get_access_token(api_key, secret_key)
  53. url = f"https://aip.baidubce.com{model_url}?access_token={access_token}"
  54. payload = json.dumps({
  55. "messages": [{"role": "user", "content": prompt}], #部分模型必要输入参数,1.最后一个message的content长度(即此轮对话的问题)不能超过4800个字符,且不能超过2000 tokens.2.messages中content总长度大于4800个字符或2000 tokens,系统会依次遗忘最早的历史会话,直到content的总长度不超过4800个字符且不超过2000 tokens
  56. "stream": True, #流式输出
  57. "temperature": temperature, #(1)较高的数值会使输出更加随机,而较低的数值会使其更加集中和确定(2)默认0.8,范围 (0, 1.0],不能为03)建议该参数和top_p只设置1个(4)建议top_p和temperature不要同时更改
  58. "top_p": top_p, #(1)影响输出文本的多样性,取值越大,生成文本的多样性越强(2)默认0.8,取值范围 [0, 1.0](3)建议该参数和temperature只设置1个(4)建议top_p和temperature不要同时更改
  59. "penalty_score": penalty_score, #通过对已生成的token增加惩罚,减少重复生成的现象。说明:(1)值越大表示惩罚越大(2)默认1.0,取值范围:[1.0, 2.0]
  60. "system": system, #模型人设,主要用于人设设定,例如,你是xxx公司制作的AI助手,长度限制1024个字符
  61. "extra_parameters": {
  62. "use_keyword": True,
  63. "use_reference": True
  64. }, #Chatlaw必要参数第三方大模型推理高级参数,依据第三方大模型厂商不同而变化
  65. "prompt": prompt, #部分模型必要输入参数,请求信息
  66. })
  67. headers = {'Content-Type': 'application/json'}
  68. response = requests.post(url, headers=headers, data=payload, stream=True)
  69. replies = []
  70. for line in response.iter_lines():
  71. if line:
  72. line_str = line.decode('utf-8')
  73. if line_str.startswith('data: '):
  74. try:
  75. json_str = line_str[6:]
  76. data = json.loads(json_str)
  77. if 'result' in data and data['result']:
  78. replies.append(data['result'])
  79. except json.JSONDecodeError as e:
  80. print("JSON decoding error:", e)
  81. return "\n".join(replies).replace("\n", "")
  82. # 传递参数
  83. def send_message(event=None):
  84. api_key = api_key_entry.get()
  85. secret_key = secret_key_entry.get()
  86. user_input = user_input_entry.get("1.0", "end-1c")
  87. selected_model = model_var.get()
  88. if user_input and api_key and secret_key and selected_model:
  89. # 从配置文件加载参数
  90. config = load_config()
  91. temperature = config["temperature"]
  92. top_p = config["top_p"]
  93. penalty_score = config["penalty_score"]
  94. system = config["system"]
  95. # 创建一个新的线程来执行聊天请求,避免卡死
  96. chat_thread = threading.Thread(target=perform_chat,
  97. args=(user_input, api_key, secret_key, model_urls[selected_model],
  98. temperature, top_p, penalty_score, system))
  99. chat_thread.start()
  100. user_input_entry.delete("1.0", tk.END)
  101. # 执行聊天请求
  102. def perform_chat(user_input, api_key, secret_key, model_url, temperature, top_p, penalty_score, system):
  103. response = chat_with_bot(user_input, api_key, secret_key, model_url, temperature, top_p, penalty_score, system)
  104. update_chat_history("You: " + user_input + "\n" + "Bot: " + response + "\n\n")
  105. # 更新对话消息
  106. def update_chat_history(message):
  107. chat_history.config(state=tk.NORMAL)
  108. chat_history.insert(tk.END, message)
  109. chat_history.config(state=tk.DISABLED)
  110. chat_history.yview(tk.END)
  111. # 保存对话消息
  112. def save_chat_history_with_timestamp():
  113. """
  114. Save the chat history to a text file with a timestamp in the file name.
  115. """
  116. chat_content = chat_history.get("1.0", tk.END).strip()
  117. if chat_content:
  118. timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
  119. filename = f"chat_history_{timestamp}.txt"
  120. with open(filename, "w") as file:
  121. file.write(chat_content)
  122. # 关闭脚本时保存配置并输出对话消息
  123. def on_closing():
  124. api_key = api_key_entry.get()
  125. secret_key = secret_key_entry.get()
  126. selected_model = model_var.get()
  127. temperature = float(temperature_entry.get())
  128. top_p = float(top_p_entry.get())
  129. penalty_score = float(penalty_score_entry.get())
  130. system = system_entry.get()
  131. save_config(api_key, secret_key, selected_model, temperature, top_p, penalty_score, system)
  132. chat_content = chat_history.get("1.0", tk.END)
  133. save_chat_history_with_timestamp()
  134. root.destroy()
  135. # 隐藏密码,保护隐私
  136. def toggle_show_hide(entry, show):
  137. entry.config(show="" if show.get() else "*")
  138. # 获取对应消息
  139. def get_last_message():
  140. """
  141. Get the last user message and bot response from the chat history.
  142. """
  143. content = chat_history.get("1.0", tk.END).strip().split("\n")
  144. last_user_message = ""
  145. last_bot_response = ""
  146. for line in content:
  147. if line.startswith("You: "):
  148. last_user_message = line[len("You: "):]
  149. elif line.startswith("Bot: "):
  150. last_bot_response = line[len("Bot: "):]
  151. return last_user_message, last_bot_response
  152. # 复制消息
  153. def copy_to_clipboard(text):
  154. """
  155. Copy a given text to the system clipboard.
  156. """
  157. root.clipboard_clear()
  158. root.clipboard_append(text)
  159. # 复制用户消息
  160. def copy_user_message():
  161. user_message, _ = get_last_message()
  162. copy_to_clipboard(user_message)
  163. #复制bot消息
  164. def copy_bot_response():
  165. _, bot_response = get_last_message()
  166. copy_to_clipboard(bot_response)
  167. # 发送后清空输出
  168. def clear_input():
  169. """
  170. Clear the user input field.
  171. """
  172. user_input_entry.delete("1.0", tk.END)
  173. chat_history.config(state=tk.NORMAL)
  174. chat_history.delete("1.0", tk.END)
  175. chat_history.config(state=tk.DISABLED)
  176. #保存配置
  177. def save_configurations():
  178. """
  179. Save the current API Key and Secret Key to the configuration file.
  180. """
  181. api_key = api_key_entry.get()
  182. secret_key = secret_key_entry.get()
  183. selected_model = model_var.get()
  184. save_config(api_key, secret_key,selected_model)
  185. # 加载配置
  186. config = load_config()
  187. # 设置应用窗口
  188. root = tk.Tk()
  189. root.title("百度大模型(18个模型,其中5个模型官方限时免费,速来体验!!!)")
  190. root.geometry("650x700")
  191. root.configure(bg=BACKGROUND_COLOR)
  192. root.protocol("WM_DELETE_WINDOW", on_closing)
  193. # API Key输入框
  194. api_key_label = tk.Label(root, text="API Key", bg=BACKGROUND_COLOR, font=FONT)
  195. api_key_label.grid(row=0, column=0, padx=10, pady=(10, 0), sticky="w")
  196. api_key_entry = tk.Entry(root, width=40, font=FONT, bg=ENTRY_BG, show="*")
  197. api_key_entry.insert(0, config["API_KEY"])
  198. api_key_entry.grid(row=0, column=1, padx=10, pady=5, columnspan=2)
  199. # 隐藏API Key
  200. show_api_key = tk.BooleanVar(value=False)
  201. api_key_toggle = tk.Checkbutton(root, text="Show", variable=show_api_key, command=lambda: toggle_show_hide(api_key_entry, show_api_key), bg=BACKGROUND_COLOR, font=FONT)
  202. api_key_toggle.grid(row=0, column=2, sticky="w")
  203. # Secret Key输入框
  204. secret_key_label = tk.Label(root, text="Secret Key", bg=BACKGROUND_COLOR, font=FONT)
  205. secret_key_label.grid(row=1, column=0, padx=10, pady=(10, 0), sticky="w")
  206. secret_key_entry = tk.Entry(root, width=40, font=FONT, bg=ENTRY_BG, show="*")
  207. secret_key_entry.insert(0, config["SECRET_KEY"])
  208. secret_key_entry.grid(row=1, column=1, padx=10, pady=5, columnspan=2)
  209. # 隐藏Secret Key
  210. show_secret_key = tk.BooleanVar(value=False)
  211. secret_key_toggle = tk.Checkbutton(root, text="Show", variable=show_secret_key, command=lambda: toggle_show_hide(secret_key_entry, show_secret_key), bg=BACKGROUND_COLOR, font=FONT)
  212. secret_key_toggle.grid(row=1, column=2, sticky="w")
  213. # 模型网址
  214. model_urls = {
  215. "ERNIE-Bot-turbo": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant",
  216. "ERNIE-Bot": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions",
  217. "ERNIE-Bot-4.0": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro",
  218. "ERNIE-Bot-8k": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k",
  219. "ERNIE-Bot-turbo-AI原生应用工作台": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ai_apaas",
  220. "BLOOMZ-7B": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/bloomz_7b1",
  221. "Qianfan-BLOOMZ-7B-compressed": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/qianfan_bloomz_7b_compressed",
  222. "Llama-2-7b-chat": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/llama_2_7b",
  223. "Llama-2-13b-chat": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/llama_2_13b",
  224. "Llama-2-70b-chat": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/llama_2_70b",
  225. "Qianfan-Chinese-Llama-2-7B": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/qianfan_chinese_llama_2_7b",
  226. "Qianfan-Chinese-Llama-2-13B(free)": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/qianfan_chinese_llama_2_13b",
  227. "ChatGLM2-6B-32K": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/chatglm2_6b_32k",
  228. "XuanYuan-70B-Chat-4bit(free)": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/xuanyuan_70b_chat",
  229. "ChatLaw(free)": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/chatlaw",
  230. "AquilaChat-7B": "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/aquilachat_7b",
  231. "SQLCoder-7B(free)": "/rpc/2.0/ai_custom/v1/wenxinworkshop/completions/sqlcoder_7b",
  232. "CodeLlama-7b-Instruct(free)": "/rpc/2.0/ai_custom/v1/wenxinworkshop/completions/codellama_7b_instruct",
  233. }
  234. # 设置模型及默认数值
  235. model_var = tk.StringVar(value=config["selected_model"])
  236. model_label = tk.Label(root, text="Selected model(选择模型)", bg=BACKGROUND_COLOR, font=FONT)
  237. model_label.grid(row=2, column=0, padx=10, pady=(10, 0), sticky="w")
  238. model_combobox = ttk.Combobox(root, textvariable=model_var, values=list(model_urls.keys()), state="readonly",width=29)
  239. model_combobox.grid(row=2, column=1, padx=10, pady=5,columnspan=1)
  240. # 温度输入框
  241. temperature_label = tk.Label(root, text="Temperature(温度)", bg=BACKGROUND_COLOR, font=FONT)
  242. temperature_label.grid(row=3, column=0, padx=10, pady=(10, 0), sticky="w")
  243. temperature_entry = tk.Entry(root, width=15, font=FONT, bg=ENTRY_BG)
  244. temperature_entry.insert(0, config["temperature"])
  245. temperature_entry.grid(row=3, column=1, padx=10, pady=5, columnspan=1)
  246. # 核采样输入框
  247. top_p_label = tk.Label(root, text="Top P(核采样)", bg=BACKGROUND_COLOR, font=FONT)
  248. top_p_label.grid(row=4, column=0, padx=10, pady=(10, 0), sticky="w")
  249. top_p_entry = tk.Entry(root, width=15, font=FONT, bg=ENTRY_BG)
  250. top_p_entry.insert(0, config["top_p"])
  251. top_p_entry.grid(row=4, column=1, padx=10, pady=5, columnspan=1)
  252. # 处罚成绩输入框
  253. penalty_score_label = tk.Label(root, text="Penalty Score(处罚成绩)", bg=BACKGROUND_COLOR, font=FONT)
  254. penalty_score_label.grid(row=5, column=0, padx=10, pady=(10, 0), sticky="w")
  255. penalty_score_entry = tk.Entry(root, width=15, font=FONT, bg=ENTRY_BG)
  256. penalty_score_entry.insert(0, config["penalty_score"])
  257. penalty_score_entry.grid(row=5, column=1, padx=10, pady=5, columnspan=1)
  258. # 系统角色输入框
  259. system_label = tk.Label(root, text="System role(系统角色)", bg=BACKGROUND_COLOR, font=FONT)
  260. system_label.grid(row=6, column=0, padx=10, pady=(10, 0), sticky="w")
  261. system_entry = tk.Entry(root, width=45, font=FONT, bg=ENTRY_BG)
  262. system_entry.insert(0, config["system"])
  263. system_entry.grid(row=6, column=1, padx=10, pady=5, columnspan=2)
  264. # 创建一个历史对话消息框
  265. chat_history = ScrolledText(root, state='disabled', width=85, height=15, bg=ENTRY_BG, font=FONT)
  266. chat_history.grid(row=8, column=0, columnspan=3, padx=10, pady=10,sticky="w")
  267. # 用户输入框
  268. user_input_entry = tk.Text(root, height=3, width=80, bd=3, font=("Arial", 10), bg="white")
  269. user_input_entry.grid(row=10, column=0, padx=10, pady=5, columnspan=2)
  270. user_input_entry.bind("<Return>", lambda event: send_message())
  271. # 发送按钮
  272. send_button = tk.Button(root, text="发送消息", command=send_message, bg=BUTTON_COLOR, font=FONT,width=33)
  273. send_button.grid(row=11, column=0, padx=10, pady=10,sticky="nsew",columnspan=1)
  274. # 清空按钮
  275. clear_button = tk.Button(root, text="清空输入", command=clear_input, bg=BUTTON_COLOR, font=FONT)
  276. clear_button.grid(row=11, column=1, padx=10, pady=5, sticky="nsew", columnspan=1)
  277. # 保存消息按钮
  278. save_with_timestamp_button = tk.Button(root, text="保存对话", command=save_chat_history_with_timestamp, bg=BUTTON_COLOR, font=FONT)
  279. save_with_timestamp_button.grid(row=12, column=0, padx=10, pady=10, sticky="nsew", columnspan=1)
  280. # 保存配置按钮
  281. save_config_button = tk.Button(root, text="保存配置", command=save_configurations, bg=BUTTON_COLOR, font=FONT)
  282. save_config_button.grid(row=12, column=1, padx=10, pady=10, sticky="nsew", columnspan=1)
  283. # 复制用户消息按钮
  284. copy_user_message_button = tk.Button(root, text="复制用户消息", command=copy_user_message, bg=BUTTON_COLOR, font=FONT)
  285. copy_user_message_button.grid(row=13, column=0, padx=5, pady=5,sticky="nsew")
  286. # 复制bot信息按钮
  287. copy_bot_response_button = tk.Button(root, text="复制bot消息", command=copy_bot_response, bg=BUTTON_COLOR, font=FONT)
  288. copy_bot_response_button.grid(row=13, column=1, padx=5, pady=5,sticky="nsew")
  289. # 全局定义用户/bot消息
  290. last_user_message = ""
  291. last_bot_response = ""
  292. root.mainloop()

本文展示了如何使用Python和Tkinter库构建一个简单但功能强大的交互式界面,使用户能够与百度大模型进行智能对话,并提供了保存对话消息的功能。通过对代码的解析和功能概述,读者可以更好地了解这个项目的意义和实现细节,并在人机交互领域中探索更多可能性。

感谢各位朋友们阅读,下期再见!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/94321
推荐阅读
相关标签
  

闽ICP备14008679号