Skip to content

Few-Shot & Chain-of-Thought

Few-Shot 提示

通过提供示例让模型学习输出格式和风格:

python
few_shot_examples = [
    {"input": "成立10年,营收5000万,负债率40%", "output": "低风险 | 评分90 | 建议批准"},
    {"input": "成立1年,营收50万,负债率90%", "output": "高风险 | 评分15 | 建议拒绝"},
    {"input": "成立4年,营收600万,负债率62%", "output": "中风险 | 评分58 | 条件批准"},
]

def build_few_shot_prompt(query: str) -> str:
    examples_text = "\n".join([
        f"输入:{ex['input']}\n输出:{ex['output']}"
        for ex in few_shot_examples
    ])
    return f"{examples_text}\n\n输入:{query}\n输出:"

Chain-of-Thought(CoT)

让模型展示推理过程,提升复杂任务准确性:

python
cot_prompt = """
分析贷款申请风险,请逐步推理:

申请信息:
- 公司:某餐饮连锁
- 成立:6年
- 营收:1200万/年
- 负债率:68%
- 申请金额:300万

推理步骤:

【步骤1:行业分析】
餐饮行业特点:...
疫情后恢复情况:...

【步骤2:财务分析】
营收规模(1200万)评估:...
负债率(68%)分析:...
贷款金额(300万)占营收比:...

【步骤3:经营稳定性】
6年经营历史说明:...
连锁模式风险:...

【步骤4:综合判断】
综合以上分析:
- 风险等级:
- 风险评分:
- 建议:
"""

Zero-Shot CoT

python
# 只需添加"让我们一步步思考"
zero_shot_cot = """
分析以下贷款申请是否应该批准:
某科技公司,成立3年,营收400万,负债率70%,申请200万贷款。

让我们一步步思考这个问题:
"""

Self-Consistency(自洽性)

python
def self_consistency_answer(question: str, n: int = 5) -> str:
    """多次采样取最一致的答案"""
    answers = []
    for _ in range(n):
        response = client.chat.completions.create(
            model="qwen-plus",
            messages=[{"role": "user", "content": question}],
            temperature=0.8  # 高温度增加多样性
        )
        answers.append(response.choices[0].message.content)
    
    # 简单投票(实际可用更复杂的一致性判断)
    from collections import Counter
    # 提取关键判断(高/中/低风险)
    risk_levels = []
    for ans in answers:
        if "高风险" in ans: risk_levels.append("高")
        elif "低风险" in ans: risk_levels.append("低")
        else: risk_levels.append("中")
    
    most_common = Counter(risk_levels).most_common(1)[0][0]
    # 返回与多数一致的答案
    for ans in answers:
        if f"{most_common}风险" in ans:
            return ans
    return answers[0]

本站内容由 褚成志 整理编写,仅供学习参考