purushah opened a new pull request, #1484:
URL: https://github.com/apache/flink-agents/pull/1484

   Linked issue: #1202
   
   First part of #1427, split out as asked in its review.
   
   ### Purpose of change
   
   A chat request that uses tools resends every earlier tool result on every 
model call. This PR lets an Agent limit how much of one tool result is sent.
   
   - `context-management.tool-results.max-chars` (unset by default): a longer 
tool result is cut in the middle. Its beginning and end are kept, and a marker 
says how many characters were left out.
   - A `ChatRequestEvent` can carry a `ContextManagementPolicy`, which replaces 
the option for that request. `ContextManagementPolicy.disabled()` switches 
truncation off for it.
   - The stored conversation is not changed. Only the messages sent to the 
model are cut.
   
   #### Runtime flow
   
   1. `ChatModelAction.chat` takes the policy of the request, else the Agent's 
option.
   2. `ToolResultTruncation.apply` returns the messages to send, a pure 
function of the stored messages and the policy.
   3. `ModelRoutingExecutor.execute` is given those messages. The tool-call 
context keeps the stored ones.
   4. A request's own policy is saved in the tool-request context, next to 
`user_context`, so the calls after a tool round apply it too.
   
   #### Key decisions
   
   - **Only the model input changes.** Nothing is written back: no new state, 
no durable call, and a call that is made again after a failure is sent the same 
messages.
   - **Cut in the middle, counted in Unicode code points.** The sent text, 
marker included, is never longer than the limit.
   - **The result of `load_skill` is never cut.** It is the instructions of a 
skill, which the model has to keep following. The tool of a result is taken 
from the assistant message that called it. A result whose call is not in the 
request may be such instructions, so it is not cut either.
   - **Applied to the conversation of the request.** The policy runs before the 
chat model prepares its request. The messages of a bound prompt are sent as the 
prompt renders them. Cutting them too would move the policy into the routing 
executor, the invoker and the chat model setup, and a Python chat model in a 
Java Agent renders its prompt on the Python side, where Java cannot see it.
   - **Media stays.** Only the text of a result is cut. An image or a document 
keeps its place.
   - **A policy object on the request, not a number.** Masking and 
summarization, in later PRs, become fields of it. The event attribute holds its 
map form, like `user_context`, so no new class is written into state. It is set 
with `withContextManagement`, as `ChatResponseEvent.withUserContext` is, so the 
constructors stay as they are after `budget`.
   - **No event yet.** Reporting what a policy did is left for the PR that adds 
masking.
   
   ### Behavioral Semantics
   
   #### Interaction decisions
   
   | Agent option | Policy on the request | What the model is sent |
   |---|---|---|
   | unset | none | every tool result in full, as today |
   | set | none | tool results cut to the option |
   | set or unset | a limit | tool results cut to the request's limit, on every 
model call of the request |
   | set or unset | `disabled()` | every tool result in full |
   
   #### Behavioral contracts
   
   1. Without an option and without a policy the model is sent the stored 
messages, as today.
   2. The stored conversation always holds the full tool results.
   3. With a limit, no tool result of the request is sent with more text than 
the limit. Two exceptions: the result of `load_skill`, and a result whose call 
is not in the messages of the request.
   4. A cut result keeps its call id, its error flag, its metadata and its 
media.
   5. A policy on a request replaces the Agent's option on every model call of 
the request, with `ChatRequestEvent` and with `ctx.chat`. For the tool loop it 
is kept as a plain map in the tool-request context, and it is restored as that 
map.
   6. Tool results in the messages a request is created with are cut like those 
of its tool loop.
   7. The messages of an earlier model call are sent unchanged on the next call.
   8. A Python action that receives a chat request with a policy keeps the 
attribute, a disabled policy (an empty map) included.
   9. The messages of a prompt bound to the chat model are sent as the prompt 
renders them.
   10. The closing turn of a loop budget is sent the same cut results as the 
turns before it.
   
   #### Failure behavior
   
   | Failure | Behavior |
   |---|---|
   | Option below 100 (`0` included), or not an integer | Raises when the job 
is submitted. The message names the option and the value. |
   | Policy below 100 | Raises `IllegalArgumentException` where the policy is 
built. |
   | A `context_management` attribute that is not the map form of a policy (not 
a map, unknown field, value that is not an integer or below 100) | Raises 
`IllegalArgumentException` where the event is built from JSON. Set in process 
with `setAttr`: where the chat action reads the request, before anything is 
started for it. |
   
   ### Tests
   
   | Contract | Tests |
   |---|---|
   | 1 | `withoutAPolicyAToolResultIsSentInFull`, 
`aResultWithinTheLimitIsSentAsItIs` |
   | 2 | `theAgentOptionCutsTheResultThatIsSentAndKeepsTheStoredOne`, 
`aResultInTheMessagesOfARequestIsCutAndStoredInFull` |
   | 3 | `aLongResultKeepsItsBeginningAndItsEndAroundAMarker`, 
