azure.go 1.2 KB

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