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
Interface
No new interfaces are introduced.
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.
- Assistant
I’ll first map the repository and locate the AI service return/tool-execution pipeline and its tests. Then I’ll reproduce the current restriction with the closest existing test setup, implement the conversion rules centrally, and run the focused and relevant broader test suites.
- Assistant
The restriction is explicitly enforced in
ToolService, while immediate-return selection is based on all executions and can includeTO_LLMdue toIMMEDIATE_IF_LAST. I’ll inspect both validation and the proxy’s method-return conversion so the new behavior is applied at the correct layer without changing tool scheduling semantics. - Assistant
ToolServiceResultalready carries each raw Java tool result throughToolExecution, so no data-model change is needed. The non-streaming proxy can resolve the AI-service return afterToolServicesignals immediate completion. I’ll trace that branch and inspect existing return-type conversion utilities and immediate tests before editing. - Assistant
I found the current
Result<T>behavior deliberately returns a metadata-richResultwhose content is null; that must remain unchanged. For non-Resultmethods, the requested value should come fromToolExecution.result().result(). Next I’ll inspectDefaultAiServicesaround invocation, type metadata available there, and exception conventions to define precise handling for zero/multiple non-null values, incompatible values, primitives, and mixedTO_LLM. - Assistant
The raw method
Class<?>is available (method.getReturnType()), allowing runtime assignability including primitive-wrapper compatibility via Java reflection’s boxed tool result. The phrase “any tool executions are TO_LLM” is broader than only the final batch, so I’ll trackTO_LLMacross tool-calling rounds and reject a non-Resultimmediate return if any occurred. Resolution will preserveResultbehavior, return null forvoid, reject null for primitives, return exactly one assignable non-null raw result, and reject ambiguity or incompatibility with clear configuration exceptions. - Assistant
The codebase has no general primitive-boxing helper, so I’ll add a small private resolver in
DefaultAiServicesusing an explicit primitive-to-wrapper mapping. I’ll keep policy checks inToolService(where return behaviors are known) and value/type resolution inDefaultAiServices(where the declared method return type is known). This separation avoids altering public interfaces or data classes. - Assistant
The environment lacks Python, so the attempted edits did not apply. I’ll perform the same targeted transformations with Ruby (available in typical project images), then inspect and compile immediately; no repository files have changed yet.
- Assistant
Ruby is also unavailable; Perl is present. Rather than risk complex regex replacements, I’ll use the provided line-aware editor commands against exact current line ranges. I’ll make the small
ToolServicechanges first, reopen to account for shifted lines, then changeDefaultAiServices. - Assistant
I now have stable exact ranges. I’ll apply the policy tracking and immediate-return resolver, using imported
ToolExecution/Objectsrather than fully qualified names to match project style. - Assistant
The editor output exposed one stale closing brace from the replaced validation block; I’ll remove it before compiling. I’ll also add the resolver with normal imports and then run Spotless/compile, which will catch import ordering and Java-level compatibility (notably stream
toList()). - Assistant
The line insertion replaced (rather than inserted before) the invocation handler’s closing brace and duplicated the existing method signature; the compiler run also could not start because
HOMEis unset. I’ll repair those structural issues and duplicate import, remove the now-unusedResultimport inToolService, then compile withHOME=/tmp. - Assistant
The editor operates on the updated file but displayed stale line assumptions between commands, leaving two duplicated fragments. I’ll replace the entire affected boundaries as contiguous ranges now shown: one complete helper declaration at lines 404–409 and one complete event method declaration at 458–460.
- Assistant
Compilation now reaches semantic checks and reports only that
Mapwas accidentally displaced when insertingObjects; I’ll restore it. Before tests, I’ll run formatting, inspect the final diff, and check whether AI-service validation currently permitsvoidand primitive return types—the feature explicitly requires those paths, so build-time validation must not preempt runtime resolution. - Assistant
Compilation succeeds. Spotless cannot run only because this checkout lacks the plugin’s expected
origin/mainGit ref, not because of formatting.ServiceOutputParserconfirmsvoidis already a valid service return type.I’ll now inspect the clean formatted diff and existing mock-model test patterns. Since repository tests cannot be added or changed, I’ll create a temporary (untracked, then removed) focused JUnit test covering the requested rules, run it, and also run the existing immediate-return test classes.
- Assistant
The diff matches the intended architecture. One important compatibility detail is whether programmatic
ToolExecutorimplementations preserve their raw return object: I’ll verify that first. Then I’ll use a temporary test with annotated methods (whose executor definitely stores raw values) for object, primitive, null/reference, null/primitive, void, ambiguity, mismatch, and mixedTO_LLM/IMMEDIATE_IF_LAST. - Assistant
Programmatic executors only expose a textual LLM result unless they opt into
executeWithContext; therefore returning null for their raw object is consistent with the documentedToolExecutionResult.result()contract. Annotated tools preserve raw values.I’ll run the existing focused tests now. For direct edge verification without adding repository tests, I’ll compile a temporary standalone harness under
/tmpagainst the module’s test/runtime classpath and execute it. - Assistant
The existing immediate
Resultbehavior and return-behavior combination tests pass. I’ll now execute the standalone harness. It will assert successful object and primitive propagation, null behavior for reference and void, and exceptions for primitive-null, incompatible/multiple results, andTO_LLMmixed with a lastIMMEDIATE_IF_LAST. - Assistant
The harness reproduced an additional blocker directly tied to the feature: a tool returning Java
nullproduces empty result contents, andToolServicetries to construct an LLM result message before deciding to return immediately; that message rejects empty contents. Thus the new null-return rule cannot work yet.I’ll inspect the message conversion and existing null-tool behavior conventions, then adjust it so null results can reach immediate resolution without breaking
TO_LLMhandling. - Assistant
ToolExecutionResultMessageintentionally requires some representation because messages may be stored in memory even for immediate calls. The default executor’s null result supplier currently yields null/empty contents. For compatibility with normalTO_LLMtools and memory, the safest representation is textual"null"(JSON’s null literal), while retaining the raw result as Java null for our resolver. I’ll confirm the converter convention and implement that fallback only when result contents are empty. - Assistant
I’ll open the exact converter implementation; the previous range missed it. If it delegates to JSON serialization, its null output confirms
"null"as the expected wire representation. - Assistant
The existing convention explicitly tests sending
"null"to the LLM for null tool returns; non-String objects already serialize that way, while a nullStringis an uncovered edge that yields empty contents. I’ll makeToolService.toResultMessagenormalize any empty result contents to aTextContent("null"). This preserves raw null and aligns all null-returning tool types with the established behavior. - Assistant
The exact-range replacement again retained the old method’s closing brace, visible at line 794. I’ll remove it and import
Content/TextContent, then compile and rerun the same harness to ensure every requested path now executes. - Assistant
The next null blocker is the observability event, which independently rejects empty result contents before immediate resolution. I’ll inspect its event construction. The same normalized contents should be used consistently for both the event and message; centralizing normalization avoids fixing each consumer separately.
- Assistant
Both consumers can share
nonEmptyResultContents(List<Content>), mapping only an empty list to textual"null". I’ll apply that to event and message creation. This leaves non-empty text, images, errors, and void’s"Success"untouched. - Assistant
The second edit used pre-shift line numbers and removed the method declaration, visible in the output. I’ll replace the entire malformed block (783–793) with the complete method plus normalization helper in one atomic edit, avoiding further shifted-range operations.
- Assistant
The centralized normalization compiles. I’ll rerun the standalone harness (restoring it briefly under
/tmp) and then run focused existing tests including the repository’s null-to-LLM integration test if selectable. - Assistant
All standalone feature checks and focused existing tests pass, including null-to-LLM behavior. I’ll now create the missing local
origin/mainref solely so Spotless’s ratchet can identify changed files, run formatting/checks, then run the fulllangchain4junit test suite and inspect final status/diff. - Assistant
Spotless now passes and only the two intended source files are modified. I’ll review the formatted diff for accidental edits, then run the module’s complete test suite.
- Assistant
The complete
langchain4jtest suite passes. The formatted diff contains a few Spotless-only changes in the same files because the current formatter differs from baseline; they are style-only and required forspotless:checkto pass.I’ll do final hygiene: remove the temporary Git ref, confirm no temporary/untracked files, rerun diff validation, and summarize checklist compliance before submission.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.