-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Fix Moonshot Chat model toolcalling token usage #1927
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
Closed
ilayaperumalg
wants to merge
2
commits into
spring-projects:main
from
ilayaperumalg:moonshot-toolcalling-usage
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -36,6 +36,8 @@ | |
import org.springframework.ai.chat.metadata.ChatGenerationMetadata; | ||
import org.springframework.ai.chat.metadata.ChatResponseMetadata; | ||
import org.springframework.ai.chat.metadata.EmptyUsage; | ||
import org.springframework.ai.chat.metadata.Usage; | ||
import org.springframework.ai.chat.metadata.UsageUtils; | ||
import org.springframework.ai.chat.model.AbstractToolCallSupport; | ||
import org.springframework.ai.chat.model.ChatModel; | ||
import org.springframework.ai.chat.model.ChatResponse; | ||
|
@@ -75,6 +77,7 @@ | |
* | ||
* @author Geng Rong | ||
* @author Alexandros Pappas | ||
* @author Ilayaperumal Gopinathan | ||
*/ | ||
public class MoonshotChatModel extends AbstractToolCallSupport implements ChatModel, StreamingChatModel { | ||
|
||
|
@@ -180,6 +183,10 @@ private static Generation buildGeneration(Choice choice, Map<String, Object> met | |
|
||
@Override | ||
public ChatResponse call(Prompt prompt) { | ||
return this.internalCall(prompt, null); | ||
} | ||
|
||
public ChatResponse internalCall(Prompt prompt, ChatResponse previousChatResponse) { | ||
ChatCompletionRequest request = createRequest(prompt, false); | ||
|
||
ChatModelObservationContext observationContext = ChatModelObservationContext.builder() | ||
|
@@ -218,8 +225,11 @@ public ChatResponse call(Prompt prompt) { | |
// @formatter:on | ||
return buildGeneration(choice, metadata); | ||
}).toList(); | ||
|
||
ChatResponse chatResponse = new ChatResponse(generations, from(completionEntity.getBody())); | ||
MoonshotApi.Usage usage = completionEntity.getBody().usage(); | ||
Usage currentUsage = (usage != null) ? MoonshotUsage.from(usage) : new EmptyUsage(); | ||
Usage cumulativeUsage = UsageUtils.getCumulativeUsage(currentUsage, previousChatResponse); | ||
ChatResponse chatResponse = new ChatResponse(generations, | ||
from(completionEntity.getBody(), cumulativeUsage)); | ||
|
||
observationContext.setResponse(chatResponse); | ||
|
||
|
@@ -232,7 +242,7 @@ && isToolCall(response, Set.of(MoonshotApi.ChatCompletionFinishReason.TOOL_CALLS | |
var toolCallConversation = handleToolCalls(prompt, response); | ||
// Recursively call the call method with the tool call message | ||
// conversation that contains the call responses. | ||
return this.call(new Prompt(toolCallConversation, prompt.getOptions())); | ||
return this.internalCall(new Prompt(toolCallConversation, prompt.getOptions()), response); | ||
} | ||
return response; | ||
} | ||
|
@@ -244,6 +254,10 @@ public ChatOptions getDefaultOptions() { | |
|
||
@Override | ||
public Flux<ChatResponse> stream(Prompt prompt) { | ||
return this.internalStream(prompt, null); | ||
} | ||
|
||
public Flux<ChatResponse> internalStream(Prompt prompt, ChatResponse previousChatResponse) { | ||
return Flux.deferContextual(contextView -> { | ||
ChatCompletionRequest request = createRequest(prompt, true); | ||
|
||
|
@@ -287,8 +301,11 @@ public Flux<ChatResponse> stream(Prompt prompt) { | |
// @formatter:on | ||
return buildGeneration(choice, metadata); | ||
}).toList(); | ||
MoonshotApi.Usage usage = chatCompletion2.usage(); | ||
Usage currentUsage = (usage != null) ? MoonshotUsage.from(usage) : new EmptyUsage(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. as above |
||
Usage cumulativeUsage = UsageUtils.getCumulativeUsage(currentUsage, previousChatResponse); | ||
|
||
return new ChatResponse(generations, from(chatCompletion2)); | ||
return new ChatResponse(generations, from(chatCompletion2, cumulativeUsage)); | ||
} | ||
catch (Exception e) { | ||
logger.error("Error processing chat completion", e); | ||
|
@@ -303,7 +320,7 @@ public Flux<ChatResponse> stream(Prompt prompt) { | |
var toolCallConversation = handleToolCalls(prompt, response); | ||
// Recursively call the stream method with the tool call message | ||
// conversation that contains the call responses. | ||
return this.stream(new Prompt(toolCallConversation, prompt.getOptions())); | ||
return this.internalStream(new Prompt(toolCallConversation, prompt.getOptions()), response); | ||
} | ||
return Flux.just(response); | ||
}) | ||
|
@@ -325,6 +342,16 @@ private ChatResponseMetadata from(ChatCompletion result) { | |
.build(); | ||
} | ||
|
||
private ChatResponseMetadata from(ChatCompletion result, Usage usage) { | ||
Assert.notNull(result, "Moonshot ChatCompletionResult must not be null"); | ||
return ChatResponseMetadata.builder() | ||
.id(result.id() != null ? result.id() : "") | ||
.usage(usage) | ||
.model(result.model() != null ? result.model() : "") | ||
.keyValue("created", result.created() != null ? result.created() : 0L) | ||
.build(); | ||
} | ||
|
||
/** | ||
* Convert the ChatCompletionChunk into a ChatCompletion. The Usage is set to null. | ||
* @param chunk the ChatCompletionChunk to convert | ||
|
@@ -336,10 +363,11 @@ private ChatCompletion chunkToChatCompletion(ChatCompletionChunk chunk) { | |
if (delta == null) { | ||
delta = new ChatCompletionMessage("", ChatCompletionMessage.Role.ASSISTANT); | ||
} | ||
return new ChatCompletion.Choice(cc.index(), delta, cc.finishReason()); | ||
return new ChatCompletion.Choice(cc.index(), delta, cc.finishReason(), cc.usage()); | ||
}).toList(); | ||
|
||
return new ChatCompletion(chunk.id(), "chat.completion", chunk.created(), chunk.model(), choices, null); | ||
// Get the usage from the latest choice | ||
MoonshotApi.Usage usage = choices.get(choices.size() - 1).usage(); | ||
return new ChatCompletion(chunk.id(), "chat.completion", chunk.created(), chunk.model(), choices, usage); | ||
} | ||
|
||
/** | ||
|
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
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
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
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
Oops, something went wrong.
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.
I think this line of code seems unnecessary.
MoonshotApi.Usage
can directly implement theUsage
interface, andUsageUtils.getCumulativeUsage
already handles null checks for the input. This approach ensures that callers don’t need to repeatedly check forcurrentUsage
in every call, avoiding redundant code and improving cohesion.If an
EmptyUsage
is truly needed, it could simply be a static constant likeUsage.empty()
orEmptyUsage.instance()
.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.
I understand your perspective but we wanted to address this as part of #1487 - not just for OpenAI usage but across the models. But for now, I think we can go with the consistent approach across the models by passing the EmptyUsage object when the ChatModel API usage is null. I hope that is ok with you.
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.
i understand, i think is ok