{
  "id": "prompting-basics",
  "module": "ai-basics",
  "level": 1,
  "minutes": 15,
  "audiences": [
    "beginner",
    "developer"
  ],
  "software": [
    "chatgpt",
    "claude",
    "chatbox"
  ],
  "text": {
    "en": {
      "title": "Prompting Basics: How to Get More Reliable Answers from AI (with Templates)",
      "description": "A practical introduction to prompting: state the goal, context, format and constraints; use few-shot examples and step-by-step reasoning; get JSON you can validate; and know when to switch to retrieval (RAG) or tools. Based on OpenAI, Anthropic and Google guides and the research papers.",
      "updated": "2026-10-22",
      "takeaways": [
        "A good prompt = goal + context + output format + constraints. Treat the model as a brilliant new colleague who knows nothing about your situation.",
        "Few-shot examples — 2 to 5 “input → output” pairs in the prompt — steer the model better than long descriptions.",
        "Asking the model to work through steps before answering (chain of thought) clearly helps on maths and multi-step reasoning; sampling several answers and taking the majority (self-consistency) helps further.",
        "When code will read the result, use the platform's structured-output (JSON Schema) feature and validate it again in your code.",
        "Prompting cannot supply what the model does not know: use retrieval (RAG) for fresh or private data and tools for exact calculations or actions."
      ],
      "faq": [
        {
          "q": "Are longer prompts better?",
          "a": "No. What matters is complete information, not word count. Irrelevant background distracts; put key requirements somewhere clear and separate instructions from material with headings or XML/Markdown tags."
        },
        {
          "q": "Does giving the AI a role (“You are a senior lawyer”) help?",
          "a": "Somewhat: it helps the model pick the right tone and depth, and Anthropic's guide recommends setting a role in the system prompt. But a role is no substitute for a specific task description and the relevant material."
        },
        {
          "q": "Do reasoning models still need “think step by step”?",
          "a": "Usually not. OpenAI's guide notes that reasoning models do better with high-level guidance. For ordinary chat models, asking for step-by-step reasoning still helps."
        },
        {
          "q": "Why does the same prompt give different answers?",
          "a": "Generation involves random sampling. For stable results, lower the temperature, add examples and a fixed format, and re-run a set of test questions after every change."
        }
      ],
      "sources": [
        {
          "title": "OpenAI, Prompt engineering guide",
          "url": "https://developers.openai.com/api/docs/guides/prompt-engineering"
        },
        {
          "title": "OpenAI, Structured Outputs guide",
          "url": "https://developers.openai.com/api/docs/guides/structured-outputs"
        },
        {
          "title": "Anthropic, Prompt engineering overview (Claude docs)",
          "url": "https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview"
        },
        {
          "title": "Anthropic, Prompting best practices (Claude docs)",
          "url": "https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices"
        },
        {
          "title": "Anthropic, Prompt Engineering Interactive Tutorial (GitHub)",
          "url": "https://github.com/anthropics/prompt-eng-interactive-tutorial"
        },
        {
          "title": "Google, Gemini API prompting strategies",
          "url": "https://ai.google.dev/gemini-api/docs/prompting-strategies"
        },
        {
          "title": "Brown et al. (2020), Language Models are Few-Shot Learners (GPT-3)",
          "url": "https://arxiv.org/abs/2005.14165"
        },
        {
          "title": "Wei et al. (2022), Chain-of-Thought Prompting Elicits Reasoning in Large Language Models",
          "url": "https://arxiv.org/abs/2201.11903"
        },
        {
          "title": "Kojima et al. (2022), Large Language Models are Zero-Shot Reasoners",
          "url": "https://arxiv.org/abs/2205.11916"
        },
        {
          "title": "Wang et al. (2022), Self-Consistency Improves Chain of Thought Reasoning in Language Models",
          "url": "https://arxiv.org/abs/2203.11171"
        },
        {
          "title": "DAIR.AI, Prompt Engineering Guide",
          "url": "https://www.promptingguide.ai/"
        },
        {
          "title": "Lilian Weng (2023), Prompt Engineering",
          "url": "https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/"
        }
      ],
      "url": "https://aimap.page/en/learn/ai-basics/prompting-basics/",
      "markdown": "## The short answer\n\nA **prompt** is everything you give a large language model: instructions, material, examples and format requirements. The model can only predict the next token from the context you provide (see [What Is a Large Language Model?](/learn/what-is-an-llm)), so the clearer the prompt, the more reliable the answer. The official guides from OpenAI, Anthropic and Google agree closely: **be clear, give examples, give structure, and define what “good” looks like.**\n\n## Step 1: instructions, roles and context\n\nPicture the model as a brilliant new colleague who **knows nothing about your situation** (Anthropic's guide uses the same image). A complete prompt usually has four parts:\n\n| Part | What to write | Example |\n|---|---|---|\n| Goal | What to produce and for whom | “Write a refund-process guide for newly hired support staff” |\n| Context | Information the model cannot know | The policy text, product names, an existing template |\n| Format | What the output looks like | “A numbered list of 5 steps, each under 20 words” |\n| Constraints | What not to do, what to do when unsure | “If the policy doesn't cover a case, answer ‘escalate to a human’; don't guess” |\n\nPractical tips:\n\n- **Separate instructions from material.** Wrap the content to process in headings, triple quotes or XML tags (for example `<policy>…</policy>`) so the model is less likely to treat sentences in it as instructions.\n- **Long documents first, question last.** Anthropic's docs recommend placing long documents at the top of the prompt and the query at the end.\n- **Add a role, but don't rely on it.** “You are a senior financial analyst” adjusts tone and depth; the specific task and material still decide quality.\n- **Use the system prompt** for rules that stay the same, and the user message for each specific task.\n\n## Step 2: few-shot examples\n\nInstead of describing the style you want at length, **show 2–5 examples**. The GPT-3 paper showed that a model can perform tasks it was never specifically trained for just from a few examples in the prompt — “in-context learning” ([Brown et al., 2020](https://arxiv.org/abs/2005.14165)).\n\n```text\nClassify user feedback as: feature request / bug / praise.\n\nFeedback: The export button does nothing when I click it → bug\nFeedback: Please let me filter by date → feature request\nFeedback: Your support agent was so patient, thanks! → praise\n\nFeedback: The mobile app shows a blank screen after login →\n```\n\nMake examples **cover different cases** (including edge cases) and match the exact output format you want. Avoid near-identical examples, or the model learns only the surface pattern.\n\n## Step 3: let the model think step by step\n\nFor maths, logic or multi-step problems, asking the model to **write out its reasoning before the answer** improves accuracy noticeably. This is **chain-of-thought prompting** ([Wei et al., 2022](https://arxiv.org/abs/2201.11903)). Even adding “Let's think step by step” helps ([Kojima et al., 2022](https://arxiv.org/abs/2205.11916)). Going further, have the model **solve the problem several times and take the most common answer** — **self-consistency** ([Wang et al., 2022](https://arxiv.org/abs/2203.11171)).\n\nTwo caveats:\n\n- **Reasoning models** (which “think” before answering) already do this internally. OpenAI's guide likens a reasoning model to a senior co-worker who can be given a goal and trusted with the details, while GPT models need more explicit instructions.\n- A written-out chain of reasoning is not guaranteed to be correct; still check the final answer.\n\n## Step 4: structured output (JSON)\n\nIf a program will consume the result, ask for a fixed format such as **JSON**.\n\n1. **Prefer the platform feature.** OpenAI's Structured Outputs, for example, makes the output conform to a JSON Schema you supply ([OpenAI docs](https://developers.openai.com/api/docs/guides/structured-outputs)).\n2. **Without such a feature,** list the field names and types with a full example, and say “output JSON only, no extra text”.\n3. **Always validate in code.** If parsing fails or fields are missing, retry or raise an error rather than using it as is.\n\n```json\n{\"category\": \"bug\", \"product_area\": \"login\", \"urgency\": \"high\", \"summary\": \"Blank screen after mobile login\"}\n```\n\n## Step 5: iterate on prompts like code\n\nPrompts are rarely right the first time. A dependable loop:\n\n1. Collect **5–20 real test questions** (including hard and edge cases) and write down what a good answer looks like.\n2. After every prompt change, run the same set and compare results.\n3. **Split complex tasks into steps** (extract, then analyse, then write), one prompt each — easier to control than one giant prompt.\n\nFor evaluating model outputs systematically, see [How to Evaluate LLMs](/learn/llm-evaluation).\n\n## When prompting is not enough\n\nPrompting can only draw on what the model **already can do**; it cannot add what the model doesn't know:\n\n| Problem | Better approach |\n|---|---|\n| You need fresh information or internal documents | Retrieval-augmented generation ([RAG](/learn/what-is-rag)), web search or file upload |\n| You need exact calculation, database lookups or system actions | [Tool calling and MCP](/learn/tool-calling-mcp), a code interpreter |\n| You need multi-step execution that adapts to results | [AI agents](/learn/how-agents-work) |\n| High-volume tasks with strict, stable style requirements | Fine-tuning |\n\nAlso, when processing **external content** — web pages, emails, documents — it may contain text like “ignore previous instructions”. That is [prompt injection](/learn/prompt-injection), and prompting alone cannot defend against it.\n\n## Try it yourself\n\n1. Pick a task you repeat every week, write it as a goal + context + format + constraints template, test it on 5 real cases, and revise it three times, noting what went wrong each time.\n2. Work through Anthropic's [interactive prompt-engineering tutorial](https://github.com/anthropics/prompt-eng-interactive-tutorial).\n3. Compare the [OpenAI prompting guide](https://developers.openai.com/api/docs/guides/prompt-engineering), [Gemini prompting strategies](https://ai.google.dev/gemini-api/docs/prompting-strategies) and the [Prompt Engineering Guide](https://www.promptingguide.ai/) and note what they agree on."
    },
    "zh-hans": {
      "title": "提示词基础：怎样让 AI 的回答更可靠（附模板）",
      "description": "提示词（Prompt）入门：写清目标、背景、格式和约束；用少样本示例和分步思考提升准确率；让模型输出可校验的 JSON；以及什么时候该改用检索（RAG）或工具。依据 OpenAI、Anthropic、Google 官方指南与论文。",
      "updated": "2026-10-22",
      "takeaways": [
        "好提示 = 目标 + 背景 + 输出格式 + 约束。把模型当成一个聪明但完全不了解你情况的新同事。",
        "少样本示例（few-shot）：在提示里给 2–5 个“输入 → 输出”的例子，比长篇描述更能让模型照着做。",
        "让模型先列出步骤再给答案（思维链），在数学和多步推理题上效果明显；多次采样取多数（自洽性）还能再提高。",
        "需要程序读取结果时，用平台的结构化输出（JSON Schema）功能，并且在代码里再校验一次。",
        "提示词解决不了“模型不知道的事”：需要最新或私有资料时改用检索（RAG），需要精确计算或操作时改用工具。"
      ],
      "faq": [
        {
          "q": "提示词越长越好吗？",
          "a": "不是。要的是“信息完整”，不是字数多。无关的背景会分散注意力；把关键要求放在清楚的位置，并用标题或 XML/Markdown 标签分隔指令和资料。"
        },
        {
          "q": "给 AI 设定角色（“你是一名资深律师”）有用吗？",
          "a": "有一定作用，能帮助模型选对语气和专业深度，Anthropic 的指南就建议用系统提示给模型设定角色。但角色代替不了具体的任务说明和资料。"
        },
        {
          "q": "推理模型还需要写“一步一步想”吗？",
          "a": "通常不需要。OpenAI 的指南指出，推理模型在只给高层指引时效果更好；对普通聊天模型，要求分步思考仍然有用。"
        },
        {
          "q": "同一个提示为什么每次回答不一样？",
          "a": "生成时有采样随机性。需要稳定结果时，调低 temperature、给出示例和固定格式，并用一组测试问题检查每次改动。"
        }
      ],
      "sources": [
        {
          "title": "OpenAI，Prompt engineering 指南",
          "url": "https://developers.openai.com/api/docs/guides/prompt-engineering"
        },
        {
          "title": "OpenAI，Structured Outputs 指南",
          "url": "https://developers.openai.com/api/docs/guides/structured-outputs"
        },
        {
          "title": "Anthropic，Prompt engineering overview（Claude 文档）",
          "url": "https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview"
        },
        {
          "title": "Anthropic，Prompting best practices（Claude 文档）",
          "url": "https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices"
        },
        {
          "title": "Anthropic，Prompt Engineering Interactive Tutorial（GitHub）",
          "url": "https://github.com/anthropics/prompt-eng-interactive-tutorial"
        },
        {
          "title": "Google，Gemini API 提示策略",
          "url": "https://ai.google.dev/gemini-api/docs/prompting-strategies"
        },
        {
          "title": "Brown 等（2020），Language Models are Few-Shot Learners（GPT-3）",
          "url": "https://arxiv.org/abs/2005.14165"
        },
        {
          "title": "Wei 等（2022），Chain-of-Thought Prompting Elicits Reasoning in Large Language Models",
          "url": "https://arxiv.org/abs/2201.11903"
        },
        {
          "title": "Kojima 等（2022），Large Language Models are Zero-Shot Reasoners",
          "url": "https://arxiv.org/abs/2205.11916"
        },
        {
          "title": "Wang 等（2022），Self-Consistency Improves Chain of Thought Reasoning in Language Models",
          "url": "https://arxiv.org/abs/2203.11171"
        },
        {
          "title": "DAIR.AI，Prompt Engineering Guide",
          "url": "https://www.promptingguide.ai/"
        },
        {
          "title": "Lilian Weng（2023），Prompt Engineering",
          "url": "https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/ai-basics/prompting-basics/",
      "markdown": "## 一句话回答\n\n**提示词（prompt）** 就是你交给大模型的全部输入：指令、资料、例子和格式要求。大模型只能根据你给的上下文去预测下一个 token（见 [大模型是什么](/learn/what-is-an-llm)），所以提示写得越清楚，回答越可靠。OpenAI、Anthropic、Google 的官方指南给出的建议高度一致：**说清楚、给例子、给结构、给检验标准。**\n\n## 第一步：指令、角色与上下文\n\n把模型想象成一个聪明但**对你的情况一无所知**的新同事（Anthropic 的指南也用了这个比喻）。一个完整的提示通常包含四块：\n\n| 部分 | 写什么 | 例子 |\n|---|---|---|\n| 目标 | 要完成什么、给谁看 | “为新入职的客服写一份退款流程说明” |\n| 背景 | 模型不可能知道的信息 | 公司政策原文、产品名称、已有的模板 |\n| 格式 | 输出长什么样 | “5 个步骤的编号列表，每步不超过 30 字” |\n| 约束 | 不能做什么、遇到不确定怎么办 | “政策里没写的情况，回答‘需转人工’，不要猜” |\n\n几个实用技巧：\n\n- **把指令和资料分开**。用标题、三引号或 XML 标签（如 `<政策>…</政策>`）把要处理的材料包起来，模型更不容易把资料里的句子当成指令。\n- **长资料放前面、问题放最后**。Anthropic 的文档建议，处理长文档时把文档放在提示开头、把问题放在末尾。\n- **角色可以加，但不能只靠角色**。“你是一名资深财务分析师”能调整语气和深度，但真正决定质量的仍是具体任务和资料。\n- **系统提示（system prompt）** 放长期不变的规则，用户消息放每次的具体任务。\n\n## 第二步：少样本示例（few-shot）\n\n与其用一大段话描述你想要的风格，不如**直接给 2–5 个例子**。GPT-3 的论文显示，模型只看提示里的几个例子，就能完成它没专门训练过的任务，这被称为“上下文学习”（in-context learning）（[Brown 等，2020](https://arxiv.org/abs/2005.14165)）。\n\n```text\n把用户反馈分类为：功能建议 / 故障 / 表扬。\n\n反馈：导出按钮点了没反应 → 故障\n反馈：希望能按日期筛选 → 功能建议\n反馈：客服小王很耐心，谢谢！ → 表扬\n\n反馈：手机端登录后一直白屏 →\n```\n\n要点：例子要**覆盖不同情况**（包括边界情况），格式要和你期望的输出完全一致；例子之间别太相似，否则模型会只学到表面的套路。\n\n## 第三步：让模型分步思考\n\n对数学、逻辑或多步骤的问题，让模型**先写出推理步骤再给答案**，准确率会明显提高。这就是**思维链提示**（Chain-of-Thought，[Wei 等，2022](https://arxiv.org/abs/2201.11903)）。研究还发现，只加一句“让我们一步一步地思考”也有效果（[Kojima 等，2022](https://arxiv.org/abs/2205.11916)）。更进一步，可以让模型**独立解几遍，取出现最多的答案**，这叫**自洽性**（Self-Consistency，[Wang 等，2022](https://arxiv.org/abs/2203.11171)）。\n\n注意两点：\n\n- **推理模型**（会先“思考”再回答的模型）已经在内部做这件事。OpenAI 的指南说，推理模型像“资深同事”，给出高层目标就能自己补全细节；普通 GPT 模型则更需要精确的指令。\n- 写出来的推理过程不保证就是正确的，最终答案仍需核对。\n\n## 第四步：结构化输出（JSON）\n\n如果结果要交给程序处理，就让模型输出 **JSON** 这类固定格式。\n\n1. **优先用平台功能**：OpenAI 的 Structured Outputs 等功能可以让输出严格符合你提供的 JSON Schema（[OpenAI 文档](https://developers.openai.com/api/docs/guides/structured-outputs)）。\n2. **没有该功能时**：在提示里写出字段名、类型和一个完整示例，并说明“只输出 JSON，不要多余文字”。\n3. **始终在代码里校验**：解析失败或字段缺失时，重试或报错，不要直接用。\n\n```json\n{\"category\": \"故障\", \"product_area\": \"登录\", \"urgency\": \"高\", \"summary\": \"手机端登录后白屏\"}\n```\n\n## 第五步：像写代码一样迭代提示\n\n一个提示很少一次就写对。可靠的做法是：\n\n1. 准备 **5–20 个真实测试问题**（包括难例和边界情况），并写下“什么算好回答”；\n2. 每改一次提示，就用同一组问题跑一遍，对比结果；\n3. 把复杂任务**拆成几步**（先提取、再分析、最后写作），每一步一个提示，比一个超长提示更好控制。\n\n系统地评估模型输出，见 [如何评估大模型](/learn/llm-evaluation)。\n\n## 什么时候提示词不够用\n\n提示词只能调动模型**已有的能力**，补不上它不知道的东西：\n\n| 问题 | 更合适的做法 |\n|---|---|\n| 需要最新信息或公司内部资料 | 检索增强生成 [RAG](/learn/what-is-rag)，或开启联网搜索、上传文件 |\n| 需要精确计算、查数据库、调用系统 | [工具调用与 MCP](/learn/tool-calling-mcp)、代码解释器 |\n| 需要多步执行并根据结果调整 | [AI Agent](/learn/how-agents-work) |\n| 同一类任务量大、风格要求高且稳定 | 微调（fine-tuning） |\n\n另外，处理来自网页、邮件、文档等**外部内容**时，里面可能藏着“忽略之前的指令”之类的文字，这就是 [提示注入](/learn/prompt-injection)，不能只靠提示词防住。\n\n## 动手试试\n\n1. 选一个你每周都要做的重复任务，按“目标 + 背景 + 格式 + 约束”写成模板，用 5 个真实案例测试，改三版并记录每版的问题。\n2. 跟着 Anthropic 的 [交互式提示工程教程](https://github.com/anthropics/prompt-eng-interactive-tutorial) 做练习。\n3. 对照 [OpenAI 提示指南](https://developers.openai.com/api/docs/guides/prompt-engineering)、[Gemini 提示策略](https://ai.google.dev/gemini-api/docs/prompting-strategies) 和 [Prompt Engineering Guide](https://www.promptingguide.ai/)，看看不同厂商的建议有哪些共同点。"
    }
  }
}