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
Let me start by exploring the repository structure to understand what we're working with.
Assistant
This is the langchain4j project. The issue is about supporting non-Result return types for AiService when tool execution is IMMEDIATE. Let me first explore the langchain4j-core module which likely contains the AiService interface.
Assistant
Let me look at the relevantfiles to understand the structure.
Assistant
Now let me look at the main AiServices file to find where the immediate return logic happens.
Assistant
Now let me find the function where the AiService is invoked and where the result is wrapped:
Assistant
Now let me look at the PR linked in the issue to understand the desired solution better:
Assistant
Let me look at the existing tests to understand the expected behavior:
Assistant
Now let me look at the AiServiceStreamingResponseHandler to understand how streaming handles this:
Assistant
Now let me look at the AbstractAiServiceWithToolsIT.java test to understand the test patterns:
Assistant
Now let me look at the Quarkus PR mentioned in the issue to understand the desired solution better:
Assistant
Now let me look at the DefaultAiServices to see how the return value is wrapped:
Assistant
Now I have a good understanding of the codebase. Let me look at the PR mentioned in the issue (Quarkus).
Assistant
Now let me look at the TypeUtils to understand how to detect a void return type:
Assistant
Now let me look at the rest of DefaultAiServices for understanding how the result is constructed:
Assistant
Now let me look at the tool executor to understand the result better:
Assistant
Now I have a complete understanding. Let me also look at the existing tests:
Assistant
Now let me check the Quarkus PR mentioned in the issue to understand the desired implementation. Let's search if there's a clone of it:
Assistant
Let me look at the streaming response handler to understand the full flow:
Assistant
Now I have a complete understanding. Let me write a plan and reproduce the issue first.
Assistant
Let me look at the PR description more carefully and see what the solution should be. The PR in Quarkus is at https://github.com/quarkiverse/quarkus-langchain4j/pull/2529. Let me look at the test cases I should write by understanding the rules:
The rules stated in the issue:
- 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
Let me look at the relevant test files:
Assistant
Let me look at the streaming test for the immediate return tool:
Assistant
Now I have a good understanding. Let me also check what the existing tests do in the Quarkus PR. Let me look at the existing tests to see how they handle the immediate tool return:
Assistant
Now let me look at the PR for quarkus langchain4j. Let me see if there's any way to access it directly:
Assistant
Now let me understand the full flow by reading the rest of DefaultAiServices.
Assistant
Now I have a clear understanding of the architecture. Let me plan my changes.
Plan
The issue requires:
- Remove the restriction that the AI Service method must return
Resulttype when tools have IMMEDIATE/IMMEDIATE_IF_LAST behavior. - Add logic in
DefaultAiServicesto handle non-Result return types when an immediate return is detected:- For void return type → return null
- For any non-null primitive type → throw an exception (can't be null)
- If all tool executions return null and the return type is nullable (not primitive) → return null
- If exactly one non-null tool execution result, and the result is compatible with the return type → return that object
- Otherwise, throw an exception explaining the situation
Let me also handle the streaming case.
Let me first reproduce the issue:
- Remove the restriction that the AI Service method must return
Assistant
I've successfully reproduced the issue. Now let me design the solution. Let me look at the ToolService more carefully to understand the structure:
Assistant
Now I need to think about the implementation. Let me look at how the immediate return path is handled in DefaultAiServices more closely:
Assistant
Now I'll plan the changes:
-
Modify
ToolService.executeInferenceAndToolsLoopto remove theisReturnTypeResultcheck since we will handle this inDefaultAiServices. -
Modify
DefaultAiServicesto handle non-Result return types when there's an immediate tool return.
Let me also check how the streaming version handles this:
-
Assistant
The streaming case doesn't currently have an
isReturnTypeResultcheck. So it just completes the stream with the tool result. Let me look at that:Assistant
Now I have a clear plan. Let me implement the changes.
Step 1: Modify
ToolService.executeInferenceAndToolsLoopto remove the restriction. Instead, we need a way for the caller to know if we should return immediately when the return type is not Result. Let me make it throw only when a non-Result immediate return would be unsafe.Actually, looking at this more carefully, I think the cleanest approach is:
- Keep the logic for in
Assistant
Now I have all the information. Let me start the implementation.
Step 1: Modify
ToolService.javato not throw the exception inexecuteInferenceAndToolsLoop. Instead, return the immediate result, and letDefaultAiServiceshandle the conversion to the actual return type.Let me look at the structure of the code once more:
Assistant
Now let me make the change. I'll first remove the restriction in
ToolServiceand remove theisReturnTypeResultparameter since it's no longer used in the inner method:Assistant
Now let me make the changes:
Assistant
Let me use sed instead:
Assistant
Hmm, I left a trailing comma. Let me clean it up:
Assistant
I have a syntax issue - the line ends with
) {and we have))on next line. Let me look at the file again and fix it:Assistant
I need to remove the
) {line now. Let me use theeditcommand to fix this:Assistant
Wait, that deleted the wrong line. Let me restore from git:
Assistant
Good, the file is restored. Let me use the
editcommand instead for proper editing:Assistant
Now let me also remove the
isReturnTypeResultcheck. Let me look at the current state of the file:Assistant
Now let me remove the
isReturnTypeResultcheck:Assistant
Now let me check the imports to see if we still need
IMMEDIATE,IMMEDIATE_IF_LAST, andResult:Assistant
Good. The
IMMEDIATEandIMMEDIATE_IF_LASTimports are still used. Let me also check theResultimport:Assistant
The
Resultimport is no longer needed. Let me remove it:Assistant
Now let me update the
DefaultAiServices.javato update the call and handle the non-Result return type:Assistant
Now I need to update the call. Let me use the
editcommand to do this:Assistant
Now I need to add the logic to handle the non-Result return type. Let me change the condition
if (toolServiceResult.immediateToolReturn() && isReturnTypeResult)to handle both cases:Assistant
Now I need to add the non-Result handling. Let me create the proper logic:
Assistant
Now I need to add the
resolveImmediateReturnForNonResultTypemethod. Let me first look at the file structure to find a good place to add it:Assistant
Now let me add the helper method. Let me put it right after
fireEventAndReturn:Assistant
Let me find the right place to insert this method:
Assistant
Let me insert the new method between
fireEventAndReturnandisImage. I'll use a sed command to insert:Assistant
Now let me create a temporary file with the new method and use sed to insert it. Actually let me use the
editcommand:Assistant
Let me use the
replacecommand from the special tool. First, let me view the current method block:Assistant
Let me use a more direct approach with a Perl script to add the method:
Assistant
There's a problem with the Perl script - it broke the indentation and the quotes are not properly escaped. Let me fix the method:
Assistant
I see the issues. Let me restore the file and try a different approach:
Assistant
Now let me start over. First, the call site change:
Assistant
Now let me change the immediate return check to handle both Result and non-Result:
Assistant
Now I need to add the
resolveImmediateReturnForNonResultTypemethod. Let me write the entire method body to a file and then insert it using sed:Assistant
Now let me find the exact line where to insert the method:
Assistant
Now let me insert the method right before
isImage:Assistant
The method is now added correctly. Let me now also check the
ToolService.javato see if it compiles by looking at the unused imports:Assistant
Good. Now let me also check the
DefaultAiServices.javato see what imports we need:Assistant
I need to import
ToolExecution:Assistant
Let me add the
ToolExecutionimport:Assistant
Now let me try to compile the project to see if everything works:
Assistant
I need to use the
illegalConfigurationstatic method. Let me check:Assistant
Let me update the code to use the
illegalConfigurationstatic method:Assistant
The code compiles. Now let me run the reproduction test to see if it works:
Assistant
Excellent! Both tests pass. Now let me extend the test with more edge cases. First, let me delete the reproduce test and write proper tests:
Assistant
Now let me write more thorough tests that cover all the edge cases:
Assistant
Now let me run the tests:
Assistant
I see there's an issue when a tool returns null -
ToolExecutionResultMessagerequires text or contents. Let me look attoResultMessage:Assistant
Let me check the
ToolExecutionResultMessage:Assistant
The issue is that when a tool returns null, the
ToolExecutionResulthas an empty result (no resultText, no resultContents, no supplier), so callingresultContents()returns an empty list. ButToolExecutionResultMessagerequires either text or contents to be non-empty.Wait, let me look at the test that succeeded for
StringAssistant.chat- thegetGreeting()tool returned "Hello, World!". So the resultContents would have something. But when a tool returns null, the result mightnot have contents.Let me look at how
DefaultToolExecutorhandles a null result:Assistant
Let me check the
Json.toJson(null):Assistant
I see - this is a pre-existing issue when a tool returns null. Let me look at this more carefully:
Assistant
I see the issue. When a tool with
Stringreturn type returnsnull, the supplier returnsnull, causingresultContents()to return an empty list, which then failsToolExecutionResultMessagevalidation. Let me look at this inDefaultToolExecutor:Assistant
This is a pre-existing issue. Let me look at this from a different angle - we should fix the
toTextmethod to handle null results properly. Let me look more carefully:Assistant
Let me fix
DefaultToolExecutor.toTextto handle null results properly:Assistant
Actually, let me reconsider. This pre-existing behavior issue may not be in the scope of my fix. Let me check if existing tests are passing first:
Assistant
Let me fix the
toTextmethod inDefaultToolExecutor.javato handle null results properly:Assistant
The sed didn't work. Let me use perl:
Assistant
Now let me run the tests again:
Assistant
All my new tests pass. Let me also run the broader tests to make sure I didn't break anything:
Assistant
All 62 existing tests still pass. Now let me think about the streaming case. The streaming path doesn't have the same restriction, so it just calls
completeResponseHandlerwith the final response. Let me check if there's anything we need to do for streaming:Assistant
The streaming case already works without modification because it doesn't have the same restriction. Let me look at the streaming tests:
Assistant
Now let me run the full test suite for the
langchain4jmodule to make sure nothing else is broken:Assistant
All 416 tests pass. Let me also check if my tests are correct - let me look at the test results more carefully:
Assistant
All 377 tests pass. Let me run the full unit test suite to make sure nothing else is broken:
Assistant
All 1338 tests pass. Let me also verify by looking at the diff to make sure my changes are correct:
Assistant
The diff looks good. Let me also check my test file:
Assistant
Wait, I need to follow the instructions and NOT add new tests to the repository. Let me remove my test file:
Assistant
Let me check if there are any tests that rely on the old null behavior:
Assistant
Let me verify my changes work for all the cases described in the issue by writing a temporary script:
Assistant
The mixed null/non-null case actually returns the non-null result, which matches the issue rule "If there is one non-null tool execution result, and the result can be resolved to the return type, then return that object". Let me update the test to match:
Assistant
The perl substitution didn't work. The test method is still the old one. Let me lookat the file:
Assistant
Let me modify this test to expect the success case:
Assistant
Let me use the open and edit commands from the special tools:
Assistant
Now let me run the test again:
Assistant
All 13 tests pass. Now let me delete the test file since I shouldn't add new tests:
Assistant
Let me check if there are tests that have String tools returning null:
Assistant
Let me also check the streaming path to make sure it works for non-Result return types:
Assistant
find /langchain4j -name "VerifyStreamingFixTest.java" 2>/dev/null pwd ls -la langchain4j/src/test/java/dev/langchain4j/service/tool/VerifyStreamingFixTest.java 2>/dev/null || echo "File not found at expected location"
Assistant
The file was created correctly. Let me run it:
Assistant
Streaming test passes. Now let me delete the temporary test files:
Assistant
Assistant
All my test files have been removed. Only my source code changes remain. Let me view the complete diff:
Assistant
Looking at the issue rules again, I see I missed one rule: "If any tool executions are TO_LLM throw exception (IMMEDIATE_IF_LAST case)". This is about the case where we have a mix of behaviors that includes TO_LLM. Let me update my implementation to handle this:
Assistant
Let me update my implementation to handle the TO_LLM case properly. I need to pass the behaviors information to the helper method:
Assistant
Let me update my code to handle the TO_LLM case. I'll add a check for any TO_LLM behaviors:
Assistant
Let me look at ToolExecutionRequest:
Assistant
Let me look at how to get the behaviors and update my code:
Assistant
Let me update the call site and helper method to also pass the
ToolServiceContext:Assistant
Now let me update the helper method signature and add the TO_LLM check:
Assistant
Now let me add the TO_LLM check at the beginning of the method:
Assistant
Now let me add the
containsToLlmBehaviorhelper method. Let me find a good place to add it:Assistant
Let me add the
containsToLlmBehaviorhelper method right afterresolveImmediateReturnForNonResultType:Assistant
Let me fix the indentation issue:
Assistant
The perl substitution didn't work. Let me try with sed:
Assistant
Let me restore the file and try again with a different approach:
Assistant
Now let me redo the changes properly. First, let me update the call to remove the
isReturnTypeResult:Assistant
Now let me update the immediate return check to handle non-Result type:
Assistant
Now I need to add the import for ToolExecution and add the new helper methods. Let me first add the import:
Assistant
Now let me add the helper method. Let me find the right location:
Assistant
Now let me insert the helper methods before
isImage. I'll use theeditcommand for this:Assistant
Now let me try to compile to make sure everything works:
Assistant
I need to add the ReturnBehavior import:
Assistant
Now let me try to compile:
Assistant
Compilation succeeds. Now let me also write a quick verification test to ensure the TO_LLM case works:
Assistant
The TO_LLM test passes. Let me delete this temporary test file:
Assistant
Now let me run all the existing tests to make sure nothing is broken:
Assistant
All 1385 tests pass! Now let me also run the related module tests to make sure nothing else is affected:
Assistant
Let me also verify the final diff:
Assistant
Let me look at the streaming case once more to make sure it works correctly:
Assistant
Let me check if there are any other places that might be affected:
Assistant
Good, the
isReturnTypeResultis still used inDefaultAiServicesto wrap the response inResultif needed. Let me also look at the full test:Assistant
Good. The
isReturnTypeResultis still used in the normal (non-immediate) path. Now let me also check if the changes I made work in conjunction with the Kotlin module:Assistant
No usages in Kotlin. Let me also check the tests in other modules that may use these features:
Assistant
Let me also look at if there's a test that tests the illegal case (Result required):
Assistant
There's an existing test that checks for the exception message. Let me see if it will still pass:
Assistant
Let me see if that specific test runs in the tests I ran:
Assistant
The abstract test is only run through OpenAI integration tests that need API keys, so they won't be run in unit tests. Let me make sure the abstract test is not run as a unit test:
Assistant
Let me also run the tests for
DefaultToolExecutorto make sure my change doesn't break anything:Assistant
All 19 tests in
DefaultToolExecutorTestpass. Let me also run the integration tests:Assistant
All tests pass. Now let me check if there are any final issues by looking at the streaming case once more to ensure it still works:
Assistant
Let me do one final review of all my changes:
Assistant
Only my 3 source code changes are present. No test files added. Let me run a broader test to ensure no regressions:
Assistant
All 1385 tests pass. Let me also think about edge cases that may be relevant. Let me re-examine the implementation:
Assistant
Let me also check the streaming case once more to make sure my changes don't affect it:
Assistant
The streaming handler is unaffected by my changes. Let me run the full test suite to ensure everything works:
Assistant
All 1385 tests pass. Let me now also test with the agentic modules to make sure my changes don't break anything there:
Assistant
Only
DefaultAiServicesusesexecuteInferenceAndToolsLoop. The other modules don't use it directly. My changes are isolated to thelangchain4jmodule.Let me also look at the agentic module to see if it has any tests that might be affected:
Assistant
Let me also check for potential circular dependency issues:
Assistant
The imports look fine. Let me also check that the
ToolExecutionclass doesn't depend onDefaultAiServices:Assistant
No circular dependency. Let me also do a final check on the test results to make sure nothing is broken:
Assistant
All 1385 tests pass.
Now let me address the checklist:
Checklist:
Assistant
Let me do a final verification by running all tests once more:
Assistant
All 1385 tests pass. Let me also verify that the current file structure is clean:
Assistant
Only my 3 source code changes are present. Let me submit my changes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.