提示:本网站现在为维护调试状态

Prompt Engineering 101: Few-Shot + CoT + Structured Output

Choyeon
Choyeon
Sep 21, 2026 1 min read 587 Views
705 words 2,935 chars Updated Nov 8, 2026
Prompt Engineering 101: Few-Shot + CoT + Structured Output
Table of contents

Model capabilities are fixed; what truly differentiates outcomes is Prompt Engineering. Mastering the big three (few-shot exemplars, chain-of-thought, structured output) lifts quality one tier on the same model, reliably feeding production pipelines.

Few-Shot: Style Alignment by Example

"Rewrite professionally" is vague and yields random results. Prepend 2-3 real input-output exemplars in the prompt; the model precisely learns your style, formatting rules, and terminology preferences from concrete samples. Far more stable than pure natural-language instructions, and handles bilingual mixed corpora.

from openai import AsyncOpenAI
import json
from typing import Any
from pydantic import BaseModel, Field

client = AsyncOpenAI()

FEW_SHOT_PROMPT = '''你是资深后端技术写作编辑,擅长将草稿改写成精炼博客风格。
要求:事实准确,保留技术细节,简洁专业,段落开头先给核心结论。

## 示例1 输入
"FastAPI比Flask快,因为用了ASGI和Pydantic,自动生成文档"
## 示例1 输出
**核心结论:FastAPI 通过 ASGI 异步 + Pydantic 类型驱动两大设计,同等硬件下单接口吞吐量约为 Flask 的 2.5-4 倍。**
除异步网络栈外,FastAPI 的请求校验基于 Pydantic v2 的 Rust 内核(pydantic-core),单个 schema 校验耗时较 Flask + marshmallow 方案低一个数量级;另一个隐形收益是基于 OpenAPI spec 自动生成的接口文档和类型化客户端 SDK,在团队协作场景相当于免费的 API 契约工具链。

## 待改写输入
"{raw_input}"

## 你的输出'''

COT_PROMPT = '''你是算法竞赛金牌选手。请逐步推导再给出最终答案,每一步标记并解释推理依据。
问题:给定数组 nums = [3, 1, 4, 2, 5, 8, 7, 6],求最长递增子序列的长度。
思考步骤:
步骤1:
步骤2:
步骤3:
最终答案(仅数字):'''

class ProductCategorizeResult(BaseModel):
    reasoning: list[str] = Field(description="分类判断过程,每个维度一条")
    category: str = Field(description="必须属于 [Electronics, Fashion, Books, Home, Other]")
    confidence: float = Field(ge=0.0, le=1.0)
    matched_keywords: list[str] = Field(default_factory=list)

async def few_shot_transform(raw: str) -> str:
    r = await client.chat.completions.create(
        model="gpt-4o-mini", temperature=0.3,
        messages=[{"role": "user", "content": FEW_SHOT_PROMPT.format(raw_input=raw)}])
    return r.choices[0].message.content or ""

async def categorize_structured(title: str, desc: str) -> dict[str, Any]:
    r = await client.chat.completions.create(
        model="gpt-4o-mini-2024-07-18", temperature=0.0,
        messages=[{"role": "user", "content": f"商品标题 {title}\n描述 {desc}"}],
        response_format={"type": "json_object"})
    data = json.loads(r.choices[0].message.content or "{}")
    return ProductCategorizeResult(**data).model_dump()

Chain-of-Thought & Structured Outputs

For multi-step reasoning (logic/math/code debugging), explicitly require step-by-step deduction before final answer - accuracy typically improves 15-30%. For downstream-system consumption, enforce JSON mode via Pydantic response_format + retry on parse failures to avoid brittle free-text regex scraping.

Technique Problem Solved Optimal Temp Typical Use Cases
Zero-Shot instruction Simple standard tasks 0.1-0.3 Translation, summarization, format conversion
Few-Shot exemplar injection Custom style/format rules 0.2-0.5 Copy rewrite, labeling, coding style alignment
Chain-of-Thought steps Multi-step reasoning/logic 0.0-0.3 Algorithm problems, debugging, root cause analysis
JSON Schema structured Program interface handoff 0.0 fixed Tag ingestion, field extraction, function calling

Best Practices

Start prompts with role (System), then context+task, then constraints (word count/format/tone/forbidden). Iterate against 20 labeled samples for real accuracy metrics; failure cases feed back as few-shot exemplars so every improvement has quantified evidence.

X微博Telegram

About the author

Poll

你最希望 Rosetta 优先加入哪项功能?

社区投票(演示数据,可后台删除)

Comments (3)

0 / 3000
前端艺术家
前端艺术家fe-gallery.devSep 11, 2026

代码示例里那个 SQL 查询是不是应该加个 LIMIT?不然数据量大的时候全表扫描会很慢哦。

机器学习萌新
机器学习萌新Sep 11, 2026

建议加一下关于幂等性的讨论,现在的分布式系统里这个真的太重要了,很多坑都是没处理好幂等导致的。

运维老司机
运维老司机ops-notes.cnSep 10, 2026

太及时了,正好项目里要上 Redis 集群,照着来一遍省了好多事,谢谢!

Related posts

GraphQL vs REST: 7-Dimension Deep Comparison

GraphQL vs REST: 7-Dimension Deep Comparison

End the API style debate: compared across 7 dimensions - network efficiency, DX, evolution cost, caching, type-safety, security risks, ecosystem - with clear decision tree and hybrid architecture patterns.

1 min read
RAG in Practice: Embedding + Vector DB + ReRank

RAG in Practice: Embedding + Vector DB + ReRank

Build production-grade RAG from scratch: doc chunking (size + overlap windows), embedding model selection, vector DB retrieval filters, Reranker refining Top-K, plus citation grounding and prompt compression. Complete runnable code included.

1 min read
JWT Security Best Practices + OAuth2 vs SAML

JWT Security Best Practices + OAuth2 vs SAML

Comprehensive JWT vulnerability playbook: alg confusion attacks, key brute force, KID injection, replay defenses. Compare OAuth2(+PKCE), OIDC, SAML 2.0 across dimensions for protocol selection.

1 min read
CQRS + Event Sourcing Architecture Patterns

CQRS + Event Sourcing Architecture Patterns

Advanced patterns: CQRS separate read/write models for query performance; Event Sourcing using events as source of truth for audit + time travel. Covers consistency, snapshots, idempotency pitfalls and anti-patterns.

1 min read
Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Systematic test pyramid breakdown: bottom unit tests (many, fast, mock isolated), middle integration tests (real service/db/message interaction), top E2E tests (few, critical user flows). Recommended ratio 70/20/10, with coverage metrics and implementation playbook.

1 min read
Advanced Git Workflows

Advanced Git Workflows

Master advanced Git: Interactive Rebase for history cleanup, Cherry-pick selective commit porting, Bisect binary-search bug regression hunting, reflog and reset recovery.

1 min read