Repository navigation
feat(go-models): add Azure OpenAI model driver - #15022
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds an Azure OpenAI model provider: new config, driver implementation (chat sync/stream, embeddings, model listing/check), factory wiring, and stubs for unsupported interface methods. Uses deployment-scoped endpoints and ChangesAzure OpenAI Driver Implementation
Sequence Diagram(s)sequenceDiagram
participant Client
participant AzureOpenAIModel
participant AzureAPI as Azure OpenAI API
Client->>AzureOpenAIModel: ChatWithMessages / ChatStreamlyWithSender / Embed / ListModels
AzureOpenAIModel->>AzureAPI: POST/GET /deployments/{deployment}/{op}?api-version=...
AzureAPI-->>AzureOpenAIModel: choices / SSE data events (delta.content, delta.reasoning_content) / embeddings / deployments list
AzureOpenAIModel-->>Client: ChatResponse or streamed deltas and synthetic [DONE] / Embedding vectors / Deployment ids
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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: 1
🧹 Nitpick comments (1)
internal/entity/models/azure_openai.go (1)
468-474: ⚡ Quick winEnforce embedding output order by
indexinstead of response order.The function comment guarantees input order, but current appending assumes the API returns sorted items. Place results by
Indexto make ordering deterministic.💡 Suggested refactor
- embeddings := make([]EmbeddingData, 0, len(parsed.Data)) - for _, d := range parsed.Data { - embeddings = append(embeddings, EmbeddingData{ - Embedding: d.Embedding, - Index: d.Index, - }) - } + embeddings := make([]EmbeddingData, len(texts)) + for _, d := range parsed.Data { + if d.Index < 0 || d.Index >= len(texts) { + return nil, fmt.Errorf("invalid embedding index %d", d.Index) + } + embeddings[d.Index] = EmbeddingData{ + Embedding: d.Embedding, + Index: d.Index, + } + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/azure_openai.go` around lines 468 - 474, The code currently appends parsed.Data items into embeddings in response order; instead, create embeddings with length len(parsed.Data) and place each EmbeddingData at position d.Index (using parsed.Data and d.Index) to enforce deterministic ordering per the function contract; also validate that d.Index is within [0, len(parsed.Data)-1] before assigning to avoid panics and handle duplicates or missing indices appropriately (e.g., log or return an error).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/azure_openai.go`:
- Around line 234-245: The function ChatStreamlyWithSender must validate the
sender callback before use: add a nil-check at the start of
ChatStreamlyWithSender (alongside the existing checks for messages, apiConfig,
and modelName) and return a clear error (e.g., "sender callback is required") if
sender is nil so that the streaming loop and final send calls never attempt to
invoke a nil function pointer.
---
Nitpick comments:
In `@internal/entity/models/azure_openai.go`:
- Around line 468-474: The code currently appends parsed.Data items into
embeddings in response order; instead, create embeddings with length
len(parsed.Data) and place each EmbeddingData at position d.Index (using
parsed.Data and d.Index) to enforce deterministic ordering per the function
contract; also validate that d.Index is within [0, len(parsed.Data)-1] before
assigning to avoid panics and handle duplicates or missing indices appropriately
(e.g., log or return an error).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b22e8c80-2e2f-4295-b230-436a168345c1
📒 Files selected for processing (3)
conf/models/azure-openai.jsoninternal/entity/models/azure_openai.gointernal/entity/models/factory.go
|
Hi, @JinHai-CN , |
|
@web-dev0521 Since previous PR includes a binary file which is very big. So, I reset the head of main branch. Would you please re-submit the commit from current HEAD of main branch? Thank you very much. |
Azure OpenAI is not a base-URL swap of the OpenAI driver: endpoints are deployment-scoped with an api-version query param, auth uses the api-key header instead of a Bearer token, and listing models means listing deployments. Add a dedicated driver, factory registration, and provider config implementing chat, streaming chat, and embeddings.
- Reject a nil sender callback in ChatStreamlyWithSender instead of panicking when it is invoked. - Place embedding vectors by their response Index (sized to the input count, with bounds validation) so Embed honors its documented input-order guarantee even if Azure returns items out of order.
|
Hi, @JinHai-CN . Done! |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/azure_openai.go`:
- Around line 569-572: The Balance stub on AzureOpenAIModel returns an error
message that omits the model identifier; change the error from fmt.Errorf("no
such method") to include the model name consistent with other stubs (e.g.,
fmt.Errorf("azure-openai, no such method")) so that
AzureOpenAIModel.Balance(apiConfig *APIConfig) reports the model name in its
error like the other stub methods.
- Around line 472-488: The code fills an embeddings slice by Index from
parsed.Data but doesn't validate that every slot was populated; after the loop
over parsed.Data, iterate the embeddings slice (or check entries) and if any
EmbeddingData.Embedding is nil (or its length is zero), return an error
indicating which input indices are missing/filtered instead of returning a
partially populated slice; reference the embeddings slice, the EmbeddingData
type and parsed.Data when adding this validation and construct a clear error
message listing missing indices.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 42ae2edb-83bc-42a9-a226-154302dbbe63
📒 Files selected for processing (3)
conf/models/azure-openai.jsoninternal/entity/models/azure_openai.gointernal/entity/models/factory.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/azure-openai.json
| // Azure returns one item per input, but does not guarantee response | ||
| // order. Each item's Index refers to its position in the input list, so | ||
| // place vectors by Index to honor the documented input-order guarantee. | ||
| // Reject an out-of-range index instead of panicking. | ||
| embeddings := make([]EmbeddingData, len(texts)) | ||
| for _, d := range parsed.Data { | ||
| if d.Index < 0 || d.Index >= len(embeddings) { | ||
| return nil, fmt.Errorf("embedding index %d out of range [0,%d)", d.Index, len(embeddings)) | ||
| } | ||
| embeddings[d.Index] = EmbeddingData{ | ||
| Embedding: d.Embedding, | ||
| Index: d.Index, | ||
| } | ||
| } | ||
|
|
||
| return embeddings, nil | ||
| } |
There was a problem hiding this comment.
Missing validation that all embedding slots are populated.
If Azure returns fewer embeddings than inputs (e.g., due to content filtering or API errors), unfilled slots remain zero-initialized with nil embeddings. The caller receives a slice that appears complete but contains invalid entries where Embedding == nil.
🛡️ Proposed fix to validate all slots are filled
embeddings := make([]EmbeddingData, len(texts))
+ filled := make([]bool, len(texts))
for _, d := range parsed.Data {
if d.Index < 0 || d.Index >= len(embeddings) {
return nil, fmt.Errorf("embedding index %d out of range [0,%d)", d.Index, len(embeddings))
}
embeddings[d.Index] = EmbeddingData{
Embedding: d.Embedding,
Index: d.Index,
}
+ filled[d.Index] = true
+ }
+
+ for i, ok := range filled {
+ if !ok {
+ return nil, fmt.Errorf("missing embedding for input at index %d", i)
+ }
}
return embeddings, nil📝 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.
| // Azure returns one item per input, but does not guarantee response | |
| // order. Each item's Index refers to its position in the input list, so | |
| // place vectors by Index to honor the documented input-order guarantee. | |
| // Reject an out-of-range index instead of panicking. | |
| embeddings := make([]EmbeddingData, len(texts)) | |
| for _, d := range parsed.Data { | |
| if d.Index < 0 || d.Index >= len(embeddings) { | |
| return nil, fmt.Errorf("embedding index %d out of range [0,%d)", d.Index, len(embeddings)) | |
| } | |
| embeddings[d.Index] = EmbeddingData{ | |
| Embedding: d.Embedding, | |
| Index: d.Index, | |
| } | |
| } | |
| return embeddings, nil | |
| } | |
| // Azure returns one item per input, but does not guarantee response | |
| // order. Each item's Index refers to its position in the input list, so | |
| // place vectors by Index to honor the documented input-order guarantee. | |
| // Reject an out-of-range index instead of panicking. | |
| embeddings := make([]EmbeddingData, len(texts)) | |
| filled := make([]bool, len(texts)) | |
| for _, d := range parsed.Data { | |
| if d.Index < 0 || d.Index >= len(embeddings) { | |
| return nil, fmt.Errorf("embedding index %d out of range [0,%d)", d.Index, len(embeddings)) | |
| } | |
| embeddings[d.Index] = EmbeddingData{ | |
| Embedding: d.Embedding, | |
| Index: d.Index, | |
| } | |
| filled[d.Index] = true | |
| } | |
| for i, ok := range filled { | |
| if !ok { | |
| return nil, fmt.Errorf("missing embedding for input at index %d", i) | |
| } | |
| } | |
| return embeddings, nil | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/azure_openai.go` around lines 472 - 488, The code
fills an embeddings slice by Index from parsed.Data but doesn't validate that
every slot was populated; after the loop over parsed.Data, iterate the
embeddings slice (or check entries) and if any EmbeddingData.Embedding is nil
(or its length is zero), return an error indicating which input indices are
missing/filtered instead of returning a partially populated slice; reference the
embeddings slice, the EmbeddingData type and parsed.Data when adding this
validation and construct a clear error message listing missing indices.
| // Balance is not exposed by the Azure OpenAI API. | ||
| func (z *AzureOpenAIModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { | ||
| return nil, fmt.Errorf("no such method") | ||
| } |
There was a problem hiding this comment.
Balance error message inconsistent with other stub methods.
Other stub methods include the model name in the error (e.g., "azure-openai, no such method"), but Balance does not. This makes error messages less informative for debugging.
✏️ Proposed fix
// Balance is not exposed by the Azure OpenAI API.
func (z *AzureOpenAIModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
- return nil, fmt.Errorf("no such method")
+ return nil, fmt.Errorf("%s, no such method", z.Name())
}📝 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.
| // Balance is not exposed by the Azure OpenAI API. | |
| func (z *AzureOpenAIModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { | |
| return nil, fmt.Errorf("no such method") | |
| } | |
| // Balance is not exposed by the Azure OpenAI API. | |
| func (z *AzureOpenAIModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { | |
| return nil, fmt.Errorf("%s, no such method", z.Name()) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/azure_openai.go` around lines 569 - 572, The Balance
stub on AzureOpenAIModel returns an error message that omits the model
identifier; change the error from fmt.Errorf("no such method") to include the
model name consistent with other stubs (e.g., fmt.Errorf("azure-openai, no such
method")) so that AzureOpenAIModel.Balance(apiConfig *APIConfig) reports the
model name in its error like the other stub methods.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15022 +/- ##
=======================================
Coverage 93.12% 93.12%
=======================================
Files 10 10
Lines 713 713
Branches 116 116
=======================================
Hits 664 664
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Hi, @JinHai-CN , Passed Successfully. |
What problem does this PR solve?
Closes #15021.
The Go model-provider layer had no support for Azure OpenAI. Azure OpenAI is not a drop-in base-URL swap of the OpenAI driver — it differs in authentication, endpoint structure, and how models are listed — so it needs its own
ModelDriverimplementation.What is changed and how it works?
Adds a dedicated Azure OpenAI driver, registers it in the model factory, and ships a provider config.
internal/entity/models/azure_openai.goAzureOpenAIModelimplementing theModelDriverinterfaceinternal/entity/models/factory.goazure-openaiprovider inCreateModelDriverconf/models/azure-openai.jsonvllm)Azure-specific handling
{baseURL}/deployments/{deployment}/{op}?api-version=2024-10-21.The model name passed in is the Azure deployment name and goes in the URL path, so the
modelfield is intentionally omitted from request bodies.api-keyrequest header instead ofAuthorization: Bearer.2024-10-21(latest GA, non-preview) via the requiredapi-versionquery parameter.ListModelsenumerates deployments at{baseURL}/deployments?api-version=...and returns theirids.https://<resource>.openai.azure.com/openai), so the config ships no default, consistent with the existingvllmprovider.Implemented methods
ChatWithMessages— non-streaming chat (single JSON response)ChatStreamlyWithSender— streaming chat over SSE, with a 1 MB scanner buffer and a guard that won't emit a synthetic[DONE]on a truncated streamEmbed— embeddings deployment, preserves input order, supportsdimensionsListModels/CheckConnection— connectivity + key validation via thedeployments endpoint
All other interface methods (
Rerank,Balance, audio, OCR, file parse, tasks) return"no such method", matching the OpenAI driver.The HTTP transport mirrors the OpenAI driver: cloned
http.DefaultTransportwith a tuned connection pool, no client-wide timeout (to avoid cutting off SSE streams),ResponseHeaderTimeoutto cap connection setup, andcontext.WithTimeouton every non-streaming call.Type of change
How was this patch tested?
ModelDriverinterface — all 17 methods are implemented, imports are all used, and there are no symbol conflicts in themodelspackage.name: "Azure-OpenAI"→strings.ToLower→azure-openai, which matches the new factory case.Checklist
ModelDriverinterfacego build,go vet)