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
20	endpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")      // ex: https://foo.openai.azure.com
21	apiVersion := os.Getenv("AZURE_OPENAI_API_VERSION") // ex: 2025-04-01-preview
22
23	if endpoint == "" || apiVersion == "" {
24		return &azureClient{openaiClient: newOpenAIClient(opts).(*openaiClient)}
25	}
26
27	reqOpts := []option.RequestOption{
28		azure.WithEndpoint(endpoint, apiVersion),
29	}
30
31	if opts.apiKey != "" || os.Getenv("AZURE_OPENAI_API_KEY") != "" {
32		key := opts.apiKey
33		if key == "" {
34			key = os.Getenv("AZURE_OPENAI_API_KEY")
35		}
36		reqOpts = append(reqOpts, azure.WithAPIKey(key))
37	} else if cred, err := azidentity.NewDefaultAzureCredential(nil); err == nil {
38		reqOpts = append(reqOpts, azure.WithTokenCredential(cred))
39	}
40
41	base := &openaiClient{
42		providerOptions: opts,
43		client:          openai.NewClient(reqOpts...),
44	}
45
46	return &azureClient{openaiClient: base}
47}