使用DeepSeek建立一个智能聊天机器人0.07

进一步完善获取API密钥和DeepSeek的API端点,我们可以添加更多的错误处理和默认值设置,确保程序在各种情况下都能正常运行。同时,我们还可以提供一个更友好的用户界面,以便用户可以轻松地设置和查看配置信息。

以下是进一步完善的代码:

完善后的代码

python 复制代码
import tkinter as tk
from tkinter import scrolledtext, filedialog, messagebox
import requests
import os
import threading
import json

# 从环境变量中获取API密钥和DeepSeek的API端点
API_KEY = os.getenv('DEEPSEEK_API_KEY')
DEEPSEEK_API_URL = os.getenv('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat')

# 如果环境变量未设置,尝试从配置文件中读取
CONFIG_FILE = 'config.json'
if not API_KEY or not DEEPSEEK_API_URL:
    try:
        with open(CONFIG_FILE, 'r') as f:
            config = json.load(f)
            API_KEY = config.get('API_KEY', API_KEY)
            DEEPSEEK_API_URL = config.get('DEEPSEEK_API_URL', DEEPSEEK_API_URL)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        messagebox.showwarning("警告", f"配置文件加载失败: {str(e)}")
        API_KEY = ''
        DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat'

# 存储对话历史
conversation_history = []

def get_response(prompt):
    headers = {
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    }
    data = {
        'model': 'deepseek-7b',  # 使用的模型名称
        'messages': conversation_history + [{'role': 'user', 'content': prompt}],
        'max_tokens': 150  # 生成的最大token数
    }
    
    response = requests.post(DEEPSEEK_API_URL, json=data, headers=headers)
    if response.status_code == 200:
        model_response = response.json()['choices'][0]['message']['content']
        conversation_history.append({'role': 'user', 'content': prompt})
        conversation_history.append({'role': 'assistant', 'content': model_response})
        return model_response
    else:
        raise Exception(f"错误: {response.status_code}, {response.text}")

def send_message():
    user_input = entry.get()
    if user_input.strip():
        chat_log.config(state=tk.NORMAL)
        chat_log.insert(tk.END, f"你: {user_input}\n")
        chat_log.config(state=tk.DISABLED)
        
        # 在新线程中处理API请求
        threading.Thread(target=process_response, args=(user_input,)).start()
        
        entry.delete(0, tk.END)
        chat_log.yview(tk.END)

def process_response(user_input):
    try:
        response = get_response(user_input)
        chat_log.config(state=tk.NORMAL)
        chat_log.insert(tk.END, f"DeepSeek: {response}\n")
        chat_log.config(state=tk.DISABLED)
        chat_log.yview(tk.END)
    except Exception as e:
        chat_log.config(state=tk.NORMAL)
        chat_log.insert(tk.END, f"错误: {str(e)}\n")
        chat_log.config(state=tk.DISABLED)
        chat_log.yview(tk.END)

def on_closing():
    root.destroy()

def clear_conversation():
    global conversation_history
    conversation_history = []
    chat_log.config(state=tk.NORMAL)
    chat_log.delete(1.0, tk.END)
    chat_log.config(state=tk.DISABLED)

def load_config():
    file_path = filedialog.askopenfilename(filetypes=[("JSON files", "*.json")])
    if file_path:
        try:
            with open(file_path, 'r') as f:
                config = json.load(f)
                global API_KEY, DEEPSEEK_API_URL
                API_KEY = config.get('API_KEY', '')
                DEEPSEEK_API_URL = config.get('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat')
                chat_log.config(state=tk.NORMAL)
                chat_log.insert(tk.END, f"配置加载成功: API_KEY={API_KEY}, DEEPSEEK_API_URL={DEEPSEEK_API_URL}\n")
                chat_log.config(state=tk.DISABLED)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            chat_log.config(state=tk.NORMAL)
            chat_log.insert(tk.END, f"错误: {str(e)}\n")
            chat_log.config(state=tk.DISABLED)

