embabel-agent icon indicating copy to clipboard operation
embabel-agent copied to clipboard

Introduce new LlmInvocationEvent to expose Usage per LlmInvocation

Open stefanks-px opened this issue 7 months ago • 18 comments

Requirement: My organization wants to track cost per LlmInvocation for usage limit controlling and fine granular analysis of costs.

Required data:

  • LlmMetadata
  • Usage
  • InteractionId
  • AgentProcess.id

Gap:

Usage and LlmMetadata is currently recorded as a history of LlmInvocations in the AgentProcess via ToolLoopLlmOperations.recordUsage. Currently there is no way to deterministically retrieve usage data for each LlmInvocation.

A listener for LlmResponseEvent does not solve the problem. Retrieving the last LlmInvocations from the agent process is not accurate

  • when CONCURRENT mode is active
  • in case there are multiple retries due to data binding or validation problems

ToolLoopCompletedEvent is missing LlmMetadata

Proposed Solution:

Publish a new LlmInvocationEvent on ToolLoopLlmOperations.recordUsage. Required data is available at this point.

I can provide a PR if you greenlight this idea

stefanks-px avatar Apr 14 '26 12:04 stefanks-px

@stefanks-px - could you please confirm proper understanding:

a. Current issue and issue #1597 are essentially two parts of the same problem: global config on cost usage validation b. your ultimate goal is not really intermmediary ops (issue #1597 ), but rather at the end of LLMInvocation c. from that perspective Assistant Message Guardrails seems as more appropriate facility (need to verify whether LLM Invocation with Total Usage got properly propagted).

@azanux - for your awareness.

Thank you.

igordayen avatar Apr 16 '26 16:04 igordayen

Hi @igordayen, a) https://github.com/embabel/embabel-agent/issues/1597 and this issue are two sides of the same coin: This ticket is about writing of usage / cost logs so that in https://github.com/embabel/embabel-agent/issues/1597 the monthly cost limit can be verified b) Yes after the LlmInvocation, I need to inform another service in our application external to embabel about the invocation characteristics, e.g. usage, LlmMetadata .. c) While AssistantMessageGuardRail would be at the right spot (after the generation of the AssistantMessage), I don't think it is the correct primitive for logging of data. I also don't see that the required data is available at that time.

A requirement is that retries or validation errors don’t cause under-reporting the actual LlmInvocations made A flexible solution could look like this:

+------------------------------+
| ToolLoopStarts               |
| -> Publish Event             |
+------------------------------+
               |
               v
      (Inside the tool loop)
               |
               v
+----------------------------------------------+
| 1) Right before invocation                   |
|    of LlmMessageSender -> Publish event      |
+----------------------------------------------+
               |
               v
+------------------------------+
| 2) LlmMessageSender call     |
+------------------------------+
               |
               v
+----------------------------------------------+
| 3) Right after invocation                   |
|    of LlmMessageSender -> Publish event      |
|    (with required data)                     |
+----------------------------------------------+
               |
               v
      (Outside the tool loop)
               |
               v
+----------------------------------------------+
| ToolLoopEnded -> Publish event               |
| (with required data; usage aggregated)       |
+----------------------------------------------+

stefanks-px avatar Apr 20 '26 13:04 stefanks-px

@stefanks-px - thanks, that is very helpful.

  1. ToolLoop Start event - publishToolLoopStartEvent
  2. ToolLoop Completion Event - handleToolLoopCompletion [maybe we need to inverse ln 297 and 304] to ensure usage recorded prior to event publishing
  3. Before LLM Invocation - how this is important for usage recording / validation. Reason: before very first iteration net effect effectively the same as after [1], and moving forward you may rely on after LLM invocation
  4. in SPI notifyAfterLlmCall - perhaps, would be ok to publish Event as it already contains accumulated usage

igordayen avatar Apr 21 '26 01:04 igordayen

@stefanks-px - lets close outstanding issues if possible before addressing Agent Chat Bot Budget configuration. Could you please confirm course of action on above solution regarding event publishing. thank you

igordayen avatar Apr 22 '26 19:04 igordayen