`aCutResultIsNeverLongerThanTheLimitAndLeavesOutWhatItsMarkerSays`, 
`charactersAreCountedAsCodePoints`, 
`theInstructionsOfASkillAndAResultOfAnUnknownCallAreNotCut` |
   | 4 | `aCutResultKeepsItsCallIdItsErrorFlagAndItsMetadata`, 
`anImageInAResultStaysWhereItIs`, `textInTwoBlocksIsCutLikeTheSameTextInOne` |
   | 5 | `aPolicyOnTheRequestReplacesTheAgentOption`, 
`aRequestCanSwitchTruncationOff`, 
`aChatRequestCarriesItsContextManagementPolicyAsItsMapForm`, 
`theRequestOfAChatCallKeepsItsContextManagementPolicy`, 
`restoredToolRequestMemoryKeepsTheOriginalRequestContext` (existing test, now 
with a policy) |
   | 6 | `aResultInTheMessagesOfARequestIsCutAndStoredInFull`, 
`everyLongResultOfTheMessagesIsCut` |
   | 7 | `theMessagesOfAnEarlierCallAreSentUnchangedOnTheNextCall` |
   | 8 | 
`test_python_keeps_the_context_management_of_a_chat_request_from_java_snapshot` 
and its Java twin, 
`test_python_keeps_an_empty_context_management_of_a_chat_request` |
   | 9 | `theMessagesOfABoundPromptAreSentAsThePromptRendersThem` |
   | 10 | `theClosingTurnOfALoopBudgetIsSentTheCutResult` |
   | Failure behavior | 
`connectToAgentRejectsAContextManagementOptionOutOfRange`, 
`ContextManagementConfigurationTest`, `ContextManagementPolicyTest`, 
`fromJsonRejectsChatRequestWithAContextManagementThatIsNotAPolicy`, 
`aRequestWhosePolicyIsMalformedFailsBeforeItStarts` |
   
   Test classes: `ToolResultTruncationTest`, 
`ChatModelActionContextManagementTest`, `ContextManagementPolicyTest`, 
`ContextManagementConfigurationTest`, `BuiltInEventsTest`, 
`CrossLanguageEventSnapshotTest` (and its Python twin), `CompileUtilsTest`, 
`ChatSubgraphDefinitionTest`, `ChatModelActionContextRecoveryTest`.
   
   Not verified:
   
   - No test runs against a real model.
   - A model router with a policy. By reading: every candidate of a fallback or 
an escalation, and its quality signals, get the same messages, and the routing 
strategy reads the stored conversation.
   - Sub-agents. By reading: the outcome of a sub-agent that the model calls is 
a tool result like any other, and an internal sub-agent has the Agent's 
configuration.
   - A restore: the test checks the stored map. That a stored map is applied is 
tested in process.
   - `ctx.chat` with a policy end to end. The copy of the request is covered.
   
   <details>
   <summary>Sizes and local runs</summary>
   
   24 files, 1,605 added lines: 463 Java main, 18 Python main, 966 tests and 
snapshots, 158 docs.
   
   `mvn install -pl api,plan,runtime` on JDK 17: api 969 tests, plan 946, 
runtime 1,923, no failure. Six of the runtime tests need Testcontainers and 
could not start a container on the machine they ran on. All modules build, the 
`e2e-test` ones included. `spotless:check`, `tools/check-license.sh`, `ruff 
check`, `check_java_python_config_options_parity.py`, 
`check_resource_consistency.py`, `test_agent_plan_compatibility.sh` and the 
Python `api` and `plan` suites (2,043 tests) pass. The docs site builds with 
Hugo 0.110.0.
   
   </details>
   
   ### API
   
   New: `ContextManagementPolicy`, `ChatRequestEvent.withContextManagement` / 
`getContextManagement` with the optional event attribute `context_management`, 
and `AgentExecutionOptions.CONTEXT_MANAGEMENT_TOOL_RESULTS_MAX_CHARS`.
   
   Compatibility: off by default. No existing signature, event or state format 
changes.
   
   Python: two small changes keep the languages consistent. Nothing in Python 
applies a policy yet, and the docs say so.
   
   - The option is also declared in `core_options.py`, because 
`check_java_python_config_options_parity.py` compares the option classes in 
both directions.
   - The Python `ChatRequestEvent` accepts `context_management` and keeps it. 
Without that, a Python action that listens to chat requests in a Java Agent 
rejects a request with a policy. The cross-language snapshots of the attribute 
are committed on both sides. Python does not check the map. Java does when the 
event crosses to Java.
   
   ### Documentation
   
   - [ ] `doc-needed`
   - [ ] `doc-not-needed`
   - [x] `doc-included`
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   - [x] Yes
   - [ ] No
   
   Generated-by: Claude Code 2.1.332 (Claude Fable 5.2)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to