Fix: Support Chat Template Tokenization with vLLM Parameters in Prefix Cache Router#2002
Fix: Support Chat Template Tokenization with vLLM Parameters in Prefix Cache Router#2002penfree wants to merge 4 commits intovllm-project:mainfrom
Conversation
…x cache router This commit fixes two issues that caused prefix cache mismatches between Gateway and vLLM Pods: 1. ChatMessage Content serialization: Changed Content field from string to json.RawMessage to preserve structured multimodal content (images, audio) without double JSON encoding. 2. Chat template tokenization: Updated kvSyncPrefixCacheRouter to use TokenizeWithOptions with proper chat template parameters for /v1/chat/completions endpoints, matching vLLM's tokenization behavior. Changes: - Add ChatCompletionRequest struct with vLLM-specific parameters (add_generation_prompt, add_special_tokens, return_token_strs) - Update ChatMessage.Content to json.RawMessage for multimodal support - Add buildTokenizeInputFromChatRequest helper for converting requests - Implement chat template tokenization in Route method with fallback - Export IntToByteArray for external use - Add comprehensive tests for ChatMessage serialization Benefits: - Correct prefix cache matching in kv-sync mode - Support for multimodal chat content (images, audio) - Backward compatible with existing endpoints - Proper handling of vLLM chat template parameters Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> Change-Id: I8144268509d4311bc7483bd7e7a7f5088507e429 Signed-off-by: penfree <pengfei.qiu@gmail.com>
Signed-off-by: penfree <pengfei.qiu@gmail.com> Change-Id: I37280f0bdfba67e5fc03f7dc842059863ae4bc78
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the Gateway's ability to interact with vLLM Pods, particularly for chat completion requests and multimodal content. By resolving issues related to double JSON serialization and the lack of chat template support, it ensures consistent tokenization between the Gateway and vLLM, leading to a higher prefix cache hit rate and improved performance in kv-sync mode. The changes also introduce support for vLLM-specific chat parameters and robust error handling. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request effectively addresses prefix cache mismatches by integrating chat template tokenization and correcting a JSON serialization issue with multimodal content. The changes are well-structured and include appropriate tests. My review includes a few suggestions to enhance code efficiency, readability, and maintainability by refactoring an inefficient JSON handling pattern, simplifying a complex conditional block, and removing a redundant function alias.
This commit includes several refactoring improvements based on code review: 1. Extract chat tokenization logic into separate method - Add tokenizeChatRequest() method to reduce nesting in Route() - Eliminate "pyramid of doom" pattern for better readability - All error handling and logging encapsulated in the helper 2. Simplify message content extraction - Directly marshal msg.GetContent() instead of double marshal/unmarshal - Remove unnecessary intermediate map creation - More efficient and clearer code 3. Remove redundant intToByteArray alias - Update all callers to use exported IntToByteArray directly - Simplify utils.go by removing the internal alias Benefits: - Improved code readability and maintainability - Better performance (fewer marshal/unmarshal operations) - Cleaner separation of concerns Testing: All tokenizer tests pass, including vLLM serialization tests. Signed-off-by: penfree <pengfei.qiu@gmail.com> Change-Id: Id2b356d946db35b25d6c20493510de85e2b893d9
- Add error checking for json.Unmarshal calls to fix errcheck lint errors
- Replace interface{} with any for Go 1.18+ compatibility
Signed-off-by: penfree <pengfei.qiu@gmail.com>
Change-Id: Ic742890ad4675fdd1a920d36aacb748e356d1735
Problem
There were two critical issues causing prefix cache mismatches between Gateway and vLLM Pods in kv-sync mode:
Double JSON Serialization Issue:
ChatMessage.Contentwas defined asstring, causing structured multimodal content (images, audio) to be double-encoded when sent to vLLM tokenization API. This resulted in Gateway tokenizing differently than vLLM Pods.Missing Chat Template Support: The
kvSyncPrefixCacheRouterused simple text tokenization (TokenizeInputText) for all requests, instead of applying chat templates for/v1/chat/completionsendpoints. This caused prefix cache misses because Gateway wasn't tokenizing messages the same way vLLM does with its chat template.Example of the Issue
Before this fix:
{"role": "user", "content": [{"type": "text", "text": "Hello"}, {"type": "image_url", ...}]}"[{\"type\":\"text\",\"text\":\"Hello\"}...]"(double-encoded string)[{"type": "text", "text": "Hello"}...](structured array)After this fix:
Solution
1. Define vLLM-Compatible Request Structure
File:
pkg/types/request.go(NEW)Created
ChatCompletionRequestthat embedsopenai.ChatCompletionNewParamsand adds vLLM-specific parameters:add_generation_prompt- Controls whether to add generation prompt to chat template (default: true)add_special_tokens- Controls whether to add special tokens on top of chat template (default: false)return_token_strs- Returns token strings for debugging (default: false)These parameters match vLLM's chat completion protocol.
2. Fix ChatMessage Content Type
File:
pkg/utils/tokenizer/types.goChanged
ChatMessage.Contentfromstringtojson.RawMessage:This preserves the original JSON structure without double-encoding, supporting:
"Hello world"[{"type": "text", ...}, {"type": "image_url", ...}]3. Implement Chat Template Tokenization in Router
File:
pkg/plugins/gateway/algorithms/prefix_cache.goAdded
buildTokenizeInputFromChatRequest()helper that:Updated
kvSyncPrefixCacheRouter.Route()to:/v1/chat/completionsvs/v1/completions)ChatCompletionRequestTokenizeInputwith chat template parametersTokenizeWithOptionswithChatInputtype4. Export Helper Functions
File:
pkg/utils/tokenizer/utils.goExported
IntToByteArrayfunction for converting token IDs to byte array format needed by prefix cache indexer.Testing
Unit Tests Added
types_test.go: Tests for ChatMessage serialization/deserializationserialization_test.go: Tests for sonic/JSON compatibilitysonic.Marshalcorrectly handlesjson.RawMessageTest Results
Compatibility
Supported Engines
Backward Compatibility
/v1/completionsendpoints work unchangedExtendedTokenizerBenefits
Improved Prefix Cache Hit Rate: Gateway now tokenizes chat messages the same way as vLLM Pods, significantly improving cache hits in kv-sync mode
Multimodal Content Support: Properly handles images, audio, and other structured content in chat messages
vLLM Parameter Compatibility: Gateway can now parse and respect vLLM-specific chat template parameters
Better Debugging: Logs detailed tokenization information at V(4) level
Robust Error Handling: Multiple fallback layers ensure the router continues working even if chat tokenization fails
Files Changed
pkg/types/request.gopkg/utils/tokenizer/types.gopkg/utils/tokenizer/utils.gopkg/plugins/gateway/algorithms/prefix_cache.gopkg/utils/tokenizer/types_test.gopkg/utils/tokenizer/serialization_test.goTotal: 6 files changed, 274 insertions(+), 12 deletions(-)
Verification Steps
To verify this fix works correctly:
Compare token IDs from Gateway tokenization with vLLM tokenization API:
Related Issues
This fix addresses the root cause of prefix cache mismatches in kv-sync mode when:
Breaking Changes
None - This is a backward-compatible enhancement. All existing functionality remains unchanged.