-
Notifications
You must be signed in to change notification settings - Fork 2k
fix(deepseek): reset tool_choice handling to prevent infinite loop when returnDirect=false (#4617) #4649
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kuntal1461
wants to merge
4
commits into
spring-projects:main
Choose a base branch
from
kuntal1461:fix/deepseekchatmodel-toolchoice-loop-4617
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+149
−3
Open
fix(deepseek): reset tool_choice handling to prevent infinite loop when returnDirect=false (#4617) #4649
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9ce8356
fix(deepseek): reset tool_choice handling to prevent infinite loop wh…
kuntal1461 68e8f79
test(deepseek): refine DeepSeekChatModelToolChoiceResetTests for forc…
kuntal1461 d05c8dd
fix(deepseek): reset tool_choice handling to prevent infinite loop wh…
kuntal1461 5bd16ee
refactor: extract duplicated code (line 223) into separate method
kuntal1461 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
116 changes: 116 additions & 0 deletions
116
.../src/test/java/org/springframework/ai/deepseek/DeepSeekChatModelToolChoiceResetTests.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
/* | ||
* Copyright 2023-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.ai.deepseek; | ||
|
||
import java.time.Instant; | ||
import java.util.List; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.mockito.ArgumentCaptor; | ||
|
||
import org.springframework.ai.chat.model.ChatResponse; | ||
import org.springframework.ai.chat.prompt.Prompt; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi.ChatCompletion; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi.ChatCompletion.Choice; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi.ChatCompletionFinishReason; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi.ChatCompletionMessage; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi.ChatCompletionMessage.ChatCompletionFunction; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi.ChatCompletionMessage.ToolCall; | ||
import org.springframework.ai.deepseek.api.DeepSeekApi.ChatCompletionRequest; | ||
import org.springframework.ai.tool.function.FunctionToolCallback; | ||
import org.springframework.http.ResponseEntity; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
import static org.mockito.Mockito.mock; | ||
import static org.mockito.Mockito.when; | ||
|
||
/** | ||
* Verifies that DeepSeekChatModel resets tool_choice to AUTO when resubmitting tool | ||
* results (returnDirect=false) to avoid infinite tool call loops. | ||
* | ||
* @author : kuntal maity | ||
*/ | ||
class DeepSeekChatModelToolChoiceResetTests { | ||
|
||
@Test | ||
void resetsToolChoiceToAutoOnToolResultPushback() { | ||
// Arrange: mock API to return a tool call first, then a normal assistant message | ||
DeepSeekApi api = mock(DeepSeekApi.class); | ||
|
||
// Capture requests to verify tool_choice on the second call | ||
ArgumentCaptor<ChatCompletionRequest> reqCaptor = ArgumentCaptor.forClass(ChatCompletionRequest.class); | ||
|
||
AtomicInteger apiCalls = new AtomicInteger(0); | ||
when(api.chatCompletionEntity(reqCaptor.capture())).thenAnswer(invocation -> { | ||
int call = apiCalls.incrementAndGet(); | ||
if (call == 1) { | ||
// First response: model requests tool call | ||
ChatCompletionMessage msg = new ChatCompletionMessage("", // content | ||
ChatCompletionMessage.Role.ASSISTANT, null, null, List.of(new ToolCall("call_1", "function", | ||
new ChatCompletionFunction("getMarineYetiDescription", "{}"))), | ||
null, null); | ||
ChatCompletion cc = new ChatCompletion("id-1", | ||
List.of(new Choice(ChatCompletionFinishReason.TOOL_CALLS, 0, msg, null)), | ||
Instant.now().getEpochSecond(), DeepSeekApi.ChatModel.DEEPSEEK_CHAT.getName(), null, | ||
"chat.completion", null); | ||
return ResponseEntity.ok(cc); | ||
} | ||
else { | ||
// Second response: normal assistant message | ||
ChatCompletionMessage msg = new ChatCompletionMessage("Marine yeti is orange.", | ||
ChatCompletionMessage.Role.ASSISTANT, null, null, null, null, null); | ||
ChatCompletion cc = new ChatCompletion("id-2", | ||
List.of(new Choice(ChatCompletionFinishReason.STOP, 0, msg, null)), | ||
Instant.now().getEpochSecond(), DeepSeekApi.ChatModel.DEEPSEEK_CHAT.getName(), null, | ||
"chat.completion", null); | ||
return ResponseEntity.ok(cc); | ||
} | ||
}); | ||
|
||
// Tool callback increments counter; returnDirect defaults to false | ||
AtomicInteger toolInvocations = new AtomicInteger(0); | ||
var tool = FunctionToolCallback.builder("getMarineYetiDescription", () -> { | ||
toolInvocations.incrementAndGet(); | ||
return "Marine yeti is orange"; | ||
}).build(); | ||
|
||
DeepSeekChatOptions options = DeepSeekChatOptions.builder() | ||
.model(DeepSeekApi.ChatModel.DEEPSEEK_CHAT) | ||
.toolCallbacks(List.of(tool)) | ||
.toolChoice(ChatCompletionRequest.ToolChoiceBuilder.FUNCTION("getMarineYetiDescription")) | ||
.build(); | ||
|
||
DeepSeekChatModel model = DeepSeekChatModel.builder().deepSeekApi(api).defaultOptions(options).build(); | ||
|
||
// Act | ||
ChatResponse response = model.call(new Prompt("What is the color of a marine yeti?")); | ||
|
||
// Assert: API was called twice (tool call, then final text) | ||
assertThat(apiCalls.get()).isEqualTo(2); | ||
// Second request tool_choice should be AUTO | ||
assertThat(reqCaptor.getAllValues()).hasSize(2); | ||
Object secondToolChoice = reqCaptor.getAllValues().get(1).toolChoice(); | ||
assertThat(secondToolChoice).isEqualTo(ChatCompletionRequest.ToolChoiceBuilder.AUTO); | ||
// Tool executes exactly once | ||
assertThat(toolInvocations.get()).isEqualTo(1); | ||
// And final content is normal text | ||
assertThat(response.getResult().getOutput().getText()).containsIgnoringCase("orange"); | ||
} | ||
|
||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
duplicated code with 223. you can extract these duplicated line to seperate method.