You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
djangoBlogStudy/src/servermanager/api/commonapi.py

141 lines
4.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import logging
import os
import openai
from servermanager.models import commands
#wjl# 获取当前模块的 logger用于记录日志
logger = logging.getLogger(__name__)
#wjl# 从环境变量中读取 OpenAI API 密钥
openai.api_key = os.environ.get('OPENAI_API_KEY')
#wjl# 如果设置了 HTTP 代理,则配置 openai 库使用该代理
if os.environ.get('HTTP_PROXY'):
openai.proxy = os.environ.get('HTTP_PROXY')
class ChatGPT:
#wjl
"""
封装与 OpenAI 的 ChatGPT 模型进行交互的功能。
提供静态方法 `chat` 用于发送用户提示并获取模型回复。
"""
@staticmethod
def chat(prompt):
# wjl
"""
调用 OpenAI 的 GPT-3.5 Turbo 模型生成回复。
参数:
prompt (str): 用户输入的提示文本(问题或请求)。
返回:
str: 模型生成的回复内容;如果调用失败,则返回错误提示。
流程:
1. 使用 openai.ChatCompletion.create 发起请求,指定模型为 "gpt-3.5-turbo"
2. 将用户提示作为 role="user" 的消息发送。
3. 提取并返回模型返回的第一条消息内容。
4. 如果发生异常(如网络错误、认证失败等),记录错误日志并返回友好提示。
"""
try:
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo", #wjl# 使用 GPT-3.5 Turbo 模型
messages=[{"role": "user", "content": prompt}] #wjl# 构造对话消息
)
return completion.choices[0].message.content #wjl# 返回模型生成的文本
except Exception as e:
logger.error(e) #wjl# 记录异常信息到日志
return "服务器出错了" #wjl # 返回用户友好的错误提示
class CommandHandler:
# wjl
"""
命令处理器类,用于管理、查找和执行预定义的系统命令。
从数据库加载命令列表,支持通过名称查找并执行命令,以及获取帮助信息。
"""
def __init__(self):
# wjl
"""
初始化 CommandHandler 实例。
从数据库中加载所有预定义的命令对象,存储在实例变量 self.commands 中。
"""
self.commands = commands.objects.all() #wjl# 查询数据库中所有命令记录
def run(self, title):
# wjl
"""
根据命令标题查找并执行对应的系统命令。
参数:
title (str): 用户输入的命令标题。
返回:
str: 命令执行后的输出结果;如果未找到命令,则返回帮助提示。
流程:
1. 在 self.commands 列表中查找 title忽略大小写匹配的命令。
2. 如果找到匹配的命令,调用私有方法 __run_command__ 执行其对应的操作。
3. 如果未找到,则返回提示信息,引导用户输入 'hepme' 获取帮助。
"""
cmd = list(
filter(
lambda x: x.title.upper() == title.upper(), #wjl# 忽略大小写比较
self.commands))
if cmd:
return self.__run_command__(cmd[0].command) #wjl# 执行找到的命令
else:
return "未找到相关命令请输入hepme获得帮助。"
def __run_command__(self, cmd):
# wjl
"""
执行给定的系统命令shell 命令)。
参数:
cmd (str): 要执行的系统命令字符串。
返回:
str: 命令执行的标准输出;如果执行出错,则返回错误提示。
说明:
使用 os.popen 打开一个管道来执行命令,并读取其输出。
捕获所有异常(包括执行失败、权限问题等),防止程序崩溃。
"""
try:
res = os.popen(cmd).read() #wjl# 执行命令并读取输出
return res
except BaseException:
return '命令执行出错!'
def get_help(self):
# wjl
"""
生成帮助信息,列出所有可用的命令及其描述。
返回:
str: 格式化的帮助文本,每行包含一个命令的标题和描述,用冒号分隔。
说明:
遍历 self.commands 中的所有命令,拼接成一个字符串,用于向用户展示可用命令。
"""
rsp = ''
for cmd in self.commands:
rsp += '{c}:{d}\n'.format(c=cmd.title, d=cmd.describe) #wjl# 拼接命令帮助信息
return rsp
if __name__ == '__main__':
# wjl
"""
主程序入口,用于测试 ChatGPT 类的功能。
创建 ChatGPT 实例,发送一个测试提示,并打印模型回复。
"""
chatbot = ChatGPT()
prompt = "写一篇1000字关于AI的论文"
print(chatbot.chat(prompt))