Prompt工程八大技巧:打造高效LLM应用

在开发大型语言模型(LLM)原生应用的过程中,Prompt工程无疑是一项至关重要的技能。通过精心设计的Prompt,可以显著提升应用的性能和可靠性。正确的 Prompt 能够引导 LLM 生成符合需求的高质量输出,在不同的应用场景中发挥重要作用。本文将深入探讨 Prompt 工程的多种技巧,希望对大家有所帮助。

一、明确认知过程边界

在与 LLM 交互时,定义清晰的认知过程边界至关重要。这有助于保持 LLM 交互的专注性和清晰度,符合 LLM 三角原理中的工程技术顶点要求。每个步骤都应是一个独立的过程,避免在同一个 Prompt 中混合不同的认知过程,否则可能会产生次优的结果。

以 “Landing Page Generator” 为例,我们可以将生成Landing Page的过程分解为多个独立的函数,如generate_landing_page_concept用于定义Landing Page,select_landing_page_components用于选择组件,generate_component_content用于生成组件内容。通过这种方式,每个函数都专注于一个特定的认知任务,提高了输出质量,并且更易于调试和优化。

def generate_landing_page_concept(input_data: LandingPageInput) -> LandingPageConcept:`    `"""`    `Generate a landing page concept based on the input data.`    `This function focuses on the creative process of conceptualizing the landing page.`    `"""`    `pass``   ``def select_landing_page_components(concept: LandingPageConcept) -> List[LandingPageComponent]:`    `"""`    `Select appropriate components for the landing page based on the concept.`    `This function is responsible only for choosing components,`    `not for generating their content or layout.`    `"""`    `pass``   ``def generate_component_content(component: LandingPageComponent, concept: LandingPageConcept) -> ComponentContent:`    `"""`    `Generate content for a specific landing page component.`    `This function focuses on creating appropriate content based on the component type and overall concept.`    `"""`    `pass

二、明确指定输入 / 输出

定义清晰的输入和输出结构能够反映目标,并创建明确的数据模型。这涉及到 LLM 三角原理中的工程技术和上下文数据顶点。例如,通过定义LandingPageInput和LandingPageConcept等,我们明确了输入数据的结构,包括品牌、产品描述、活动描述等,以及输出数据的结构,如活动描述的反映、动机、叙事等。

class LandingPageInput(BaseModel):`    `brand: str`    `product_desc: str`    `campaign_desc: str`    `cta_message: str`    `target_audience: str`    `unique_selling_points: List[str]``   ``class LandingPageConcept(BaseModel):`    `campaign_desc_reflection: str`    `campaign_motivation: str`    `campaign_narrative: str`    `campaign_title_types: List[str]`    `campaign_title: str`    `tone_and_style: List[str]

这种明确的输入 / 输出定义为 LLM 提供了清晰的指导,使其能够更好地理解任务要求。在不同的应用场景中,无论是处理文本生成、信息检索还是其他任务,明确的数据模型都有助于提高结果的准确性和可靠性。

三、实施防护栏

为了确保 LLM 输出的质量和适度性,我们可以实施防护栏。Pydantic 是一个很好的工具,它可以用于实现简单的验证,如定义字段的最小长度或最小数量。同时,我们还可以使用自定义的验证器,如field_validator来确保生成的内容符合特定的内容政策。

在 “Landing Page Generator” 中,对于LandingPageConcept模型,我们可以使用 Pydantic 的Field来定义campaign_narrative字段的最小长度为 50,以及tone_and_style列表的最小项目数为 2。此外,还可以使用自定义验证器来检查campaign_narrative是否符合内容政策,通过调用另一个 AI 模型进行验证,如果不符合则抛出异常。

class LandingPageConcept(BaseModel):`    `campaign_narrative: str = Field(..., min_length=50)  # native validations`    `tone_and_style: List[str] = Field(..., min_items=2)  # native validations``   `    `# ...rest of the fields... #``   `    `@field_validator("campaign_narrative")`    `@classmethod`    `def validate_campaign_narrative(cls, v):`        `"""Validate the campaign narrative against the content policy, using another AI model."""`        `response = client.moderations.create(input=v)``   `        `if response.results[0].flagged:`            `raise ValueError("The provided text violates the content policy.")``   `        `return v

四、与人类认知过程对齐

(一)模仿人类思维的步骤分解

为了提高 LLM 的性能,我们可以将复杂任务分解为更小的步骤,使其结构与人类认知过程对齐。这遵循 LLM 三角原理中的标准操作程序(SOP)指导原则。例如,在创建Landing Page概念时,我们可以通过引导 LLM 输出特定的字段,如活动描述的分析、动机、叙事等,来鼓励它遵循类似于人类营销人员或设计师的思维过程。

class LandingPageConcept(BaseModel):`    `campaign_desc_reflection: str  # Encourages analysis of the campaign description`    `campaign_motivation: str       # Prompts thinking about the 'why' behind the campaign`    `campaign_narrative: str        # Guides creation of a cohesive story for the landing page`    `campaign_title_types: List[str]# Promotes brainstorming different title approaches`    `campaign_title: str            # The final decision on the title`    `tone_and_style: List[str]      # Defines the overall feel of the landing page``   

(二)多步骤 / 代理的应用

对于复杂任务,我们可以采用多步骤或多代理的方法。以生成Landing Page为例,我们可以先概念化活动,然后选择组件,接着为每个组件生成内容,最后组合成最终的 HTML。这种多代理的方法类似于人类解决复杂问题的方式,将问题分解为更小的部分,提高了处理效率和结果质量。

