EN

思维链提示:完整指南与示例

掌握思维链提示——在提示中进行逐步推理——最适合数学和逻辑任务

返回教程列表🌐 Read in English
进阶12 分钟

思维链提示:完整指南与示例

掌握思维链提示——在提示中进行逐步推理——最适合数学和逻辑任务

思维链提示:完整指南 什么是思维链提示? 思维链提示是一种在提示中进行逐步推理的提示技术。它对于数学和逻辑任务特别有效。 何时使用

思维链提示:完整指南

什么是思维链提示?

思维链提示是一种在提示中进行逐步推理的提示技术。它对于数学和逻辑任务特别有效。

何时使用思维链提示

在以下情况下使用此技术:

  • 你需要处理数学和逻辑任务
  • 标准提示给出不一致的结果
  • 任务需要在提示中进行逐步推理
  • 你想要更可靠、结构化的输出
  • 工作原理

    思维链提示的核心思想:

  • 设置:准备带有思维链提示结构的提示
  • 执行:使用适当参数发送给LLM
  • 解析:提取结构化响应
  • 验证:检查输出质量和格式
  • 基本示例

    python
    from openai import OpenAI

    client = OpenAI()

    def chain_of_thought_prompting_prompt(task: str, context: str = "") -> str: """应用思维链提示技术。""" # 思维链提示的提示结构 system = """你是一位专家级AI助手。 对每个任务进行系统推理。 要精确、准确且结构良好。""" # 思维链提示的核心提示 prompt = f"""任务:{task} {"上下文:" + context if context else ""}

    请通过逐步推理来完成此任务。""" response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": system}, {"role": "user", "content": prompt} ], temperature=0.3, max_tokens=1500 ) return response.choices[0].message.content

    使用示例

    result = chain_of_thought_prompting_prompt( task="分析微服务架构的优缺点", context="针对一个拥有5名开发者和1000名用户的初创公司" ) print(result)

    高级实现

    python
    from pydantic import BaseModel
    from typing import Optional

    class PromptResult(BaseModel): output: str technique: str = "思维链提示" confidence: Optional[float] = None reasoning: Optional[str] = None

    class ChainofThoughtPromptingPrompter: """生产就绪的思维链提示实现。""" def __init__(self, model: str = "gpt-4o"): self.client = OpenAI() self.model = model self.technique = "思维链提示" def run(self, task: str, **kwargs) -> PromptResult: """执行思维链提示。""" response = self.client.chat.completions.create( model=self.model, messages=self._build_messages(task, **kwargs), temperature=kwargs.get("temperature", 0.3), max_tokens=kwargs.get("max_tokens", 2000) ) content = response.choices[0].message.content return PromptResult( output=content, technique=self.technique ) def _build_messages(self, task: str, **kwargs) -> list[dict]: """构建思维链提示特定的消息。""" system = f"""你是一位使用{self.technique}解决任务的专家。 系统地应用逐步推理。 格式:提供清晰、结构化的响应。""" return [ {"role": "system", "content": system}, {"role": "user", "content": self._build_prompt(task, **kwargs)} ] def _build_prompt(self, task: str, **kwargs) -> str: """构建思维链提示的具体提示。""" return f"""使用{self.technique}完成以下任务:

    任务:{task}

    应用逐步推理来得出高质量答案。"""

    使用

    prompter = ChainofThoughtPromptingPrompter() result = prompter.run("编写一个Python函数来安全地解析JSON") print(result.output)

    真实世界用例

    用例1:数学和逻辑任务

    python
    

    专门用于数学和逻辑任务

    prompter = ChainofThoughtPromptingPrompter(model="gpt-4o")

    示例:数学和逻辑任务

    result = prompter.run( f"解决这个数学和逻辑任务问题:[你的具体问题在此]" ) print(f"解决方案:{result.output}")

    用例2:内容生成

    python
    

    应用于内容创作

    result = prompter.run( "写一篇关于AI代理的技术博客文章引言", temperature=0.7, # 创意任务使用更高温度 max_tokens=500 ) print(result.output)

    与其他技术的比较

    技术最适合令牌数可靠性

    标准提示简单任务低中等 思维链提示数学和逻辑任务中等高 思维链数学/逻辑高高 少样本提示格式任务高非常高

    常见错误

    衡量有效性

    python
    import json
    from statistics import mean

    def evaluate_prompt_quality( prompter: ChainofThoughtPromptingPrompter, test_cases: list[dict], n_runs: int = 3 ) -> dict: """通过多次运行评估提示质量。""" scores = [] for test in test_cases: run_scores = [] for _ in range(n_runs): result = prompter.run(test["task"]) # 根据预期输出评分 score = 1.0 if test.get("expected") in result.output else 0.5 run_scores.append(score) scores.append(mean(run_scores)) return { "technique": "思维链提示", "avg_score": mean(scores), "test_cases": len(test_cases) }

    资源

    相关工具

    openaianthropicpython