少样本提示

使用 OpenAI API 的 Prompt Engineering

Fouad Trad

Machine Learning Engineer

少样本提示

  • 向模型提供示例(问答对)

一个少样本提示的可视化,展示示例问答以及需要模型回答的问题。

使用 OpenAI API 的 Prompt Engineering

少样本提示

  • 向模型提供示例(问答对)

一个示意图,展示如何向 LLM 发送少样本提示。

使用 OpenAI API 的 Prompt Engineering

少样本提示

  • 向模型提供示例(问答对)

一个示意图,展示如何向 LLM 发送少样本提示并获得回答。

使用 OpenAI API 的 Prompt Engineering

少样本提示

  • 向模型提供示例(问答对)

一个示意图,展示如何向 LLM 发送少样本提示并获得回答。

  • 示例数量:
    • 0 -> 零样本提示
    • 1 -> 单样本提示
    • 多于 1 -> 少样本提示
使用 OpenAI API 的 Prompt Engineering

零样本提示

  • 不提供示例的提示
  • 模型基于已有知识生成回答
  • 适合快速、简单的任务
prompt = "What is prompt engineering?"
print(get_response(prompt))
Prompt engineering refers to designing and refining prompts or instructions given 
to a language model like ChatGPT to elicit desired responses or behaviors. It 
involves formulating specific guidelines or hints to guide the model's output 
towards a desired outcome.
使用 OpenAI API 的 Prompt Engineering

单样本提示

  • 提供给模型一个示例
  • 适用于保持一致的格式或风格
prompt =  """ 
Q: Sum the numbers 3, 5, and 6. A: 3+5+6=14
Q: Sum the numbers 2, 4, and 7. A: 
"""
print(get_response(prompt))
2+4+7=13
使用 OpenAI API 的 Prompt Engineering

单样本提示

prompt = """
Q: Sum the numbers 3, 5, and 6. A: The sum of 3, 5, and 6 is 14
Q: Sum the numbers 2, 4, and 7. A: 
"""
print(get_response(prompt))
The sum of 2, 4, and 7 is 13
使用 OpenAI API 的 Prompt Engineering

少样本提示

  • 提供多个示例
  • 对情境化任务更强
prompt = """
Text: Today the weather is fantastic -> Classification: positive
Text: The furniture is small -> Classification: neutral
Text: I don't like your attitude -> Classification: negative

"""

使用 OpenAI API 的 Prompt Engineering

少样本提示

  • 提供多个示例
  • 适合情境化任务
prompt = """
Text: Today the weather is fantastic -> Classification: positive
Text: The furniture is small -> Classification: neutral
Text: I don't like your attitude -> Classification: negative
Text: That shot selection was awful -> Classification: 
"""
print(get_response(prompt))
negative
使用 OpenAI API 的 Prompt Engineering

使用聊天模型进行少样本提示

response = client.chat.completions.create(
  model = "gpt-4o-mini",

messages = [{"role": "user", "content": "Today the weather is fantastic"},
{"role": "assistant", "content": "positive"},
{"role": "user", "content": "I don't like your attitude"}, {"role": "assistant", "content": "negative"},
{"role": "user", "content": "That shot selection was awful"} ], temperature = 0 )
print(response.choices[0].message.content)
negative
使用 OpenAI API 的 Prompt Engineering

注意事项

  • 根据任务复杂度选择示例数量
    • 少量示例 -> 基础任务
    • 多样示例 -> 复杂任务

一张显示自我提问者的图片。

使用 OpenAI API 的 Prompt Engineering

¡Vamos a practicar!

使用 OpenAI API 的 Prompt Engineering

Preparing Video For Download...