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
Let me look at the structureof the langchain4j-core module since that's where the AiService logic likely lives.
Assistant
Now let me look at the Tool.java file to understand the context better.
Assistant
Now let me look at the AiServices.java main code where the immediate return is processed:
Assistant
Let me look at the AiServices file to see how it processes the result from the tool service:
Assistant
Let me look at the existing test file for
ReturnBehaviorCombinationsTest:Assistant
Let me look at the PR to understand what's being proposed. Let me look at the related test files and the existing logic:
Assistant
Now let me look at the ToolExecution class:
Assistant
Let me look at the related test for lazy calculation since it's similar:
Assistant
Now let me look at the referenced PR to understand the actual changes proposed:
Assistant
Let me look at the actual PR changes:
Assistant
Now let me look at the issue source file. Let me find the GitHub issue link:
Assistant
Let me look at the actual implementation in
AiServices.javaandDefaultAiServices.javain more detail. I want to understand the flow whenimmediateToolReturnis true:Assistant
Now let me look at the ToolService logic more carefully:
Assistant
Let me now check if there's a related PR or branch in this repo:
Assistant
Let me now look at the TypeUtils to understand how type checking is done:
Assistant
Let me also look at the IllegalConfigurationException and Result class:
Assistant
Now I have a good understanding. Let me design the solution.
Assistant
Now let me look at the IllegalConfigurationException to understand error handling:
Assistant
Let me look at the test files for current understanding:
Assistant
Now let me look at the existing immediate return test for context:
Assistant
Let me look at the
AbstractAiServiceWithToolsIT.javafor more context:Assistant
Now let me search for tests that show how the immediate return flow works:
Assistant
Now I have a good understanding of the codebase. Let me make a plan:
-
The issue is in
ToolService.javawhere it throws an exception if the AI service method's return type is notResultwhen usingIMMEDIATEorIMMEDIATE_IF_LASTreturn behaviors. -
According to the requirements, we need to:
- If return type is void, 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
-
The fix needs to happen in:
ToolService.java- Remove the exception throwingDefaultAiServices.java- Update the logic to handle the new return types
Let me first understand if there's a streaming path I need to consider too:
-
Assistant
Let me look at the streaming handler:
Assistant
Now let me look at the whole
ToolService.javafile for context:Assistant
Now let me look at the area where the issue exists, where
isReturnTypeResultis checked:Assistant
Now let me understand the full flow. Looking at the code, I see the requirements state:
- If return type is void, 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
shouldReturnImmediatelymethod to better understand:Assistant
Now let me create a test script to verify the current behavior:
Assistant
Now let me look at the existing PR referenced in the issue to understand the approach:
Assistant
Let me see the ToolExecution class one more time to make sure I understand the resultObject:
Assistant
Now let me design my solution:
The strategy is:
-
Modify
ToolService.java:- Remove the
isReturnTypeResultparameter (no longer needed) - Remove the
!isReturnTypeResultcheck that throws an exception - Pass the tool execution results to the caller for processing
- Remove the
-
Modify
DefaultAiServices.java:- Update the logic to handle the new return types based on the rules
Let me look at how the return type information can be passed through:
-
Assistant
Now I have a good understanding. Let me start implementing the fix:
First, let me look at the
ToolServiceResultto understand the field:Assistant
Let me first set up my plan, then write a small reproducer to verify the current behavior:
Assistant
Now let me write a small test script to verify the current behavior:
Assistant
Let me now first write a test to reproduce the current issue:
Assistant
Now I understand the issue. Let me now implement the fix:
Assistant
Let me look at how void tool results are handled:
Assistant
Now I have enough understanding to implement the fix. Let me start with the changes:
Assistant
Let me look at all the callers of
executeInferenceAndToolsLoop:Assistant
Good, only one caller. Now let me look at how this is used in DefaultAiServices:
Assistant
Now let me start implementing. I'll first modify
ToolService.java:Assistant
Let me try a simpler approach with smaller edits:
Assistant
The replacement didn't work because theperl pattern was wrong. Let me try with a different approach.
Assistant
Now let me remove the
if (!isReturnTypeResult)block:Assistant
Now I need to also remove unused imports (Result, illegalConfiguration, IMMEDIATE_IF_LAST may still be needed):
Assistant
Both are still needed for other purposes. Now let me update
ToolServiceResultto add the return behaviors field:Assistant
Now let me rewrite
ToolServiceResult.javato include thereturnBehaviorsfield:Assistant
Now let me look at how the streaming handler uses this:
Assistant
Now let me update
DefaultAiServices.javato:- Not pass
isReturnTypeResultanymore - Add the new logic for non-Result return types
- Not pass
Assistant
Now let me update the logic for handling immediate tool return in DefaultAiServices.java:
Assistant
Now I need to extend the logic to handle non-Result return types. Let me first add the necessary helper logic. Let me look at the existing imports:
Assistant
Now I need to update the logic. Let me first look at the part of the code that determines
isReturnTypeResult:Assistant
Now let me update the logic to handle non-Result return types. I'll need to add new logic:
Assistant
Now I need to add the
computeImmediateReturnValuehelper method. Let me also add it. First, let me find a good place to put it:Assistant
Now let me find a good place to add the helper. Let me add it right before
fireEventAndReturn:Assistant
Let me use a different approach by writing the file directly:
Assistant
Now let me try to compile and run the tests:
Assistant
Now let me run the reproducer test:
Assistant
All tests pass. Let me check the test report:
Assistant
All 4 tests pass. Now let me delete the reproducer file (since I shouldn't add new tests):
Assistant
Good, the reproducer is removed. Now let me think about edge cases and verify the changes don't break existing tests:
Assistant
Now let me run the related tests to make sure I didn't break anything:
Assistant
Let me check if there are any failures:
Assistant
No failures or errors. Now let me also clean up the old surefire report for the removed Reproduce test:
Assistant
Now let me look at the test files to understand what tests exist for IMMEDIATE behavior more carefully:
Assistant
Let me check the test that's expecting the throw:
Assistant
Let me look at the subclasses of this abstract test:
Assistant
Let me find tests that directly run the test methods locally:
Assistant
Now let me look at the test more carefully and understand what runs locally:
Assistant
All 1385 tests pass. Now let me also look at the AiServiceStreamingResponseHandler to consider if streaming path needs an update:
Assistant
Let me look at the AiServices.java main file for the tools() method that I might have missed:
Assistant
Now let me write a more comprehensive test to ensure all edge cases work:
Assistant
I need to set the
@Toolannotation behavior. Let me check the default behavior.Let me look at the default behavior for@Tool: Looking at the Tool annotation:ReturnBehavior returnBehavior() default ReturnBehavior.TO_LLM;So the default is TO_LLM. My test will work correctly.
Let me also reconsider - the
shouldReturnImmediatelyrule for IMMEDIATE_IF_LAST at last returns true even if there are TO_LLM tools. So my test for[toLlmTool, lastTool]should throw.Now let me run the test:</tool_call><tool_call> < <function_calls> cd /langchain4j/langchain4j && mvn test -Dtest=Reproduce2 -DfailIfNoTests=false -q 2>&1 | tail -100 </function_calls>
Assistant
Let me check the toResultMessage function:
Assistant
The
toResultMessageis callingresult.resultContents()which lazily computes the text from the supplier. If the supplier returns null (because the tool method returned null), thenresultContents()returnsList.of()(an empty list).Then
ToolExecutionResultMessage.builder().contents(List.of()).build()throws because there are no contents.Wait, let me check that. Let me look at ToolExecutionResultMessage.
Assistant
Let me check how
Json.toJson(null)behaves:Assistant
Let me look at ToolExecutionResultMessage:
Assistant
I need to handle the case where a tool returns null. Let me update the
toResultMessagemethod:Assistant
Let me fix the
toTextmethod to handle null String results:Assistant
Let me fix the
toTextmethod:Assistant
Now let me run the tests again:
Assistant
All 12 tests pass. Let me also check that I haven't broken any existing tests by running all tests in the langchain4j module:
Assistant
All 1385 tests pass. Now let me delete the reproducer and check the langchain4j-core module too:
Assistant
Good, the reproducer is removed. Now let me also test the langchain4j-core module:
Assistant
All 1116 tests pass. Now let me look at how the streaming path handles non-Result types to ensure consistency:
Assistant
Let me look at how
adaptworks for streaming:Assistant
Let me check the existing code that uses
ToolServiceResult:Assistant
Let me also verify the revapi config:
Assistant
Let me run all the tests in the langchain4j module one more time to confirm everything works:
Assistant
All 1385 tests pass. Let me also verify the changes in DefaultAiServices look correct:
Assistant
Now let me look at the final state of my changes:
Assistant
Let me see all my changes:
Assistant
Let me check for any tests that might be affected by the toText change:
Assistant
Let me look at the AbstractAiServiceWithToolsIT file to find tests that might be affected:
Assistant
OK, these tests use tools that return non-null values, so they wouldn't be affected by my change.
Now let me also consider the test that does the
modify(int ignored)returning "" (empty string):Assistant
This test verifies that an empty string "" is correctly handled. My changes don't affect this.
Let me also check the
AiServicesWithToolsIT.javato see the null serialized test:Assistant
Let me also run the full test suite one more time:
Assistant
All 1385 tests pass. Now let me also consider some additional edge cases by looking at the docs:
Assistant
Let me update the docs to reflect the new behavior:
Assistant
Let me also check the ReturnBehavior javadoc to see if I need to update it:
Assistant
Now let me update the IMMEDIATE_IF_LAST part:
Assistant
Now let me also update the class-level Javadoc:
Assistant
Good, no more "Only allowed" text. Let me also check the class-level Javadoc:
Assistant
Now let me check the langchain4j-core compiles:
Assistant
Now let me run all tests one more time:
Assistant
All tests pass. Let me also run a quick test to ensure my changes work in a real scenario:
Assistant
All 10 tests pass. Now let me delete the reproducer:
Assistant
Good, the reproducer is removed. Let me also check the docs to update other places:
Assistant
Now let me run all tests one more time:
Assistant
All tests pass. Let me also see the final state of the changes:
Assistant
Let me also look at the test for the issue and verify my changes are correct in DefaultAiServices:
Assistant
Let me also clean up the formatting - I notice there's an extra blank line:
Assistant
Let me also clean up the imports in DefaultAiServices - let me check the
Resultimport:Assistant
Let me also verify the changes compile cleanly:
Assistant
Now let me look at the entire diff for the DefaultAiServices file once more:
Assistant
Now let me run all the tests one more time to make sure everything is in order:
Assistant
All 1385 tests pass. Now let me think about a few more edge cases:
Assistant
Let me check the execute function:
Assistant
Let me run a final comprehensive test to verify all the edge cases:
Assistant
All 5 tests pass. Now let me delete the reproducer:
Assistant
Let me run all tests one more time to verify nothing is broken:
Assistant
All tests pass. Let me also look at the diff one more time to ensure my changes are complete and correct:
Assistant
Let me also check if there are any other docs that need updating:
Assistant
Let me also check the imports in my modified files:
Assistant
Let me also check that I'm using
dev.langchain4j.agent.tool.ReturnBehavior.TO_LLMcorrectly - I should probably import it instead:Assistant
Let me refactor to import ReturnBehavior for cleaner code:
Assistant
Let me use a different approach with separate operations:
Assistant
Let me also update the Javadoc references to use the imported class:
Assistant
Now let me run the tests to make sure everything still works:
Assistant
All tests pass. Let me also check that
ToolService.javastill hasResultimport (since it was used for the error message before):Assistant
Let me check if the
Resultimport is still needed inToolService.java:Assistant
Let me remove the unused
Resultimport inToolService.java:Assistant
Good, the unused import is removed. Let me verify everything compiles:
Assistant
All tests pass. Let me also look at the final state of the diff:
Assistant
Now let me also look at the full diff:
Assistant
Now let me also check the comprehensive view:
Assistant
Now let me look at the final state of the DefaultAiServices:
Assistant
Let me clean up the imports in DefaultAiServices:
Assistant
Now let me add the missing import for ToolExecution:
Assistant
Now let me compile and run tests:
Assistant
All tests pass. Let me now also look at the modified DefaultAiServices once more to ensure it's clean:
Assistant
Code is clean. Let me run all tests one more time:
Assistant
All tests pass. Let me do a final check on all my changes:
Assistant
Let me now think about the checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- Yes, I created a reproducer test that confirmed the issue: when using
IMMEDIATEreturn behavior on a non-Result return type, the framework threwIllegalConfigurationException.
- Yes, I created a reproducer test that confirmed the issue: when using
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- Yes, after my changes, the reproducer test passes.
-
I have thought about edge cases and made sure my fix handles them as well.
- Yes, I've handled:
- void return type
- String return type with String tool
- Integer return type with Integer tool
- int return type with Integer tool (unwrapping)
- int return type with int tool (unwrapping)
- Yes, I've handled:
-
Assistant
Now let me do a final check and make sure everything compiles and tests pass:
Assistant
All tests pass. Let me make a final summary of the changes:
Assistant
Let me check one more time to make sure I don't have any issues with my changes:
Assistant
Let me also do one more test - verify the changes work for a future reader by running through the scenarios once more:
Assistant
All 9 comprehensive tests pass. Let me delete the reproducer:
Assistant
Now let me do a final check on the state of the repo:
Assistant
All my changes are in place. Let me run all the tests one more time to verify:
Assistant
All tests pass. Let me also check the diff one more time:
Assistant
All changes look good. Let me write a final summary:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.