Prompt Engineering Overview
核心概念: 了解如何设计有效的提示 (prompts),以指导语言模型生成期望的输出。这涉及到理解语言模型的行为和能力,以及如何通过巧妙的指令、上下文和示例来引导模型。
基本技巧: 学习 Prompt Engineering 的基本技巧,例如:
- 清晰而具体的指令: 明确告知模型你希望它做什么。
- 提供上下文信息: 为模型提供必要的背景知识,帮助它理解你的需求。
- 使用合适的格式: 例如,使用特定的分隔符、列表或代码块来组织输入和输出。
- 提供少量的示例 (Few-shot Learning): 通过提供几个输入-输出的示例,让模型学习你期望的生成模式。
- 角色扮演: 指示模型扮演特定的角色,以获得更符合特定风格的输出。
- 思维链 (Chain of Thought): 引导模型逐步思考,展示其推理过程,从而提高复杂任务的生成质量。
进阶技巧: 探索更高级的 Prompt Engineering 技术,例如:
- 迭代优化: 通过不断尝试和调整提示,找到最佳的prompt。
- Prompt 模板和框架: 了解和使用一些常用的 prompt 模板和框架,例如 LangChain 的 PromptTemplate。
- 对抗性提示 (Adversarial Prompting): 了解如何评估模型的鲁棒性和安全性。
Prompt Engineering 基础概念
Prompt
定义: Prompt 是你给语言模型的输入指令或问题,决定了模型的输出内容和风格。
解释: 它像是你对一个“聪明助手”的提问方式。例如:
• 简单Prompt:
• 高级Prompt:
重点:Prompt设计质量 = 输出质量(Garbage in, garbage out
解释: 它像是你对一个“聪明助手”的提问方式。例如:
• 简单Prompt:
"Summarize the following paragraph."• 高级Prompt:
"Act as a risk analyst and extract all liquidity risks. Format response in JSON."重点:Prompt设计质量 = 输出质量(Garbage in, garbage out
Completion
定义: Completion 是模型基于Prompt生成的文本回复结果。
解释: 它就是模型对你问题的“作答”,比如你问了一个问题,它生成了一段回答。
你设计的Prompt越清晰、结构越明确,Completion就越准确、专业。示例:Prompt: “List 3 types of credit risk.” → Completion:
“1. Default Risk
2. Downgrade Risk
3. Credit Spread Risk”
解释: 它就是模型对你问题的“作答”,比如你问了一个问题,它生成了一段回答。
你设计的Prompt越清晰、结构越明确,Completion就越准确、专业。示例:Prompt: “List 3 types of credit risk.” → Completion:
“1. Default Risk
2. Downgrade Risk
3. Credit Spread Risk”
System Prompt
定义: 是“系统角色设定”的特殊Prompt,影响整个对话过程中的模型行为。
解释: 它不是一个问题,而是“设定角色规则”,只需要一次设定,在整个对话中生效。示例 System Prompt:
常用于: ChatGPT API、LangChain agent、定制AI助手场景。
与 Role Prompting 不同: System Prompt是全局设定,Role Prompt是局部引导。
解释: 它不是一个问题,而是“设定角色规则”,只需要一次设定,在整个对话中生效。示例 System Prompt:
"You are an AI risk analyst who is expert in credit risk, model validation, and regulatory compliance. You always respond with concise and structured analysis."常用于: ChatGPT API、LangChain agent、定制AI助手场景。
与 Role Prompting 不同: System Prompt是全局设定,Role Prompt是局部引导。
User Prompt
用户直接输入给模型的具体指令或问题,用于触发模型响应。它通常是任务主句,比如“提取风险”、“生成摘要”、“回答问题”等。是你和模型交互中最关键的实际“问题本体”。
🔍 深入解释:
- 在对话型模型中(如 GPT-4-Turbo 或 ChatGPT),用户输入的每一句话就是一个 User Prompt。
- 它通常配合一个隐藏的 System Prompt 共同影响输出效果。
- 设计良好的 User Prompt 可以极大提高完成任务的精度、格式控制和生成逻辑。
✅ 示例:
System Prompt:
“You are a financial risk expert.”
User Prompt:
“Identify all liquidity risks from this 10-K paragraph and summarize them in three bullet points with source quotes.”
Role Prompting
定义: 指定模型“扮演某个角色”来接收任务。
解释: 明确告诉模型“你现在是一个风险分析师”,它就会生成专业语气和术语更符合语境的回答。示例 Prompt:
“You are a senior credit risk officer at a large bank. Based on the following loan data, identify key red flags.”
优点: 输出风格更专业、语境更贴切,适合金融、法律、审计等行业应用。
解释: 明确告诉模型“你现在是一个风险分析师”,它就会生成专业语气和术语更符合语境的回答。示例 Prompt:
“You are a senior credit risk officer at a large bank. Based on the following loan data, identify key red flags.”
优点: 输出风格更专业、语境更贴切,适合金融、法律、审计等行业应用。
When you’re working with AI language models, one of the most effective ways to get precise,
contextually appropriate responses is through role prompting. Think of role prompting as
giving the AI model a specific persona or expertise lens through which to view and respond to
your queries. It’s similar to how an actor takes on a character’s perspective to deliver a more
authentic performance.
In our daily lives, we naturally adjust our communication style based on our roles - a doctor
speaks differently about health issues than a journalist writing about the same topic. Role
prompting brings this same adaptability to AI interactions, allowing us to harness specific
types of expertise and communication styles for different tasks
contextually appropriate responses is through role prompting. Think of role prompting as
giving the AI model a specific persona or expertise lens through which to view and respond to
your queries. It’s similar to how an actor takes on a character’s perspective to deliver a more
authentic performance.
In our daily lives, we naturally adjust our communication style based on our roles - a doctor
speaks differently about health issues than a journalist writing about the same topic. Role
prompting brings this same adaptability to AI interactions, allowing us to harness specific
types of expertise and communication styles for different tasks
Components of Role Prompting
Role prompting consists of several key elements that work together to create effective interactions:
1.Role Assignment: This is where you explicitly define the role you want the AI to assume. For
example, instead of simply asking for an explanation of a topic, you might say “You are a
middle school science teacher explaining this concept to your students.”
1.Role Assignment: This is where you explicitly define the role you want the AI to assume. For
example, instead of simply asking for an explanation of a topic, you might say “You are a
middle school science teacher explaining this concept to your students.”
2.Role Description: This provides the specific characteristics, expertise, and background of the
role. The more detailed and relevant the description, the better the AI can align its responses
with the intended role.
role. The more detailed and relevant the description, the better the AI can align its responses
with the intended role.
3.Context Setting: This gives the AI model the necessary background information to operate effectively within its assigned role. It might include the setting, audience, or specific
circumstances relevant to the task.
circumstances relevant to the task.
4.Task Specification: This is the actual work you want the AI to perform while maintaining the
assigned role
assigned role
financial_advisor_prompt = PromptTemplate( 2 input_variables=["client_situation"], 3 template="""You are a seasoned financial advisor with over 20 years of experience in personal finance, investment strategies, and retirement planning. ,→ ,→ 4 You have a track record of helping clients from diverse ,→ backgrounds achieve their financial goals. 5 Your approach is characterized by: 6 1. Thorough analysis of each client's unique financial ,→ situation 7 2. Clear and jargon-free communication of complex financial ,→ concepts 8 3. Ethical considerations in all recommendations 9 4. A focus on long-term financial health and stability 10 11 Given the following client situation, provide brief ,→ financial advice: {client_situation}""" 13 )
Fine-tuning Role Descriptions
As you work with role prompting, you’ll want to refine your role descriptions for more precise outcomes. Consider this example for creative writing:
storyteller_prompt = PromptTemplate( 2 input_variables=["style", "scenario"], 3 template="""You are a master storyteller known for your ,→ ability to adapt to various narrative styles. 4 Your current task is to write in the style of {style}. 5 Key characteristics of this style include: 6 1. {style_char1} 7 2. {style_char2} 8 3. {style_char3} 9 10 Write a short paragraph in this style about: {scenario}""" 12 )
Exercises
Exercise 1: Basic Role Creation
Create three different role prompts for explaining a concept you’re familiar with:
Create three different role prompts for explaining a concept you’re familiar with:
- As an expert in your field
- As a teacher explaining to beginners
- As a consultant advising a client
Exercise 2: Role Description Refinement
Take one of your role prompts from Exercise 1 and:
Take one of your role prompts from Exercise 1 and:
- Add specific qualifications and experience
- Include communication style preferences
- Define approach characteristics
- Test with different tasks
Exercise 3: Comparative Analysis
Choose a topic and create prompts for three different roles:
Choose a topic and create prompts for three different roles:
- Write prompts for each role
- Generate responses for the same topic
- Analyze how the responses differ
- Identify which elements of the role descriptions influenced these differences
Self-Consistency
定义:
一种提升模型推理准确性与稳定性的技术,通过多次生成答案后,从多个推理路径中选出最一致的结论。
解释:
类似“一个问题问模型多次 → 得到多个不同版本的回答 → 看哪种答案出现得最多”。
它常与 Chain-of-Thought(CoT) 联合使用,特别适合解决逻辑判断类任务,避免偶发性错误。示例结构:
提升金融领域中的风险判断一致性、模型解释可靠性、审计意见稳定性,常用于复杂多因子逻辑任务,如信用评分、合规分类、策略推荐等。推荐工具:
Python 多轮循环调用、LangChain with
一种提升模型推理准确性与稳定性的技术,通过多次生成答案后,从多个推理路径中选出最一致的结论。
解释:
类似“一个问题问模型多次 → 得到多个不同版本的回答 → 看哪种答案出现得最多”。
它常与 Chain-of-Thought(CoT) 联合使用,特别适合解决逻辑判断类任务,避免偶发性错误。示例结构:
Prompt:Let’s think step by step. Should this loan be considered high risk?
Step 1:Run this CoT Prompt 5 times(开启 temperature = 0.7)
Step 2:得到5个不同的推理路径和结论
Step 3:统计哪种结论出现次数最多(如:3次是“high risk”,2次是“moderate”)
Step 4:输出众数作为最终结论
用途:提升金融领域中的风险判断一致性、模型解释可靠性、审计意见稳定性,常用于复杂多因子逻辑任务,如信用评分、合规分类、策略推荐等。推荐工具:
Python 多轮循环调用、LangChain with
Self-Ask, OpenAI API + Temperature 设置,或自定义 majority voting 逻辑。When working with language models, getting reliable and accurate responses can sometimes
feel like a challenge. Have you ever received different answers to the same question? Or
wondered if you could trust the model’s output? This chapter introduces powerful techniques
to enhance the reliability of AI responses through self-consistency and multiple paths of
reasoning.
Think of self-consistency like asking multiple experts the same question and comparing their
answers. Instead of relying on a single response, we generate multiple solutions through
different reasoning approaches. This strategy helps us identify the most reliable answer and
understand the problem from various angles
feel like a challenge. Have you ever received different answers to the same question? Or
wondered if you could trust the model’s output? This chapter introduces powerful techniques
to enhance the reliability of AI responses through self-consistency and multiple paths of
reasoning.
Think of self-consistency like asking multiple experts the same question and comparing their
answers. Instead of relying on a single response, we generate multiple solutions through
different reasoning approaches. This strategy helps us identify the most reliable answer and
understand the problem from various angles
Exercise 1: Understanding Multiple Paths
Take a simple arithmetic problem (e.g., calculating the area of a triangle) and solve it using
three different methods. Compare the results and explain any differences you find.
Take a simple arithmetic problem (e.g., calculating the area of a triangle) and solve it using
three different methods. Compare the results and explain any differences you find.
Exercise 2: Implementing Self-Consistency
Modify the provided generate_multiple_paths function to include at least one additional parameter that helps ensure even more diverse reasoning paths. Test your modification
with a sample problem.
Modify the provided generate_multiple_paths function to include at least one additional parameter that helps ensure even more diverse reasoning paths. Test your modification
with a sample problem.
Exercise 3: Result Analysis
Choose a complex problem from your field and apply the complete problem-solving pipeline
(multiple paths, aggregation, and consistency check). Write a detailed analysis of how the
different components contributed to the final solution.
Choose a complex problem from your field and apply the complete problem-solving pipeline
(multiple paths, aggregation, and consistency check). Write a detailed analysis of how the
different components contributed to the final solution.
Exercise 4: Error Detection
Create a scenario where different reasoning paths intentionally lead to different results. Imple
Create a scenario where different reasoning paths intentionally lead to different results. Imple
Task Decomposition in Prompts
Key Components
- Breaking Down Complex Tasks: Techniques for analyzing and dividing complex problems into simpler subtasks.
- Chaining Subtasks: Methods for sequentially connecting multiple subtasks to solve a larger problem.
- Prompt Design for Subtasks: Crafting effective prompts for each decomposed subtask.
- Result Integration: Combining the outputs from individual subtasks to form a comprehensive solution.
Method Details
The tutorial employs a step-by-step approach to demonstrate task decomposition:
- Problem Analysis: We start by examining a complex task and identifying its component parts.
- Subtask Definition: We define clear, manageable subtasks that collectively address the main problem.
- Prompt Engineering: For each subtask, we create targeted prompts that guide the AI model.
- Sequential Execution: We implement a chain of prompts, where the output of one subtask feeds into the next.
- Result Synthesis: Finally, we combine the outputs from all subtasks to form a comprehensive solution.
Prompt设计技巧(Prompt Engineering Strategy)
明确任务 + 限制格式
目的:让模型知道你要它“做什么”,并“怎么输出”
🔍 步骤指导:
步骤 | 操作说明 |
1. 写明清晰任务目标 | e.g. “Summarize risks”, “Classify by type”, “Score severity” |
2. 加上动作动词 | e.g. “List”, “Extract”, “Rate”, “Group”, “Explain” |
3. 指定输出结构 | Markdown, Bullet points, JSON, 表格等 |
✅ 示例(信用风险摘要):
text 复制编辑 Task: Extract all credit risks from the following paragraph. Instructions: - List 3–5 risks as bullet points - Each bullet must start with a verb - Output in Markdown format
⚠️ 常见误区:
- ❌ “帮我看看有没有风险” → 太模糊
- ✅ “列出所有信用风险,并引用原文” → 明确可执行
使用关键词指令
📌 目的:让模型更可控地产生内容风格、格式或行为
🔍 关键词建议(英文):
功能 | 推荐关键词 |
步骤推理 | Let's think step by step / Explain your reasoning |
控制输出格式 | in JSON format, use bullet points, as a table |
情感/语气控制 | in professional tone, for senior executives |
可引用内容 | include source quotes, label with paragraph number |
✅ 示例(监管报告摘要):
text 复制编辑 Summarize this 10-K paragraph into 3 bullet points. Respond in formal tone, using plain business English. Include a direct quote from the source for each point.
⚠️ 常见误区:
- ❌ 不使用关键词会让模型自由发挥、风格不一致
- ✅ 使用关键词能提升输出“稳准美”
加入反例对照
📌 目的:让模型知道“什么不应该包含”,提升准确率
🔍 使用方法:
类型 | 示例 |
否定指令 | “Do NOT include ESG risks.” |
非目标排除 | “Exclude operational and reputational risks.” |
错误示例对照 | “Incorrect: The company had strong liquidity. Correct: Liquidity risk arises from...” |
✅ 示例(提取非ESG风险):
text 复制编辑 Extract all material risks from this text. Do NOT include ESG-related risks such as climate or social governance issues. Only include financial and operational risks.
⚠️ 常见误区:
- ❌ 未设置边界 → 模型会“捡到篮子都是菜”
- ✅ 明确告诉它“不要做什么” → 减少误识别
Negative examples are one of the most straightforward ways to guide model outputs. Instead of just telling the model what to do, we explicitly state what we don’t want to see in the response. Here’s how we can implement this
negative_example_prompt = PromptTemplate( input_variables=["topic"], template="""Provide a brief explanation of {topic}. Do NOT include any of the following in your explanation: - Technical jargon or complex terminology - Historical background or dates - Comparisons to other related topics Your explanation should be simple, direct, and focus only on the core concept.""" ) response = get_response(negative_example_prompt.format(topic="photosynthesis")) print(response)
constraint_prompt = PromptTemplate( input_variables=["topic", "style", "excluded_words"], template="""Write a {style} description of {topic}. Constraints: 1. Do not use any of these words: {excluded_words} 2. Keep the description under 100 words 3. Do not use analogies or metaphors 4. Focus only on factual information""" ) response = get_response(constraint_prompt.format( topic="artificial intelligence", style="technical", excluded_words="robot, human-like, science fiction" )) print(response)
分阶段Prompting
📌 目的:拆解复杂任务,避免模型一口吃完
🔍 推荐拆解模板:
阶段 | 示例 Prompt |
Step 1:提取原始风险句 | “Extract all sentences mentioning credit or liquidity risks.” |
Step 2:分类标签 | “Classify each sentence as Credit / Liquidity / Market risk.” |
Step 3:打分 + 建议 | “Rate each risk severity from 1–5. Add a mitigation suggestion.” |
Step 4:统一结构输出 | “Format result in a Markdown table with columns: Type |
✅ 示例(流动性风险多步分析):
text 复制编辑 Step 1: Extract sentences related to liquidity issues. Step 2: Classify each sentence into: Cash Flow, Debt, or Contingency. Step 3: For each, assign a severity score (1–5). Step 4: Format as a JSON array.
⚠️ 常见误区:
- ❌ 一句让模型做完多个任务 → 输出混乱
- ✅ 分步执行 → 模型稳定输出
Prompt模块化
目的:搭建可复用、可插拔的提示系统,像乐高一样组合任务
🔍 构建方法:
模块类型 | 示例语句 |
🎯 任务模块 | Your task is to extract all credit risk signals. |
🎨 风格模块 | Use concise business English, in bullet list format. |
📌 格式模块 | Respond in Markdown with source references. |
🚫 限制模块 | Do not include ESG or reputational risk. |
✅ 金融模板组合示例:
text 复制编辑 Role: You are a model risk reviewer. Task: Identify potential model governance issues. Constraints: Do not mention model performance or accuracy. Format: Return in JSON with fields: ["issue", "section", "severity"]
⚠️ 常见误区:
- ❌ 每次Prompt从头写 → 不统一、不高效
- ✅ 构建模块库 → 复用性强、方便RAG/自动化系统调用
Prompt Formatting and Structure
- Different prompt formats (Q&A, dialogue, instructions)
- Structural elements (headings, bullet points, numbered lists)
- Comparison of prompt effectiveness
- Best practices for prompt formatting
Method Details
We'll use the OpenAI API through LangChain to interact with the GPT model. The tutorial will demonstrate:
- Setting up the environment with necessary libraries
- Creating various prompt formats (Q&A, dialogue, instructions)
- Incorporating structural elements like headings and lists
- Comparing responses from different prompt structures
Different prompt formats (Q&A, dialogue, instructions)
1. Question and Answer (Q&A) Format
qa_prompt = """Q: What is photosynthesis? A:""" get_response(qa_prompt)
2. Dialogue Format
dialogue_prompt = """Student: Can you explain photosynthesis to me? Teacher: Certainly! Photosynthesis is... Student: What does a plant need for photosynthesis? Teacher:""" get_response(dialogue_prompt)
3.Instruction Format
instruction_prompt = """Provide a brief explanation of photosynthesis, including its main components and importance.""" get_response(instruction_prompt)
Structural elements (headings, bullet points, numbered lists)
1.Using Headings
Headings help organize complex information into digestible sections.
headings_prompt = """Explain photosynthesis using the following structure: # Definition # Process # Importance """ get_response(headings_prompt)
2.Using Bullet Points
Bullet points are excellent for listing items or highlighting key points without implying a
specific order:
specific order:
bullet_points_prompt = """List the key components needed for photosynthesis: • • • """ get_response(bullet_points_prompt)
3.Using Numbered Lists
When sequence matters, numbered lists help maintain a clear order of steps or priorities:
numbered_list_prompt = """Describe the steps of photosynthesis in order: 1. 2. 3. 4. """ get_response(numbered_list_prompt)
Comparison of prompt effectiveness
Different prompt structures can yield varying results for the same query. Let’s examine how
changing the structure impacts the response:
changing the structure impacts the response:
comparison_prompts = [ "Explain the importance of photosynthesis for life on Earth.", """Explain the importance of photosynthesis for life on Earth. Structure your answer as follows: 1. Oxygen production 2. Food chain support 3. Carbon dioxide absorption""", """Q: Why is photosynthesis important for life on Earth? A: Photosynthesis is crucial for life on Earth because: 1. 2. 3.""" ] for i, prompt in enumerate(comparison_prompts, 1): print(f"Prompt {i}:") get_response(prompt)
Prompt 1: Photosynthesis is a crucial biological process that significantly impacts life on Earth for several reasons: 1. **Oxygen Production**: Photosynthesis is the primary source of atmospheric oxygen. During the process, plants, algae, and some bacteria convert carbon dioxide and water into glucose and oxygen using sunlight. This oxygen is essential for the survival of most living organisms that rely on aerobic respiration to generate energy. 2. **Foundation of Food Chains**: Photosynthesis forms the base of the food chain. Producers, such as plants and phytoplankton, harness solar energy to create organic matter. Herbivores consume these producers, and in turn, carnivores feed on herbivores. This flow of energy and nutrients is vital for the survival of all ecosystems. 3. **Carbon Dioxide Regulation**: Photosynthesis plays a critical role in regulating atmospheric carbon dioxide levels. By absorbing CO2, photosynthetic organisms help mitigate the greenhouse effect and climate change. This regulation is essential for maintaining the planet's climate and supporting diverse life forms. 4. **Energy Source**: Photosynthesis is the primary means of converting solar energy into chemical energy stored in glucose. This energy is then available to be consumed by other organisms, making it a fundamental energy source for almost all life on Earth. 5. **Biodiversity Support**: By producing organic matter and oxygen, photosynthesis supports a wide variety of ecosystems and promotes biodiversity. Healthy ecosystems contribute to the stability and resilience of the environment, providing habitats for countless species. 6. **Soil Formation and Health**: Photosynthetic organisms contribute to soil health by creating organic matter through decaying plant material. This organic matter enriches the soil, improving its structure, fertility, and ability to retain water, which is vital for agriculture and natural vegetation. In summary, photosynthesis is essential for life on Earth as it provides oxygen, forms the basis of food chains, helps regulate carbon dioxide levels, serves as a primary energy source, supports biodiversity, and contributes to soil health. Its significance extends beyond individual organisms to the overall health of the planet's ecosystems. -------------------------------------------------- --------------------------------------------------
Prompt 2: Photosynthesis is a vital process that supports life on Earth in several key ways. Here’s a structured explanation of its importance: ### 1. Oxygen Production Photosynthesis is primarily responsible for the production of oxygen in the atmosphere. During this process, plants, algae, and certain bacteria convert carbon dioxide and water into glucose and oxygen, using sunlight as an energy source. The overall equation for photosynthesis can be summarized as: \[ \text{6 CO}_2 + \text{6 H}_2\text{O} + \text{light energy} \rightarrow \text{C}_6\text{H}_{12}\text{O}_6 + \text{6 O}_2 \] The oxygen released is crucial for the survival of aerobic organisms, including humans. It is utilized in cellular respiration, a process that generates energy for living beings. Without photosynthesis, the oxygen levels in the atmosphere would diminish, leading to a collapse of most life forms that depend on it for respiration. ### 2. Food Chain Support Photosynthesis forms the foundation of the food chain. The glucose produced during photosynthesis serves as an energy source for autotrophs (organisms that produce their own food, such as plants). These autotrophs are then consumed by herbivores (primary consumers), which are in turn eaten by carnivores (secondary and tertiary consumers). This interconnected network of energy transfer is vital for maintaining ecological balance. As a result, the health and productivity of ecosystems are largely dependent on the efficiency of photosynthesis, making it essential for sustaining life on Earth. ### 3. Carbon Dioxide Absorption Photosynthesis plays a crucial role in regulating atmospheric carbon dioxide levels. Plants absorb carbon dioxide from the atmosphere during the process of photosynthesis, helping to mitigate the greenhouse effect and combat climate change. By removing CO2, which is a significant greenhouse gas, photosynthesis contributes to climate regulation and maintains the balance of carbon in the ecosystem. This absorption is particularly important in the context of rising CO2 levels due to human activities, as it helps to offset some of the impacts of global warming. In summary, photosynthesis is fundamental to life on Earth through its production of oxygen, support of food chains, and absorption of carbon dioxide. It not only sustains individual organisms but also plays a critical role in maintaining the planet's ecological and atmospheric balance.
Prompt 3: A: Photosynthesis is crucial for life on Earth because: 1. **Oxygen Production**: Photosynthesis generates oxygen as a byproduct, which is essential for the survival of most living organisms. It provides the oxygen that we breathe, supporting aerobic respiration. 2. **Food Source**: It serves as the primary source of energy for nearly all ecosystems. Plants, algae, and some bacteria convert sunlight into chemical energy in the form of glucose, which is then used as food by herbivores and, subsequently, by carnivores. 3. **Carbon Dioxide Absorption**: Photosynthesis helps regulate atmospheric carbon dioxide levels. By absorbing CO2 from the atmosphere, it plays a key role in mitigating climate change and maintaining the planet's carbon balanc
高级 Prompt 技术(为构建系统做准备)
Zero-shot Prompting
定义: 不给模型任何示例,直接发出任务指令。
解释: 模型完全依靠其训练时学到的“常识”来理解并完成任务。示例 Prompt:
→ 模型直接输出它认为是market risk的内容。
优点: 简洁快速。
风险: 输出不稳定、不一定符合你期望的格式。
解释: 模型完全依靠其训练时学到的“常识”来理解并完成任务。示例 Prompt:
"Extract all market risks from this paragraph."→ 模型直接输出它认为是market risk的内容。
优点: 简洁快速。
风险: 输出不稳定、不一定符合你期望的格式。
Few-shot Prompting
Few-Shot Learning is like teaching by example, but with a minimal set of demonstrations.
Imagine you’re teaching someone to identify mushrooms - instead of showing them thousands
of pictures, you might show them just three or four examples of each type, highlighting the
key features that distinguish edible from poisonous varieties. This is exactly what Few-Shot
Learning does with AI models
Imagine you’re teaching someone to identify mushrooms - instead of showing them thousands
of pictures, you might show them just three or four examples of each type, highlighting the
key features that distinguish edible from poisonous varieties. This is exactly what Few-Shot
Learning does with AI models
定义: 在Prompt中提供1–3个示例,模型据此模仿风格/格式/语气来完成任务。
解释: 类似“我来给你示范怎么做,然后你模仿我完成新任务”。示例 Prompt:
“Example 1: Risk Type: Credit | Summary: Late payments noted | Severity: High
Example 2: Risk Type: Market | Summary: FX volatility risk | Severity: Medium
Now analyze this new paragraph...”
优点: 控制输出结构和语言风格非常有效。
用途: 建结构化问答、总结、自动审计摘要非常常用。
解释: 类似“我来给你示范怎么做,然后你模仿我完成新任务”。示例 Prompt:
“Example 1: Risk Type: Credit | Summary: Late payments noted | Severity: High
Example 2: Risk Type: Market | Summary: FX volatility risk | Severity: Medium
Now analyze this new paragraph...”
优点: 控制输出结构和语言风格非常有效。
用途: 建结构化问答、总结、自动审计摘要非常常用。
def multi_task_few_shot(input_text, task): few_shot_prompt = PromptTemplate( input_variables=["input_text", "task"], template=""" Perform the specified task on the given text. Examples: Text: I love this product! It's amazing. Task: sentiment Result: Positive Text: Bonjour, comment allez-vous? Task: language Result: French Now, perform the following task: Text: {input_text} Task: {task} Result: """ )
Practical Exercises
Exercise 1: Basic Few-Shot Implementation
Create a few-shot learning system for:
Create a few-shot learning system for:
- Classifying emails as spam or not spam using three examples
- Identifying the tone of business communications (formal, casual, urgent)
- Testing your system with at least five new examples
Exercise 2: Multi-Task Challenge
Design a system that can:
Design a system that can:
- Detect the language of a text
- Determine if it’s a question or statement
- Assess its formality level Use the multi-task template provided above and create appropriate
examples for each task.
Exercise 3: In-Context Learning Application
Create an in-context learning system for:
Create an in-context learning system for:
- Converting dates between different formats
- Transforming numbers into words
- Extracting key information from product descriptions Test your system with various inputs
and refine your examples based on the results.
Exercise 4: Evaluation Framework
- Create a test set of at least 10 cases for your chosen task
- Implement the evaluation function provided above
- Run your tests and calculate accuracy
- Analyze which types of inputs tend to cause errors
Chain-of-Thought (CoT)
定义|What is CoT?
Chain-of-Thought Prompting 是一种引导大语言模型(LLM)逐步推理(step-by-step reasoning)的方法,使其能够在面对多步骤、复杂判断任务时产生更准确、有逻辑支撑的回答。
它模拟人类思维过程:先思考 → 再作答,而不是直接输出结论。
为什么重要?
应用场景 | 为什么用 CoT |
风险判断(如信用评级) | 强调条件 + 逻辑推导路径 |
多因子模型解释 | 拆解影响因子逐个分析 |
审计/合规问答 | 提供推理链条,满足可追溯性 |
LLM输出可解释性增强 | 输出过程能被追踪与审查 |
Prompt 格式结构
Let’s think step by step: 1. Identify key financial metrics 2. Compare against thresholds 3. Evaluate if risk criteria are met 4. Output the conclusion
金融风控应用示例
🎯 场景 1:信用风险判断
Prompt:
Let’s think step by step. Based on the following customer profile, determine if they are a high credit risk: - DTI ratio = 55% - Credit history = 3 missed payments - FICO score = 580
Model Output:
Step 1: A DTI > 50% indicates potential repayment issues. Step 2: 3 missed payments show prior delinquency. Step 3: FICO 580 is below the subprime threshold. Conclusion: This is a high credit risk profile.
场景 2:是否存在流动性压力
Prompt:
Let’s think step by step. Does this firm face liquidity pressure based on the Q4 data?
Model Output:
Step 1: Operating cash flow is negative for 2 consecutive quarters. Step 2: Short-term debt increased by $800M. Step 3: Cash reserves fell by 25%. Conclusion: Yes, the firm faces liquidity pressure.
与 Zero-shot Prompting 对比
类型 | 输出对比 |
Zero-shot | “Yes, the firm has liquidity risk.” (缺推理) |
CoT | “Step 1: … Step 2: … → Conclusion: Liquidity risk exists.” (具逻辑) |
技术提示
- ✅ 搭配 temperature > 0.7 可用于Self-Consistency
- ✅ 可作为模型解释性模块集成到 RAG 或审计系统中
- ✅ 可嵌入 Tree-of-Thought 或 Self-Reflection 中进一步增强复杂推理能力
推荐模版语句
- “Let’s think through this step by step.”
- “First, identify… Then evaluate… Finally…”
- “Analyze each factor individually and summarize.”
- “Consider the following: 1) Financial indicators, 2) Historical trends, 3) Thresholds…”
Exercise 1: Basic CoT Implementation
Create a CoT prompt for each of these scenarios:
Create a CoT prompt for each of these scenarios:
- Calculate the total cost of a shopping cart with a 15% discount
- Find the area of a triangular garden
- Determine how many boxes needed to pack 247 items if each box holds 35 items
Exercise 2: Advanced Problem Solving
Take this complex problem: “A store increases its prices by 20%, then offers a 25% discount.
Calculate the final price of an item that originally cost $80.”
Take this complex problem: “A store increases its prices by 20%, then offers a 25% discount.
Calculate the final price of an item that originally cost $80.”
- Write a CoT prompt that breaks down the solution
- Implement it using the provided code template
- Compare the results with a standard prompt
Exercise 3: Logical Analysis
Create a CoT prompt for this puzzle: “In a room, there are three switches. Each switch controls
one of three lamps in another room. You can only enter the lamp room once. How can you
determine which switch controls which lamp?”
Create a CoT prompt for this puzzle: “In a room, there are three switches. Each switch controls
one of three lamps in another room. You can only enter the lamp room once. How can you
determine which switch controls which lamp?”
- Write the prompt
- Test it
- Analyze how CoT improves the solution process
Exercise 4: Real-world Application
Choose a complex problem from your field of work or study:
Choose a complex problem from your field of work or study:
- Write both a standard prompt and a CoT prompt
- Compare the responses
- Document which aspects of the problem benefited most from the CoT approach
ReAct Prompting
原理:
结合“推理”和“工具调用”的流程式提示方法。
模型会先分析情境,再决定是否调用某种函数、图表、搜索引擎或API。
为什么用它:
适用于结构化数据/文档+外部函数调用的复杂任务,如:
- 财报分析中先总结结论 → 再画图
- 多步骤的合规审计工作流
设计方法:
text 复制编辑 You are a risk analyst. Think aloud first. Then decide whether to [LOOK UP], [SEARCH], or [ANSWER]. Format: Thought: ... Action: ... Observation: ...
金融实战场景示例:
Prompt:
text 复制编辑 “What is the company's short-term debt exposure?” → 模型输出: Thought: I should first identify the short-term liabilities in the 10-K. Action: SEARCH[“short-term debt” section in 10-K] Observation: Paragraph mentions $1.2B maturing in 12 months Final Answer: The company has a short-term debt exposure of $1.2B.
Self-Ask with Search
原理:
模型先提出自己需要的问题(子问题)→ 自动查找上下文 → 再回答原始问题
为什么用它:
适用于问题不明确或需要中间信息跳转的情况,比如:
- 问题中有隐含变量
- 多轮问答系统
设计方法:
text 复制编辑 Question: What is the company's liquidity risk this quarter? → Sub-question: Does the firm report cash shortfall or large short-term liabilities? → Search: “cash flow”, “debt maturity” sections → Answer: Summarize based on retrieved content
金融实战场景示例:
text 复制编辑 "What is the company’s short-term debt exposure?" → 模型自问: Sub-question: Where is short-term debt mentioned? → 检索“debt table” → 回答原始问题
Tree-of-Thought (ToT)
原理:
并行生成多条思路(不同推理路径)→ 对比 → 投票选择最佳答案
为什么用它:
适合复杂推理问题,有多个可能方案时:
- 信用评级评估
- 模型策略解释
- 风险缓解建议生成
设计方法:
text 复制编辑 Step 1: Generate 3 different reasoning paths Step 2: Evaluate outcomes Step 3: Select the most coherent answer
金融实战场景示例:
text 复制编辑 Prompt: “Should this loan be approved?” → 思路1:Based on debt-to-income, likely default → 思路2:Low loan-to-value makes it safer → 思路3:Credit history stable, but income volatile → 投票:2/3说 approve → 输出 YES with explanation
Instruction Tuning Prompt
原理:
模仿 OpenAI API 风格写法:Task + Format + Constraints,对模型下达“强指令”
这类 Prompt 清晰、结构化,易于系统使用
为什么用它:
适合做产品接口 / 系统提示模板 / 多任务统一调度,如:
- 风险自动摘要系统
- RegTech报告生成器
- 风控AI助手
设计方法:
text 复制编辑 You are a [role]. Task: [目标任务] Format: [返回格式] Constraints: [限制条件]
金融实战场景示例:
text 复制编辑 You are an AI auditor. Task: Validate model risk. Format: JSON Constraints: No external assumptions.
Reflection Prompting(反思机制)
原理:
模型先生成第一版回答 → 自我评估/审查 → 输出修订后的更优版本
为什么用它:
用于提升内容质量、合规性和语言准确性,适合:
- 模型输出校正
- 报告撰写
- 审计场景(去掉模糊、不准确语言)
设计方法:
text 复制编辑 Step 1: Generate initial answer Step 2: Review for ambiguity, errors, or missing logic Step 3: Refine answer to remove vague language
金融实战场景示例:
text 复制编辑 Prompt: "Now review the previous answer and refine to remove vague statements. Make it suitable for a regulatory review with clear justification.”
