-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.go
More file actions
220 lines (206 loc) · 6.21 KB
/
Copy pathproxy.go
File metadata and controls
220 lines (206 loc) · 6.21 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
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
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strings"
)
type Proxy struct {
APIKey string
BaseURL string
Models []Model
}
type OpenAIMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type OpenAIRequest struct {
Model string `json:"model"`
Messages []OpenAIMessage `json:"messages"`
Stream bool `json:"stream"`
}
type AnthropicContent struct {
Type string `json:"type"`
Text string `json:"text"`
}
type AnthropicMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type AnthropicRequest struct {
Model string `json:"model"`
Messages []AnthropicMessage `json:"messages"`
Stream bool `json:"stream"`
MaxTokens int `json:"max_tokens"`
}
func anthropicToOpenAI(ar *AnthropicRequest) *OpenAIRequest {
messages := make([]OpenAIMessage, len(ar.Messages))
for i, m := range ar.Messages {
messages[i] = OpenAIMessage{Role: m.Role, Content: m.Content}
}
return &OpenAIRequest{
Model: ar.Model,
Messages: messages,
Stream: ar.Stream,
}
}
func openaiSSEToAnthropic(data []byte) []byte {
if !bytes.HasPrefix(data, []byte(`data: `)) {
return data
}
payload := bytes.TrimPrefix(data, []byte(`data: `))
if bytes.Equal(payload, []byte("[DONE]")) {
return data
}
var event struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"`
} `json:"delta"`
FinishReason *string `json:"finish_reason"`
Index int `json:"index"`
} `json:"choices"`
}
if err := json.Unmarshal(payload, &event); err != nil {
return data
}
for _, choice := range event.Choices {
delta := choice.Delta
switch {
case choice.FinishReason != nil && *choice.FinishReason == "stop":
return []byte(`data: {"type":"message_stop"}`)
case delta.ReasoningContent != "":
evt := fmt.Sprintf(
`data: {"type":"content_block_delta","index":%d,"delta":{"type":"thinking_delta","thinking":"%s"}}`,
choice.Index, escapeJSON(delta.ReasoningContent))
return []byte(evt)
case delta.Content != "":
evt := fmt.Sprintf(
`data: {"type":"content_block_delta","index":%d,"delta":{"type":"text_delta","text":"%s"}}`,
choice.Index, escapeJSON(delta.Content))
return []byte(evt)
}
}
return data
}
func openaiToAnthropic(body []byte) ([]byte, error) {
var oai struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"`
} `json:"message"`
} `json:"choices"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
} `json:"usage"`
}
if err := json.Unmarshal(body, &oai); err != nil {
return nil, fmt.Errorf("parse openai response: %w", err)
}
if len(oai.Choices) == 0 {
return nil, fmt.Errorf("no choices in response")
}
content := oai.Choices[0].Message.Content
if content == "" {
content = oai.Choices[0].Message.ReasoningContent
}
anthropic := map[string]interface{}{
"id": "msg_1",
"type": "message",
"role": "assistant",
"model": "claude",
"content": []map[string]interface{}{{"type": "text", "text": content}},
"stop_reason": "end_turn",
"usage": map[string]int{
"input_tokens": oai.Usage.PromptTokens,
"output_tokens": oai.Usage.CompletionTokens,
},
}
return json.Marshal(anthropic)
}
func (p *Proxy) Forward(w http.ResponseWriter, r *http.Request, oaiReq *OpenAIRequest) {
body, err := json.Marshal(oaiReq)
if err != nil {
http.Error(w, `{"error":{"message":"marshal request failed"}}`, http.StatusInternalServerError)
return
}
url := strings.TrimRight(p.BaseURL, "/") + "/chat/completions"
slog.Info("forwarding", "url", url, "model", oaiReq.Model, "stream", oaiReq.Stream)
upstream, err := http.NewRequestWithContext(r.Context(), "POST", url, bytes.NewReader(body))
if err != nil {
http.Error(w, `{"error":{"message":"create upstream request failed"}}`, http.StatusInternalServerError)
return
}
upstream.Header.Set("Content-Type", "application/json")
upstream.Header.Set("Authorization", "Bearer "+p.APIKey)
resp, err := http.DefaultClient.Do(upstream)
if err != nil {
slog.Error("upstream failed", "error", err)
http.Error(w, fmt.Sprintf(`{"error":{"message":"upstream request failed: %v"}}`, err), http.StatusBadGateway)
return
}
defer resp.Body.Close()
if oaiReq.Stream {
p.streamResponse(w, resp)
} else {
p.nonStreamResponse(w, resp)
}
}
func (p *Proxy) streamResponse(w http.ResponseWriter, resp *http.Response) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming not supported", http.StatusInternalServerError)
return
}
w.Write([]byte("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude\",\"content\":[],\"usage\":{\"input_tokens\":0,\"output_tokens\":0}}}\n\n"))
flusher.Flush()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data: ") {
continue
}
converted := openaiSSEToAnthropic([]byte(line))
w.Write(converted)
w.Write([]byte("\n\n"))
flusher.Flush()
}
w.Write([]byte("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"))
flusher.Flush()
}
func (p *Proxy) nonStreamResponse(w http.ResponseWriter, resp *http.Response) {
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, `{"error":{"message":"read upstream response failed"}}`, http.StatusInternalServerError)
return
}
if resp.StatusCode >= 400 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(resp.StatusCode)
w.Write(body)
return
}
converted, err := openaiToAnthropic(body)
if err != nil {
slog.Error("convert response failed", "error", err)
w.Header().Set("Content-Type", "application/json")
w.Write(body)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(converted)
}
func escapeJSON(s string) string {
encoded, _ := json.Marshal(s)
return string(encoded[1 : len(encoded)-1])
}