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

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

相关推荐
天下无敌笨笨熊41 分钟前
ES作为向量库研究
大数据·python·elasticsearch
数据知道1 小时前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目
程序员爱钓鱼1 小时前
Python 编程实战 · 进阶与职业发展:数据分析与 AI(Pandas、NumPy、Scikit-learn)
后端·python·trae
软件开发技术深度爱好者1 小时前
Python库/包/模块管理工具
开发语言·python
程序员爱钓鱼1 小时前
Python 编程实战 · 进阶与职业发展:Web 全栈(Django / FastAPI)
后端·python·trae
郝学胜-神的一滴2 小时前
Python中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
机器人行业研究员2 小时前
六维力传感器和关节力传感器国产替代正当时:机器人“触觉神经”的角逐
机器人·自动化·人机交互·六维力传感器·关节力传感器
烤汉堡3 小时前
Python入门到实战:post请求和响应
python·html
夫唯不争,故无尤也3 小时前
Python广播机制:张量的影分身术
开发语言·python
流浪猪头拯救地球3 小时前
利用 Python 解密 / 加密 PDF 文件
python·pdf·php