【Prompting】ChatGPT Prompt Engineering开发指南(6)

该教程介绍了如何使用ChatGPT的PromptEngineering来生成针对客户电子邮件的定制回复。第一部分涉及根据客户评论创建个性化邮件,第二部分展示了如何扩展对话以适应特定任务。通过情绪分析和引用电子邮件的详细信息,自动回复能更准确地回应客户。此外,还展示了如何构建聊天机器人,以专业且简洁的风格进行交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在本教程中,第一部分学习生成客户服务电子邮件,这些电子邮件是根据每个客户的评论量身定制的。第二部分将探索如何利用聊天格式与针对特定任务或行为进行个性化或专门化的聊天机器人进行扩展对话。

注意:基本环境设置与前文保持一致,请参考设置。这里适当修改一下get_completion()函数:

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def get_completion(prompt, model="gpt-3.5-turbo", temperature = 0):
    messages = [{'role': 'user', 'content': prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        max_tokens=1024,
        n=1,
        temperature=temperature,  # this is the degree of randomness of the model's output
        stop=None,
        top_p=1,
        frequency_penalty=0.0,
        presence_penalty=0.6,
    )
    return response['choices'][0]['message']['content']

Expanding

自定义对客户电子邮件的自动回复

# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email
sentiment = "negative"

# review for a blender
review = f"""
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""

生成回复:

prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service.
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt)
print(response)

回复结果

提醒模型使用客户电子邮件中的详细信息

prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service. 
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt, temperature=0.7)
print(response)

生成回复

The Chat Format

新增一个函数,从回复的消息中补全信息:

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
#     print(str(response.choices[0].message))
    return response.choices[0]['message']['content']

开始聊天:

messages =  [
{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},
{'role':'user', 'content':'tell me a joke'},
{'role':'assistant', 'content':'Why did the chicken cross the road'},
{'role':'user', 'content':'I don\'t know'}  ]

response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

To get to the other side, good sir!
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

Hi Isa! It's nice to meet you. How are you feeling today?
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

I apologize, but as a chatbot, I do not have access to your personal information such as your name. Can you please remind me?
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'},
{'role':'assistant', 'content': "Hi Isa! It's nice to meet you. \
Is there anything I can help you with today?"},
{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

Your name is Isa.

订单机器人:我们可以自动化用户提示和助手响应的收集以构建订单机器人。Orderbot将在比萨餐厅接受订单。

def collect_messages(_):
    prompt = inp.value_input
    inp.value = ''
    context.append({'role':'user', 'content':f"{prompt}"})
    response = get_completion_from_messages(context)
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))

    return pn.Column(*panels)

绘制面板:

import panel as pn  # GUI
pn.extension()

panels = [] # collect display

context = [ {'role':'system', 'content':"""
You are OrderBot, an automated service to collect orders for a pizza restaurant. \
You first greet the customer, then collects the order, \
and then asks if it's a pickup or delivery. \
You wait to collect the entire order, then summarize it and check for a final \
time if the customer wants to add anything else. \
If it's a delivery, you ask for an address. \
Finally you collect the payment.\
Make sure to clarify all options, extras and sizes to uniquely \
identify the item from the menu.\
You respond in a short, very conversational friendly style. \
The menu includes \
pepperoni pizza  12.95, 10.00, 7.00 \
cheese pizza   10.95, 9.25, 6.50 \
eggplant pizza   11.95, 9.75, 6.75 \
fries 4.50, 3.50 \
greek salad 7.25 \
Toppings: \
extra cheese 2.00, \
mushrooms 1.50 \
sausage 3.00 \
canadian bacon 3.50 \
AI sauce 1.50 \
peppers 1.00 \
Drinks: \
coke 3.00, 2.00, 1.00 \
sprite 3.00, 2.00, 1.00 \
bottled water 5.00 \
"""} ]  # accumulate messages


inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard

面板

messages =  context.copy()
messages.append(
{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\
 The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},
)
 #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},

response = get_completion_from_messages(messages, temperature=0)
print(response)

执行结果

总结

  • Principles:
    • Write clear and specific instructions
    • Give the model time to “think”
  • Iterative prompt development
  • Capabilitis: Summarizing, Inferring, Transforming, Expanding
  • Building a ChatBot

内容来源

  1. DeepLearning.AI: 《ChatGPT Prompt Engineering for Developers》
<think>好的,我现在需要处理用户关于寻找提示词工程相关IPython Notebook文件或教程的请求。首先,我要回顾用户提供的系统级指令和引用内容,确保回答符合格式要求。用户要求使用中文,行内数学公式用$...$,独立公式用$$...$$,并且生成相关问题。同时,回答需要结构清晰,引用适当的内容。 首先,我需要确定用户的需求。用户提到“prompt engineering ipynb 文件 教程 示例”,说明他们正在寻找Jupyter Notebook格式的教程或示例,这可能包括代码示例、实践指南或案例分析。接下来,我需要根据提供的引用内容,寻找相关的资源。引用[1]到[4]中提到了提示工程的概述、应用、方法以及注意事项,比如小样本提示、思维链(CoT)提示和减少幻觉问题的方法。这些内容可以作为推荐教程的理论基础。 然后,我应该列出一些可能的资源。例如,官方文档如OpenAI Cookbook和LangChain文档通常会有Notebook示例。GitHub上的热门仓库如“Prompt-Engineering-Guide”可能包含教程。Kaggle和Google Colab也是常见的资源平台。教育平台如Coursera和Udemy可能有相关课程附带Notebook。此外,社区博客如Towards Data Science也会发布实践教程。 接下来,需要确保推荐的每个资源都符合用户需求,即包含IPython Notebook文件。例如,OpenAI的GitHub仓库中的示例代码,或者Hugging Face的Transformer教程。同时,引用用户提供的资料中的内容来支持推荐,比如引用[3]中提到的小样本提示和思维链提示,可以在教程中找到对应的实例。 然后,生成相关问题,这些问题应该围绕用户可能进一步探索的方向,比如如何优化提示词、评估提示效果、处理模型幻觉等,这些问题在引用[3]和[4]中都有涉及。 最后,检查回答是否符合格式要求:行内公式正确使用$...$,独立公式单独成段,引用标识正确添加,结构清晰。确保没有使用Markdown格式,语言自然口语化,分步骤说明思考过程,并在最后列出相关问题。</think>### 提示词工程相关IPython Notebook资源推荐 以下是结合理论知识和实践示例的IPython Notebook(.ipynb)资源推荐,涵盖提示词工程的核心方法(如小样本提示、思维链推理等)和实际应用场景: --- #### 1. **OpenAI官方示例库** - **内容**:包含基础提示设计、文本生成优化、代码生成等案例,例如使用$temperature$参数控制输出多样性。 - **资源链接**: [OpenAI Cookbook GitHub仓库](https://github.com/openai/openai-cookbook) 推荐文件:`getting-started-with-prompt-engineering.ipynb` - **特点**:官方维护,代码可直接运行,适合快速上手[^1]。 --- #### 2. **LangChain提示模板实战** - **内容**:通过`PromptTemplate`封装提示词模板,实现动态变量注入(如用户输入、上下文拼接)[^2]。 - **示例代码**: ```python from langchain import PromptTemplate template = "请将以下文本翻译为{target_language}:\n{text}" prompt = PromptTemplate(input_variables=["text", "target_language"], template=template) formatted_prompt = prompt.format(text="Hello, world!", target_language="法语") ``` - **资源链接**: [LangChain官方文档-提示工程章节](https://python.langchain.com/docs/modules/model_io/prompts/) --- #### 3. **小样本提示与思维链(CoT)实现** - **场景**:通过添加少量示例(Few-Shot)引导模型完成复杂推理任务[^3]。 - **Notebook示例**: ```python prompt = """ 任务:解决数学应用题 示例输入:小明有3个苹果,买了5个后吃掉2个,还剩多少? 示例输出:3 + 5 = 8,8 - 2 = 6。答案是6。 请解决以下问题:{question} """ ``` - **推荐资源**: [Google Colab - CoT Prompting教程](https://colab.research.google.com/github/google-research/prompt-tuning/blob/main/notebooks/ChainOfThought.ipynb) --- #### 4. **对抗模型幻觉的参考文本注入** - **方法**:通过附加参考文本约束生成结果,减少虚构回答(如引用[4]所述)。 - **代码片段**: ```python context = "根据《2023人工智能白皮书》,大模型幻觉发生率为12%。" user_query = "大模型幻觉的常见发生率是多少?" prompt = f"参考文本:{context}\n问题:{user_query}\n答案:" ``` - **实践案例**: [Hugging Face Prompt Engineering教程](https://huggingface.co/learn/nlp-course/chapter8/2) --- #### 5. **结构化输出生成** - **技术**:通过自然语言指令定义JSON/XML格式输出,结合函数调用(如OpenAI的`response_format`参数)。 - **Notebook链接**: [OpenAI结构化输出示例](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb) --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

镰刀韭菜

看在我不断努力的份上,支持我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值