Telegram+ChatGPT机器人响应与输入提示无关问题求助
Telegram机器人调用OpenAI返回重复混乱响应的问题
我开发了一款可根据用户提示生成回复的Telegram机器人,虽能正常运行,但返回的响应异常且与输入提示无关。例如发送指令/text hello, how are you?后,机器人返回了重复且混乱的内容:?”“I’m good. How are you?”“I’m good.”等重复语句。我尝试更换不同引擎、调整参数但问题依旧,相关代码如下:
import telegram from telegram.ext import Updater, CommandHandler import re import openai # Initialize the Telegram Bot bot = telegram.Bot(token='hidden') # Initialize the OpenAI API openai.api_key = "hidden" # Define the command handler def text_handler(update, context): # Get the input text from the user input_text = update.message.text # Extract the prompt from the input text prompt = re.sub('/text', '', input_text).strip() # Generate response using OpenAI response = openai.Completion.create( engine="davinci", prompt=prompt, max_tokens=100, n=1, stop=None, temperature=0.4, ) # Get the generated text from the response generated_text = response.choices[0].text.strip() # Send the generated text back to the user update.message.reply_text(generated_text) # Create an Updater object and attach the command handler to it updater = Updater(token='hidden', use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('text', text_handler)) # Start the bot updater.start_polling()
请问有人遇到过类似问题吗?
问题分析与解决方案
1. 优化Prompt的对话格式
旧版Completion模型(如davinci)对prompt的上下文边界敏感,无明确角色标识时容易重复生成内容。给prompt添加清晰的对话角色分隔,引导模型生成符合预期的回复:
user_input = re.sub('/text', '', input_text).strip() prompt = f"User: {user_input}\nAssistant:"
2. 设置终止生成的Stop序列
通过stop参数指定生成终止标记,避免模型无限制重复输出:
response = openai.Completion.create( engine="davinci", prompt=prompt, max_tokens=100, n=1, stop=["\n", "User:"], # 遇到换行或User标识时停止生成 temperature=0.4, )
3. 移除冗余代码
代码中bot = telegram.Bot(token='hidden')属于冗余初始化,Updater已完成Bot实例的创建,可直接删除该行。
4. 切换到Chat Completion接口(推荐)
OpenAI官方已推荐使用针对对话场景优化的Chat Completion接口(如gpt-3.5-turbo),这类接口更不容易出现重复输出问题,调整后的代码示例:
def text_handler(update, context): input_text = update.message.text user_input = re.sub('/text', '', input_text).strip() response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": user_input} ], temperature=0.6 ) generated_text = response.choices[0].message['content'].strip() update.message.reply_text(generated_text)
5. 调整Temperature参数
温度值过低(如0.4)会导致模型生成内容保守重复,可尝试将温度调整至0.6-0.8区间,平衡生成内容的多样性与准确性。
内容的提问来源于stack exchange,提问作者stangielen2
相关产品推荐
相关产品推荐