@igordayen Yes sure, let's take it step by step.

  1. ✔️
  2. Switching this up makes sense to me. The important part is that the LlmInvocation object is created once, then used for recordUsage and as an attribute for the ToolLoopCompletedEvent
  3. Not important for my cost tracking use case. From a framework perspective publishing events symmetrical gives all the options devs might need in the future
  4. Usage is already available in notifyAfterLlmCall but AfterLlmCallContext misses LlmMetadata, InteractionId, AgentProcessId. At the moment this data is not available in the ToolLoop implementations. This data can be added at creation time of the ToolLoop implementation or passed in ToolLoop.execute. Not sure at the moment, what approach to prefer.

stefanks-px avatar Apr 23 '26 08:04 stefanks-px

@stefanks-px - thank you Re # 4. I think you can obtain AgentProcess.get() as "global" API along with id and Invocation History. As for LLMMetadata - need to do some research. Is it employed in observability, @azanux ?

igordayen avatar Apr 23 '26 15:04 igordayen

Hi @stefanks-px @igordayen

Sorry, I was a bit busy lately, tomorrow I'll catch up on the whole conversation and linked issues

azanux avatar Apr 23 '26 23:04 azanux

@igordayen, @stefanks-px

this issue and #1597 are two sides of the same problem, as @stefanks-px noted earlier. If we properly address per-invocation publication here (the cost-writing side), #1597 (monthly limit validation) becomes almost automatic. So solving this one unblocks the other.

Re your question: yes, LlmMetadata is used in observability:

  • EmbabelMetricsEventListener: model tag on embabel.llm.requests.total / embabel.llm.duration
  • EmbabelFullObservationEventListener: drives the LLM span name + gen_ai.request.model / gen_ai.provider.name tags
  • ChatModelObservationFilter: per-call gen_ai.usage.input_tokens / output_tokens are already on the Spring AI ChatModel span

