ISSUE DESCRIPTION [FEATURE] support non Result return types for AiService when tool…
- User
ISSUE DESCRIPTION
[FEATURE] support non Result return types for AiService when tool execution is IMMEDIATE Is your feature request related to a problem? Please describe. If using ReturnBehavior.IMMEDIATE, your AiService method has to return Result even if all tools called return
voidor all returnnullor there's one tool method that returns same type as AiService return type.Describe the solution you'd like I'd like to support non-Result return types for AiService methods when tool execution has IMMEDIATE results based on these rules:
- If ai service method return type is void, just return null
- If any tool executions are TO_LLM throw exception (IMMEDIATE_IF_LAST case)
- If all tool executions have a null result and return type is nullable (not a primitive), then return null
- If there is one non-null tool execution result, and the result can be resolved to the return type, then return that object
I have a PR for this open in Quarkus too:
https://github.com/quarkiverse/quarkus-langchain4j/pull/2529
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- Assistant
I’ll first map the repository and locate
ReturnBehavior.IMMEDIATE, AI service invocation, and existing tests. Then I’ll reproduce the current return-type restriction, implement the conversion rules centrally, and run the focused test suite plus any relevant broader tests. - Assistant
rgis unavailable, so I’ll use recursivegrepto find the implementation and tests without installing unnecessary tooling. - Assistant
The restriction is in
ToolService, while the actual AI-service result adaptation likely occurs in the invocation handler. I’ll inspect both the validation and the immediate-execution result model before changing behavior, because the feature must distinguish TO_LLM executions and preserveResult<T>compatibility. - Assistant
Immediate return currently throws before producing
ToolServiceResult, so I need to remove that gate and adapt at the outer method boundary. I’ll inspectAiServiceInvocationHandler/method support andToolServiceResult, along with the streaming path to determine whether this issue applies only synchronous methods (non-Resultreturn types strongly suggests it does). - Assistant
I found the adaptation point in
DefaultAiServices. I’ll read the complete invocation flow and type-resolution helpers so the implementation handlesvoid, primitives, generic return types, and existingResult<T>behavior consistently with the project’s reflection utilities. - Assistant
The raw Java object is already retained in each
ToolExecution, but return behavior is not. To enforce “any TO_LLM” robustly (including prior tool rounds), I’ll inspect context APIs, exception conventions, and recent git history. I’ll also locate tests around immediate results to mirror expected messages and event behavior. - Assistant
The rules leave invalid cases to an exception: multiple non-null results, null for a primitive, or a non-assignable result. I’ll inspect
TypeUtilssemantics and existing configuration-error style, then implement a small, directly testable resolver inDefaultAiServices. I’ll also carry ananyToolExecutionToLLMflag inToolServiceResult, since tool names/context can change dynamically and cannot reliably reconstruct behavior afterward. - Assistant
I’ll follow the rule order literally:
voidreturnsnull; otherwise mixed TO_LLM executions are rejected; then null/cardinality/type compatibility is checked. For primitive compatibility I’ll use the project’s existing boxing utility if available, rather than duplicate mappings. I’ll now locate that utility and the unit-test model helpers needed for a temporary reproduction (without adding repository tests, per instructions). - Assistant
No boxing helper exists in the relevant modules, so I’ll use
ClassUtilsonly if already depended upon; otherwise a private primitive-to-wrapper helper is safest. Before editing, I’ll inspect module dependencies and formatting conventions, then modify the result metadata, tool loop, resolver, and outdatedReturnBehaviordocumentation. - Assistant
I’m implementing now. The resolver will return the original object (no JSON/text conversion), use raw-type assignability for parameterized returns, accept boxed values for primitive method returns, and emit specific
IllegalConfigurationExceptions for each unsupported case. ExistingResult<T>behavior remains unchanged. - Assistant
Python is not installed, and no files were changed. I’ll use the repository editor’s exact replacements instead, keeping each edit narrow and reviewable.
- Assistant
The metadata structure is in place. I’ll now update
ToolServiceto accumulate TO_LLM across all rounds and stop rejecting every non-Resultreturn. I’m retaining the existing public/internal method parameter for source compatibility even though it is no longer needed by the loop. - Assistant
The editor limits replacements to the displayed window, so those edits did not apply. I’ll use standard
sedfor import deletion, then open the exact implementation region and apply multiline replacements while it is active. - Assistant
Next I’ll wire immediate adaptation into
DefaultAiServices. The method completion event will still fire with the actual returned value, includingnullforvoid/nullable all-null cases, while invalid configurations continue through the existing error-event path. - Assistant
Core behavior is implemented. I’ll run Spotless and compile the
langchain4jmodule first; this should expose import ordering, line length, language-level, and signature issues before I build a focused runtime reproduction. - Assistant
Maven requires
HOME, which is unset in this container. I’ll rerun with a temporary home directory; this is an environment fix only and does not alter repository files. - Assistant
Spotless’s ratchet expects a missing
origin/mainref in this uploaded repository. I’ll compile with Spotless checking skipped, then later format explicitly after creating a temporary local ref or using the plugin’s ratchet override. - Assistant
Compilation showed that
ToolServiceuses both exception imports elsewhere; onlyResultbecame unused. I’ll restore the exception imports and recompile. - Assistant
Compilation now passes. To reproduce and verify the feature end-to-end without modifying repository tests, I’ll create a temporary Java program under
/tmp. It will exercise: same-type non-null return, primitive boxing, all-null nullable return, void return, multiple non-null rejection, incompatible-type rejection, and mixed TO_LLM/IMMEDIATE_IF_LAST rejection. First I’ll build test classes and a runtime classpath so the program can useChatModelMock. - Assistant
The low-level
ToolExecutorAPI does not preserve raw objects by default, so the reproduction will use annotated Java tools, which exercise the productionDefaultToolExecutorpath and retain exact result objects. - Assistant
The first two feature cases passed before the temporary harness reached an unrelated existing limitation: AI services cannot declare raw
Objectreturn types because output-format validation runs before tool execution. I’ll adjust the nullable case toString, which directly tests the requested non-primitive null behavior, and rerun all checks. - Assistant
The null-return case exposed a pre-existing blocker in the same path:
DefaultToolExecutorpreserves a null raw result but also produces null text, andToolServiceeagerly builds a result message that forbids null text—even though immediate execution never sends it to the LLM. Supporting “all tool executions have a null result” therefore also requires a valid textual representation for message/history/event consistency. I’ll inspect the executor’s established void/null conventions before fixing that boundary. - Assistant
ToolServiceconverts viaresultContents(), which materializes the lazy text supplier. I’ll inspecttoTextandToolExecutionResult.resultContents()to choose the narrowest fix—likely representing null as the literal"null"while preserving the raw null used by the new resolver. - Assistant
The established convention is
"Success"forvoidand JSON serialization for other values; only a nullStringfalls through as absent content. I’ll normalize any non-void null result to the JSON literal"null"while retaining the rawnull. This both enables the requested all-null rule and makes null tool results valid if they ever need to go back to the LLM. - Assistant
All temporary end-to-end checks now pass, including the original failure mode and edge cases. I’ll update the public
ReturnBehaviorJavadocs, which currently incorrectly state that onlyResultmethods are allowed. Then I’ll review and format the complete diff. - Assistant
I’ll document both modes succinctly:
Resultretains tool-execution metadata; non-Resultmethods can receive a uniquely compatible raw value (or null forvoid/nullable all-null outcomes), but cannot do so when a TO_LLM execution participated. - Assistant
The docs are correct but contain lines Spotless will wrap. I’ll create the missing local
refs/remotes/origin/mainpointing at the current HEAD solely so Spotless’s ratchet can identify these working-tree changes, run formatting on both affected modules, and then inspect the diff. - Assistant
The formatted diff is sound; Spotless also normalized a few pre-existing lines in touched files. I’ll now run the focused tests for immediate behavior, return-behavior combinations, programmatic tools, and default tool execution (including null handling), followed by the module test suite if focused tests pass.
- Assistant
I’ll run these four focused test classes with formatting checks enabled now that the missing ref exists.
- Assistant
All focused tests pass. I’ll run the full
langchain4jmodule test suite to detect regressions in AI-service parsing, observability events, guardrails, and tool loops. - Assistant
The full module suite passes. I’ll do a final design review: inspect all changed hunks, search acronym conventions, confirm no generated/untracked files, and verify the temporary harness is outside the repository. I’ll also consider whether the metadata flag should remain internal and whether all public docs align with actual rule ordering.
- Assistant
The final review confirms the rules are implemented in the intended order and across all tool rounds. The new flag is confined to the
@InternalToolServiceResult; existing builders default it to false, preserving equality for existing paths. I’ll run one final Spotless check/compile for both affected modules and rerun the temporary end-to-end harness after formatting. - Assistant
One checklist nuance remains: I confirmed the old throwing branch in source before editing, but to make the reported problem an executed reproduction rather than only static confirmation, I’ll temporarily compile the original
ToolServicefrom HEAD against the otherwise compatible tree, run the same harness and assert the old “must return Result” failure, then restore the fixed file and rebuild. No baseline source change will remain.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.