async def generate_landing_page(input_data: LandingPageInput) -> LandingPageOutput:`    `# Step 1: Conceptualize the campaign`    `concept = await generate_concept(input_data)`    `    # Step 2: Select appropriate components`    `selected_components = await select_components(concept)`    `    # Step 3: Generate content for each selected component`    `component_contents = {`        `component: await generate_component_content(input_data, concept, component)`        `for component in selected_components`    `}`    `    # Step 4: Compose the final HTML`    `html = await compose_html(concept, component_contents)`    `    return LandingPageOutput(concept, selected_components, component_contents, html)

五、利用结构化数据

YAML是一种流行的、对人类友好的数据序列化格式,易于人类阅读和机器解析,非常适合LLM使用。

我们发现YAML在LLM交互中特别有效,能够跨不同模型产生更好的结果。它使令牌处理集中在有价值的内容上,而不是语法上。此外,YAML在不同LLM提供商之间更具可移植性,并允许维护结构化的输出格式。

以 “Landing Page Generator” 为例,我们使用YAML格式定义输入、概念和组件,并通过few-shot示例向模型展示期望的输出结构。这种方法比直接在Prompt中提供明确的指令更有效。

sync def generate_component_content(input_data: LandingPageInput, concept: LandingPageConcept,component: LandingPageComponent) -> ComponentContent:`    `few_shots = {`        `LandingPageComponent.HERO: {`            `"input": LandingPageInput(`                `brand="Mustacher",`                `product_desc="Luxurious mustache cream for grooming and styling",`                `# ... rest of the input data ...`            `),`            `"concept": LandingPageConcept(`                `campaign_title="Celebrate Dad's Dash of Distinction",`                `tone_and_style=["Warm", "Slightly humorous", "Nostalgic"]`                `# ... rest of the concept ...`            `),`            `"output": ComponentContent(`                `motivation="The hero section captures attention and communicates the core value proposition.",`                `content={`                    `"headline": "Honor Dad's Distinction",`                    `"subheadline": "The Art of Mustache Care",`                    `"cta_button": "Shop Now"`                `}`            `)`        `},`        `# Add more component examples as needed`    `}``   `    `sys = "Craft landing page component content. Respond in YAML with motivation and content structure as shown."`    `    messages = [{"role": "system", "content": sys}]`    `messages.extend([`        `message for example in few_shots.values() for message in [`            `{"role": "user", "content": to_yaml({"input": example["input"], "concept": example["concept"], "component": component.value})},`            `{"role": "assistant", "content": to_yaml(example["output"])}`        `]`    `])`    `messages.append({"role": "user", "content": to_yaml({"input": input_data, "concept": concept, "component": component.value})})``   `    `response = await client.chat.completions.create(model="gpt-4o", messages=messages)`    `raw_content = yaml.safe_load(sanitize_code_block(response.choices[0].message.content))`    `return ComponentContent(**raw_content)

六、精心设计上下文数据

精心考虑如何向 LLM 呈现数据是至关重要的。即使是最强大的模型也需要相关和结构良好的上下文数据才能发挥最佳效果。我们不应丢弃所有的数据,而是应该选择与定义的目标相关的信息来告知模型。

async def select_components(concept: LandingPageConcept) -> List[LandingPageComponent]:`    `sys_template = jinja_env.from_string("""`    `Your task is to select the most appropriate components for a landing page based on the provided concept.`    `Choose from the following components:`    `{% for component in components %}`    `- {{ component.value }}`    `{% endfor %}`    `You MUST respond ONLY in a valid YAML list of selected components.`    `""")``   `    `sys = sys_template.render(components=LandingPageComponent)``   `    `prompt = jinja_env.from_string("""`    `Campaign title: "{{ concept.campaign_title }}"`    `Campaign narrative: "{{ concept.campaign_narrative }}"`    `Tone and style attributes: {{ concept.tone_and_style | join(', ') }}`    `""")``   `    `messages = [{"role": "system", "content": sys}] + few_shots + [`        `{"role": "user", "content": prompt.render(concept=concept)}]``   `    `response = await client.chat.completions.create(model="gpt-4", messages=messages)``   `    `selected_components = yaml.safe_load(response.choices[0].message.content)`    `return [LandingPageComponent(component) for component in selected_components]``   

在实际应用中,我们可以使用 Jinja 模板来动态构建提示。例如,在选择Landing Page组件时,我们可以使用 Jinja 模板根据概念动态生成系统提示和用户提示,从而为 LLM 交互创建聚焦和相关的上下文。

Few-Shot Learning是 Prompt 工程中的一项重要技术。它通过向 LLM 提供相关示例来显著提高其对任务的理解。在我们讨论的方法中,我们可以将示例作为消息添加到列表中,或者直接在提示中使用与当前任务相关的示例,以帮助 LLM 更好地理解预期的输入 - 输出模式。

messages.extend([`    `message for example in few_shots for message in [`        `{"role": "user", "content": to_yaml(example["input"])},`        `{"role": "assistant", "content": to_yaml(example["output"])}`    `]``])``# then we can add the user prompt``messages.append({"role": "user", "content": to_yaml(input_data)})

七、保持简单

尽管像“思想树”或“思想图”这样的高级Prompt工程技术对于研究很有吸引力,但在实际应用中往往不切实际且过于复杂。对于真实应用,应专注于设计适当的LLM架构(即工作流工程)。

这同样适用于在LLM应用中使用代理。了解标准代理和自主代理之间的区别至关重要。自主代理提供灵活性和更快的开发速度,但也可能引入不可预测性和调试挑战。因此,应谨慎使用自主代理,仅当收益明显大于潜在的控制损失和复杂性增加时才使用。

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范

第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署

第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建

第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值