SilverIce Toolbox
Back to course

Stage 6 / Chapter 28

第28章:LLM 应用与 Agent | Chapter 28: LLM Applications & Agents

阶段定位 | Stage: 第六阶段 — 无监督学习与生成式 AI 预计学时 | Duration: 3~4 小时

---

学习目标 | Learning Objectives

中文:

  • 掌握 Greedy/Beam Search/Sampling/Top-p 四种解码策略的原理与适用场景
  • 理解 Temperature 对采样分布的数学影响
  • 掌握 RAG 的完整流程:索引 → 检索 → 增强生成
  • 理解 Chain-of-Thought 的推理增强机制
  • 了解 Agent 的基本架构:LLM + 工具 + 规划 + 记忆
  • 掌握 Function Calling 的格式与实现

English:

  • Master four decoding strategies: Greedy, Beam Search, Sampling, Top-p
  • Understand Temperature's mathematical effect on sampling distribution
  • Master complete RAG pipeline: index → retrieve → augmented generation
  • Understand Chain-of-Thought reasoning enhancement
  • Know Agent architecture: LLM + tools + planning + memory
  • Master Function Calling format and implementation

---

28.1 解码策略 | Decoding Strategies

中文解释

Greedy Decoding

每次选择概率最高的词:

t_t = argmax P(w | w_{<t})
  • 优点:确定性强,可重复
  • 缺点:容易陷入重复,缺乏多样性

Beam Search

保留 top-k 个候选序列,每步扩展并选择最优的 k 个:

Beam size = k
每步: 扩展所有候选 × 词汇表 → 选 top-k
  • 优点:比 Greedy 质量更高
  • 缺点:仍然偏"安全",创造性不足;k 大时计算量高

Sampling(随机采样)

按概率分布随机选择:

w ~ P(w | w_{<t})
  • 优点:多样性好
  • 缺点:可能采样到低概率的荒谬词

Top-p(Nucleus Sampling)

只从累积概率达到 p 的最小词集合中采样:

按概率排序词,取前几个使累积概率 ≥ p
然后在这几个词中按重新归一化的概率采样

例如 p=0.9,可能只取 5~10 个词,排除长尾的低概率荒谬词。

English Explanation

Greedy: deterministic but repetitive. Beam Search: keeps top-k candidates. Sampling: diverse but may sample nonsense. Top-p: samples from smallest set with cumulative prob ≥ p.

---

28.2 Temperature | Temperature

中文解释

数学形式

在 softmax 之前除以 Temperature T:

P(w_i) = exp(z_i / T) / Σ_j exp(z_j / T)

效果

T 值效果
T → 0接近 Greedy,只选概率最高的词
T = 1按原始概率采样
T → ∞接近均匀分布,完全随机

T < 1(如 0.7)

  • 概率分布更"尖锐"
  • 高概率词更高,低概率词更低
  • 输出更确定、更保守

T > 1(如 1.5)

  • 概率分布更"平坦"
  • 低概率词有机会被选中
  • 输出更多样、更有创造性

实践建议

  • 代码生成、数学推理:T=0~0.3(确定性)
  • 对话、创意写作:T=0.7~1.0(平衡)
  • 头脑风暴:T=1.2~1.5(创造性)

English Explanation

T < 1: sharper distribution, more deterministic. T > 1: flatter distribution, more creative.

---

28.3 RAG | Retrieval-Augmented Generation

中文解释

核心问题

LLM 有幻觉(Hallucination):会编造不存在的事实。

RAG 的解决方案

让模型在生成前先查资料:

1. 用户查询 → 向量化(Embedding)
2. 向量检索(Vector Search)→ 召回 Top-K 相关文档
3. 文档 + 查询 → LLM 生成回答

优势

  • 减少幻觉(有事实依据)
  • 知识可更新(换文档就行,不用重新训练模型)
  • 可溯源(知道回答来自哪篇文档)

关键组件

组件技术
文档切分按段落/句子切分,控制 chunk 大小
向量化Embedding 模型(如 text-embedding-ada-002)
向量数据库FAISS, Milvus, Pinecone
检索策略相似度排序 + 重排序(Reranker)

English Explanation

RAG: retrieve relevant docs before generation. Pros: reduces hallucination, updatable knowledge, traceable.

---

28.4 Chain-of-Thought | Chain-of-Thought

中文解释

核心思想

在提示词中加入"Let's think step by step",让模型显式地写出推理过程:

Q: 一个农场有鸡和兔,共 35 头,94 脚。各多少只?
A: 设鸡 x 只,兔 y 只。
   x + y = 35
   2x + 4y = 94
   由第一式得 x = 35 - y
   代入第二式: 2(35-y) + 4y = 94
   70 - 2y + 4y = 94
   2y = 24
   y = 12, x = 23
   所以鸡 23 只,兔 12 只。

