使用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端点。

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

相关推荐
liuhaoran___2 分钟前
解释区块链技术的应用场景和优势
python
独好紫罗兰4 分钟前
洛谷题单2-P5712 【深基3.例4】Apples-python-流程图重构
开发语言·python·算法
东方佑19 分钟前
深度解析Python-PPTX库:逐层解析PPT内容与实战技巧
开发语言·python·powerpoint
Python大数据分析@28 分钟前
python 常用的6个爬虫第三方库
爬虫·python·php
一顿操作猛如虎,啥也不是!36 分钟前
JAVA-Spring Boot多线程
开发语言·python
斯内科1 小时前
Python入门(7):Python序列结构-字典
python·字典·dictionary
云徒川1 小时前
【设计模式】过滤器模式
windows·python·设计模式
橘猫云计算机设计2 小时前
基于django优秀少儿图书推荐网(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·python·小程序·django·毕业设计
互联网杂货铺2 小时前
如何用Postman实现自动化测试?
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
予安灵2 小时前
一文详细讲解Python(详细版一篇学会Python基础和网络安全)
开发语言·python