435 lines
14 KiB
Markdown
435 lines
14 KiB
Markdown
# 第03章:LLM 智能体详解
|
||
|
||
## 📌 本章目标
|
||
|
||
- 深入理解 LlmAgent 的工作原理
|
||
- 掌握 Agent 的指令设计(Instruction Design)
|
||
- 学习如何选择和配置不同的 LLM 模型
|
||
- 了解 output_key、before/after 回调等高级特性
|
||
- 使用 Google 内置工具(搜索、代码执行等)
|
||
|
||
---
|
||
|
||
## 3.1 LlmAgent 工作原理
|
||
|
||
### 3.1.1 执行流程
|
||
|
||
```
|
||
用户输入
|
||
│
|
||
▼
|
||
┌─────────────────────────────────────────────────┐
|
||
│ LlmAgent │
|
||
│ │
|
||
│ 1. 接收用户消息 │
|
||
│ ↓ │
|
||
│ 2. before_model_callback(模型调用前回调) │
|
||
│ ↓ │
|
||
│ 3. 构建上下文(系统指令 + 历史消息 + 工具定义) │
|
||
│ ↓ │
|
||
│ 4. 调用 LLM 获取响应 │
|
||
│ ↓ │
|
||
│ 5. after_model_callback(模型调用后回调) │
|
||
│ ↓ │
|
||
│ 6. 判断是否需要调用工具 │
|
||
│ ├── 是 → before_tool_callback → 执行工具 │
|
||
│ │ → after_tool_callback → 回到步骤3 │
|
||
│ └── 否 → 输出最终响应 │
|
||
│ ↓ │
|
||
│ 7. 保存输出到 State(如果设置了 output_key) │
|
||
│ ↓ │
|
||
│ 8. 返回响应给用户 │
|
||
└─────────────────────────────────────────────────┘
|
||
```
|
||
|
||
### 3.1.2 Agent 与 LlmAgent 的关系
|
||
|
||
```python
|
||
# Agent 是 LlmAgent 的别名,两者完全等价
|
||
from google.adk.agents import Agent # Agent = LlmAgent 的别名
|
||
from google.adk.agents import LlmAgent # LlmAgent 是完整类名
|
||
|
||
# 以下两种写法效果完全相同:
|
||
agent1 = Agent(name="test", model="gemini-2.0-flash")
|
||
agent2 = LlmAgent(name="test", model="gemini-2.0-flash")
|
||
```
|
||
|
||
---
|
||
|
||
## 3.2 指令设计(Instruction Design)
|
||
|
||
### 3.2.1 好的指令设计原则
|
||
|
||
```python
|
||
"""
|
||
Agent 指令设计示例
|
||
展示如何编写高质量的 Agent 系统指令
|
||
"""
|
||
|
||
from google.adk.agents import Agent
|
||
|
||
# ❌ 不好的指令设计:过于简单、缺乏约束
|
||
bad_agent = Agent(
|
||
name="bad_agent",
|
||
model="gemini-2.0-flash",
|
||
instruction="你是一个助手。", # 太模糊,Agent 不知道该做什么
|
||
)
|
||
|
||
# ✅ 好的指令设计:清晰、具体、有约束
|
||
good_agent = Agent(
|
||
name="good_agent",
|
||
model="gemini-2.0-flash",
|
||
instruction="""你是一个专业的旅行规划助手。
|
||
|
||
## 你的职责
|
||
- 帮助用户规划旅行行程
|
||
- 提供目的地推荐和旅行建议
|
||
- 使用工具查询天气、航班等信息
|
||
|
||
## 回答规范
|
||
1. 始终使用中文回答
|
||
2. 回答要简洁明了,使用列表格式
|
||
3. 如果信息不足,主动询问用户
|
||
4. 不要编造不存在的信息
|
||
|
||
## 工具使用规则
|
||
- 查询天气时,使用 get_weather 工具
|
||
- 查询航班时,使用 search_flights 工具
|
||
- 只有在需要实时数据时才使用工具
|
||
""",
|
||
)
|
||
```
|
||
|
||
### 3.2.2 指令模板
|
||
|
||
```python
|
||
"""
|
||
常用指令模板
|
||
可以根据自己的需求修改使用
|
||
"""
|
||
|
||
# 模板一:数据分析助手
|
||
data_analyst_instruction = """你是一个数据分析专家。
|
||
|
||
## 核心能力
|
||
- 分析数据并生成洞察
|
||
- 创建数据可视化建议
|
||
- 解释统计指标的含义
|
||
|
||
## 工作流程
|
||
1. 理解用户的数据分析需求
|
||
2. 使用工具获取和处理数据
|
||
3. 生成分析报告,包含关键发现
|
||
4. 提供可操作的建议
|
||
|
||
## 输出格式
|
||
- 使用 Markdown 格式
|
||
- 包含数据表格和关键指标
|
||
- 提供结论和建议
|
||
"""
|
||
|
||
# 模板二:代码助手
|
||
code_assistant_instruction = """你是一个编程助手。
|
||
|
||
## 核心能力
|
||
- 编写和审查代码
|
||
- 调试和修复错误
|
||
- 代码重构和优化建议
|
||
|
||
## 规则
|
||
1. 代码注释使用中文
|
||
2. 遵循最佳实践和设计模式
|
||
3. 解释代码的工作原理
|
||
4. 提供测试建议
|
||
"""
|
||
|
||
# 模板三:客服助手
|
||
customer_service_instruction = """你是一个专业的客服代表。
|
||
|
||
## 核心职责
|
||
- 解答用户问题
|
||
- 处理投诉和反馈
|
||
- 引导用户完成操作
|
||
|
||
## 规则
|
||
1. 语气友好、专业
|
||
2. 先理解用户问题,再提供解决方案
|
||
3. 无法解决时,转交人工客服
|
||
4. 记录用户反馈
|
||
"""
|
||
```
|
||
|
||
---
|
||
|
||
## 3.3 模型选择与配置
|
||
|
||
### 3.3.1 Gemini 模型(默认)
|
||
|
||
```python
|
||
"""
|
||
使用 Gemini 模型配置 Agent
|
||
Gemini 是 ADK 默认优化的模型
|
||
"""
|
||
|
||
from google.adk.agents import Agent
|
||
|
||
# 使用 Gemini 2.0 Flash(推荐,性价比高)
|
||
agent_flash = Agent(
|
||
name="flash_agent",
|
||
model="gemini-2.0-flash", # 快速、经济
|
||
instruction="你是一个高效的助手。",
|
||
)
|
||
|
||
# 使用 Gemini 2.5 Pro(更强推理能力)
|
||
agent_pro = Agent(
|
||
name="pro_agent",
|
||
model="gemini-2.5-pro-preview-05-06", # 更强的推理能力
|
||
instruction="你是一个需要深度推理的助手。",
|
||
)
|
||
|
||
# 使用 Gemini 3 Pro(最新版本)
|
||
agent_latest = Agent(
|
||
name="latest_agent",
|
||
model="gemini-3-pro-preview", # 最新版本
|
||
instruction="你是一个使用最新模型的助手。",
|
||
)
|
||
```
|
||
|
||
### 3.3.2 使用其他模型(LiteLLM)
|
||
|
||
```python
|
||
"""
|
||
使用 LiteLLM 适配其他模型
|
||
LiteLLM 支持 100+ 种模型
|
||
"""
|
||
|
||
from google.adk.agents import Agent # 导入 Agent 类
|
||
from google.adk.models.lite_llm import LiteLlm # 导入 LiteLLM 适配器
|
||
|
||
# ========================================
|
||
# 使用 DeepSeek 模型
|
||
# ========================================
|
||
deepseek_agent = Agent(
|
||
name="deepseek_agent", # Agent 名称
|
||
model=LiteLlm( # 使用 LiteLLM 适配器
|
||
model="deepseek/deepseek-chat", # 格式:provider/model_name
|
||
api_key="你的_DEEPSEEK_API_KEY", # DeepSeek API Key
|
||
# api_base="https://api.deepseek.com", # 可选:自定义 API 地址
|
||
),
|
||
instruction="你是一个使用 DeepSeek 模型的助手。",
|
||
)
|
||
|
||
# ========================================
|
||
# 使用 OpenAI 模型
|
||
# ========================================
|
||
openai_agent = Agent(
|
||
name="openai_agent", # Agent 名称
|
||
model=LiteLlm( # 使用 LiteLLM 适配器
|
||
model="openai/gpt-4o", # OpenAI GPT-4o 模型
|
||
api_key="你的_OPENAI_API_KEY", # OpenAI API Key
|
||
),
|
||
instruction="你是一个使用 GPT-4o 模型的助手。",
|
||
)
|
||
|
||
# ========================================
|
||
# 使用 Claude 模型
|
||
# ========================================
|
||
claude_agent = Agent(
|
||
name="claude_agent", # Agent 名称
|
||
model=LiteLlm( # 使用 LiteLLM 适配器
|
||
model="anthropic/claude-3-5-sonnet-20241022", # Claude 模型
|
||
api_key="你的_ANTHROPIC_API_KEY", # Anthropic API Key
|
||
),
|
||
instruction="你是一个使用 Claude 模型的助手。",
|
||
)
|
||
```
|
||
|
||
### 3.3.3 模型选择指南
|
||
|
||
| 场景 | 推荐模型 | 原因 |
|
||
|------|----------|------|
|
||
| 简单对话 | gemini-2.0-flash | 速度快、成本低 |
|
||
| 复杂推理 | gemini-2.5-pro | 推理能力强 |
|
||
| 代码生成 | gemini-2.5-pro / gpt-4o | 代码质量高 |
|
||
| 中文场景 | deepseek-chat | 中文能力强 |
|
||
| 长文本处理 | gemini-2.5-pro | 支持长上下文 |
|
||
|
||
---
|
||
|
||
## 3.4 使用 Google 内置工具
|
||
|
||
### 3.4.1 Google Search(网络搜索)
|
||
|
||
```python
|
||
"""
|
||
使用 Google Search 工具
|
||
让 Agent 能够搜索互联网获取最新信息
|
||
"""
|
||
|
||
from google.adk.agents import Agent # 导入 Agent 类
|
||
from google.adk.tools import google_search # 导入 Google 搜索工具
|
||
|
||
# 创建带有搜索能力的 Agent
|
||
search_agent = Agent(
|
||
name="search_agent", # Agent 名称
|
||
model="gemini-2.0-flash", # 使用 Gemini 模型
|
||
instruction=( # 系统指令
|
||
"你是一个信息查询助手。\n"
|
||
"当用户提问时,使用 Google Search 工具搜索最新信息。\n"
|
||
"根据搜索结果提供准确、全面的回答。\n"
|
||
"如果搜索结果不够充分,可以多次搜索不同关键词。"
|
||
),
|
||
tools=[google_search], # 注册 Google 搜索工具
|
||
)
|
||
```
|
||
|
||
### 3.4.2 Code Execution(代码执行)
|
||
|
||
```python
|
||
"""
|
||
使用 Code Execution 工具
|
||
让 Agent 能够执行 Python 代码进行计算和分析
|
||
"""
|
||
|
||
from google.adk.agents import Agent # 导入 Agent 类
|
||
from google.adk.tools import code_execution # 导入代码执行工具
|
||
|
||
# 创建带有代码执行能力的 Agent
|
||
code_agent = Agent(
|
||
name="code_agent", # Agent 名称
|
||
model="gemini-2.0-flash", # 使用 Gemini 模型
|
||
instruction=( # 系统指令
|
||
"你是一个数据分析助手。\n"
|
||
"当需要进行数学计算、数据分析或生成图表时,\n"
|
||
"使用 Code Execution 工具执行 Python 代码。\n"
|
||
"确保代码正确且高效。"
|
||
),
|
||
tools=[code_execution], # 注册代码执行工具
|
||
)
|
||
```
|
||
|
||
### 3.4.3 组合多个内置工具
|
||
|
||
```python
|
||
"""
|
||
组合使用多个 Google 内置工具
|
||
创建功能更强大的 Agent
|
||
"""
|
||
|
||
from google.adk.agents import Agent # 导入 Agent 类
|
||
from google.adk.tools import google_search # 导入 Google 搜索工具
|
||
from google.adk.tools import code_execution # 导入代码执行工具
|
||
|
||
# 创建多功能 Agent
|
||
super_agent = Agent(
|
||
name="super_agent", # Agent 名称
|
||
model="gemini-2.0-flash", # 使用 Gemini 模型
|
||
instruction=( # 系统指令
|
||
"你是一个全能助手。\n"
|
||
"你可以搜索互联网获取最新信息。\n"
|
||
"你也可以执行代码来进行计算和分析。\n"
|
||
"根据用户的需求选择合适的工具。"
|
||
),
|
||
tools=[ # 注册多个工具
|
||
google_search, # 网络搜索
|
||
code_execution, # 代码执行
|
||
],
|
||
)
|
||
```
|
||
|
||
---
|
||
|
||
## 3.5 output_key — 输出到 State
|
||
|
||
```python
|
||
"""
|
||
output_key 参数详解
|
||
将 Agent 的输出保存到会话状态(State)中
|
||
用于在多 Agent 系统中传递数据
|
||
"""
|
||
|
||
from google.adk.agents import Agent # 导入 Agent 类
|
||
|
||
# 创建一个将输出保存到 State 的 Agent
|
||
capital_agent = Agent(
|
||
name="capital_agent", # Agent 名称
|
||
model="gemini-2.0-flash", # 使用 Gemini 模型
|
||
instruction="回答用户关于国家首都的问题。只回答首都名称,不要多余内容。", # 指令
|
||
output_key="capital_city", # 🔑 关键参数:将输出保存到 state['capital_city']
|
||
)
|
||
|
||
# 当这个 Agent 运行后,它的最终响应文本会自动保存到 session.state['capital_city']
|
||
# 其他 Agent 可以通过 {capital_city} 在指令中引用这个值
|
||
```
|
||
|
||
---
|
||
|
||
## 3.6 Agent Transfer — 动态任务委派
|
||
|
||
```python
|
||
"""
|
||
Agent Transfer 机制
|
||
LLM 可以根据用户需求动态地将任务委派给其他 Agent
|
||
"""
|
||
|
||
from google.adk.agents import LlmAgent # 导入 LlmAgent 类
|
||
|
||
# 定义专门的子 Agent
|
||
booking_agent = LlmAgent(
|
||
name="BookingAgent", # 预订 Agent
|
||
model="gemini-2.0-flash", # 使用 Gemini 模型
|
||
description="负责处理航班和酒店的预订请求。", # 描述:用于 LLM 路由决策
|
||
instruction="你是一个预订助手,帮助用户预订航班和酒店。", # 系统指令
|
||
)
|
||
|
||
info_agent = LlmAgent(
|
||
name="InfoAgent", # 信息查询 Agent
|
||
model="gemini-2.0-flash", # 使用 Gemini 模型
|
||
description="负责回答一般性问题和提供信息。", # 描述:用于 LLM 路由决策
|
||
instruction="你是一个信息助手,回答用户的各种问题。", # 系统指令
|
||
)
|
||
|
||
# 定义协调器 Agent(父 Agent)
|
||
coordinator = LlmAgent(
|
||
name="Coordinator", # 协调器 Agent
|
||
model="gemini-2.0-flash", # 使用 Gemini 模型
|
||
description="主协调器,负责将用户请求分配给合适的子 Agent。", # 描述
|
||
instruction=( # 系统指令
|
||
"你是一个协调器助手。\n"
|
||
"当用户需要预订航班或酒店时,将任务委派给 BookingAgent。\n"
|
||
"当用户询问一般性问题时,将任务委派给 InfoAgent。\n"
|
||
"使用 transfer_to_agent 工具来委派任务。"
|
||
),
|
||
sub_agents=[ # 🔑 注册子 Agent
|
||
booking_agent, # 预订 Agent
|
||
info_agent, # 信息 Agent
|
||
],
|
||
)
|
||
|
||
# 工作原理:
|
||
# 1. 用户发送消息给 Coordinator
|
||
# 2. Coordinator 的 LLM 分析消息,决定委派给哪个子 Agent
|
||
# 3. LLM 生成 transfer_to_agent(agent_name='BookingAgent') 调用
|
||
# 4. ADK 框架自动将执行切换到目标 Agent
|
||
# 5. 目标 Agent 处理请求并返回结果
|
||
```
|
||
|
||
---
|
||
|
||
## 3.7 完整代码示例
|
||
|
||
详见 `code/llm_agent_demo.py` — 包含完整的 LlmAgent 配置和运行示例。
|
||
|
||
---
|
||
|
||
## 📌 本章小结
|
||
|
||
- LlmAgent 是 ADK 最常用的智能体类型,以 LLM 为核心引擎
|
||
- 好的指令设计是 Agent 效果的关键
|
||
- ADK 默认优化 Gemini 模型,通过 LiteLLM 支持其他模型
|
||
- Google 内置工具(搜索、代码执行)可直接使用
|
||
- `output_key` 用于在多 Agent 系统中传递数据
|
||
- Agent Transfer 实现动态任务委派
|
||
|
||
**下一章**:[第04章 - 自定义工具开发](./04-custom-tools.md) → 学习如何为 Agent 创建自定义工具。
|