So per-call usage is already visible in OTel. The need here is on the applicative event bus (transactional control for #1597), not OTel, the two are complementary.

The data is also already accessible internally: LlmService extends LlmMetadata, LlmRequestEvent.llmMetadata exists, and LlmInvocation carries it. The "single LlmInvocation instance" invariant proposed by @stefanks-px is therefore trivial to honor.

Re where to inject LlmMetadata / InteractionId / AgentProcessId into ToolLoop: I'd lean toward adding them at ToolLoop creation time rather than passing them in ToolLoop.execute(...). Reasons:

  • SpringAiLlmMessageSender is built with an immutable ChatModel and FallbackByNameModelSelectionCriteria resolves before loop creation, so LlmMetadata is stable for the loop's lifetime, no reason to re-pass it on every execute() call.
  • Consistent with the existing pattern:inspectors, transformers, maxIterations, toolNotFoundPolicy are already constructor params today.
  • ToolLoop is instantiated fresh per call via toolLoopFactory.create(...) in ToolLoopLlmOperations, so the "reusable instance" argument doesn't apply.

For AgentProcessId / InteractionId: agreed that AgentProcess.get() works as a global API internally, but for an external listener subscribing to the event, having these on the payload is cleaner than forcing a ThreadLocal-style lookup, the same constructor injection covers both needs.

azanux avatar Apr 29 '26 15:04 azanux

@azanux - thank you.

DefaultToolLoop / ParallelToolLoop already include dozen of constructor params. How many need to be passed or wrapped. (btw, more params are coming, seeing RJ work-in-progress PR). Could you outline your envision on param usage, preferrebly, with min changes to Tool Loop (callbacks, event publishing?). thank you

@stefanks-px - given direction your request is going on, perhaps you may consider renaming related issue under name "Global Guardrails" ? or merge with this one. Thanks.

igordayen avatar Apr 30 '26 02:04 igordayen

Thanks @igordayen for the feedback - that's a fair concern. We're waiting on @stefanks-px 's input first to make sure we're aligned on the direction and what he is looking for, then I'll look at RJ's in-progress PR to give a more detail approach of teh implementation

azanux avatar Apr 30 '26 20:04 azanux

so LLMMetadata is just property of LLmInvocation and available thru agent -->invocation history --> invocation --> llm metadata. PR fom R J #1630 got merged.

igordayen avatar May 02 '26 22:05 igordayen

@igordayen - agreed on both points.

  1. LlmMetadata: confirmed accessible via AgentProcess.llmInvocations[].llmMetadata. Dropping the constructor-injection idea.
  2. #1630 confirms the constructor concern - wrong direction to keep adding params.

Revised proposal - per-call instead of per-loop:

After thinking a little about it, publishing once per tool loop (via post-loop recordUsage with aggregated usage) is too coarse for cost control. Concrete risk: a 10-iteration loop on Claude Opus with 1M-input-token calls = ~$225 spent before the event fires. Tight time-window limits would overrun massively. (1 hours)

I'd go with @stefanks-px's earlier suggestion of passing data via ToolLoop.execute(...) and avoiding the constructor - which aligns with @igordayen's point about #1630 bloat.

One small refinement: instead of passing the raw fields (LlmMetadata, interactionId, agentProcessId) as parameters, pass a callback. That way, DefaultToolLoop doesn't need to know anything about LLM-specific data - it just invokes the callback when an LLM call completes.

Concretely:

  • Add onLlmCall: (Usage) -> Unit to ToolLoop.execute(...)
  • The lambda is created in ToolLoopLlmOperations, where llm and llmRequestEvent are already in scope (captured via closure)
  • Inside the lambda: call recordUsage(...) and publish LlmInvocationEvent

Benefits over passing raw fields:

  • DefaultToolLoop stays agnostic of LlmService / LlmRequestEvent - it just invokes the callback
  • No need to enrich AfterLlmCallContext with extra fields
  • No new constructor params

recordUsage then moves from post-loop to per-call inside the loop. Side effect: agentProcess.llmInvocations becomes per-call instead of per-loop.

Symmetric for embeddings: publish EmbeddingInvocationEvent from EmbeddingOperations after recordEmbeddingInvocation(...). Embedding calls are already per-call by nature.

Both events or just (one type Event for both) would be dedicated (LlmInvocationEvent / EmbeddingInvocationEvent) extending AbstractAgentProcessEvent, carrying Metadata, Usage, interactionId, agentProcessId. Dedicated types give symmetry with embedding and future-proof other billable invocation types (text-to-image, TTS, video). Both survive CONCURRENT mode and retries.

This covers the logging side. The enforcement side of #1597 stays orthogonal - a globally-registered GuardRail running before the LLM call.


@stefanks-px - moving to per-LLM-call should match your original diagram better (the "right after LlmMessageSender" point), and your execute(...) parameter idea

@stefanks-px @igordayen What do you think about this ?

azanux avatar May 04 '26 00:05 azanux

@azanux - replied on discord, thank you

igordayen avatar May 04 '26 00:05 igordayen

@azanux

This would definitely work for our purpose.

Some further thoughts

After thinking a little about it, publishing once per tool loop (via post-loop recordUsage with aggregated usage) is too coarse for cost control. Concrete risk: a 10-iteration loop on Claude Opus with 1M-input-token calls = ~$225 spent before the event fires. Tight time-window limits would overrun massively. (1 hours)

This is one of the concerns we have right now. That's why I proposed the solution to fire events with usage data inside and outside the tool loop.

recordUsage then moves from post-loop to per-call inside the loop. Side effect: agentProcess.llmInvocations becomes per-call instead of per-loop.

  • The proposed changes alter the semantics of LlmInvocation, which might break existing framework integrations. Right now a LlmInvocation can be seen as a logical request to an LLM to perform some action including the optional tool loop, if tools are present and are called.
  • recordUsage could be kept outside the ToolLoop. You probably don't need a new event type as on this level there is already ToolLoopCompletedEvent Creating the LlmInvocation object on and passing it to ToolLoopCompletedEvent would be sufficient.
  • Introduction of a new event type which is published inside the ToolLoop after a concrete LlmCall was made would allow for the fine granular tracking of usage. Could also pass the iteration number to the event to allow ordering.

Benefit: Does not alter the LlmInvocation semantics and break existing integrations

Open question

Side effect: agentProcess.llmInvocations becomes per-call instead of per-loop.

I wonder if this has any effect on other parts of the framework

stefanks-px avatar May 04 '26 09:05 stefanks-px

Hi @stefanks-px

Thanks for the feedback, we are going to take a different approach on this.

Before going further though - for your case do you need streaming support as part of this first delivery, or can we ship the first phase and add streaming support later?

azanux avatar May 07 '26 04:05 azanux

@azanux We don't use streaming right now.

stefanks-px avatar May 07 '26 07:05 stefanks-px

Great !

We almost have a clean solution , will talk with @igordayen and ship it

azanux avatar May 07 '26 08:05 azanux

Closed, as addressed by PR #1663

igordayen avatar May 09 '26 20:05 igordayen