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 the AI service/tool execution return-handling code and its existing tests. Then I’ll reproduce the current restriction, implement the return-resolution rules in the narrowest shared layer, and run the relevant test suite plus focused edge-case checks.
- Assistant
ripgrepis unavailable, so I’ll use recursivegrepto identify definitions and call sites, focusing on the corelangchain4jmodule where AI service proxy behavior is typically implemented. - Assistant
The key validation appears in
ToolService; I’ll inspect that class and the AI service invocation flow to see where immediateResultobjects are currently returned and where the declared Java method return type is available. - Assistant
I’ll narrow to
ToolService’s validation and immediate-return decision, then find consumers of its result container. This should clarify whether the feature belongs in configuration-time validation, runtime conversion, or both. - Assistant
The current restriction is runtime and explicitly checks for
Result. I’ll read the complete branch andDefaultAiServicesresponse conversion to preserve existingResultbehavior while adding direct-value resolution. - Assistant
DefaultAiServicesknows the exact declaredTypeand currently only special-cases immediate return when it isResult. I’ll inspect this invocation block, imports/utilities, and tool result object semantics before choosing an API change. - Assistant
The raw tool object is retained as
ToolExecution.resultObject(), enabling direct return without serialization. The nuanced case isIMMEDIATE_IF_LAST: the existing decision permits precedingTO_LLMexecutions, but the requested direct-return mode explicitly forbids that. I’ll inspect upstream history/remotes and existing exception-message conventions, then implement deterministic validation for zero, one, multiple, incompatible, and primitive-null outcomes. - Assistant
There is no configured remote to consult. I’ll inspect current immediate-return integration tests and test model helpers so I can reproduce the exact failure using established fixtures, without modifying tests as required.
- Assistant
The common integration test’s immediate tool currently returns a value into
Result; I’ll inspect that setup and lightweight mock chat models to build a temporary focused JUnit or JShell reproduction. I also need to verify primitive/wrapper type handling utilities already present. - Assistant
I’ll preserve the existing
Resultpath exactly. For non-Resultmethods, the tool loop will only reject an immediate batch containingTO_LLM(exceptvoid, which has no value contract), whileDefaultAiServiceswill resolve raw results as follows:void→ null; zero non-null values → null only for references; exactly one compatible value → that object (including primitive-wrapper compatibility); otherwise anIllegalConfigurationException. I’ll base the count on all executions accumulated in the invocation, matching the issue’s “all tool executions” wording. - Assistant
Python is also unavailable, so no files were changed. I’ll apply the same edits with the repository’s non-interactive patch tooling, then inspect imports and formatting.
- Assistant
apply_patchis unavailable as well. I’ll use the providededitcommand directly, first opening exact line windows so line ranges remain safe. - Assistant
I’ll update the method signature and replace only the obsolete “must return Result” guard with the mixed-
TO_LLMguard. - Assistant
The first edit shifted line numbers before the second edit, causing the outer
if (shouldReturnImmediately...)line to be overwritten and leaving an extra brace. I’ve identified the malformed range and will replace the entire branch atomically before touchingDefaultAiServices. - Assistant
The tool branch is now structurally correct. Next I’ll replace the immediate-return handling in
DefaultAiServices, insert the resolver before event completion, and add only the missingToolExecution/Objectsimports. - Assistant
I’ll inspect the full import block to place imports according to the project’s existing ordering, then make the code edits.
- Assistant
I’ll now apply the complete resolver and imports. The helper explicitly boxes primitive types so an
intservice method can directly receive theIntegerproduced by reflective tool invocation. - Assistant
The insertion range started one line too late, retaining the old method declaration and overwriting part of its body. I’ll repair the entire helper/event-method region in one edit, then add imports by exact line ranges rather than text replacement.
- Assistant
The repaired region is correct. I’ll add the two imports with line-numbered replacements, remove now-unused
Result/IMMEDIATEimports fromToolServiceif compilation reports them, and run formatting/compilation. - Assistant
ToolServiceno longer needs theResultimport, while both static return-behavior imports remain used. I’ll make those import edits and run Maven compile for the affected module, which will also expose any other call sites of the changed internal signature. - Assistant
The source edits are now syntactically coherent; Maven failed before execution because this environment has no
HOME. I’ll rerun with a temporary home, then address formatter/compiler findings. - Assistant
Compilation passes. To reproduce and verify behavior end-to-end without adding repository tests, I’ll create a temporary Java smoke program under
/tmp. It will use a minimalChatModelthat requests configured tools and exercise: direct reference value, primitive value, all-null reference, void, incompatible value, multiple non-null values, and mixedTO_LLM/IMMEDIATE_IF_LAST. - Assistant
ChatModelis easy to stub by overridingdoChat. I’ll inspectAiMessageconstructors and generate the temporary program plus Maven dependency classpath. - Assistant
The smoke program will use annotated tools (so raw reflective results are tested, including
void), assert successful outcomes, and assert failures are specificallyIllegalConfigurationException. It lives entirely in/tmpand will be removed afterward. - Assistant
The direct non-null and primitive cases passed; the smoke test exposed a pre-existing obstacle for the requested null/void cases:
ToolService.toResultMessage()rejects an empty tool result before immediate resolution. I’ll inspect conversion andDefaultToolExecutoroutput for null/void, then adjust message construction so empty immediate results remain valid while preserving normalTO_LLMsemantics. - Assistant
ToolExecutionResultMessagerequires at least one content item because messages may be persisted or sent to the model. For null/void tool methods, the established old executor likely represented null text as"null"; the new content-aware path currently yields an empty list. I’ll inspect the exact conversion helper and tests around null results to choose a compatible representation rather than weakening the core message invariant. - Assistant
I’ll inspect
toTextand existing null-return integration expectations. If normal tool round-trips already rely on null being supported, the correct fix is intoResultMessage; otherwise the feature should avoid constructing a message only when all current executions immediately short-circuit—but that would alter memory/event behavior. - Assistant
voidalready maps to"Success"and works; only aStringtool returning null yields no text, while non-String null serializes as"null". The issue explicitly requires all null results, including null-returning String tools. Existing test expectations will show the intended model message representation. - Assistant
The established convention is to send null as the literal text
"null"while retaining the raw object as null. I’ll makeDefaultToolExecutor.toTextfollow that convention for nullStringresults. This unblocks immediate null returns without weakening message validation and also fixes normal null-String tool round-trips. - Assistant
I’ll change only the null branch for declared
Stringreturn types, then recompile and rerun all smoke scenarios. - Assistant
All focused scenarios now pass. Before running the suite, I’ll review API compatibility and programmatically-created tool executors. The changed
ToolServicemethod is public (though internal), so I’ll likely retain its old overload; and null programmatic results must satisfy the same feature rule rather than failing duringToolExecutionResultconstruction. - Assistant
Two compatibility points need hardening:
- A low-level
ToolExecutorreturning null currently cannot even build a result; I’ll encode its model-facing text as"null"while keepingresultObject()null. - I’ll restore the old public
ToolService.executeInferenceAndToolsLoop(..., boolean)overload, delegating to the new overload, to avoid source breakage for internal extensions.
For non-null low-level executors, the API intentionally does not expose a raw result unless
executeWithContextis overridden, so direct-value resolution correctly relies on that documented contract. - A low-level
- Assistant
I’ll apply these two small compatibility changes and then rerun compilation and the focused smoke program.
- Assistant
The insertion retained the original declaration and consumed the expanded overload’s first parameter. I’ll replace the entire declarations/delegation range explicitly, as done for the prior shifted-line issue.
- Assistant
Compilation and all focused scenarios pass after compatibility fixes. I’ll now run the most affected existing tests: return-behavior combinations, immediate programmatic tools, tool executor behavior, and the broad mock-based AI-services-with-tools suite. Then I’ll run Spotless to enforce repository style.
- Assistant
All relevant tests pass. Spotless could not start because this checkout has no
origin/mainref required by its ratchet configuration, not because of a formatting violation.One edge case remains: an earlier tool round may contain
TO_LLM, followed by a later immediate round. Since the requirement says “any tool executions,” I’ll trackTO_LLMacross the full invocation rather than only the final batch. This aligns validation with the same accumulated execution list used for result counting. - Assistant
I’ll add a single invocation-scoped flag and update it as each tool’s configured behavior is recorded.
- Assistant
The second line edit again used stale post-insertion numbers, duplicating the error update and removing the loop’s closing brace. I’ll repair the complete loop tail and switch the condition to the invocation-scoped flag.
- Assistant
The condition replacement again targeted shifted lines and partially overwrote the throw call. I’ll replace the whole immediate-condition header and exception block in one atomic edit.
- Assistant
The accumulated-
TO_LLMedge case is now implemented cleanly, and compilation/smoke checks pass again. I’ll create a temporary localorigin/mainref solely so Spotless’s ratchet can run, apply formatting if needed, then delete that ref and rerun tests. - Assistant
Spotless completed successfully and reports no whitespace errors. I’ll review the final diff carefully for accidental edits, especially because Spotless expanded compact primitive-boxing branches and import/order formatting, then rerun tests.
- Assistant
The functional diff is correct, but Spotless reformatted several pre-existing unrelated lines because the temporary ratchet caused whole-file formatting. I’ll restore those unrelated hunks to keep the patch focused while retaining import ordering and formatting directly associated with changed code.
- Assistant
I’ll restore the unrelated ternary/template wrapping, argument wrapping, validation argument wrapping, and pre-existing import order. This reduces review noise without changing behavior.
- Assistant
One restoration used shifted lines and duplicated the
prepareSystemMessagedeclaration while consuming the next method declaration. I’ll repair that complete method boundary, restore the remaining unrelated validation wrapping, and compile immediately to verify structure. - Assistant
Compilation passes and the patch is much cleaner. I’ll inspect the reduced diff once more, then rerun the focused tests and smoke program.
- Assistant
Only three unrelated formatting artifacts remain in
ToolService(import order and a pre-existing long line). I’ll restore them, while keeping the necessary removedResultimport, and then perform final validation. - Assistant
I’ll now restore those exact lines and run the final test command, smoke test, compile, diff check, and repository status.
- Assistant
The final long-line restoration retained the original closing brace one line below, producing one extra brace. I’ll remove that single duplicate and rerun the full final validation command.
- Assistant
Final affected tests and all smoke scenarios pass, and
git diff --checkis clean. I’ll perform one last concise diff/status inspection, ensure no temporary files or refs are inside the repository, then submit.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.