使用 OpenAI API 生成幽默笑话(二)

上篇文章初步实现了生成笑话的流程,但是每次启动只能生成固定个数的笑话,且每次输出笑话还得等待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

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值