def save_config():
    config = {
        'API_KEY': API_KEY,
        'DEEPSEEK_API_URL': DEEPSEEK_API_URL
    }
    file_path = filedialog.asksaveasfilename(defaultextension=".json", filetypes=[("JSON files", "*.json")])
    if file_path:
        try:
            with open(file_path, 'w') as f:
                json.dump(config, f, indent=4)
            chat_log.config(state=tk.NORMAL)
            chat_log.insert(tk.END, f"配置保存成功: {file_path}\n")
            chat_log.config(state=tk.DISABLED)
        except IOError as e:
            chat_log.config(state=tk.NORMAL)
            chat_log.insert(tk.END, f"错误: {str(e)}\n")
            chat_log.config(state=tk.DISABLED)

root = tk.Tk()
root.title("DeepSeek 聊天机器人")

# 设置窗口大小
root.geometry("600x400")

# 创建聊天记录区域
chat_log = scrolledtext.ScrolledText(root, wrap=tk.WORD, state=tk.DISABLED)
chat_log.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)

# 创建输入框
entry = tk.Entry(root, width=80)
entry.pack(pady=10, padx=10, side=tk.LEFT, fill=tk.X, expand=True)

# 创建发送按钮
send_button = tk.Button(root, text="发送", command=send_message)
send_button.pack(pady=10, padx=10, side=tk.RIGHT)

# 创建清除对话按钮
clear_button = tk.Button(root, text="清除对话", command=clear_conversation)
clear_button.pack(pady=10, padx=10, side=tk.RIGHT)

# 创建加载配置按钮
load_config_button = tk.Button(root, text="加载配置", command=load_config)
load_config_button.pack(pady=10, padx=10, side=tk.RIGHT)

# 创建保存配置按钮
save_config_button = tk.Button(root, text="保存配置", command=save_config)
save_config_button.pack(pady=10, padx=10, side=tk.RIGHT)

# 绑定关闭事件
root.protocol("WM_DELETE_WINDOW", on_closing)

# 启动主循环
root.mainloop()

改进点说明:

环境变量和配置文件:

从环境变量中获取API密钥和API端点。

如果环境变量未设置,尝试从配置文件(config.json)中读取。

配置文件 config.json 的示例格式如下:

json 复制代码
{
  "API_KEY": "your_api_key_here",
  "DEEPSEEK_API_URL": "https://api.deepseek.com/v1/chat"
}

如果配置文件不存在或格式错误,显示警告信息,并使用默认值。

错误处理:

添加了对配置文件读取错误的处理,确保程序在文件不存在或格式错误时能够继续运行。

在加载和保存配置文件时,捕获并显示可能的IO错误。

用户界面:

增加了一个"加载配置"按钮,方便用户在不修改代码的情况下更改API密钥和API端点。

增加了一个"保存配置"按钮,方便用户保存当前的配置信息。

使用 messagebox 显示警告信息,提高用户体验。

默认值设置:

如果环境变量和配置文件均未设置,使用默认的API端点。

希望这些改进能帮助你创建一个更完善、更灵活的聊天机器人应用!

相关推荐
52Hz11823 分钟前
二叉树理论、力扣94.二叉树的中序遍历、104.二叉树的最大深度、226.反转二叉树、101.对称二叉树
python·算法·leetcode
卖个几把萌28 分钟前
解决 Python 项目依赖冲突:使用 pip-tools 一键生成现代化的 requirements.txt
开发语言·python·pip
黎雁·泠崖31 分钟前
Java字符串入门:API入门+String类核心
java·开发语言·python
薛定e的猫咪34 分钟前
【ICRA 2025】面向杂技机器人的分阶段奖励塑形:一种约束多目标强化学习方法
人工智能·深度学习·机器学习·机器人
哈哈不让取名字1 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
程序员敲代码吗1 小时前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python
sunfove1 小时前
Python小游戏:在 2048 游戏中实现基于线性插值(Lerp)的平滑动画
开发语言·python·游戏
2501_944526421 小时前
Flutter for OpenHarmony 万能游戏库App实战 - 抽牌游戏实现
android·开发语言·python·flutter·游戏
副露のmagic1 小时前
python基础复健
python·算法
学Linux的语莫1 小时前
python项目打包为镜像
java·python·spring