GitHub user eemario created a discussion: [Discussion] Per-chat budgets for
turns, time, and tokens
Related issue: #1398
Proposed implementation: #1397
## 1. Background
A ReAct loop in Flink Agents may involve multiple turns of model inference and
tool execution. To prevent unbounded loops and continuous resource consumption,
this proposal introduces budget controls, allowing users to configure resource
budgets for an individual ReAct loop and specify how to handle budget
exhaustion.
## 2. Overall Design
### 2.1 Budget Limits
An individual ReAct loop supports three types of budgets: turns, time, and
tokens. Multiple budgets can be configured together; exhausting any budget
triggers budget-exhaustion handling. No budget limits apply by default.
Before each inference turn starts, check whether any budget has reached or
exceeded its limit.
| Budget | Accounting |
| --- | --- |
| Turns | One model inference and the tool calls it triggers constitute one
turn. |
| Time | Elapsed time since the loop started. |
| Tokens | Accumulated input and output token counts reported when model calls
return. |
None of these budgets guarantees that actual consumption stays strictly within
the configured limit. When a model service does not provide token usage, the
call does not reduce the token budget, and a warning is logged.
### 2.2 Budget Exhaustion
Two modes are supported: `soft` and `hard`.
| Mode | Behavior |
| --- | --- |
| `soft` (default) | Replace the upcoming inference turn with a tool-free
closing turn, prompting the model to generate a final answer using only the
available information. If the final output still does not meet the
requirements, return a failed `ChatResponseEvent` and end the loop. |
| `hard` | Return a failed `ChatResponseEvent` directly and end the loop. |
## 3. API
Budgets support job-level and per-chat configuration. When a chat does not
specify a budget, the job-level budget configuration applies.
### 3.1 Job-Level Configuration
| Configuration option | Type | Default | Description |
| --- | --- | --- | --- |
| `react-loop.budget.max-turns` | int | — | Maximum number of inference turns
per loop. |
| `react-loop.budget.max-time` | duration | — | Time limit per loop. |
| `react-loop.budget.max-tokens` | long | — | Maximum accumulated input and
output tokens per loop. |
| `react-loop.budget.mode` | enum | `soft` | Behavior when a budget is
exhausted: `soft` attempts finalization once; `hard` returns a failure
directly. |
### 3.2 Per-Chat Configuration
Introduce `ReActLoopBudget` to declare the budget for an individual chat.
```python
from datetime import timedelta
from enum import Enum
from pydantic import BaseModel
class BudgetMode(str, Enum):
SOFT = "SOFT"
HARD = "HARD"
class ReActLoopBudget(BaseModel):
max_turns: int | None = None
max_time: timedelta | None = None
max_tokens: int | None = None
mode: BudgetMode = BudgetMode.SOFT
```
#### Starting a Chat from a Custom Action
To await the result within the current asynchronous action, pass the budget
through `ctx.chat`:
```python
result = await ctx.chat(
model="review_model",
messages=...,
budget=ReActLoopBudget(max_turns=2, max_time=timedelta(seconds=60)),
)
```
If another action listens for `ChatResponseEvent` and handles the result, pass
the budget when sending the request event directly:
```python
ctx.send_event(
ChatRequestEvent(
model="review_model",
messages=...,
budget=ReActLoopBudget(max_turns=2, max_time=timedelta(seconds=60)),
)
)
```
#### Using the Built-in ReActAgent
Pass the budget when constructing a `ReActAgent`.
```python
agent = ReActAgent(
chat_model=...,
budget=ReActLoopBudget(max_turns=2, max_time=timedelta(seconds=60)),
)
```
The Java API is aligned with the Python API.
## 4. Detailed Design
### 4.1 Budget-Exhaustion Failure Handling
When a budget is exhausted in `hard` mode, or finalization fails in `soft`
mode, send `ChatResponseEvent.failed(...)` and end the loop.
The event's `error` field contains the specific budget-exhaustion identifier.
When `soft` finalization fails, it also includes the finalization failure
reason.
- `TURN_BUDGET_EXCEEDED`: the turn budget is exhausted.
- `TIME_BUDGET_EXCEEDED`: the time budget is exhausted.
- `TOKEN_BUDGET_EXCEEDED`: the token budget is exhausted.
### 4.2 Subagent Budgets
Parent and child agents configure and track their budgets independently:
- For the parent agent, a subagent invocation is treated as a tool call. The
child's internal inference turns and token consumption do not count toward the
parent's budget usage.
- The child's budget is configured independently. Each chat starts accounting
for usage from zero and does not inherit the parent's budget configuration or
accumulated usage.
Budget sharing and coordination between parent and child agents can be
considered as future work if needed.
### 4.3 Recovery and Replay
Budget usage state is stored in sensory memory and persisted through
checkpoints.
When a persistent `ActionStateStore` is configured, an action's sensory-memory
updates are saved together with its execution result. During recovery, these
updates are replayed to restore the budget state. Without a persistent
`ActionStateStore`, execution continues from the restored checkpoint state.
Calls whose results have not yet been persisted may execute again after
recovery and incur additional consumption. Budget accounting therefore does not
guarantee that it covers all actual consumption before and after a failure.
## Feedback
Feedback on the proposed design and API is welcome, particularly on budget
accounting, soft/hard exhaustion behavior, and independent budgets for
subagents.
GitHub link: https://github.com/apache/flink-agents/discussions/1409
----
This is an automatically sent email for [email protected].
To unsubscribe, please send an email to: [email protected]