第 7 章:用 Strands Steering 提升 Agent 可靠性
第 7 章:用 Strands Steering 提升 Agent 可靠性
关于本课
本课程的视频是某个时间点的快照。Strands 仍在活跃开发中,所以本页展示的代码反映的是最新写法,而视频里讲的概念依然成立。有疑问时,以代码为准。
本课代码:samples/07-steering
让 Agent 不要跑偏
Prompt 里的指令并不总能被可靠执行,上下文越长越明显。Steering 让你在运行时检查并影响 Agent 的行为。一个 steering handler 会看 Agent 接下来要做什么,然后返回三种结果之一:Proceed、Guide(把反馈发给 Model,让它重试)或 Interrupt(暂停,等人介入)。
在一份公开的基准测试中,Strands 的 steering hook 做到了 600 次评测全部通过,而基于 prompt 的指令是 82.5%,基于 graph 的 workflow 是 80.8%。
两种 Steering
| 类型 | 工作方式 | 适用场景 |
|---|---|---|
Deterministic(SteeringHandler) |
用 Python 逻辑检查事件账本 | 强制 workflow 的执行顺序、校验参数 |
LLM-based(LLMSteeringHandler) |
由第二个 Agent 来评判输出 | 语气/策略合规、更细致的质量检查 |
确定性 Steering:强制退款流程
我们的客服 Agent 不该在没查客户、没查订单历史的情况下直接退款。与其指望 prompt 被遵守,不如让 SteeringHandler 在允许 process_refund 运行之前,先检查之前 Tool 调用留下的账本:
from strands.vended_plugins.steering import (
SteeringHandler, Proceed, Guide, ToolSteeringAction, LedgerProvider,
)
class RefundWorkflowHandler(SteeringHandler):
name = "refund-workflow"
def __init__(self):
super().__init__(context_providers=[LedgerProvider()])
async def steer_before_tool(self, *, agent, tool_use, **kwargs) -> ToolSteeringAction:
if tool_use.get("name") != "process_refund":
return Proceed(reason="Not a refund operation")
ledger = self.steering_context.data.get("ledger", {})
tool_calls = ledger.get("tool_calls", [])
# Must look up customer first
customer_verified = any(
c["tool_name"] == "lookup_customer" and c["status"] == "success"
for c in tool_calls
)
if not customer_verified:
return Guide(reason="You must look up the customer first.")
# Must check order history
order_checked = any(
c["tool_name"] == "get_order_history" and c["status"] == "success"
for c in tool_calls
)
if not order_checked:
return Guide(reason="You must check order history first.")
return Proceed(reason="Refund workflow validated")当 handler 返回 Guide 时,这次 Tool 调用会被拦下,原因会回传给 Model,Model 补上缺失的那一步后再试一次。
基于 LLM 的 Steering:语气护栏
有些规则没法写成 Python 条件判断。“不要过度承诺时间表”这类要求得靠判断力。LLMSteeringHandler 用第二个 Model 按策略评估回复,不达标就引导 Agent:
from strands.vended_plugins.steering import LLMSteeringHandler
class ToneGuardrailHandler(LLMSteeringHandler):
name = "tone-guardrail"
def __init__(self):
super().__init__(
system_prompt="""Evaluate the customer service response against these policies:
- Don't overpromise timelines
- Acknowledge customer frustration
- Don't offer unauthorized compensation
- Keep responses concise
If violated, provide specific guidance on what to fix."""
)把各部分组装成一个 Agent
steering handler 本身就是 Plugin,所以能和 Skill 以及其他 Plugin 叠在一起用:
from strands import Agent
agent = Agent(
tools=[lookup_customer, get_order_history, process_refund],
plugins=[
skills_plugin, # On-demand workflow instructions
RefundWorkflowHandler(), # Deterministic: enforce refund steps
tone_handler, # LLM-based: enforce communication quality
],
system_prompt=SYSTEM_PROMPT,
)📂 customer_service_steering.py · steering_handlers.py