AI: 生成式 AI 与大模型
最后更新:2026-08-26
生成式 AI 是当前最火的技术方向——ChatGPT、Midjourney、GitHub Copilot 都是它的产物。本章帮你搞清楚:什么是生成式 AI?大语言模型怎么工作?Token、上下文窗口、温度参数是什么?如何用 5 行 Python 代码调通 LLM API?
1. 你将学到
- 生成式 AI vs 判别式 AI 的区别
- 大语言模型(LLM)的工作原理
- Token 与上下文窗口
- GPT/Claude/Llama 模型家族概览
- 用 Python 调用 LLM API
2. 故事:5 行代码的 AI 助手
(1) 痛点:客服系统的智能升级
Alice 在一家电商公司做后端开发,老板要求给客服系统加一个 AI 助手,能自动回答用户常见问题。Alice 听说了 GPT 和 ChatGPT,但不知道怎么用——"那是搞算法的人的事吧?我一个写 CRUD 的能搞定?"
(2) Bob 的 5 行代码解法
Bob 拉过键盘,5 分钟写了 5 行 Python 代码调通了 OpenAI API:
from openai import OpenAI
client = OpenAI(api_key="your-api-key")
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "How to return a product?"}]
)
print(response.choices[0].message.content)
Bob 说:"你看,大模型就是一个超级强大的文本生成器,你给它 Prompt,它给你回答。跟调 REST API 没区别。"
▶ 示例:5 行代码调通 OpenAI API(难度⭐)
# Minimal OpenAI API call
from openai import OpenAI
client = OpenAI() # Uses OPENAI_API_KEY env variable
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say hello in 3 languages."}]
)
print(response.choices[0].message.content)
Hello! / ¡Hola! / Hello!
(3) 收益:API 思维破局
Alice 发现——调用 LLM 不需要懂 Transformer 的数学推导,就像调用数据库不需要懂 B+ 树的实现。理解原理帮你做更好的选择,但上手只需要 API。
3. 判别式 AI vs 生成式 AI
(1) 两种 AI 范式
AI 模型按输出目标分为两大范式:
| 维度 | 判别式 AI(Discriminative) | 生成式 AI(Generative) |
|---|---|---|
| 目标 | 区分/分类已有数据 | 生成新数据 |
| 学习内容 | 决策边界(分类线) | 数据分布(如何生成) |
| 输入→输出 | 特征 → 类别/数值 | Prompt → 新文本/图片/代码 |
| 典型任务 | 分类、回归、检测 | 文本生成、图像生成、代码生成 |
| 代表模型 | ResNet、SVM、BERT(编码器) | GPT、Stable Diffusion、Midjourney |
| 典型应用 | 垃圾邮件过滤、人脸识别 | ChatGPT、AI 绘图、代码补全 |
| 输出确定性 | 确定性(同类输入同类输出) | 随机性(同一 Prompt 多次输出不同) |
直觉理解:判别式 AI 回答"这是什么",生成式 AI 回答"给我创造一个"。
(2) 为什么生成式 AI 这么火?
生成式 AI 在 2022-2023 年爆发,三个原因:
- Transformer 架构(2017)让模型能处理长文本
- 海量数据 + 大算力让模型规模从亿级跃升到千亿级
- RLHF(人类反馈强化学习)让模型输出对齐人类偏好
(3) 判别式和生成式能结合吗?
能。现代 AI 应用经常组合两者——先用判别式模型做意图分类,再用生成式模型生成回复。ChatGPT 的"函数调用"功能本质就是判别(判断该调哪个函数)+ 生成(生成函数参数和自然语言回复)。
4. 大语言模型(LLM)的工作原理
(1) 核心机制:下一个 Token 预测
LLM 的本质极其简单——给定前面的文本,预测下一个最可能出现的 Token。反复执行这个预测,就生成了完整回复。
Input: "The cat sat on the"
Step 1: "The cat sat on the" → predict "mat" (most likely next token)
Step 2: "The cat sat on the mat" → predict "."
Step 3: "The cat sat on the mat." → predict "<END>"
Output: "The cat sat on the mat."
这不是"理解"文本,而是学到了海量文本中 Token 出现的统计规律。但因为训练数据足够大(互联网级别),这种统计规律展现出了令人惊叹的"智能"。
(2) LLM 生成流程
graph LR
A[Prompt<br/>Input Text] --> B[Tokenizer<br/>Tokenize]
B --> C[Transformer<br/>Model Inference]
C --> D[Next Token<br/>Probability Dist.]
D --> E[Sampling<br/>Temp/Top-P Sample]
E --> F[Decode<br/>Decode to Text]
F --> G{Done?}
G -->|No| C
G -->|Yes| H[Output<br/>Full Output Text]
(3) Transformer 架构直觉
Transformer 是 LLM 的核心引擎,2017 年由 Google 在论文 "Attention Is All You Need" 中提出。它的关键创新是自注意力机制(Self-Attention)——让模型在处理每个 Token 时,能"看到"输入中所有其他 Token 并计算相关性。
| 组件 | 作用 | 直觉 |
|---|---|---|
| Self-Attention | 计算 Token 间关联度 | 阅读时自动关注关键信息 |
| Feed-Forward | 对每个 Token 做非线性变换 | 理解和加工信息 |
| Layer Norm | 稳定训练 | 保持数值稳定 |
| Positional Encoding | 标注位置信息 | 理解词序("猫吃鱼"≠"鱼吃猫") |
5. Token 与上下文窗口
(1) 什么是 Token?
Token 是 LLM 处理文本的最小单位。它不是字符也不是单词,而是介于两者之间的"子词"(subword)。
Text: "Hello, world!"
Tokens: ["Hello", ",", " world", "!"] → 4 tokens
Text: "artificial intelligence"
Tokens: ["art", "ific", "ial"] → 3 tokens (subword tokenization)
英文平均 1 个 Token ≈ 4 个字符(约 0.75 个单词)。中文平均 1 个 Token ≈ 1-2 个汉字,所以中文的 Token 消耗通常是英文的 2-3 倍。
▶ 示例:用 tiktoken 计算 Token 数(难度⭐)
# Calculate token count using tiktoken
import tiktoken
encoding = tiktoken.encoding_for_model("gpt-4o-mini")
texts = [
"Hello, world!",
"The quick brown fox jumps over the lazy dog.",
"Artificial intelligence is changing the world.",
"Generative AI is transforming the world."
]
for text in texts:
tokens = encoding.encode(text)
print(f"Text: {text}")
print(f" Tokens: {len(tokens)} | Decoded: {encoding.decode(tokens[:3])}...")
print()
Text: Hello, world!
Tokens: 3 | Decoded: Hello...
Text: The quick brown fox jumps over the lazy dog.
Tokens: 10 | Decoded: The quick brown...
Text: Artificial intelligence is changing the world.
Tokens: 8 | Decoded: Artifici...
Text: Generative AI is transforming the world.
Tokens: 8 | Decoded: Generative AI is...
(2) 上下文窗口(Context Window)
上下文窗口是 LLM 一次能处理的最大 Token 数。它决定了模型能"记住"多少信息——输入 + 输出的总 Token 数不能超过这个限制。
| 模型 | 上下文窗口 | 大约能容纳 |
|---|---|---|
| GPT-4o-mini | 128K tokens | ~300 页英文书 |
| GPT-4o | 128K tokens | ~300 页英文书 |
| Claude 3.5 Sonnet | 200K tokens | ~500 页英文书 |
| Llama 3.1 405B | 128K tokens | ~300 页英文书 |
(3) Token 计费方式对比
LLM API 按 Token 用量计费,输入和输出价格不同:
| 模型 | 输入价格(/1M tokens) | 输出价格(/1M tokens) | 说明 |
|---|---|---|---|
| GPT-4o-mini | $0.15 | $0.60 | 性价比最高,日常首选 |
| GPT-4o | $2.50 | $10.00 | 高质量,复杂任务 |
| Claude 3.5 Sonnet | $3.00 | $15.00 | 长文本、代码强 |
| Llama 3.1 70B(托管) | ~$0.20 | ~$0.20 | 开源模型,自部署免费 |
6. 温度与采样参数
(1) 温度(Temperature)
温度控制 LLM 输出的随机性。温度越低,输出越确定;温度越高,输出越多样。
Temperature = 0 → Always pick the most likely token (deterministic)
Temperature = 0.7 → Mostly likely but with some variation (default for chat)
Temperature = 1.0 → Natural variation, follows the learned distribution
Temperature = 2.0 → Very random, often nonsensical
(2) Top-P(核采样)
Top-P 是另一种控制随机性的参数。它只从概率累计前 P 的 Token 中采样:
Top-P = 0.1 → Only consider top 10% most likely tokens (conservative)
Top-P = 0.9 → Consider tokens covering 90% probability (moderate)
Top-P = 1.0 → Consider all tokens (no filtering)
| 参数场景 | Temperature | Top-P | 效果 |
|---|---|---|---|
| 代码生成 | 0 | 1 | 确定性强,代码正确 |
| 创意写作 | 0.8 | 0.9 | 有创意但不离谱 |
| 头脑风暴 | 1.2 | 0.95 | 多样性高,可能出奇 |
| 数据提取 | 0 | 1 | 格式稳定,JSON 可靠 |
▶ 示例:不同温度参数的输出对比(难度⭐⭐)
# Compare outputs at different temperatures
from openai import OpenAI
client = OpenAI()
prompt = "Write a one-sentence description of a sunset."
temperatures = [0, 0.5, 1.0, 1.5]
for temp in temperatures:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=temp,
max_tokens=50
)
text = response.choices[0].message.content
print(f"Temperature={temp}: {text}")
print()
Temperature=0: The sun dipped below the horizon, painting the sky in shades of orange and pink.
Temperature=0.5: Golden light spilled across the horizon as the sun melted into a sea of amber clouds.
Temperature=1.0: The day's final breath set the clouds ablaze, draping the world in a warm, fading embrace of crimson and gold.
Temperature=1.5: Colors—copper, violet, impossible rose—bloomed like dying flowers across the fractured sky as the sun surrendered.
7. GPT 系列演进与模型家族
(1) GPT 系列演进
| 模型 | 年份 | 参数量 | 关键突破 |
|---|---|---|---|
| GPT-1 | 2018 | 1.17 亿 | 证明预训练 + 微调范式可行 |
| GPT-2 | 2019 | 15 亿 | 展示规模化能力,"太危险"不敢全量发布 |
| GPT-3 | 2020 | 1750 亿 | In-context Learning,少样本学习 |
| Codex | 2021 | 12 亿(代码专项) | 代码生成,GitHub Copilot 的引擎 |
| ChatGPT | 2022 | GPT-3.5 | 加 RLHF,对话式 AI 走向大众 |
| GPT-4 | 2023 | 未公开(推测 trillion-level) | 多模态(文本 + 图像),推理能力飞跃 |
| GPT-4o | 2024 | 未公开 | 原生多模态(文本/图像/语音),速度翻倍 |
(2) 主流 LLM 对比
| 维度 | GPT-4o | Claude 3.5 Sonnet | Llama 3.1 405B | Qwen 2.5 72B |
|---|---|---|---|---|
| 开发商 | OpenAI | Anthropic | Meta | Alibaba |
| 类型 | 闭源 | 闭源 | 开源 | 开源 |
| 上下文 | 128K | 200K | 128K | 128K |
| 多模态 | 文本/图/音 | 文本/图 | 文本 | 文本/图 |
| 强项 | 综合均衡 | 长文本/代码/安全 | 自部署/可定制 | 中文/多语言 |
| API 价格 | 中高 | 中高 | 自部署免费 | 自部署免费 |
| 适合 | 通用生产环境 | 企业级应用 | 私有化/研究 | 中文场景 |
(3) 开源 vs 闭源模型对比
| 维度 | 闭源模型(GPT/Claude) | 开源模型(Llama/Qwen/Mistral) |
|---|---|---|
| 权重 | 不公开 | 公开可下载 |
| 部署 | 只能通过 API | 可自部署(需 GPU) |
| 数据隐私 | 数据经第三方服务器 | 数据不出本地 |
| 定制 | 仅 Prompt/微调 API | 全量微调/LoRA/RLHF |
| 成本 | 按 Token 计费,量大贵 | GPU 成本固定,量大便宜 |
| 上手难度 | 低(调 API 即可) | 高(需 GPU + 部署知识) |
| 模型能力 | 最强(GPT-4o 级) | 接近但略弱(Llama 3.1 405B 接近 GPT-4) |
8. API 调用模式
(1) 基础调用模式
调用 LLM API 的核心参数只有三个:model、messages、可选的 temperature。
▶ 示例:OpenAI API 基础调用(难度⭐)
# Basic OpenAI API call with system prompt
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "What is a Transformer in 2 sentences?"}
],
temperature=0.3
)
print(response.choices[0].message.content)
print(f"\nTokens used: {response.usage.total_tokens}")
A Transformer is a neural network architecture based on self-attention, allowing it to process all input tokens in parallel rather than sequentially. Introduced in 2017, it became the foundation for modern LLMs like GPT and BERT.
Tokens used: 58
(2) 多轮对话模式
Chat API 通过 messages 数组维护对话历史,每轮追加一条消息:
▶ 示例:多轮对话 API 调用(难度⭐⭐)
# Multi-turn conversation with OpenAI API
from openai import OpenAI
client = OpenAI()
conversation = [
{"role": "system", "content": "You are a helpful Python tutor."}
]
questions = [
"What is a list comprehension?",
"Can you show me an example?",
"What if I want to filter even numbers?"
]
for q in questions:
conversation.append({"role": "user", "content": q})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=conversation,
temperature=0.3
)
reply = response.choices[0].message.content
conversation.append({"role": "assistant", "content": reply})
print(f"User: {q}")
print(f"Bot: {reply[:120]}...")
print()
User: What is a list comprehension?
Bot: A list comprehension is a concise way to create lists in Python using a single line of syntax, combining a for loop and optional conditions...
User: Can you show me an example?
Bot: Sure! Here's a basic example: squares = [x**2 for x in range(10)] This creates a list [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]....
User: What if I want to filter even numbers?
Bot: Add a condition: evens = [x for x in range(20) if x % 2 == 0] This produces [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]....
(3) 流式输出模式
流式输出逐 Token 返回,用户体验更好(像打字机效果),也更快显示首个 Token:
▶ 示例:流式输出(stream=True)体验(难度⭐⭐)
# Streaming output with OpenAI API
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Explain quantum computing in 3 sentences."}],
temperature=0.5,
stream=True
)
print("Streaming response: ", end="")
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="", flush=True)
print("\n\n[Stream complete]")
Streaming response: Quantum computing uses quantum bits (qubits) that can exist in superposition, representing 0 and 1 simultaneously. This allows quantum computers to process many calculations in parallel, exponentially speeding up certain problems. Key applications include cryptography, drug discovery, and optimization.
[Stream complete]
stream=True 时返回的是迭代器而非完整响应,适合 Web 应用中逐字显示。但无法预先知道总 Token 数,需要通过最后一条 chunk 的 usage 字段获取。
9. 综合示例:AI 文案助手
构建一个"AI 文案助手":输入产品描述,调用 OpenAI API 生成 3 种风格的广告文案,打印对比。
▶ 示例:AI 文案助手——3 种风格广告文案生成(难度⭐⭐⭐)
# ============================================
# AI Copywriting Assistant
# Input: product description
# Output: 3 styles of ad copy
# ============================================
from openai import OpenAI
client = OpenAI()
product = "Wireless noise-cancelling headphones, 40-hour battery, $199"
styles = [
("Professional", "Write a professional, feature-focused ad copy."),
("Emotional", "Write an emotional, lifestyle-focused ad copy."),
("Humorous", "Write a humorous, witty ad copy.")
]
print("=" * 60)
print(f"Product: {product}")
print("=" * 60)
for style_name, style_prompt in styles:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": f"You are an expert copywriter. {style_prompt}"},
{"role": "user", "content": f"Write ad copy for: {product}. Keep it under 80 words."}
],
temperature=0.8,
max_tokens=150
)
copy = response.choices[0].message.content
tokens = response.usage.total_tokens
cost = (response.usage.prompt_tokens * 0.15 + response.usage.completion_tokens * 0.60) / 1_000_000
print(f"\n[{style_name}]")
print(f"{copy}")
print(f"\n(Tokens: {tokens}, Cost: ${cost:.6f})")
print("\n" + "=" * 60)
============================================================
Product: Wireless noise-cancelling headphones, 40-hour battery, $199
============================================================
[Professional]
Experience premium noise-cancelling technology with 40 hours of uninterrupted battery life. Our wireless headphones deliver crystal-clear audio and comfortable design for $199. Perfect for professionals who demand focus and quality.
(Tokens: 72, Cost: $0.000032)
[Emotional]
Escape the noise. Slip on these headphones and let the world fade away—40 hours of pure, uninterrupted bliss. Whether it's your morning commute or a quiet evening, your soundtrack awaits. Just $199 for peace you can hear.
(Tokens: 68, Cost: $0.000030)
[Humorous]
Tired of hearing your neighbor's karaoke? These noise-cancelling headphones block the chaos and deliver 40 hours of sweet silence. At $199, it's cheaper than moving. Your ears will thank you.
(Tokens: 58, Cost: $0.000025)
============================================================
❓ 常见问题
📖 小节
- 生成式 AI 学习数据分布来创造新内容,判别式 AI 学习决策边界来分类——两者可以组合使用
- LLM 的核心是"下一个 Token 预测":反复预测最可能的下一个 Token,串联成完整输出
- Token 是 LLM 的最小处理单位,中文 Token 消耗是英文的 2-3 倍;上下文窗口决定模型一次能处理多长的文本
- 温度控制输出随机性:0 = 确定,0.7 = 自然,1.5+ = 创意;Top-P 是另一种随机性过滤器
- GPT 系列从 1 亿参数演进到 trillion-level,GPT-4o 是当前 OpenAI 旗舰;开源阵营有 Llama、Qwen、Mistral
- 调用 LLM API 只需 3 个核心参数:model、messages、temperature;多轮对话需维护完整历史;流式输出提升用户体验
📝 作业
- 基础题(难度⭐):用 OpenAI API 写一个翻译小程序——输入中文,输出英文翻译。要求:system prompt 指定角色为翻译助手,temperature=0 保证翻译稳定。
- 进阶题(难度⭐⭐):用同一个 Prompt(如"写一首关于秋天的诗"),分别设置 temperature=0 和 temperature=1 各调用 5 次,记录并对比输出差异,总结温度对输出的影响规律。
- 挑战题(难度⭐⭐⭐):用 API 做一个简单的对话机器人:支持多轮对话(维护 messages 数组),遇到"bye"时退出循环;加入系统提示让机器人扮演某个角色(如"Python 编程导师"),并尝试用流式输出逐字打印回复。