Skip to content

feat(go-models): add Azure OpenAI model driver - #15022

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Lobster-0429:feat/azure-openai-go-driver
May 21, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Lobster-0429:feat/azure-openai-go-driver

Conversation

@Lobster-0429

Copy link
Copy Markdown
Contributor

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 ModelDriver implementation.

What is changed and how it works?

Adds a dedicated Azure OpenAI driver, registers it in the model factory, and ships a provider config.

File Change
internal/entity/models/azure_openai.go New AzureOpenAIModel implementing the ModelDriver interface
internal/entity/models/factory.go Register the azure-openai provider in CreateModelDriver
conf/models/azure-openai.json Provider config (user-supplied endpoint, like vllm)

Azure-specific handling

  • Deployment-scoped endpoints — requests target
    {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 model field is intentionally omitted from request bodies.
  • Authentication — uses the api-key request header instead of Authorization: Bearer.
  • API version — pinned to 2024-10-21 (latest GA, non-preview) via the required api-version query parameter.
  • Listing models — Azure has no shared model catalog, so ListModels enumerates deployments at {baseURL}/deployments?api-version=... and returns their ids.
  • Base URL — user-supplied (each Azure resource has its own endpoint, e.g. https://<resource>.openai.azure.com/openai), so the config ships no default, consistent with the existing vllm provider.

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 stream
  • Embed — embeddings deployment, preserves input order, supports dimensions
  • ListModels / CheckConnection — connectivity + key validation via the
    deployments 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.DefaultTransport with a tuned connection pool, no client-wide timeout (to avoid cutting off SSE streams), ResponseHeaderTimeout to cap connection setup, and context.WithTimeout on every non-streaming call.

Type of change

  • New feature (non-breaking change which adds functionality)

How was this patch tested?

  • Manual code review against the ModelDriver interface — all 17 methods are implemented, imports are all used, and there are no symbol conflicts in the models package.
  • Provider-name mapping verified: JSON name: "Azure-OpenAI" → strings.ToLower → azure-openai, which matches the new factory case.

Note: a local go build / go test was not run in my environment (no Go
toolchain available on the dev machine). Please confirm CI passes
go build ./... and go vet ./....

Checklist

  • Driver implements the full ModelDriver interface
  • Factory registration added
  • Provider config added
  • CI green (go build, go vet)

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 19, 2026
@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b80ba17f-eb51-471d-b479-1cde781aa6ee

📥 Commits

Reviewing files that changed from the base of the PR and between 5f615cf and 0534f87.

📒 Files selected for processing (1)
  • internal/entity/models/factory.go

📝 Walkthrough

Walkthrough

Adds 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 api-key header with fixed api-version.

Changes

Azure OpenAI Driver Implementation

Layer / File(s) Summary
Configuration file and driver scaffold
conf/models/azure-openai.json, internal/entity/models/azure_openai.go
Adds azure-openai.json with url_suffix for chat/embedding/models; driver struct, constructor, per-region baseURL map, and HTTP client transport initialization.
Chat completion methods (sync & streaming)
internal/entity/models/azure_openai.go
ChatWithMessages: POST to deployment-scoped chat endpoint with stream=false, parse choices[0].message and optional reasoning_content. ChatStreamlyWithSender: POST with stream=true, parse SSE data: events, forward delta.reasoning_content/delta.content to sender, detect termination and emit synthetic [DONE].
Embeddings and model discovery
internal/entity/models/azure_openai.go
Embed: POST to embeddings deployment endpoint, parse embeddings, reorder by returned index. ListModels GETs deployments catalog and returns deployment ids; CheckConnection delegates to ListModels.
Factory wiring and unsupported-method stubs
internal/entity/models/factory.go, internal/entity/models/azure_openai.go
Factory CreateModelDriver recognizes "azure-openai" and returns NewAzureOpenAIModel. Other interface methods are stubbed to return "no such method" errors.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • #14814 — Adds a new Go model driver and factory registration; related to provider-driver addition patterns.

Possibly related PRs

Suggested labels

💞 feature

"I hopped with keyboard paws and cheer,
Brought Azure endpoints nice and near,
Streams that trickle, embeddings bright,
Model lists fetched in morning light,
A rabbit claps — the code takes flight!"

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(go-models): add Azure OpenAI model driver' clearly describes the main change: adding a new Azure OpenAI model driver to the Go models layer.
Description check ✅ Passed The description fully covers the template requirements: clearly explains the problem (Azure OpenAI support gap), marks the change type as 'New Feature', and documents implementation details and testing approach.
Linked Issues check ✅ Passed The PR addresses all core objectives from #15021: adds AzureOpenAIModel implementing ModelDriver, registers in factory, provides provider config, implements ChatWithMessages, ChatStreamlyWithSender, Embed, ListModels, CheckConnection, and returns 'no such method' for unsupported features.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue #15021 objective: three files modified (azure_openai.go, factory.go, azure-openai.json) with no unrelated modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/entity/models/azure_openai.go (1)

468-474: ⚡ Quick win

Enforce embedding output order by index instead of response order.

The function comment guarantees input order, but current appending assumes the API returns sorted items. Place results by Index to 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

📥 Commits

Reviewing files that changed from the base of the PR and between eacec86 and 9ea36dd.

📒 Files selected for processing (3)
  • conf/models/azure-openai.json
  • internal/entity/models/azure_openai.go
  • internal/entity/models/factory.go

Comment thread internal/entity/models/azure_openai.go Resolved
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN ,
Could you please review this PR?

@JinHai-CN

Copy link
Copy Markdown
Member

@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.
@Lobster-0429

Lobster-0429 commented May 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN . Done!
Thank you.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Haruko386 Haruko386 added the ci Continue Integration label May 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c21fc23 and 5f615cf.

📒 Files selected for processing (3)
  • conf/models/azure-openai.json
  • internal/entity/models/azure_openai.go
  • internal/entity/models/factory.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/azure-openai.json

Comment on lines +472 to +488
// 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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
// 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.

Comment on lines +569 to +572
// 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")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
// 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

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (fec0b96) to head (0534f87).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN , Passed Successfully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add Go driver for Azure OpenAI model provider

3 participants