为什么有效?

  • 强制模型逐步推理,减少跳步导致的错误
  • 中间步骤可检查,便于调试
  • 对数学、逻辑、代码任务效果显著

变体

  • Zero-shot CoT:直接加"Let's think step by step"
  • Few-shot CoT:给几个带推理过程的示例
  • Self-Consistency:多次采样取多数投票

English Explanation

Prompt model to show reasoning steps explicitly.

---

28.5 Agent | Agent

中文解释

核心定义

Agent = LLM + 工具 + 规划 + 记忆

组件作用例子
LLM大脑,做决策GPT-4
工具执行外部操作搜索、计算器、API 调用
规划分解复杂任务把"订机票"分解为查航班→选座位→支付
记忆保存上下文和历史短期(对话历史)+ 长期(用户偏好)

ReAct 模式

Reasoning + Acting 交替:

思考 → 行动 → 观察 → 思考 → 行动 → 观察 → ...

Function Calling

让 LLM 输出结构化的函数调用:

json
{
  "function": "search",
  "arguments": {
    "query": "北京今天天气"
  }
}

系统执行函数后,把结果返回给 LLM 继续推理。

English Explanation

Agent = LLM + tools + planning + memory ReAct: alternate reasoning and acting. Function Calling: structured tool invocation.

---

28.6 完整实现

代码案例

python
import numpy as np

# ========== Temperature Sampling ==========
def temperature_sampling(logits, temperature=1.0):
    """带 temperature 的采样"""
    logits = np.array(logits)
    adjusted = logits / temperature
    probs = np.exp(adjusted - np.max(adjusted))
    probs /= np.sum(probs)
    return np.random.choice(len(probs), p=probs)

# 模拟 logits
logits = np.array([2.0, 1.5, 0.5, -0.5, -1.0])

print("=" * 50)
print("Temperature 效果对比")
print("=" * 50)

for T in [0.3, 0.7, 1.0, 1.5, 2.0]:
    adjusted = logits / T
    probs = np.exp(adjusted - np.max(adjusted))
    probs /= np.sum(probs)
    print(f"T={T:.1f}: 概率分布 = {probs.round(3)}")

# ========== Top-p Sampling ==========
def top_p_sampling(logits, top_p=0.9, temperature=1.0):
    """Nucleus Sampling"""
    logits = np.array(logits)
    adjusted = logits / temperature
    probs = np.exp(adjusted - np.max(adjusted))
    probs /= np.sum(probs)

    sorted_idx = np.argsort(probs)[::-1]
    sorted_probs = probs[sorted_idx]
    cumsum = np.cumsum(sorted_probs)

    cutoff = np.where(cumsum >= top_p)[0][0] + 1
    selected_idx = sorted_idx[:cutoff]
    selected_probs = probs[selected_idx]
    selected_probs /= np.sum(selected_probs)

    chosen = np.random.choice(selected_idx, p=selected_probs)
    return chosen, selected_idx

chosen, selected = top_p_sampling(logits, top_p=0.9)
print(f"\nTop-p=0.9 采样:")
print(f"  被选中的词: {chosen}")
print(f"  候选词集合: {selected}")

# ========== RAG 简化流程 ==========
def simple_rag(query, documents, embed_fn, top_k=2):
    """
    简化 RAG 流程
    """
    query_vec = embed_fn(query)
    doc_vecs = [embed_fn(d) for d in documents]

    scores = [np.dot(query_vec, dv) for dv in doc_vecs]
    top_idx = np.argsort(scores)[-top_k:][::-1]

    context = "\n".join([documents[i] for i in top_idx])
    prompt = f"基于以下信息回答问题:\n{context}\n\n问题: {query}\n回答:"
    return prompt, top_idx

# 模拟文档库
docs = [
    "Transformer 是 2017 年 Google 提出的架构",
    "BERT 使用双向注意力进行预训练",
    "GPT 使用自回归方式生成文本",
    "LLaMA 是 Meta 开源的大语言模型",
]

def mock_embed(text):
    """模拟 embedding"""
    np.random.seed(hash(text) % 1000)
    return np.random.randn(10)

query = "什么是 GPT?"
rag_prompt, retrieved = simple_rag(query, docs, mock_embed, top_k=2)

print(f"\n{'=' * 50}")
print("RAG 流程示例")
print(f"{'=' * 50}")
print(f"查询: {query}")
print(f"召回文档索引: {retrieved}")
print(f"生成提示:\n{rag_prompt}")

