|
| 1 | +package azure |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "net/http" |
| 9 | + "net/url" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/sipeed/picoclaw/pkg/providers/common" |
| 14 | + "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" |
| 15 | +) |
| 16 | + |
| 17 | +type ( |
| 18 | + LLMResponse = protocoltypes.LLMResponse |
| 19 | + Message = protocoltypes.Message |
| 20 | + ToolDefinition = protocoltypes.ToolDefinition |
| 21 | +) |
| 22 | + |
| 23 | +const ( |
| 24 | + // azureAPIVersion is the Azure OpenAI API version used for all requests. |
| 25 | + azureAPIVersion = "2024-10-21" |
| 26 | + defaultRequestTimeout = common.DefaultRequestTimeout |
| 27 | +) |
| 28 | + |
| 29 | +// Provider implements the LLM provider interface for Azure OpenAI endpoints. |
| 30 | +// It handles Azure-specific authentication (api-key header), URL construction |
| 31 | +// (deployment-based), and request body formatting (max_completion_tokens, no model field). |
| 32 | +type Provider struct { |
| 33 | + apiKey string |
| 34 | + apiBase string |
| 35 | + httpClient *http.Client |
| 36 | +} |
| 37 | + |
| 38 | +// Option configures the Azure Provider. |
| 39 | +type Option func(*Provider) |
| 40 | + |
| 41 | +// WithRequestTimeout sets the HTTP request timeout. |
| 42 | +func WithRequestTimeout(timeout time.Duration) Option { |
| 43 | + return func(p *Provider) { |
| 44 | + if timeout > 0 { |
| 45 | + p.httpClient.Timeout = timeout |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// NewProvider creates a new Azure OpenAI provider. |
| 51 | +func NewProvider(apiKey, apiBase, proxy string, opts ...Option) *Provider { |
| 52 | + p := &Provider{ |
| 53 | + apiKey: apiKey, |
| 54 | + apiBase: strings.TrimRight(apiBase, "/"), |
| 55 | + httpClient: common.NewHTTPClient(proxy), |
| 56 | + } |
| 57 | + |
| 58 | + for _, opt := range opts { |
| 59 | + if opt != nil { |
| 60 | + opt(p) |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return p |
| 65 | +} |
| 66 | + |
| 67 | +// NewProviderWithTimeout creates a new Azure OpenAI provider with a custom request timeout in seconds. |
| 68 | +func NewProviderWithTimeout(apiKey, apiBase, proxy string, requestTimeoutSeconds int) *Provider { |
| 69 | + return NewProvider( |
| 70 | + apiKey, apiBase, proxy, |
| 71 | + WithRequestTimeout(time.Duration(requestTimeoutSeconds)*time.Second), |
| 72 | + ) |
| 73 | +} |
| 74 | + |
| 75 | +// Chat sends a chat completion request to the Azure OpenAI endpoint. |
| 76 | +// The model parameter is used as the Azure deployment name in the URL. |
| 77 | +func (p *Provider) Chat( |
| 78 | + ctx context.Context, |
| 79 | + messages []Message, |
| 80 | + tools []ToolDefinition, |
| 81 | + model string, |
| 82 | + options map[string]any, |
| 83 | +) (*LLMResponse, error) { |
| 84 | + if p.apiBase == "" { |
| 85 | + return nil, fmt.Errorf("Azure API base not configured") |
| 86 | + } |
| 87 | + |
| 88 | + // model is the deployment name for Azure OpenAI |
| 89 | + deployment := model |
| 90 | + |
| 91 | + // Build Azure-specific URL safely using url.JoinPath and query encoding |
| 92 | + // to prevent path traversal or query injection via deployment names. |
| 93 | + base, err := url.JoinPath(p.apiBase, "openai/deployments", deployment, "chat/completions") |
| 94 | + if err != nil { |
| 95 | + return nil, fmt.Errorf("failed to build Azure request URL: %w", err) |
| 96 | + } |
| 97 | + requestURL := base + "?api-version=" + azureAPIVersion |
| 98 | + |
| 99 | + // Build request body — no "model" field (Azure infers from deployment URL) |
| 100 | + requestBody := map[string]any{ |
| 101 | + "messages": common.SerializeMessages(messages), |
| 102 | + } |
| 103 | + |
| 104 | + if len(tools) > 0 { |
| 105 | + requestBody["tools"] = tools |
| 106 | + requestBody["tool_choice"] = "auto" |
| 107 | + } |
| 108 | + |
| 109 | + // Azure OpenAI always uses max_completion_tokens |
| 110 | + if maxTokens, ok := common.AsInt(options["max_tokens"]); ok { |
| 111 | + requestBody["max_completion_tokens"] = maxTokens |
| 112 | + } |
| 113 | + |
| 114 | + if temperature, ok := common.AsFloat(options["temperature"]); ok { |
| 115 | + requestBody["temperature"] = temperature |
| 116 | + } |
| 117 | + |
| 118 | + jsonData, err := json.Marshal(requestBody) |
| 119 | + if err != nil { |
| 120 | + return nil, fmt.Errorf("failed to marshal request: %w", err) |
| 121 | + } |
| 122 | + |
| 123 | + req, err := http.NewRequestWithContext(ctx, "POST", requestURL, bytes.NewReader(jsonData)) |
| 124 | + if err != nil { |
| 125 | + return nil, fmt.Errorf("failed to create request: %w", err) |
| 126 | + } |
| 127 | + |
| 128 | + // Azure uses api-key header instead of Authorization: Bearer |
| 129 | + req.Header.Set("Content-Type", "application/json") |
| 130 | + if p.apiKey != "" { |
| 131 | + req.Header.Set("api-key", p.apiKey) |
| 132 | + } |
| 133 | + |
| 134 | + resp, err := p.httpClient.Do(req) |
| 135 | + if err != nil { |
| 136 | + return nil, fmt.Errorf("failed to send request: %w", err) |
| 137 | + } |
| 138 | + defer resp.Body.Close() |
| 139 | + |
| 140 | + if resp.StatusCode != http.StatusOK { |
| 141 | + return nil, common.HandleErrorResponse(resp, p.apiBase) |
| 142 | + } |
| 143 | + |
| 144 | + return common.ReadAndParseResponse(resp, p.apiBase) |
| 145 | +} |
| 146 | + |
| 147 | +// GetDefaultModel returns an empty string as Azure deployments are user-configured. |
| 148 | +func (p *Provider) GetDefaultModel() string { |
| 149 | + return "" |
| 150 | +} |
0 commit comments