文章目录
了解LLM和OpenAI API的基础知识,之后我们就可以了解一些更高阶的知识,比如提示工程、零样本学习、少样本学习到为特定任务微调模型,接下来我们将要了解提供开发LLM驱动型应用程序所需的一切知识。
一. chat_completion函数
先来回顾一下chat_completion函数
def chat_completion(prompt, model="gpt-4", temperature=0):
res = openai.ChatCompletion.create(
model=model,
messages=[{
"role": "user", "content": prompt}],
temperature=temperature,
)
print(res["choices"][0]["message"]["content"])
model和temperature是两个可选特征,分别被默认设置为gpt-4和0。
为了说明提示工程的原理,我们使用示例文本“As Descartes said, I think therefore”(正如笛卡儿所说,我思故)。如果将此文本输入GPT-4,那么模型自然会通过迭代式地添加最可能出现的标记来补全句子:
chat_completion("As Descartes said, I think therefore")
模型的输出消息如下所示:
I am. This famous philosophical statement, also known as "Cogito, ergo
sum," emphasizes the existence of the self through the act of thinking
or doubting. Descartes used this statement as a foundational principle
in his philosophy, arguing that one's own existence is the most certain
and indubitable fact that can be known.
需要注意的是:
- 提示工程可能会影响OpenAI API的使用成本。
该成本与你发送给OpenAI并从其接收的标记数成正比
。如所述,我们强烈建议使用max_tokens参数,以避免费用超出预期。- 另外在openai库的方法中使用不同的参数,因为如果使用temperature、top_p和max_tokens等参数,那么即使使用相同的提示词,你也可能得到截然不同的结果。
二. 设计有效的提示词
很多任务可以通过提示词来完成,包括摘要、文本分类、情感分析和问题回答
。在所有这些任务中,我们通常需要在提示词中定义三大要素:角色、上下文和任务
,如下图。
这三大要素并非都是必需的,它们的顺序也不是固定的。不过,如果能够构造好提示词的结构并明确定义这三大要素,你就能够得到不错的结果。
请注意,即使使用了这三大要素,对于复杂的任务,你也可能需要采用更高级的技巧,如零样本学习、少样本学习和微调。
1.上下文
提示词的第一大要素是上下文。在为LLM编写输入文本时,必须尽可能详细地描述上下文。为了说明这一点,假设我们想使用GPT-4创建一个应用程序,用于推荐午餐的主菜。
1.1. 更多细节的上下文
接下来,我们将比较在两个上下文中获得的结果。第一个上下文提供较少的细节,第二个上下文则提供较多的细节。假设使用以下较短的提示词:
chat_completion("Give me a suggestion for the main course for
today's lunch.")
我们得到以下输出消息:
Grilled chicken with roasted vegetables and quinoa.
现在,在提示词中加入更多上下文信息:
prompt = """
Context: I do 2 hours of sport a day. I am vegetarian, and I don't
like green vegetables. I am conscientious about eating healthily.
Task: Give me a suggestion for a main course for today's lunch."""
chat_completion(prompt)
我们得到以下输出消息:
For today's lunch, you can try a Chickpea and Sweet Potato Curry
served with Quinoa. This dish is packed with protein, fiber, and
essential nutrients, while also being vegetarian and not relying
on green vegetables. The curry can be made with chickpeas, sweet
potatoes, tomatoes, onions, garlic, and a blend of spices like
turmeric, cumin, and coriander. Cook the quinoa separately and
serve it alongside the curry for a delicious and healthy meal.
在第二个例子中,由于提示词含有更多上下文,因此模型给出的句子更详细:它推荐了一道富含蛋白质的健康素食菜肴。