生产实战手册(Cookbook)
本手册面向生产环境架构设计与运维治理,覆盖自定义拦截器、有界多 Agent 委派(SubagentTool)、自定义关系型数据库 SessionStore SPI 实现、预算与超时保护以及优雅停机策略。
(关于离线脚本化单元测试、Spring Boot 集成测试、异常体系与故障排查,请参阅测试、异常体系与故障排查。)
1. 自定义三轨拦截器(LlmInterceptor / StepInterceptor / ToolInterceptor)
OpenHusky 三条扩展轨均采用同步责任链模式,在虚拟线程上直接以方法栈形式执行,无回调地狱或上下文丢失问题。
ToolInterceptor:耗时审计、敏感参数脱敏与租户限流
java
import dev.openhusky.core.interceptor.ToolInterceptor;
import dev.openhusky.core.tool.ToolResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class AuditToolInterceptor implements ToolInterceptor {
private static final Logger auditLog = LoggerFactory.getLogger("AUDIT.TOOLS");
@Override
public ToolResult intercept(Invocation invocation, Chain next) {
long startNs = System.nanoTime();
String toolName = invocation.tool().spec().name();
String tenantId = invocation.context().principal().tenantId();
String principalId = invocation.context().principal().id();
ToolResult result = next.proceed(invocation);
long elapsedMs = (System.nanoTime() - startNs) / 1_000_000L;
auditLog.info("tenant={} principal={} tool={} isError={} durationMs={}",
tenantId, principalId, toolName, result != null && result.isError(), elapsedMs);
return result;
}
}StepInterceptor:推理步前后注入与合规检查
java
import dev.openhusky.ai.model.ChatRequest;
import dev.openhusky.ai.model.ChatResponse;
import dev.openhusky.core.interceptor.StepInterceptor;
StepInterceptor complianceStepGuard = (context, next) -> {
if (context.stepIndex() > 10) {
ChatRequest constrained = context.request().toBuilder()
.temperature(0.0)
.build();
return next.proceed(context.withRequest(constrained));
}
return next.proceed(context);
};LlmInterceptor:自定义网关路由头与 SLA 计时
java
import dev.openhusky.ai.model.ChatRequest;
import dev.openhusky.ai.provider.LlmInterceptor;
LlmInterceptor headerInjector = (request, signal, onEvent, next) -> {
ChatRequest tagged = request.toBuilder()
.cacheKey("prod-" + request.model().id())
.build();
return next.proceed(tagged, signal, onEvent);
};2. 有界层级化多 Agent 委派(SubagentTool)
SubagentTool 将一个独立的专职 AgentRuntime 封装为标准 AgentTool(executionMode() == PARALLEL_SAFE),使父 Agent 能够在虚拟线程上并发委派多个子任务,并具备完整的工程级安全边界:
- 血缘与元数据追踪:自动为子会话生成
<parentSessionId>-sub-<8hex>标识,并在SessionHeader中写入parentSessionId、sessionKind = "subagent"及subagentTool名称。可通过SubagentTool.isSubagentSession(header)在历史列表中过滤内部子会话。 - 级联取消(Linked
AbortSignal):通过promptWithParentSignal(...)将子会话与父会话的AbortSignal级联绑定;父运行中止时所有子 Agent 立即同步停止,而子 Agent 超时不会反向中止父运行。 - 递归深度防爆(
maxDelegationDepth):通过透传属性SubagentTool.ATTR_DELEGATION_DEPTH(默认上限3)防止循环委派。 - 只读权限自动推导:若未显式调用
.readOnly(boolean),构造器会检查子AgentRuntime的权限策略——仅当子 Runtime 中所有非DENY工具的readOnly()均为true时,该SubagentTool的readOnly()才自动为true。 - 同会话续跑(
session_id)与归属校验:子 Agent 返回文本末尾附带[childSessionId=...](同时写入details.childSessionId);父 Agent 下次传入session_id即可续跑同一子会话,且运行时强制校验tenantId、principalId与parentSessionId完全匹配。
java
import dev.openhusky.core.policy.PermissionPolicy;
import dev.openhusky.core.runtime.AgentRuntime;
import dev.openhusky.core.subagent.SubagentTool;
import java.time.Duration;
AgentRuntime researchRuntime = AgentRuntime.builder()
.llmClient(llmClient)
.model(fastModel)
.systemPrompt("你是只读调研专家,基于工具返回的事实输出精炼结论。")
.sessionStore(sharedStore)
.tools(readOnlyTools)
.permissionPolicy(PermissionPolicy.readOnly())
.maxStepsPerTurn(12)
.build();
SubagentTool researchSubagent = SubagentTool.builder(
"research_subagent",
"将耗时的只读代码库或知识库调研委派给专职子智能体。",
researchRuntime)
.inheritHistory(false) // true 时通过 store.fork(...) 继承父分支历史
.maxDelegationDepth(2)
.timeout(Duration.ofMinutes(3))
.build();
AgentRuntime parentRuntime = AgentRuntime.builder()
.llmClient(llmClient)
.model(primaryModel)
.sessionStore(sharedStore)
.tool(researchSubagent)
.permissionPolicy(PermissionPolicy.failClosed()
.allowReadOnlyTools() // 因 researchRuntime 为只读,researchSubagent 自动继承 readOnly=true 并被放行
.build())
.build();3. 实现自定义 SessionStore SPI(接入 PostgreSQL / MySQL)
在多实例无状态 Kubernetes 集群部署场景下,推荐实现 dev.openhusky.session.SessionStore 接口以接入 PostgreSQL、MySQL 或分布式存储引擎。
推荐关系型表结构(参考 SqliteSessionStore)
sql
CREATE TABLE sessions (
id VARCHAR(128) PRIMARY KEY,
version INTEGER NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
tenant_id VARCHAR(128) NOT NULL,
principal_id VARCHAR(128) NOT NULL,
agent_id VARCHAR(128),
session_key VARCHAR(256),
parent_session_id VARCHAR(128),
parent_entry_id VARCHAR(128),
metadata_json JSONB NOT NULL,
title TEXT,
leaf_entry_id VARCHAR(128),
entry_count INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX idx_sessions_tenant_updated
ON sessions (tenant_id, principal_id, updated_at DESC);
CREATE TABLE session_entries (
seq BIGSERIAL PRIMARY KEY,
session_id VARCHAR(128) NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
entry_id VARCHAR(128) NOT NULL,
parent_id VARCHAR(128),
entry_type VARCHAR(64) NOT NULL,
timestamp TIMESTAMPTZ NOT NULL,
payload_json JSONB NOT NULL,
UNIQUE (session_id, entry_id)
);
CREATE INDEX idx_session_entries_session_seq
ON session_entries (session_id, seq);实现 SessionStore 必须遵守的 4 条核心不变量
appendToLeaf(sessionId, entryFactory)事务原子性: 必须在同一数据库事务内使用行级排他锁读取当前leaf_entry_id(例如SELECT leaf_entry_id FROM sessions WHERE id = ? FOR UPDATE),调用entryFactory.apply(currentLeafId)生成SessionEntry,校验Objects.equals(currentLeafId, entry.parentId())后插入session_entries并更新sessions.leaf_entry_id、entry_count与updated_at(若为SessionInfoEntry同步更新title)。这能彻底避免并发调用产生意外的兄弟分叉。- 保留
StatePatchEntry.patch中的null值: 在SessionProjector语义中,某键值为null代表删除该键。使用 Jackson 序列化SessionEntry时,请复用SessionJsonCodec.encodeEntry(entry)/decodeEntry(json),切勿配置全局NON_NULL过滤掉patch内部的null键值,也不要对 PostgreSQLJSONB进行剔除null的预处理。 - 版本门控(Fail-Closed)与安全 ID 校验: 在
create、getHeader、append、appendToLeaf、fork等入口调用SessionHeader.requireSafeSessionId(...);读取时若version > SessionHeader.CURRENT_FORMAT_VERSION必须抛出SessionFormatException。 - 完整实现
SessionQuery过滤与分页: 在list(SessionQuery)中准确处理tenantId、principalId、agentId、sessionKey、textQuery、includeForkedChildren、limit与offset,确保上层AgentRuntime.listSessions(principal, query)的多租户查询隔离准确无误。
4. 预算控制、超时护栏与优雅停机
生产环境中,务必在 AgentRuntime.Builder 上配置显式资源护栏,防止模型死循环或外部工具异常悬挂耗尽算力与连接:
java
AgentRuntime runtime = AgentRuntime.builder()
.llmClient(llmClient)
.model(model)
.maxStepsPerTurn(20) // 单轮最大「推理 + 工具」循环步数(默认 32)
.maxTotalTokensPerRun(200_000) // 单次 Run 累计 Token 硬上限(默认 0 不限)
.maxRunDuration(Duration.ofMinutes(5)) // 单次 Run 最大挂钟时长
.toolTimeout(Duration.ofSeconds(45)) // 默认单工具执行超时(默认 2 分钟)
.approvalTimeout(Duration.ofMinutes(5)) // HITL 人工审批最长等待时间
.stepInterceptor(DoomLoopGuardInterceptor.defaults())
.toolInterceptor(OutputOffloadToolInterceptor.spillingTo(Path.of("./data/offload"), 32_768))
.build();优雅停机释放顺序
当 JVM 进程或容器接收到 SIGTERM 时,严格按「中止活跃运行与挂起审批 → 关闭 AgentRuntime 虚拟线程工具执行器 → 关闭外部协议客户端与沙箱 → 关闭持久层存储」顺序回收资源:
java
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
agUiRunner.abortAll("JVM shutting down");
runtime.close();
mcpToolkit.close();
sandbox.close();
sessionStore.close();
}, "openhusky-shutdown"));