Repository navigation
feat: support amazon nova model - #1780
Conversation
WalkthroughAdds Nova model support alongside existing Claude flow: new model mappings and cross‑region rules, OpenAI→Nova request conversion/types, adaptor updates to branch on Nova with context flags, and relay handler changes introducing a Nova path that invokes Bedrock, parses Nova responses, and returns OpenAI‑style output. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor C as Client
participant H as awsHandler
participant A as Adaptor
participant B as Bedrock
participant T as Translator
C->>H: OpenAI-style request (model X)
H->>A: ConvertOpenAIRequest(req)
alt Model is nova-*
A-->>H: ctx{is_nova_model=true, converted_request=NovaRequest}
H->>H: Determine cross-region for nova-*
H->>B: InvokeModel(Nova JSON)
B-->>H: Nova response JSON
H->>T: Parse Nova -> OpenAITextResponse
T-->>H: OpenAI-compatible response
H-->>C: JSON response + usage
else Non-nova (e.g., Claude)
A-->>H: ctx{is_nova_model=false, converted_request=ClaudeRequest}
H->>B: InvokeModel(Claude payload)
B-->>H: Claude response
H-->>C: JSON response + usage
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks (2 passed, 1 warning)❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
relay/channel/aws/relay-aws.go (1)
158-224: Missing Nova model support in stream handlerThe
awsStreamHandlerfunction doesn't check for Nova models and will incorrectly process Nova requests as Claude requests, causing streaming to fail for Nova models.The stream handler needs to detect and handle Nova models similar to the non-streaming handler. Add Nova model detection and routing:
func awsStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, requestMode int) (*types.NewAPIError, *dto.Usage) { awsCli, err := newAwsClient(c, info) if err != nil { return types.NewError(err, types.ErrorCodeChannelAwsClientError), nil } awsModelId := awsModelID(c.GetString("request_model")) + + // Check if this is a Nova model + isNova, _ := c.Get("is_nova_model") + if isNova == true { + // Nova models don't support streaming yet + return types.NewError(errors.New("Nova models do not support streaming"), types.ErrorCodeInvalidRequest), nil + } awsRegionPrefix := awsRegionPrefix(awsCli.Options().Region)Would you like me to implement full streaming support for Nova models or add proper error handling to indicate that streaming is not supported?
🧹 Nitpick comments (15)
relay/channel/aws/constants.go (1)
98-101: Consider making the Nova detection function more robustThe comment is in Chinese while the rest of the codebase uses English. Also, the function should be case-insensitive to handle various input formats.
-// 判断是否为Nova模型 +// isNovaModel checks if the model ID is a Nova model func isNovaModel(modelId string) bool { - return strings.HasPrefix(modelId, "nova-") + return strings.HasPrefix(strings.ToLower(modelId), "nova-") }relay/channel/aws/dto.go (5)
38-46: Chinese comments should be replaced with English for consistencyThe codebase appears to use English comments predominantly. Having Chinese comments reduces maintainability for international teams.
-// NovaMessage Nova模型使用messages-v1格式 +// NovaMessage represents a message in Nova's messages-v1 format type NovaMessage struct { Role string `json:"role"` Content []NovaContent `json:"content"` }
48-52: Replace Chinese comments with Englishtype NovaRequest struct { - SchemaVersion string `json:"schemaVersion"` // 请求版本,例如 "1.0" - Messages []NovaMessage `json:"messages"` // 对话消息列表 - InferenceConfig *NovaInferenceConfig `json:"inferenceConfig,omitempty"` // 推理配置,可选 + SchemaVersion string `json:"schemaVersion"` // Request version, e.g., "messages-v1" + Messages []NovaMessage `json:"messages"` // List of conversation messages + InferenceConfig *NovaInferenceConfig `json:"inferenceConfig,omitempty"` // Inference configuration (optional) }
54-60: Replace Chinese comments with English and fix incorrect defaultsThe comment states incorrect default values that don't match AWS Nova documentation.
type NovaInferenceConfig struct { - MaxTokens int `json:"maxTokens,omitempty"` // 最大生成的 token 数 - Temperature float64 `json:"temperature,omitempty"` // 随机性 (默认 0.7, 范围 0-1) - TopP float64 `json:"topP,omitempty"` // nucleus sampling (默认 0.9, 范围 0-1) - TopK int `json:"topK,omitempty"` // 限制候选 token 数 (默认 50, 范围 0-128) - StopSequences []string `json:"stopSequences,omitempty"` // 停止生成的序列 + MaxTokens int `json:"maxTokens,omitempty"` // Maximum number of tokens to generate + Temperature float64 `json:"temperature,omitempty"` // Randomness control (range 0-1) + TopP float64 `json:"topP,omitempty"` // Nucleus sampling parameter (range 0-1) + TopK int `json:"topK,omitempty"` // Limit candidate tokens + StopSequences []string `json:"stopSequences,omitempty"` // Sequences that stop generation }
62-63: Replace Chinese comment with English-// 转换OpenAI请求为Nova格式 +// convertToNovaRequest converts an OpenAI request to Nova format func convertToNovaRequest(req *dto.GeneralOpenAIRequest) *NovaRequest {
102-103: Replace Chinese comment with English-// parseStopSequences 解析停止序列,支持字符串或字符串数组 +// parseStopSequences parses stop sequences from string, string array, or interface array func parseStopSequences(stop any) []string {relay/channel/aws/adaptor.go (2)
63-64: Replace Chinese comment with English- // 检查是否为Nova模型 + // Check if this is a Nova model if isNovaModel(request.Model) {
72-72: Replace Chinese comment with English- // 原有的Claude模型处理逻辑 + // Handle Claude models (existing logic)relay/channel/aws/relay-aws.go (7)
97-98: Replace Chinese comment with English- // 检查是否为Nova模型 + // Check if this is a Nova model
100-100: Comment translation needed- // Nova模型也支持跨区域 + // Nova models also support cross-region
109-109: Replace Chinese comment with English- // 原有的Claude处理逻辑 + // Handle Claude models (existing logic)
226-227: Replace Chinese comment with English-// Nova模型处理函数 +// handleNovaRequest processes Nova model requests func handleNovaRequest(c *gin.Context, awsCli *bedrockruntime.Client, info *relaycommon.RelayInfo, awsModelId string) (*types.NewAPIError, *dto.Usage) {
234-234: Replace Chinese comment with English- // 使用InvokeModel API,但使用Nova格式的请求体 + // Use InvokeModel API with Nova-formatted request body
252-252: Replace Chinese comment with English- // 解析Nova响应 + // Parse Nova response
272-272: Replace Chinese comment with English- // 构造OpenAI格式响应 + // Build OpenAI-compatible response
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
relay/channel/aws/adaptor.go(2 hunks)relay/channel/aws/constants.go(4 hunks)relay/channel/aws/dto.go(1 hunks)relay/channel/aws/relay-aws.go(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
relay/channel/aws/dto.go (1)
dto/openai_request.go (1)
GeneralOpenAIRequest(25-78)
relay/channel/aws/relay-aws.go (5)
types/error.go (5)
NewAPIError(82-90)NewError(187-199)ErrorCodeInvalidRequest(38-38)ErrorCodeBadResponseBody(68-68)ErrorCodeChannelAwsClientError(55-55)dto/openai_response.go (3)
Usage(217-230)OpenAITextResponse(34-42)OpenAITextResponseChoice(28-32)relay/channel/aws/dto.go (1)
NovaRequest(48-52)relay/helper/common.go (1)
GetResponseID(130-133)common/utils.go (1)
GetTimestamp(200-202)
| "us": true, | ||
| "eu": true, | ||
| "apac": true, | ||
| }, |
There was a problem hiding this comment.
Inconsistent region key naming between Claude and Nova models
The Nova models use "apac" as a region key while Claude models use "ap". This inconsistency could lead to cross-region failures for Nova models.
The region prefix mapping at line 93 maps "ap" to "apac", but the Claude models use "ap" as keys. To maintain consistency and ensure proper cross-region functionality:
// Nova models - all support three major regions
"amazon.nova-micro-v1:0": {
"us": true,
"eu": true,
- "apac": true,
+ "ap": true,
},
"amazon.nova-lite-v1:0": {
"us": true,
"eu": true,
- "apac": true,
+ "ap": true,
},
"amazon.nova-pro-v1:0": {
"us": true,
"eu": true,
- "apac": true,
+ "ap": true,
},
"amazon.nova-premier-v1:0": {
"us": true,
"eu": true,
- "apac": true,
+ "ap": true,
},Also applies to: 75-78, 80-83, 85-88
🤖 Prompt for AI Agents
In relay/channel/aws/constants.go around lines 70-73 (and similarly at 75-78,
80-83, 85-88), region keys are inconsistent between Nova ("apac") and Claude
("ap") models; update the keys so they match the rest of the code by replacing
any "apac" keys with "ap" (or vice versa to the canonical choice used across the
file) and ensure the region prefix mapping at line 93 remains consistent (map
"ap" <-> "apac" only if you keep "ap" as the canonical key); run a quick grep in
this file for "apac" and "ap" to verify no other mismatches remain and update
tests or constants consumers if necessary.
| if req.MaxTokens != 0 || (req.Temperature != nil && *req.Temperature != 0) || req.TopP != 0 || req.TopK != 0 || req.Stop != nil { | ||
| novaReq.InferenceConfig = &NovaInferenceConfig{} | ||
| if req.MaxTokens != 0 { | ||
| novaReq.InferenceConfig.MaxTokens = int(req.MaxTokens) | ||
| } | ||
| if req.Temperature != nil && *req.Temperature != 0 { | ||
| novaReq.InferenceConfig.Temperature = *req.Temperature | ||
| } | ||
| if req.TopP != 0 { | ||
| novaReq.InferenceConfig.TopP = req.TopP | ||
| } | ||
| if req.TopK != 0 { | ||
| novaReq.InferenceConfig.TopK = req.TopK | ||
| } | ||
| if req.Stop != nil { | ||
| if stopSequences := parseStopSequences(req.Stop); len(stopSequences) > 0 { | ||
| novaReq.InferenceConfig.StopSequences = stopSequences | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Inefficient condition checking for InferenceConfig creation
The condition check on line 78 is overly complex. The Temperature check *req.Temperature != 0 will panic if Temperature is nil. Additionally, checking for non-zero values may skip valid zero configurations.
// 设置推理配置
- if req.MaxTokens != 0 || (req.Temperature != nil && *req.Temperature != 0) || req.TopP != 0 || req.TopK != 0 || req.Stop != nil {
+ // Always create InferenceConfig if any parameter is explicitly set
+ if req.MaxTokens != 0 || req.Temperature != nil || req.TopP != 0 || req.TopK != 0 || req.Stop != nil {
novaReq.InferenceConfig = &NovaInferenceConfig{}
if req.MaxTokens != 0 {
novaReq.InferenceConfig.MaxTokens = int(req.MaxTokens)
}
- if req.Temperature != nil && *req.Temperature != 0 {
+ if req.Temperature != nil {
novaReq.InferenceConfig.Temperature = *req.Temperature
}
if req.TopP != 0 {
novaReq.InferenceConfig.TopP = req.TopP
}
if req.TopK != 0 {
novaReq.InferenceConfig.TopK = req.TopK
}
if req.Stop != nil {
if stopSequences := parseStopSequences(req.Stop); len(stopSequences) > 0 {
novaReq.InferenceConfig.StopSequences = stopSequences
}
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if req.MaxTokens != 0 || (req.Temperature != nil && *req.Temperature != 0) || req.TopP != 0 || req.TopK != 0 || req.Stop != nil { | |
| novaReq.InferenceConfig = &NovaInferenceConfig{} | |
| if req.MaxTokens != 0 { | |
| novaReq.InferenceConfig.MaxTokens = int(req.MaxTokens) | |
| } | |
| if req.Temperature != nil && *req.Temperature != 0 { | |
| novaReq.InferenceConfig.Temperature = *req.Temperature | |
| } | |
| if req.TopP != 0 { | |
| novaReq.InferenceConfig.TopP = req.TopP | |
| } | |
| if req.TopK != 0 { | |
| novaReq.InferenceConfig.TopK = req.TopK | |
| } | |
| if req.Stop != nil { | |
| if stopSequences := parseStopSequences(req.Stop); len(stopSequences) > 0 { | |
| novaReq.InferenceConfig.StopSequences = stopSequences | |
| } | |
| } | |
| } | |
| if req.MaxTokens != 0 || req.Temperature != nil || req.TopP != 0 || req.TopK != 0 || req.Stop != nil { | |
| novaReq.InferenceConfig = &NovaInferenceConfig{} | |
| if req.MaxTokens != 0 { | |
| novaReq.InferenceConfig.MaxTokens = int(req.MaxTokens) | |
| } | |
| if req.Temperature != nil { | |
| novaReq.InferenceConfig.Temperature = *req.Temperature | |
| } | |
| if req.TopP != 0 { | |
| novaReq.InferenceConfig.TopP = req.TopP | |
| } | |
| if req.TopK != 0 { | |
| novaReq.InferenceConfig.TopK = req.TopK | |
| } | |
| if req.Stop != nil { | |
| if stopSequences := parseStopSequences(req.Stop); len(stopSequences) > 0 { | |
| novaReq.InferenceConfig.StopSequences = stopSequences | |
| } | |
| } | |
| } |
🤖 Prompt for AI Agents
In relay/channel/aws/dto.go around lines 78 to 97, the current if-condition
dereferences Temperature and also skips valid zero values; change the condition
to check presence without dereferencing: if req.MaxTokens != 0 ||
req.Temperature != nil || req.TopP != 0 || req.TopK != 0 || req.Stop != nil {
... }. Inside the block, avoid skipping zero as a valid explicit setting: assign
MaxTokens, TopP and TopK directly (do not gate on != 0), set Temperature only if
req.Temperature != nil (and then assign its value, allowing zero), and handle
Stop exactly as before by parsing when non-nil. This removes the nil dereference
and preserves explicit zero configurations.
| if err := json.Unmarshal(awsResp.Body, &novaResp); err != nil { | ||
| return types.NewError(errors.Wrap(err, "unmarshal nova response"), types.ErrorCodeBadResponseBody), nil | ||
| } |
There was a problem hiding this comment.
Add nil check before accessing response content
The code assumes the Nova response will always have at least one content item, which could cause a panic if the response structure is unexpected.
if err := json.Unmarshal(awsResp.Body, &novaResp); err != nil {
return types.NewError(errors.Wrap(err, "unmarshal nova response"), types.ErrorCodeBadResponseBody), nil
}
+
+ // Validate response structure
+ if len(novaResp.Output.Message.Content) == 0 {
+ return types.NewError(errors.New("empty content in Nova response"), types.ErrorCodeBadResponseBody), nil
+ }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In relay/channel/aws/relay-aws.go around lines 268 to 270, the JSON-unmarshaled
novaResp is assumed to contain at least one content item which can panic if
missing; after unmarshalling, add a nil/length check (e.g., if novaResp.Content
== nil || len(novaResp.Content) == 0) and return a suitable types.NewError
(types.ErrorCodeBadResponseBody) with a descriptive message when no content is
present, before any access to novaResp.Content[0]; keep existing error wrapping
for the unmarshal failure as-is.
| Choices: []dto.OpenAITextResponseChoice{{ | ||
| Index: 0, | ||
| Message: dto.Message{ | ||
| Role: "assistant", | ||
| Content: novaResp.Output.Message.Content[0].Text, | ||
| }, | ||
| FinishReason: "stop", | ||
| }}, |
There was a problem hiding this comment.
Potential panic when accessing array element
Direct access to novaResp.Output.Message.Content[0].Text without bounds checking could cause a panic.
Given the validation added earlier, update the content access:
Choices: []dto.OpenAITextResponseChoice{{
Index: 0,
Message: dto.Message{
Role: "assistant",
- Content: novaResp.Output.Message.Content[0].Text,
+ Content: novaResp.Output.Message.Content[0].Text, // Safe after validation
},
FinishReason: "stop",
}},Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In relay/channel/aws/relay-aws.go around lines 278 to 285, the code directly
indexes novaResp.Output.Message.Content[0].Text which can panic if Content is
empty; update the access to first validate Content has at least one element
before reading index 0 and use a safe fallback (e.g., empty string or
previously-validated field) when it is empty so the Choices[0].Message.Content
assignment never dereferences an out-of-range slice.
…mazon-nova feat: support amazon nova model
…mazon-nova feat: support amazon nova model
…mazon-nova feat: support amazon nova model
例行检查
功能描述
支持amazon nova模型,https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
功能配置


测试用例
Nova模型只支持OpenAI兼容格式,渠道配置好nova模型,并且配置了模型倍率后,进行如下请求测试,模型id当前支持如上4种
返回值
{ "id": "chatcmpl-202509111235371335240004l7VwE6r", "model": "nova-micro-v1:0", "object": "chat.completion", "created": 1757565338, "choices": [ { "index": 0, "message": { "role": "assistant", "content": "I am an artificial intelligence system created by Amazon. My purpose is to assist users by providing information, answering questions, and helping with a wide range of tasks to the best of my ability based on the information I have been trained on. I don't have personal experiences or feelings, but I'm here to help you with any questions or information you need! How can I assist you today?" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 3, "completion_tokens": 80, "total_tokens": 83, "prompt_tokens_details": { "cached_tokens": 0, "text_tokens": 0, "audio_tokens": 0, "image_tokens": 0 }, "completion_tokens_details": { "text_tokens": 0, "audio_tokens": 0, "reasoning_tokens": 0 }, "input_tokens": 0, "output_tokens": 0, "input_tokens_details": null } }这个请求包含了Nova模型支持的所有推理配置参数:
Summary by CodeRabbit