Globally configurable GuardRails
I'm currently working on integrating our monthly usage limit policy. We have a service which throws when the usage limit is reached. I have trouble finding a good extension point to call this service before each Llm invocation (outside the tool loop). This policy should be active for the whole organization without the need for configuration on Agent, Action or PromptRunner level.
- On
AgentProcessEvent:MulticastAgenticEventListenersuppresses exceptions. UserInputGuardRail: Global configuration as bean not supported currently.EarlyTerminationPolicy: Runs only after eachtick. Global configuration as bean not supported currently.ToolLoopInspector: Global configuration as bean not supported currently.
My workaround is decorating the ChatModel.
Did I miss something or is a globally configurable hook for the agent process right before llm invocation not available right now?
My suggestion is to allow for globally configurable GuardRails.
You could get usage from AgentProcess.get() in these hooks. Would that suffice?
Usage / Cost logging is already solved in my case, provided by our organizations Spring AI infrastructure.
We have a bean CostLimitVerifier with method verify() which throws a RuntimeException if the limit is reached, otherwise does nothing.
We need a hook / extension point called before each Llm invocation where we can use this service. As this is a global organization policy, this check should always be performed. Manually passing a GuardRail or an Inspector for each PromptRunner call is not sufficient, as people might forget to do so.
E.g. a GlobalUserInputGuardRail interface, for which all implementations are picked up and registered for each PromptRunner call, would work for us. But this might be semantically incorrect.
@stefanks-px -
Re: "
UserInputGuardRail: Global configuration as bean not supported currently. ToolLoopInspector: Global configuration as bean not supported currently.
"
please be advised that guardrails can be created as POJO or Bean annotated appropriately As @Bean, so basically can be global, you just need to pass reference to it APY withGuardrails. Same - for Inspector.
As for:
" EarlyTerminationPolicy: Runs only after each tick. Global configuration as bean not supported currently. " - how you would like to engage it?
Thank you.
im looping @azanux - for awareness as he worked on guardrails - and @jimador - as he worked on budgeting estimation.
Are looking for something like in application-agent.properties:
embabel.agent.guardrails.global =class-name?
@stefanks-px - as Beans are supported - do you still want to keep issue open?
@igordayen
you just need to pass reference to it APY withGuardrails. Same - for Inspector.
This is the point. We don't want to pass specific GuardRails or Inspectors every time via the PromptRunner API. Some implementations should be available by default for every PromptRunner invocation.
Are looking for something like in application-agent.properties:
embabel.agent.guardrails.global =class-name?
I think your suggestion goes into the right direction. Maybe it would be easier to keep a registry of "global" GuardRails which implement a specific interface. The "global" guard rails are then part of each Llm invocation by default.
EarlyTerminationPolicy
Is not the right mechanism for our use case anyway, as the policy is only checked after each tick but we want to check cost limits before each Llm invocation (e.g. via PrompRunner API) is made
@stefanks-px - please be advised that guardrails got applied before the very first LLM invocation, for user input validation. However keep in mind that LLM can be invoked multiple times during Tool Loop. What is your use case: validate once per initial LLM call, or for subsequent "hidden" LLM invocations, done internally?
Hi @stefanks-px
As you've identified, no built-in extension point today combines the three properties you need:
- Auto-registered from the Spring context (no manual wiring per PromptRunner)
- Invoked before every LLM call (not just the initial one)
- Allowed to throw without the exception being suppressed
A GuardRail isn't the right primitive for this need, even if auto-registration existed. as @igordayen said UserInputGuardRail fires once - before the initial LLM invocation. During a tool loop, the model can be invoked many more times (tool responses, follow-up reasoning, internal summarization). For a monthly cost limit, any invocation that skips the check lets you run over budget.
While waiting for a more suitable solution, one possible approach would be to leverage Spring AI's observation mechanism via Micrometer.
Spring AI emits a ChatModelObservationContext observation around every chat call, and every ChatModel is constructed with the Spring-managed ObservationRegistry. This means a single ObservationHandler bean in the Spring context is auto-registered into the registry by Spring Boot's Micrometer auto-configuration, and fires on every LLM invocation - initial call, tool-loop iterations, internal summarization - across every provider (OpenAI, Anthropic, Gemini, Bedrock, etc.).
@Component
public class CostLimitObservationHandler implements ObservationHandler<ChatModelObservationContext> {
private final CostLimitVerifier costLimitVerifier;
public CostLimitObservationHandler(CostLimitVerifier costLimitVerifier) {
this.costLimitVerifier = costLimitVerifier;
}
@Override
public boolean supportsContext(Observation.Context context) {
return context instanceof ChatModelObservationContext;
}
@Override
public void onStart(ChatModelObservationContext context) {
costLimitVerifier.verify();
}
}
Benefits of this Approach
- Zero framework changes
- Auto-registered - no manual wiring per agent or per PromptRunner
- Fires on every LLM invocation, including tool-loop iterations
- Provider-agnostic - one handler covers every ChatModel implementation
- Official Spring AI / Micrometer extension point, not a workaround
- Exceptions propagate cleanly (no MulticastAgenticEventListener suppression)
Thanks, @azanux
Please also note, that LLM / Tool invocations can be intercepted as well thu Embabel callbacks. See @jettro blog with details. But whichever mechanism chosen, problem statement on having global config for cost collection remains same, correct?
Thanks @igordayen @azanux @johnsonr for the support.
We will look into this solution. Currently we have a workaround in place using decorated ChatModels.
When we first started implementing AI functions for our product, we used Spring AI ChatClient Advisors to provide cost logging and usage limit checks. A similar primitive which passes embabel specific information around each model call, such as the AgentProcess, InvocationId, LlmMetadata, Usage (after the call) would be amazing. https://github.com/embabel/embabel-agent/issues/1604 can also be solved with such a primitive.
@stefanks-px - please take a look at embabel-agent/embabel-agent-api/src/main/kotlin/com/embabel/agent/api/tool/callback/SimpleToolLoopCallbacks.kt.
WE can consider adding simple budget validatiion inspector, Usage is already available in After LLM Call callback. Missing part: tag interceptor as default and enable by default. Could you please advise which out of proposed approaches is the better fit for your application. Thank you
Thanks @igordayen - I red @jettro's blog.
His approach uses ToolLoopTransformer.transformBeforeLlmCall(...), which is the right native hook (fires before every LLM call, including tool-loop iterations). But it has to be wired manually on each PromptRunner:
javaoperationContext.ai()
.withToolLoopTransformers(transformer) // ← per-PromptRunner
.createObject(...);
So it can't be applied globally: if a one of his dev forgets to wire it on one call site, the cost-limit check is silently bypassed there - exactly the risk @stefanks-px wants to avoid.
Yes , the problem statement is unchanged regardless of the hook chosen: he need a system that fires events before or after every LLM invocation - both direct LLM calls and LLM calls inside the tool loop - and that can be registered globally (as a Spring bean) without per-call wiring.
@azanux - i was thinking about the following usage :
inside SPI notify-group , such as ``inspectors.notifyAfterLlmCall(afterLlmContext)``` implement default inspector look-up by configuration. then no need to use any APs explicyly. discussion thread is pretty active:) thanks
Thanks @igordayen - good idea on the intent (zero-wiring for global inspectors), but I'd nuance on the implementation layer.
If I understand the SPI mechanics correctly: these are top-level Kotlin extension functions → compiled to static methods → Spring cannot @Autowired anything into them. The only workarounds I see are a static holder, a ThreadLocal (silently breaks on async), or adding a parameter.
So, putting the lookup inside the SPI notify* functions (ToolLoopCallbackSupport.kt:37-51) can be problematic which makes tests harder to reason about (hidden global state on every notify* call).
Static lookup = hidden Spring dependency = tests that can't run without a Spring context and leak state between each other. Static lookup breaks inversion of control - the class pulls instead of receives, and tests can't run without Spring.
That said, your instinct of centralizing the discovery in a single place is right - I'd just suggest moving it one layer up from the SPI.
What do you think about doing the merge one layer above, in ToolLoopLlmOperations - which is already a Spring-managed bean?
Concretely:
** 1. Add optional constructor params to ToolLoopLlmOperations (with @JvmOverloads to preserve Java / binary compatibility). Spring Boot 3.5 natively injects List
@ThreadSafe
open class ToolLoopLlmOperations @JvmOverloads constructor(
// ... existing params ...
protected val globalInspectors: List<ToolLoopInspector> = emptyList(),
protected val globalTransformers: List<ToolLoopTransformer> = emptyList(),
protected val globalUserInputGuardRails: List<UserInputGuardRail> = emptyList(),
protected val globalAssistantGuardRails: List<AssistantMessageGuardRail> = emptyList(),
) {
protected val globalInspectors: List<ToolLoopInspector> = globalInspectors.orderedStream().toList()
protected val globalTransformers: List<ToolLoopTransformer> = globalTransformers.orderedStream().toList()
protected val globalUserInputGuardRails: List<UserInputGuardRail> = globalUserInputGuardRails.orderedStream().toList()
protected val globalAssistantGuardRails: List<AssistantMessageGuardRail> = globalAssistantGuardRails.orderedStream().toList()
}
**No @Configuration needed - Spring natively collects all beans implementing each interface into the injected List
@Component
class BudgetInspector : ToolLoopInspector { ... }
…and it's picked up automatically. @Order on the bean controls priority if multiple exist.
3. Propagate through ChatClientLlmOperations constructor to the super call (same pattern, internal class).
4. Merge at the existing call sites - trivial, no SPI change:
// 4x toolLoopFactory.create(...)
inspectors = globalInspectors + interaction.inspectors,
transformers = globalTransformers + interaction.transformers,
// validateUserInput / validateAssistantResponse sites (8 call sites total)
guardRails = globalUserInputGuardRails + interaction.userInputGuardRails,
Note the order: globals first ensures a cost-limit inspector fails fast before any interaction-level code runs - which matches your
CostLimitVerifier.verify()use case. Happy to flip it if we prefer interaction-level precedence.
Benefits:
- Same UX as your proposal - user just declares
@Component class BudgetInspector : ToolLoopInspectorand it fires on every LLM call, initial + tool-loop iterations - Zero Spring boilerplate and zero Spring types in the class signature — List
= emptyList() is all that's needed, Spring Boot 3.5 handles bean collection natively - SPI untouched → all existing tests in
DefaultToolLoop,ToolLoopCallbackSupport, etc. remain valid - Backward-compatible by default (emptyList() default → no behavior change if no bean is declared; @JvmOverloads preserves Java source and ABI)
- No static state, no
ThreadLocal, no service locator - Same pattern uniformly covers
ToolLoopInspector/ToolLoopTransformer/UserInputGuardRail/AssistantMessageGuardRail - Trivial to extend later (e.g. global EarlyTerminationPolicy) — just add one more List
= emptyList() param
@azanux - this will certainly works.
Note, however, that SPI-based solution does not really require spring-managed beans, its just simple plain POJO.
Happy to continue discussion in order to finalize the most practical approach.
@igordayen I am curious.
How will plain POJOs be discovered at runtime - ServiceLoader + META-INF/services, a config file of FQCNs, classpath scan, or something else? especially if an inspector needs a dependency (pricing service, repo, ....).
@azanux good question on integrrations with external services/databases. @stefanks-px -Could you please confirm whether you are looking for simple "usage < limit" or more complex funcionality.
thank you/
as for technicalities - pending functionality clarification: a. add proper config to AgentPlatformConfiguration. b. in respective code - dynamically check for config property and create object instance. Check if instance exists before creation (manual singleton).
one more inquiry on requirement - is cost shouod be aggregated cross all chils subagents hierarchy, Threre is PR#368 that rresonates with cost calculation.
Thanks for working on this and sorry for my late reply @azanux @igordayen
@azanux good question on integrrations with external services/databases. @stefanks-px -Could you please confirm whether you are looking for simple "usage < limit" or more complex funcionality.
A specific Introspector implementing usage < limit according to the embabel cost tracking won't work for us. We already have infrastructure in place for cost logging and verification operating on a monthly basis. This infrastructure should be reused e.g. direct usage of Spring AI via ChatClient interface. The goal is a unified cost management across different frameworks.
My inspector will require a dependency, the CostLimitVerifier, which is a Spring bean with other dependencies e.g. the log repository.
From embabel perspective I'd keep this as flexible as possible to enable different use-cases
one more inquiry on requirement - is cost shouod be aggregated cross all chils subagents hierarchy,
That's a good question related to Agent-level Budget checks using early termination right? We don't need this as our cost tracking works on per LlmInvocation level. In my opinion embabel should account for possible subagent invocation when checking for early stopping based on agent-level budget constraints.
@stefanks-px We have delivered the feature #1663 which allows listening to the LLM invocation. You can now implement this feature with the guardrail. If is ok for you, could you please close this ticket?