-
Notifications
You must be signed in to change notification settings - Fork 57
/
azure_chat_completion.go
241 lines (195 loc) · 8.26 KB
/
azure_chat_completion.go
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package proxy
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/bricks-cloud/bricksllm/internal/key"
"github.com/bricks-cloud/bricksllm/internal/stats"
"github.com/gin-gonic/gin"
goopenai "github.com/sashabaranov/go-openai"
"go.uber.org/zap"
)
func buildAzureUrl(path, deploymentId, apiVersion, resourceName string) string {
if path == "/api/providers/azure/openai/deployments/:deployment_id/chat/completions" {
return fmt.Sprintf("https://%s.openai.azure.com/openai/deployments/%s/chat/completions?api-version=%s", resourceName, deploymentId, apiVersion)
}
return fmt.Sprintf("https://%s.openai.azure.com/openai/deployments/%s/embeddings?api-version=%s", resourceName, deploymentId, apiVersion)
}
func getAzureChatCompletionHandler(r recorder, prod, private bool, psm ProviderSettingsManager, client http.Client, kms keyMemStorage, log *zap.Logger, aoe azureEstimator, timeOut time.Duration) gin.HandlerFunc {
return func(c *gin.Context) {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.requests", nil, 1)
if c == nil || c.Request == nil {
JSON(c, http.StatusInternalServerError, "[BricksLLM] context is empty")
return
}
cid := c.GetString(correlationId)
raw, exists := c.Get("key")
kc, ok := raw.(*key.ResponseKey)
if !exists || !ok {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.api_key_not_registered", nil, 1)
JSON(c, http.StatusUnauthorized, "[BricksLLM] api key is not registered")
return
}
ctx, cancel := context.WithTimeout(context.Background(), timeOut)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, buildAzureUrl(c.FullPath(), c.Param("deployment_id"), c.Query("api-version"), c.GetString("resourceName")), c.Request.Body)
if err != nil {
logError(log, "error when creating azure openai http request", prod, cid, err)
JSON(c, http.StatusInternalServerError, "[BricksLLM] failed to create azure openai http request")
return
}
copyHttpHeaders(c.Request, req)
isStreaming := c.GetBool("stream")
if isStreaming {
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Connection", "keep-alive")
}
start := time.Now()
res, err := client.Do(req)
if err != nil {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.http_client_error", nil, 1)
logError(log, "error when sending chat completion http request to azure openai", prod, cid, err)
JSON(c, http.StatusInternalServerError, "[BricksLLM] failed to send chat completion request to azure openai")
return
}
defer res.Body.Close()
for name, values := range res.Header {
for _, value := range values {
c.Header(name, value)
}
}
if res.StatusCode == http.StatusOK && !isStreaming {
dur := time.Now().Sub(start)
stats.Timing("bricksllm.proxy.get_azure_chat_completion_handler.latency", dur, nil, 1)
bytes, err := io.ReadAll(res.Body)
if err != nil {
logError(log, "error when reading azure openai chat completion response body", prod, cid, err)
JSON(c, http.StatusInternalServerError, "[BricksLLM] failed to read azure openai response body")
return
}
var cost float64 = 0
chatRes := &goopenai.ChatCompletionResponse{}
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.success", nil, 1)
stats.Timing("bricksllm.proxy.get_azure_chat_completion_handler.success_latency", dur, nil, 1)
err = json.Unmarshal(bytes, chatRes)
if err != nil {
logError(log, "error when unmarshalling azure openai http chat completion response body", prod, cid, err)
}
if err == nil {
c.Set("model", chatRes.Model)
logChatCompletionResponse(log, prod, private, cid, chatRes)
cost, err = aoe.EstimateTotalCost(chatRes.Model, chatRes.Usage.PromptTokens, chatRes.Usage.CompletionTokens)
if err != nil {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.estimate_total_cost_error", nil, 1)
logError(log, "error when estimating azure openai cost", prod, cid, err)
}
micros := int64(cost * 1000000)
err = r.RecordKeySpend(kc.KeyId, micros, kc.CostLimitInUsdUnit)
if err != nil {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.record_key_spend_error", nil, 1)
logError(log, "error when recording azure openai spend", prod, cid, err)
}
}
c.Set("costInUsd", cost)
c.Set("promptTokenCount", chatRes.Usage.PromptTokens)
c.Set("completionTokenCount", chatRes.Usage.CompletionTokens)
c.Data(res.StatusCode, "application/json", bytes)
return
}
if res.StatusCode != http.StatusOK {
dur := time.Now().Sub(start)
stats.Timing("bricksllm.proxy.get_azure_chat_completion_handler.error_latency", dur, nil, 1)
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.error_response", nil, 1)
bytes, err := io.ReadAll(res.Body)
if err != nil {
logError(log, "error when reading azyre openai http chat completion response body", prod, cid, err)
JSON(c, http.StatusInternalServerError, "[BricksLLM] failed to read azure openai response body")
return
}
logAnthropicErrorResponse(log, bytes, prod, cid)
c.Data(res.StatusCode, "application/json", bytes)
return
}
buffer := bufio.NewReader(res.Body)
var totalCost float64 = 0
var totalTokens int = 0
content := ""
model := ""
defer func() {
if len(model) != 0 {
c.Set("model", model)
}
tks, cost, err := aoe.EstimateChatCompletionStreamCostWithTokenCounts(model, content)
if err != nil {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.estimate_chat_completion_cost_and_tokens_error", nil, 1)
logError(log, "error when estimating azure openai chat completion stream cost with token counts", prod, cid, err)
}
estimatedPromptTokenCounts := c.GetInt("promptTokenCount")
promptCost, err := aoe.EstimatePromptCost(model, estimatedPromptTokenCounts)
if err != nil {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.estimate_chat_completion_cost_and_tokens_error", nil, 1)
logError(log, "error when estimating azure openai chat completion stream cost with token counts", prod, cid, err)
}
totalCost = cost + promptCost
totalTokens += tks
c.Set("costInUsd", totalCost)
c.Set("completionTokenCount", totalTokens)
}()
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.streaming_requests", nil, 1)
c.Stream(func(w io.Writer) bool {
raw, err := buffer.ReadBytes('\n')
if err != nil {
if err == io.EOF {
return false
}
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.read_bytes_error", nil, 1)
logError(log, "error when reading bytes from azure openai chat completion response", prod, cid, err)
apiErr := &goopenai.ErrorResponse{
Error: &goopenai.APIError{
Type: "bricksllm_error",
Message: err.Error(),
},
}
bytes, err := json.Marshal(apiErr)
if err != nil {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.json_marshal_error", nil, 1)
logError(log, "error when marshalling bytes for openai streaming chat completion error response", prod, cid, err)
return true
}
c.SSEvent("", string(bytes))
return true
}
noSpaceLine := bytes.TrimSpace(raw)
if !bytes.HasPrefix(noSpaceLine, headerData) {
return true
}
noPrefixLine := bytes.TrimPrefix(noSpaceLine, headerData)
c.SSEvent("", " "+string(noPrefixLine))
if string(noPrefixLine) == "[DONE]" {
return false
}
chatCompletionStreamResp := &goopenai.ChatCompletionStreamResponse{}
err = json.Unmarshal(noPrefixLine, chatCompletionStreamResp)
if err != nil {
stats.Incr("bricksllm.proxy.get_azure_chat_completion_handler.completion_response_unmarshall_error", nil, 1)
logError(log, "error when unmarshalling azure openai chat completion stream response", prod, cid, err)
}
if len(model) == 0 && len(chatCompletionStreamResp.Model) != 0 {
model = chatCompletionStreamResp.Model
}
if err == nil {
if len(chatCompletionStreamResp.Choices) > 0 && len(chatCompletionStreamResp.Choices[0].Delta.Content) != 0 {
content += chatCompletionStreamResp.Choices[0].Delta.Content
}
}
return true
})
stats.Timing("bricksllm.proxy.get_azure_chat_completion_handler.streaming_latency", time.Now().Sub(start), nil, 1)
}
}