如何将上下文学习的Completions API输入转换为Chat Completions API格式?
将上下文学习Prompt转换为Chat Completions API兼容格式
Chat Completions API的输入核心是messages数组,每个元素包含role(可选值:system、user、assistant)和content字段。我们可以把原Prompt拆分到对应角色中,让模型更清晰地理解任务约束与请求:
拆分逻辑
- system角色:存放核心规则、任务目标与约束条件,定义模型的行为模式。
- user角色:存放示例数据与当前待处理的输入请求,作为具体任务内容。
完整Python代码示例
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ { "role": "system", "content": """你是一个能根据输入序列预判动作的智能助手。执行动作的人是右利手。你只能选择示例中出现过的动作。每个动作都用方括号包裹,例如['Pick', 'cucumber_attachment']或['Cut cucumber_attachment with knife_black']。 请按任意有效顺序完成以下动作: ['RollOut dough'] ['Open milk_small'] ['Pour milk_small into mixing_bowl_green'] ['Pour flour from cup_small into mixing_bowl_green'] 或 ['Scoop flour from cup_small into mixing_bowl_green'] ['Scoop mixed contents from mixing_bowl_green into cup_large'] ['End']""" }, { "role": "user", "content": """以下是示例: Sequence = [['Pick', 'milk_small'], ['Open milk_small'], ['Place', 'milk_small_lid'], ['Pick', 'mixing_bowl_green'], ['Pour milk_small into mixing_bowl_green'], ['Place', 'mixing_bowl_green'], ['Place', 'milk_small'], ['Pick', 'tablespoon'], ['Pick', 'cup_small'], ['Scoop flour from cup_small into mixing_bowl_green'], ['Place', 'tablespoon'], ['Place', 'cup_small'], ['Pick', 'egg_whisk'], ['Pick', 'cup_large'], ['Place', 'cup_large'], ['Pick', 'mixing_bowl_green'], ['Stir contents of mixing_bowl_green'], ['Place', 'egg_whisk'], ['Pick', 'ladle'], ['Scoop mixed contents from mixing_bowl_green into cup_large'], ['Place', 'ladle'], ['Place', 'mixing_bowl_green'], ['Pick', 'rolling_pin'], ['RollOut dough'], ['Place', 'rolling_pin'], ['End']] Sequence = [['Pick', 'rolling_pin'], ['RollOut dough'], ['Place', 'rolling_pin'], ['Pick', 'tablespoon'], ['Pick', 'cup_small'], ['Scoop flour from cup_small into mixing_bowl_green'], ['Place', 'tablespoon'], ['Place', 'cup_small'], ['Pick', 'milk_small'], ['Open milk_small'], ['Pour milk_small into mixing_bowl_green'], ['Close milk_small_lid'], ['Pick', 'milk_small'], ['Place', 'milk_small'], ['Pick', 'egg_whisk'], ['Stir contents of mixing_bowl_green'], ['Place', 'egg_whisk'], ['Pick', 'ladle'], ['Pick', 'mixing_bowl_green'], ['Place', 'mixing_bowl_green'], ['Pick', 'cup_large'], ['Place', 'cup_large'], ['Scoop mixed contents from mixing_bowl_green into cup_large'], ['Place', 'ladle'], ['End']] 现在,请预判以下输入对应的动作: Input = [['Pick', 'milk_small']]""" } ] ) print(response.choices[0].message.content)
关键说明
- 这种拆分方式符合Chat模型的对话设计逻辑,system消息确立模型的行为边界,user消息传递具体任务数据。
- 如果需要多轮交互,可以继续在messages数组中追加assistant(模型回复)和user(新请求)的消息对。
内容的提问来源于stack exchange,提问作者Kong
相关产品推荐
相关产品推荐

