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.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /langchain4j, current file: none) bash-$
Assistant
Now let's view the full DefaultAiServices file section around the invoke method and imports to plan edits precisely.
Assistant
Now let's edit ToolServiceResult.java to add the new fields.
Assistant
Good. Now let's add accessor methods, update equals/hashCode/toString, and the builder class.
Assistant
No hidden characters. Let's just use edit with line range 97:173.
Assistant
Good. Now let's check
copyutility handles null list gracefully (returns empty list).Assistant
Good, null-safe. Now let's update ToolService.java to populate these new fields and remove the old throw.
Assistant
Good, structure fixed. Now let's check
isReturnTypeResultparameter still declared but unused within body, and check thatillegalConfiguration,IMMEDIATE,IMMEDIATE_IF_LASTimports are still used elsewhere (they likely are, e.g. in class-level constants).Assistant
No checkstyle/PMD configured. Now let's move to updating DefaultAiServices.java for the actual logic.
Assistant
Now let's add necessary imports and modify the immediate-return block.
Assistant
Now add import for ToolExecution.
Assistant
Now let's find and edit the immediate return block.
Assistant
Now let's add the
resolveImmediateToolReturnValueandwrapIfPrimitivehelper methods, nearfireEventAndReturn.Assistant
I need to close the
wrapIfPrimitivemethod with a}beforeprivate static boolean isImage.Assistant
Good, structure looks correct now. Let's try compiling the module.
Assistant
Compiles. Now let's run the existing relevant tests.
Assistant
Now let's run the AbstractAiServiceWithToolsIT test through its mockchat concrete subclass.
Assistant
Now check line 88 area for the void test.
Assistant
Good, that's correct (just verifying no exception thrown). Now rerun test.
Assistant
All 7 pass. Let's now run broader test suites to check for regressions.
Assistant
That's just expected test logging (mocked exception). Let's check the final summary.
Assistant
No failures. Now let's run the full module test suite to be thorough (still just langchain4j module, non-IT heavy).
Assistant
Full test suite passes (mvn -q would abort on failure). Let's confirm no failures more explicitly by checking exit code.
Assistant
All tests pass. Now let's remove the temporary scratch test file before submitting.
Assistant
Good, no leftover test files. Let's double check the diff for correctness and also update the
ReturnBehavior.javajavadoc since it states IMMEDIATE/IMMEDIATE_IF_LAST are only allowed on Result-returning services — that statement is now outdated.Assistant
Now update the "Only allowed on AI services returning Result" lines at 98 and 127 to reflect the new capability.
Assistant
Now let's compile the core module and full project to make sure everything still builds.
Assistant
Now let's re-run the full langchain4j test suite once more to confirm everything is still fine after the javadoc-only changes to core (no logic changed there, but let's be safe).
Assistant
Exit code 0 — all tests pass. Now let's review the full diff of changes for a final sanity check.
Assistant
Let's view the full diffs for the other files too.
Assistant
Passes. Now clean up scratch test.
Assistant
Let's update this doc note to reflect the new capability.
Assistant
Good, that's actually fine (3 colons, the earlier view just showed 4 due to the numbering "1395::::note" concatenation of line number with content). Let's double check with grep.
Assistant
Good, consistent with existing style (":::note" followed by line-number "9:" makes it look like "9::::note"). This is fine, matches the rest of the file's pattern.
Assistant
That's correct. Now let's do a final full compile + test run across the whole repo modules that depend on langchain4j-core/langchain4j to make sure nothing else broke.
Assistant
Good, installed cleanly. Let's do the final review of the diff overall.
Assistant
This all looks complete. Let's run the full targeted test suite one more time to be safe before submitting.
Assistant
Exit code 0, build succeeded with tests (mvn -q suppresses success output). All good.
Checklist review
Assistant
Let me go through the checklist:
- If an error was reported in the issue description, I have successfully reproduced it. This is a feature request, not a bug report, so there's no error to reproduce per se. Instead I reproduced the limitation described (AI service methods using
ReturnBehavior.IMMEDIATE/IMMEDIATE_IF_LASThad to returnResulteven when a simpler return type would suffice) via a scratch test that confirmed the old behavior threwIllegalConfigurationExceptionunconditionally for non-Resultreturn types.
- If an error was reported in the issue description, I have successfully reproduced it. This is a feature request, not a bug report, so there's no error to reproduce per se. Instead I reproduced the limitation described (AI service methods using
Assistant
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error. Confirmed via scratch tests (removed before submission) that:
voidreturn type →null; single non-null tool result assignable to return type → returned directly; all-null results with nullable return type →null; all-null results with primitive return type →IllegalConfigurationException; mismatched type →IllegalConfigurationException; mixedTO_LLM+ trailingIMMEDIATE_IF_LAST→IllegalConfigurationException. All matched the rules from the issue. -
I have thought about edge cases and made sure my fix handles them as well. Covered:
void/Voidreturn types, primitive return types (with proper boxing forisInstancechecks), all-null tool results, multiple non-null tool results (ambiguous → exception), type mismatch (exception), mixedTO_LLM/IMMEDIATE_IF_LASTin the same immediate-return round (exception, since we can't know what theTO_LLMresult would've led to), and fixed a related latent bug where a tool method returning a literalnull(not justvoid) would crash message construction ("Either text or contents must be provided") — now treated likevoidand reported as"Success"to the LLM while still preserving the realnullinresultObject(). -
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. Ran full
langchain4j-coreandlangchain4jmodule test suites (mvn test) — all passed (exit code 0), includingReturnBehaviorCombinationsTest,ProgrammaticCreatedImmediateReturnToolTest,StreamingProgrammaticCreatedImmediateReturnToolTest, andLazyCalculationIntegrationTest. The IT test asserting the oldResult-only behavior (should_throw_using_immediate_tool_on_service_not_returning_ResultinAbstractAiServiceWithToolsIT, gated behind API keys so it doesn't run here) was verified equivalent via a scratchChatModelMock-based reproduction, since it uses a type-mismatched tool result (intvsString) which still correctly throwsIllegalConfigurationExceptionmentioningIMMEDIATEandResult.
All temporary scratch test files were removed prior to submission (verified via
git status).-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →