在discord.py中编写重复对话逻辑有没有更高效的实现方式?
discord.py 对话流程循环优化方案
你原来的代码重复编写了3轮对话的相同逻辑,直接用循环替换重复段即可,同时还可以增加主动退出规则,优化后代码更易维护,调整对话轮次只需要修改循环参数即可。
完整优化后代码
@commands.command() async def start_conversation(self, ctx): # 初始对话prompt start_chat_log = '''以下是与名为Shem-Ha的AI助手的对话,Shem-Ha的人设是傲慢的女神。 人类:你好,你是谁? AI:我是Shem-Ha,你有什么事,人类? ''' chat_log = start_chat_log # 消息校验规则:仅响应当前频道、当前发起命令的用户的消息 def check(message: discord.Message): return message.channel == ctx.channel and message.author == ctx.author # 调用大模型获取回复 def ask(question, chat_log): prompt = f'{chat_log}人类:{question}\nAI:' response = completion.create( prompt=prompt, engine="davinci", stop=['\n'], temperature = 0.8, top_p = 1, frequency_penalty = 1, presence_penalty = 1, best_of = 1, max_tokens=128 ) return response.choices[0].text.strip() await ctx.send('我是Shem-Ha,你有什么事,人类?') # 配置对话参数:最多3轮对话,用户发"结束对话"可提前终止 max_round = 3 for _ in range(max_round): user_msg = await self.client.wait_for('message', check=check) # 主动退出逻辑,不需要可以直接删掉 if user_msg.content.strip() == "结束对话": await ctx.send("退下吧。") break ai_answer = ask(user_msg.content, chat_log) await ctx.send(ai_answer) # 更新对话日志 chat_log = f'{chat_log}人类:{user_msg.content}\nAI:{ai_answer}\n' await ctx.send('**对话结束**')
主要优化点
- 移除了重复的3轮对话硬编码逻辑,替换为循环实现,调整对话轮次仅需要修改
max_round参数即可 - 简化了
ask函数的冗余判断,直接传入实时更新的chat_log参数,不需要每次判断默认值 - 移除了冗余的
append_interaction_to_chat_log函数,直接在循环内更新对话日志,减少不必要的函数调用开销 - 可选增加了主动退出对话的触发规则,更符合实际使用需求
内容的提问来源于stack exchange,提问作者QOGLESBY97
相关产品推荐
相关产品推荐

