上篇文章初步实现了生成笑话的流程,但是每次启动只能生成固定个数的笑话,且每次输出笑话还得等待api请求,限制太大,本次改进了方法,将获取回复和输出笑话并行执行。
from openai import OpenAI
from collections import deque
import time
import threading
api_key='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'
client = OpenAI(api_key=api_key)
with open(r"D:\\pythonCode\\prompt.txt", "r", encoding="UTF-8") as file:
system_message = file.read()
# 创建一个队列,存储ai回复
jokes_queue = deque()
# 用于保护队列的互斥锁
queue_lock = threading.Lock()
# 获得openAi回复
def get_ai_message(user_speaking):
try:
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": user_speaking},
],
n=3 # 生成5条回复
)
for choice in completion.choices:
jokes_queue.append(choice.message.content)
print("队列中的笑话数:"+len(jokes_queue))
except Exception as e:
print("获取AI回复时出现错误:"+str(e))
# 获取回复进行存储
def get_ai_message_thread():
while True:
get_ai_message("来一段笑话")
print(len(jokes_queue))
time.sleep(5)
# 输出笑话
def output_jokes_thread():
while True:
if len(jokes_queue) == 0:
print("笑话数不足,等待30s")
time.sleep(30)
continue
ai_message = jokes_queue.popleft()
print(ai_message+"\n"+"--------------------")
time.sleep(5)
# 创建并启动两个线程
get_ai_message_thread=threading.Thread(target=get_ai_message_thread)
output_jokes_thread=threading.Thread(target=output_jokes_thread)
get_ai_message_thread.start()
output_jokes_thread.start()
后续,我会思考如何改进prompt,还有思考如何更好的存储获取到的笑话回复,Java的话我会考虑存储到Redis中,Python 中的话得找个方案。
我制作了一个自己的机器人,感兴趣的可以去试试它的效果:https://poe.com/CleloJoker