从助手到自主智能体
从聊天机器人到完全自主系统的连续谱:每一步会发生什么变化
从助手到自主智能体 是 CoddyKit 上的免费 AI Agents 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
自主性光谱
人工智能系统处于从完全被动响应到完全自主的连续光谱上。了解您的智能体处于这一光谱中的哪个位置,可以决定它需要哪些架构组件、需要多少人工监督,以及应当预见哪些故障模式。
第 1 级:纯聊天机器人
纯聊天机器人通过文本回应消息。除了当前上下文窗口之外,它没有记忆,没有工具,没有目标,也无法在现实世界中采取行动。每次交互都是无状态的。人工监督需求:最低——它只能生成文本,无法采取行动。
import anthropic
# Level 1: Pure chatbot — single turn, no memory, no tools
def pure_chatbot(user_message: str) -> str:
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=512,
messages=[{'role': 'user', 'content': user_message}]
)
return response.content[0].text
# What it has:
# - Language understanding
# - Knowledge from training
# What it lacks:
# - Memory (no history between sessions)
# - Tools (cannot access external data)
# - Goals (no objective to pursue)
# - Proactivity (only responds, never initiates)
response = pure_chatbot('What is the capital of Australia?')
print(response)第 2 级:工具增强型智能体
工具增强型智能体增加了外部能力:网络搜索、数据库查询、代码执行和应用程序接口调用。它可以回答需要最新数据的问题。记忆可能会在一次会话中持续存在。人工监督需求:中等——它可以读取数据,但其操作通常是只读的或风险较低。
import anthropic
# Level 2: Tool-augmented agent
def tool_augmented_agent(user_message: str, conversation_history: list) -> str:
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
tools = [
{
'name': 'search_web',
'description': 'Search the web for current information',
'input_schema': {'type': 'object',
'properties': {'query': {'type': 'string'}},
'required': ['query']}
}
]
conversation_history.append({'role': 'user', 'content': user_message})
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=1024,
tools=tools,
messages=conversation_history
)
# Handle tool use...
return response.content[-1].text if response.stop_reason == 'end_turn' else '[tool called]'
# What changed vs Level 1:
# + Tools (external data access)
# + Session memory (conversation history)
# Still lacking:
# - Persistent cross-session memory
# - Goals (still reactive)
# - Proactivity第 3 级:目标导向型智能体
目标导向型智能体会在多个步骤中追求明确的目标,并在工具调用之间维护状态。它拥有一个规划器,可以将目标分解为子任务。人工监督需求:较高——它会采取多步骤行动,而这些行动可能在现实世界中产生累积影响。
# Level 3: Goal-directed agent
class GoalDirectedAgent:
def __init__(self, goal: str, tools: list, client):
self.goal = goal
self.tools = tools
self.client = client
self.memory = [] # persistent across steps
self.plan = self._make_plan()
def _make_plan(self) -> list:
response = self.client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content':
f'Goal: {self.goal}\n'
'Create a numbered list of steps to achieve this goal. '
'Each step should be a single tool call or reasoning step.'
}]
)
return response.content[0].text
def step(self) -> str:
# Execute next planned step
return 'step executed'
# What changed vs Level 2:
# + Goal: has an objective to pursue
# + Planning: decomposes goal into sub-tasks
# + Persistent memory across steps
# Still lacking:
# - Self-directed (still initiated by human)
# - Self-improvement
if __name__ == '__main__':
class FakeContent:
def __init__(self, text):
self.text = text
class FakeResponse:
def __init__(self, text):
self.content = [FakeContent(text)]
class FakeMessages:
def create(self, **kwargs):
return FakeResponse('1. Search web for topic\n2. Summarize findings\n3. Draft report')
class FakeClient:
def __init__(self):
self.messages = FakeMessages()
agent = GoalDirectedAgent(goal='Write a market report', tools=[], client=FakeClient())
print('Goal:', agent.goal)
print('Plan:')
print(agent.plan)
第 4 级:自我驱动型智能体
自我驱动型智能体会设定自己的子目标,监控环境中的相关事件,并在没有人工提示的情况下发起行动。它拥有长期记忆和世界模型,并能在情况发生变化时重新规划。人工监督需求:高——它会自主发起行动。
import time
# Level 4: Self-directed agent (simplified sketch)
class SelfDirectedAgent:
def __init__(self, mission: str, client):
self.mission = mission
self.client = client
self.goals_queue = []
self.long_term_memory = []
self.running = False
def start(self):
self.running = True
self._generate_initial_goals()
while self.running:
self._observe_environment()
self._prioritise_goals()
if self.goals_queue:
goal = self.goals_queue.pop(0)
self._pursue_goal(goal)
time.sleep(60) # autonomous monitoring loop
def _observe_environment(self):
# Agent monitors for events without being asked
print('Observing environment...')
def _generate_initial_goals(self):
# Agent decomposes its mission into actionable goals
self.goals_queue = ['Monitor inbox', 'Check project status']
def _prioritise_goals(self):
# Agent re-orders goals based on new observations
pass
def _pursue_goal(self, goal: str):
print(f'Pursuing: {goal}')
if __name__ == '__main__':
agent = SelfDirectedAgent(mission='Manage my inbox proactively', client=None)
agent._generate_initial_goals()
print('Initial goals:', agent.goals_queue)
agent._observe_environment()
goal = agent.goals_queue.pop(0)
agent._pursue_goal(goal)
各级别的变化:记忆
记忆需求会随着自主性级别的提升而增长。第 1 级只使用上下文窗口(会话记忆)。第 2 级增加持久化的会话历史。第 3 级增加结构化任务状态。第 4 级需要情景记忆(发生了什么)、语义记忆(智能体知道什么)和程序记忆(如何完成任务)。
MEMORY_BY_LEVEL = {
'L1_chatbot': {
'scope': 'context_window_only',
'persistence': 'none',
'implementation': 'messages list in current API call'
},
'L2_tool_augmented': {
'scope': 'session',
'persistence': 'in-memory (lost on restart)',
'implementation': 'conversation_history list'
},
'L3_goal_directed': {
'scope': 'task',
'persistence': 'persists for task duration',
'implementation': 'SQLite or Redis with task state'
},
'L4_self_directed': {
'scope': 'long_term',
'persistence': 'indefinite',
'implementation': 'vector DB (episodic) + structured DB (semantic) + prompt cache (procedural)'
}
}
for level, info in MEMORY_BY_LEVEL.items():
print(f'{level}: {info["implementation"]}')各级别的变化:规划
规划需求也会随着自主性提升而增加。第 1 级不进行规划。第 2 级可能进行单步推理。第 3 级使用多步骤规划(思维链、ReAct)。第 4 级需要分层规划,并在失败时重新规划。
PLANNING_BY_LEVEL = {
'L1': 'None — single response',
'L2': 'Single-step tool selection (which tool to call now)',
'L3': 'Multi-step plan (goal -> ordered sub-tasks -> tool calls)',
'L4': 'Hierarchical plan (mission -> goals -> tasks -> actions) + replan on failure'
}
# L3 multi-step planning example:
def plan_goal(goal: str, client) -> list:
import anthropic
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content':
f'Break this goal into 3-5 concrete steps:\nGoal: {goal}\n'
'Return JSON: {"steps": [{"step": int, "action": str, "tool": str}]}'
}]
)
import json
return json.loads(response.content[0].text)
for lvl, desc in PLANNING_BY_LEVEL.items():
print(f'{lvl}: {desc}')各级别的人工监督需求
随着自主性增强,对人工监督机制的需求也会增加。第 1 级几乎不需要监督。第 4 级需要明确的监督架构:审批关卡、行动日志、中断机制和异常检测。
OVERSIGHT_BY_LEVEL = {
'L1_chatbot': [
'None required (output only)'
],
'L2_tool_augmented': [
'Review tool permissions (read-only vs write)',
'Audit logs of tool calls'
],
'L3_goal_directed': [
'Human approval before irreversible actions',
'Plan review before execution starts',
'Progress checkpoints',
'Full audit trail'
],
'L4_self_directed': [
'Human approval before high-impact actions',
'Real-time action streaming to oversight dashboard',
'Emergency stop mechanism',
'Anomaly detection on goal drift',
'Regular review of long-term memory state',
'Corrigibility: agent must accept shutdown'
]
}
for level, requirements in OVERSIGHT_BY_LEVEL.items():
print(f'{level}:')
for req in requirements:
print(f' - {req}')主动性:关键转变
从助手转变为自主智能体的最根本变化是主动性。助手会等待,而智能体会发起行动。这意味着智能体必须监控环境、识别相关事件,并决定何时采取行动——整个过程都无需人工提示。
# Proactive monitoring pattern
import asyncio
from datetime import datetime
class ProactiveMonitor:
def __init__(self, agent_fn, check_fn, interval_seconds: int = 60):
self.agent_fn = agent_fn
self.check_fn = check_fn
self.interval = interval_seconds
async def run(self):
print(f'Proactive monitor started, checking every {self.interval}s')
while True:
try:
events = await self.check_fn()
for event in events:
print(f'[{datetime.utcnow().isoformat()}] Event: {event}')
await self.agent_fn(event)
except Exception as e:
print(f'Monitor error: {e}')
await asyncio.sleep(self.interval)
# Example: agent monitors for new emails every 5 minutes
# and proactively drafts replies or flags urgent ones
async def example_setup():
monitor = ProactiveMonitor(
agent_fn=lambda e: print(f'Agent handling: {e}'),
check_fn=lambda: [], # replace with real inbox check
interval_seconds=300
)
# await monitor.run()
if __name__ == '__main__':
import asyncio
async def demo():
async def check_fn():
return ['New email from boss@example.com']
async def agent_fn(event):
print(f'Agent drafting reply for: {event}')
monitor = ProactiveMonitor(agent_fn=agent_fn, check_fn=check_fn, interval_seconds=1)
try:
await asyncio.wait_for(monitor.run(), timeout=0.3)
except asyncio.TimeoutError:
pass
asyncio.run(demo())
各级别的错误恢复
错误恢复需求也会随着级别提升而增加。聊天机器人只会道歉。工具智能体会重试工具调用。目标智能体会围绕失败的步骤重新规划。自我驱动型智能体会自主检测、分类并升级处理错误,同时更新其世界模型,以避免将来再次发生相同的失败。
# Error recovery strategies by autonomy level
def chatbot_error_recovery(error: Exception) -> str:
return 'I\'m sorry, I encountered an error. Please try again.'
def tool_agent_error_recovery(tool_name: str, error: Exception, retries: int) -> str:
if retries < 3:
return f'Retrying {tool_name} ({retries+1}/3)'
return f'Tool {tool_name} unavailable after 3 retries, skipping'
def goal_agent_error_recovery(failed_step: dict, plan: list, client) -> list:
import anthropic, json
client_obj = anthropic.Anthropic(api_key='YOUR_API_KEY')
response = client_obj.messages.create(
model='claude-opus-4-5', max_tokens=256,
messages=[{'role': 'user', 'content':
f'Step failed: {failed_step}\nRemaining plan: {plan}\n'
'Revise the remaining plan to work around the failure. Return JSON plan.'
}]
)
return json.loads(response.content[0].text)
print('Error recovery patterns defined for each autonomy level')选择合适的级别
并非每个使用场景都需要第 4 级。请从满足需求的最低级别开始,仅在必要时增加复杂性。更高的自主性意味着更高的复杂性、更重的监督负担,以及出现意外行为的更大可能性。
def recommend_autonomy_level(requirements: dict) -> str:
needs_realtime = requirements.get('realtime_data', False)
needs_multistep = requirements.get('multi_step_tasks', False)
needs_unsupervised = requirements.get('runs_unsupervised', False)
needs_initiative = requirements.get('initiates_actions', False)
if needs_initiative and needs_unsupervised:
return 'L4_self_directed (high oversight required)'
if needs_multistep:
return 'L3_goal_directed (plan review recommended)'
if needs_realtime:
return 'L2_tool_augmented (audit logs required)'
return 'L1_chatbot (minimal oversight)'
# Examples:
print(recommend_autonomy_level({
'realtime_data': True, 'multi_step_tasks': False,
'runs_unsupervised': False, 'initiates_actions': False
}))
print(recommend_autonomy_level({
'realtime_data': True, 'multi_step_tasks': True,
'runs_unsupervised': True, 'initiates_actions': True
}))知识检查
第 3 级的目标导向型智能体与第 4 级的自我驱动型智能体之间,最根本的能力差异是什么?
回顾:从助手到自主智能体
非常好!您已经学会了以下内容:
- L1 聊天机器人:被动响应、仅生成文本、没有记忆、无需监督
- L2 工具增强型智能体:会话记忆、工具调用、中等程度的监督
- L3 目标导向型智能体:多步骤规划、任务范围内的记忆、审批关卡
- L4 自我驱动型智能体:主动行动、长期记忆、分层规划、高度监督
- 经验法则:从满足需求的最低级别开始
下一步:世界模型与预测性规划——智能体如何在行动前进行模拟。
常见问题解答
「从助手到自主智能体」课时是免费的吗?
是的 — 「从助手到自主智能体」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「从助手到自主智能体」这节课中我会学到什么?
从聊天机器人到完全自主系统的连续谱:每一步会发生什么变化 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「从助手到自主智能体」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。