要实现下次打开程序时自动填写上次对话时使用的API密钥和系统角色,可以使用Python的configparser模块来读取和写入配置文件。下面是修改后的代码:

import os
import configparser

# 创建配置文件
config = configparser.ConfigParser()
config_file = "config.ini"

# 检查配置文件是否存在
if not os.path.exists(config_file):
    config["DEFAULT"] = {
        "api_key": "",
        "system_message": "You are a helpful assistant."
    }
    with open(config_file, "w") as file:
        config.write(file)

# 从配置文件中读取API密钥和系统角色
config.read(config_file)
api_key_var = tk.StringVar(value=config["DEFAULT"]["api_key"])
system_message_var = tk.StringVar(value=config["DEFAULT"]["system_message"])

# ...

def get_response():
    # ...

    # 保存API密钥和系统角色到配置文件
    config.set("DEFAULT", "api_key", api_key_entry.get().strip())
    config.set("DEFAULT", "system_message", system_message_entry.get())
    with open(config_file, "w") as file:
        config.write(file)

    # ...

# ...

这样,程序会在每次点击发送消息按钮时,将API密钥和系统角色保存到配置文件中。下次打开程序时,会自动读取配置文件中的值并填充到相应的文本框中。

import tkinter as tkfrom tkinter import messagebox ttkimport openaiimport threading# 设置代理网址openaiapi_base = httpsapiopenai-proxycomv1def get_response # 获取用户输入 user_input = user_input_entryget

原文地址: http://www.cveoy.top/t/topic/jav9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录