-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathazure.go
More file actions
162 lines (139 loc) · 3.95 KB
/
azure.go
File metadata and controls
162 lines (139 loc) · 3.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package iteragent
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
type AzureOpenAIConfig struct {
APIKey string
Endpoint string
Deployment string
APIVersion string
MaxTokens int
Temperature float32
ThinkingLevel ThinkingLevel
}
type AzureOpenAIProvider struct {
config AzureOpenAIConfig
client *http.Client
}
func NewAzureOpenAI(config AzureOpenAIConfig) *AzureOpenAIProvider {
return &AzureOpenAIProvider{
config: config,
client: &http.Client{Timeout: 120 * time.Second},
}
}
func (p *AzureOpenAIProvider) Name() string {
return "azure_openai"
}
// TODO: Add ThinkingLevel support for Azure OpenAI when provider supports it.
func (p *AzureOpenAIProvider) Complete(ctx context.Context, messages []Message, opts ...CompletionOptions) (string, error) {
apiVersion := p.config.APIVersion
if apiVersion == "" {
apiVersion = "2024-02-15-preview"
}
url := fmt.Sprintf("%s/openai/deployments/%s/chat/completions?api-version=%s",
p.config.Endpoint, p.config.Deployment, apiVersion)
body := map[string]interface{}{
"messages": messagesToAzureFormat(messages),
"stream": false,
}
if p.config.MaxTokens > 0 {
body["max_tokens"] = p.config.MaxTokens
}
if p.config.Temperature > 0 {
body["temperature"] = p.config.Temperature
}
jsonBody, err := json.Marshal(body)
if err != nil {
return "", fmt.Errorf("marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonBody))
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("api-key", p.config.APIKey)
resp, err := p.client.Do(req)
if err != nil {
return "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(io.LimitReader(resp.Body, 10*1024*1024))
if err != nil {
return "", fmt.Errorf("read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("Azure OpenAI error (%d): %s", resp.StatusCode, string(respBody))
}
var response struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return "", fmt.Errorf("parse response: %w", err)
}
if len(response.Choices) == 0 {
return "", fmt.Errorf("no response choices")
}
return response.Choices[0].Message.Content, nil
}
// CompleteStream implements Provider for Azure OpenAI using the SSE streaming endpoint.
func (p *AzureOpenAIProvider) CompleteStream(ctx context.Context, messages []Message, opt CompletionOptions, onToken func(string)) (string, error) {
apiVersion := p.config.APIVersion
if apiVersion == "" {
apiVersion = "2024-02-15-preview"
}
url := fmt.Sprintf("%s/openai/deployments/%s/chat/completions?api-version=%s",
p.config.Endpoint, p.config.Deployment, apiVersion)
body := map[string]interface{}{
"messages": messagesToAzureFormat(messages),
"stream": true,
}
if opt.MaxTokens > 0 {
body["max_tokens"] = opt.MaxTokens
}
if opt.Temperature > 0 {
body["temperature"] = opt.Temperature
}
jsonBody, err := json.Marshal(body)
if err != nil {
return "", fmt.Errorf("marshal request: %w", err)
}
var full strings.Builder
sseClient := NewSSEClient()
err = sseClient.Stream(ctx, url, map[string]string{"api-key": p.config.APIKey}, jsonBody, func(e SSEEvent) {
if e.Data == "[DONE]" {
return
}
if token, ok := ParseOpenAISSE(e.Data); ok && token != "" {
full.WriteString(token)
if onToken != nil {
onToken(token)
}
}
})
if err != nil {
return "", fmt.Errorf("azure stream: %w", err)
}
return full.String(), nil
}
func messagesToAzureFormat(messages []Message) []map[string]interface{} {
result := make([]map[string]interface{}, len(messages))
for i, msg := range messages {
m := map[string]interface{}{
"role": msg.Role,
"content": msg.Content,
}
result[i] = m
}
return result
}