azure.go

 1package provider
 2
 3import (
 4	"os"
 5
 6	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
 7	"github.com/openai/openai-go"
 8	"github.com/openai/openai-go/azure"
 9	"github.com/openai/openai-go/option"
10)
11
12type azureClient struct {
13	*openaiClient
14}
15
16type AzureClient ProviderClient
17
18func newAzureClient(opts providerClientOptions) AzureClient {
19	endpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")      // ex: https://foo.openai.azure.com
20	apiVersion := os.Getenv("AZURE_OPENAI_API_VERSION") // ex: 2025-04-01-preview
21
22	if endpoint == "" || apiVersion == "" {
23		return &azureClient{openaiClient: newOpenAIClient(opts).(*openaiClient)}
24	}
25
26	reqOpts := []option.RequestOption{
27		azure.WithEndpoint(endpoint, apiVersion),
28	}
29
30	if opts.apiKey != "" || os.Getenv("AZURE_OPENAI_API_KEY") != "" {
31		key := opts.apiKey
32		if key == "" {
33			key = os.Getenv("AZURE_OPENAI_API_KEY")
34		}
35		reqOpts = append(reqOpts, azure.WithAPIKey(key))
36	} else if cred, err := azidentity.NewDefaultAzureCredential(nil); err == nil {
37		reqOpts = append(reqOpts, azure.WithTokenCredential(cred))
38	}
39
40	base := &openaiClient{
41		providerOptions: opts,
42		client:          openai.NewClient(reqOpts...),
43	}
44
45	return &azureClient{openaiClient: base}
46}