# ========== ReAct 模拟 ==========
class SimpleAgent:
    def __init__(self):
        self.tools = {
            "search": lambda q: f"搜索 '{q}' 的结果: 天气晴朗,25°C",
            "calc": lambda expr: eval(expr),
        }
        self.memory = []

    def think(self, task):
        """规划下一步行动"""
        if "天气" in task:
            return {"action": "search", "input": task}
        elif any(op in task for op in ["+", "-", "*", "/"]):
            return {"action": "calc", "input": task}
        else:
            return {"action": "respond", "input": task}

    def act(self, action_plan):
        """执行行动"""
        action = action_plan["action"]
        input_val = action_plan["input"]

        if action in self.tools:
            result = self.tools[action](input_val)
            self.memory.append({"action": action, "result": result})
            return result
        return "直接回答"

    def run(self, task):
        print(f"\n任务: {task}")

        # Step 1: Think
        plan = self.think(task)
        print(f"思考: 需要执行 '{plan['action']}'")

        # Step 2: Act
        result = self.act(plan)
        print(f"行动: {plan['action']}({plan['input']}) → {result}")

        # Step 3: Observe & Final Response
        print(f"观察: 获得了必要信息")
        print(f"最终回答: 根据查询,{result}")
        return result

agent = SimpleAgent()
agent.run("北京今天天气怎么样?")
agent.run("25 * 4 + 100")

输出:

==================================================
Temperature 效果对比
==================================================
T=0.3: 概率分布 = [0.889 0.108 0.003 0.    0.   ]
T=0.7: 概率分布 = [0.552 0.296 0.1   0.037 0.015]
T=1.0: 概率分布 = [0.422 0.285 0.156 0.086 0.051]
T=1.5: 概率分布 = [0.318 0.255 0.176 0.122 0.129]
T=2.0: 概率分布 = [0.271 0.234 0.183 0.143 0.169]

Top-p=0.9 采样:
  被选中的词: 0
  候选词集合: [0 1 2]

==================================================
RAG 流程示例
==================================================
查询: 什么是 GPT?
召回文档索引: [2 3]
生成提示:
基于以下信息回答问题:
GPT 使用自回归方式生成文本
LLaMA 是 Meta 开源的大语言模型

问题: 什么是 GPT?
回答:

任务: 北京今天天气怎么样?
思考: 需要执行 'search'
行动: search(北京今天天气怎么样?) → 搜索 '北京今天天气怎么样?' 的结果: 天气晴朗,25°C
观察: 获得了必要信息
最终回答: 根据查询,搜索 '北京今天天气怎么样?' 的结果: 天气晴朗,25°C

任务: 25 * 4 + 100
思考: 需要执行 'calc'
行动: calc(25 * 4 + 100) → 200
观察: 获得了必要信息
最终回答: 根据查询,200

---

28.7 常见误区 | Common Pitfalls

1. Temperature 不是"创造力开关"

T 高只是让采样更随机,不保证输出质量更好。过高的 T(>2)可能导致语法错误或逻辑混乱。

2. RAG 不是万能的

RAG 只能减少幻觉,不能消除。如果检索到的文档本身有误,模型会跟着错。需要高质量的知识库。

3. Agent 不等于 AGI

当前 Agent 只是"LLM + 工具调用",每一步都需要人工设计工具接口。真正的自主 Agent 还有很长的路要走。

---

本章总结 | Chapter Summary

中文:

  • Greedy:确定性最强,但重复;Beam Search:质量高但保守
  • Sampling:多样性好;Top-p:平衡质量与多样性
  • Temperature 控制分布形状:T<1 保守,T>1 创造性
  • RAG = 检索 + 生成,减少幻觉,知识可更新
  • CoT = 一步一步想,提升推理能力
  • Agent = LLM + 工具 + 规划 + 记忆,ReAct 交替推理与行动
  • Function Calling 让 LLM 调用外部工具

English:

  • Greedy/Beam/Sampling/Top-p for different quality-diversity trade-offs
  • Temperature controls distribution sharpness
  • RAG: retrieve then generate, reduces hallucination
  • CoT: step-by-step reasoning
  • Agent: LLM + tools + planning + memory
  • Function Calling: structured tool invocation

---

课后练习 | Homework

  1. Temperature 实验:同一提示,对比 T=0.1, 0.5, 1.0, 1.5, 2.0 的输出差异,统计语法错误率。
  1. Top-p 对比:固定 T=1.0,对比 p=0.3, 0.5, 0.9, 1.0 的多样性和质量。
  1. RAG 实现:用 FAISS 实现完整 RAG 流程,对比有/无 RAG 的幻觉率。
  1. CoT 效果评估:在 GSM8K 数学数据集上对比直接回答 vs CoT 的准确率。
  1. Agent 设计:设计一个能调用计算器、搜索引擎、日历 API 的 Agent。
  1. Function Calling 格式:实现一个解析器,从 LLM 输出中提取函数调用 JSON。
  1. 多轮对话记忆:设计一个对话系统,如何在多轮中保持上下文一致性?