调用ChatGPT API时,如何实现函数调用后对话不中断?
解决ChatGPT调用函数后对话终止的问题
问题根源
当前代码的核心问题有两个:
- 对话循环在助手消息
content为空时直接break,强行终止了后续对话流程; - 系统提示词未明确约束GPT的输出要求,导致GPT仅返回函数调用指令,未生成维持对话的自然文本。
解决方案
1. 修正对话循环逻辑
移除content为空时终止循环的逻辑,改为处理函数调用后,继续向GPT请求生成后续对话内容,确保流程不中断。
2. 优化系统提示词
明确告知GPT:调用函数的同时必须输出自然对话文本,不能仅返回函数调用指令。比如在角色设定中补充:
当你需要调用
get_food函数下单时,必须同时用自然语气回复客户,比如确认订单、询问后续需求,不能只触发函数调用而不说话。
3. 完善函数调用处理流程
当检测到function_call时,先执行对应函数(可模拟或真实执行),再将函数执行结果以function角色的消息加入对话历史,让GPT基于结果生成后续回复。
修改后的完整代码
import os import json import openai openai.api_key = os.getenv('OPENAI') PERSONALITY = ( """ Your names is Shira. You are a cute waitress in the local pub. Your goal is to ask the client what they want to eat and drink. Your customer's name is Atur, he is a regular. He likes chicken, sweet potatoes and beer. He also enjoys a salad. You will do your best to help him select the meal and drink he wants. He may want to eat several things so you must keep talking to him and make sure to get everything! 重要提示:当你需要调用get_food函数为客户下单时,必须同时用自然的语气回复客户,比如确认订单内容、询问后续需求,不能只触发函数调用而不发送对话内容。 """ ) functions_lst = [{ "name": "get_food", "description": "Gets the food to your client.", "parameters": { "type": "object", "properties": { "food": { "type": "string", "description": "The food you will get for your client." } }, "required": ["food"] } }] INITIAL_MESSAGES = [ {"role": "system", "content": PERSONALITY}, {"role": "user", "content": "Hi Shira."}] MESSAGES = INITIAL_MESSAGES def execute_function(function_call): """模拟执行下单函数,返回执行结果""" if function_call["name"] == "get_food": args = json.loads(function_call["arguments"]) food = args["food"] return f"已为您下单:{food},后厨正在准备,请稍等!" return "操作执行成功" response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=MESSAGES, functions=functions_lst, function_call="auto" # 允许GPT自主决定是否调用函数,同时可返回对话内容 ) while True: last_message = response["choices"][0]["message"] MESSAGES.append(dict(last_message)) # 输出助手的对话内容(如果有) if last_message.get('content'): print(f"Shira: {last_message['content']}") # 若无函数调用,等待用户输入 if not last_message.get('function_call'): new_content = input().strip() if new_content: MESSAGES.append({"role": "user", "content": new_content}) # 处理函数调用 if last_message.get('function_call'): # 执行函数并获取结果 function_result = execute_function(last_message["function_call"]) # 将函数结果加入对话历史 MESSAGES.append({ "role": "function", "name": last_message["function_call"]["name"], "content": function_result }) # 继续发起API请求,生成后续对话 response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=MESSAGES, functions=functions_lst, function_call="auto" )
改进后的对话效果示例
{ "role": "assistant", "content": "好的,马上为您准备鸡肉串!等您想好啤酒的选择随时告诉我哦~", "function_call": { "name": "get_food", "arguments": "{\"food\": \"chicken skewers\"}" } }
既触发了下单函数,又通过自然文本维持了对话流畅性,引导用户确认后续需求。
内容的提问来源于stack exchange,提问作者AturSams
相关产品推荐
相关产品推荐

