nfsn commited on
Commit
7be6f21
·
verified ·
1 Parent(s): c484766

Update api/main.go

Browse files
Files changed (1) hide show
  1. api/main.go +304 -260
api/main.go CHANGED
@@ -1,62 +1,73 @@
1
  package main
2
 
3
  import (
4
- "bufio"
5
- "encoding/json"
6
- "fmt"
7
- "net/http"
8
- "strings"
9
- "time"
10
  )
11
 
12
  type YouChatResponse struct {
13
- YouChatToken string `json:"youChatToken"`
14
  }
15
 
16
  type OpenAIStreamResponse struct {
17
- ID string `json:"id"`
18
- Object string `json:"object"`
19
- Created int64 `json:"created"`
20
- Model string `json:"model"`
21
- Choices []Choice `json:"choices"`
22
  }
23
 
24
  type Choice struct {
25
- Delta Delta `json:"delta"`
26
- Index int `json:"index"`
27
- FinishReason string `json:"finish_reason"`
28
  }
29
 
30
  type Delta struct {
31
- Content string `json:"content"`
32
  }
33
 
34
  type OpenAIRequest struct {
35
- Messages []Message `json:"messages"`
36
- Stream bool `json:"stream"`
37
- Model string `json:"model"`
38
  }
39
 
40
  type Message struct {
41
- Role string `json:"role"`
42
- Content string `json:"content"`
43
  }
44
 
45
  type OpenAIResponse struct {
46
- ID string `json:"id"`
47
- Object string `json:"object"`
48
- Created int64 `json:"created"`
49
- Model string `json:"model"`
50
- Choices []OpenAIChoice `json:"choices"`
51
  }
52
 
53
  type OpenAIChoice struct {
54
- Message Message `json:"message"`
55
- Index int `json:"index"`
56
- FinishReason string `json:"finish_reason"`
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
58
 
59
- // modelMap 存储 OpenAI 模型名称到 You.com 模型名称的映射。
60
  var modelMap = map[string]string{
61
  "deepseek-reasoner": "deepseek_r1",
62
  "deepseek-chat": "deepseek_v3",
@@ -83,7 +94,7 @@ var modelMap = map[string]string{
83
  "gemini-2-flash": "gemini_2_flash",
84
  "gemini-1.5-flash": "gemini_1_5_flash",
85
  "gemini-1.5-pro": "gemini_1_5_pro",
86
- "databricks-dbrx-instruct":"databricks_dbrx_instruct",
87
  "qwen-2.5-72b": "qwen2p5_72b",
88
  "qwen-2.5-coder-32b": "qwen2p5_coder_32b",
89
  "command-r-plus": "command_r_plus",
@@ -92,256 +103,289 @@ var modelMap = map[string]string{
92
  }
93
 
94
  func getReverseModelMap() map[string]string {
95
- reverse := make(map[string]string, len(modelMap))
96
- for k, v := range modelMap {
97
- reverse[v] = k
98
- }
99
- return reverse
100
  }
101
 
102
  func mapModelName(openAIModel string) string {
103
- if mappedModel, exists := modelMap[openAIModel]; exists {
104
- return mappedModel
105
- }
106
- return "deepseek_v3"
107
  }
108
 
109
  func reverseMapModelName(youModel string) string {
110
- reverseMap := getReverseModelMap()
111
- if mappedModel, exists := reverseMap[youModel]; exists {
112
- return mappedModel
113
- }
114
- return "deepseek-chat"
115
  }
116
 
117
  var originalModel string
118
 
119
  func Handler(w http.ResponseWriter, r *http.Request) {
120
- if r.URL.Path != "/hf/v1/chat/completions" {
121
- w.Header().Set("Content-Type", "application/json")
122
- json.NewEncoder(w).Encode(map[string]string{
123
- "status": "You2Api Service Running...",
124
- "message": "MoLoveSze...",
125
- })
126
- return
127
- }
128
-
129
- w.Header().Set("Access-Control-Allow-Origin", "*")
130
- w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
131
- w.Header().Set("Access-Control-Allow-Headers", "*")
132
-
133
- if r.Method == "OPTIONS" {
134
- w.WriteHeader(http.StatusOK)
135
- return
136
- }
137
-
138
- authHeader := r.Header.Get("Authorization")
139
- if !strings.HasPrefix(authHeader, "Bearer ") {
140
- http.Error(w, "Missing or invalid authorization header", http.StatusUnauthorized)
141
- return
142
- }
143
- dsToken := strings.TrimPrefix(authHeader, "Bearer ")
144
-
145
- var openAIReq OpenAIRequest
146
- if err := json.NewDecoder(r.Body).Decode(&openAIReq); err != nil {
147
- http.Error(w, "Invalid request body", http.StatusBadRequest)
148
- return
149
- }
150
-
151
- originalModel = openAIReq.Model
152
- lastMessage := openAIReq.Messages[len(openAIReq.Messages)-1].Content
153
- var chatHistory []map[string]interface{}
154
- for _, msg := range openAIReq.Messages {
155
- chatMsg := map[string]interface{}{
156
- "question": msg.Content,
157
- "answer": "",
158
- }
159
- if msg.Role == "assistant" {
160
- chatMsg["question"] = ""
161
- chatMsg["answer"] = msg.Content
162
- }
163
- chatHistory = append(chatHistory, chatMsg)
164
- }
165
-
166
- chatHistoryJSON, _ := json.Marshal(chatHistory)
167
-
168
- youReq, _ := http.NewRequest("GET", "https://you.com/api/streamingSearch", nil)
169
-
170
- q := youReq.URL.Query()
171
- q.Add("q", lastMessage)
172
- q.Add("page", "1")
173
- q.Add("count", "10")
174
- q.Add("safeSearch", "Moderate")
175
- q.Add("mkt", "zh-HK")
176
- q.Add("enable_worklow_generation_ux", "true")
177
- q.Add("domain", "youchat")
178
- q.Add("use_personalization_extraction", "true")
179
- q.Add("pastChatLength", fmt.Sprintf("%d", len(chatHistory)-1))
180
- q.Add("selectedChatMode", "custom")
181
- q.Add("selectedAiModel", mapModelName(openAIReq.Model))
182
- q.Add("enable_agent_clarification_questions", "true")
183
- q.Add("use_nested_youchat_updates", "true")
184
- q.Add("chat", string(chatHistoryJSON))
185
- youReq.URL.RawQuery = q.Encode()
186
-
187
- youReq.Header = http.Header{
188
- "sec-ch-ua-platform": {"Windows"},
189
- "Cache-Control": {"no-cache"},
190
- "sec-ch-ua": {`"Not(A:Brand";v="99", "Microsoft Edge";v="133", "Chromium";v="133"`},
191
- "sec-ch-ua-bitness": {"64"},
192
- "sec-ch-ua-model": {""},
193
- "sec-ch-ua-mobile": {"?0"},
194
- "sec-ch-ua-arch": {"x86"},
195
- "sec-ch-ua-full-version": {"133.0.3065.39"},
196
- "Accept": {"text/event-stream"},
197
- "User-Agent": {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0"},
198
- "sec-ch-ua-platform-version": {"19.0.0"},
199
- "Sec-Fetch-Site": {"same-origin"},
200
- "Sec-Fetch-Mode": {"cors"},
201
- "Sec-Fetch-Dest": {"empty"},
202
- "Host": {"you.com"},
203
- }
204
-
205
- cookies := getCookies(dsToken)
206
- var cookieStrings []string
207
- for name, value := range cookies {
208
- cookieStrings = append(cookieStrings, fmt.Sprintf("%s=%s", name, value))
209
- }
210
- youReq.Header.Add("Cookie", strings.Join(cookieStrings, ";"))
211
-
212
- if !openAIReq.Stream {
213
- handleNonStreamingResponse(w, youReq)
214
- return
215
- }
216
-
217
- handleStreamingResponse(w, youReq)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  }
219
 
220
  func getCookies(dsToken string) map[string]string {
221
- return map[string]string{
222
- "guest_has_seen_legal_disclaimer": "true",
223
- "youchat_personalization": "true",
224
- "DS": dsToken,
225
- "you_subscription": "youpro_standard_year",
226
- "youpro_subscription": "true",
227
- "ai_model": "deepseek_r1",
228
- "youchat_smart_learn": "true",
229
- }
230
  }
231
 
232
  func handleNonStreamingResponse(w http.ResponseWriter, youReq *http.Request) {
233
- client := &http.Client{
234
- Timeout: 60 * time.Second,
235
- }
236
- resp, err := client.Do(youReq)
237
- if err != nil {
238
- http.Error(w, err.Error(), http.StatusInternalServerError)
239
- return
240
- }
241
- defer resp.Body.Close()
242
-
243
- var fullResponse strings.Builder
244
- scanner := bufio.NewScanner(resp.Body)
245
-
246
- buf := make([]byte, 0, 64*1024)
247
- scanner.Buffer(buf, 1024*1024)
248
-
249
- for scanner.Scan() {
250
- line := scanner.Text()
251
- if strings.HasPrefix(line, "event: youChatToken") {
252
- scanner.Scan()
253
- data := scanner.Text()
254
- if !strings.HasPrefix(data, "data: ") {
255
- continue
256
- }
257
- var token YouChatResponse
258
- if err := json.Unmarshal([]byte(strings.TrimPrefix(data, "data: ")), &token); err != nil {
259
- continue
260
- }
261
- fullResponse.WriteString(token.YouChatToken)
262
- }
263
- }
264
-
265
- if scanner.Err() != nil {
266
- http.Error(w, "Error reading response", http.StatusInternalServerError)
267
- return
268
- }
269
-
270
- openAIResp := OpenAIResponse{
271
- ID: "chatcmpl-" + fmt.Sprintf("%d", time.Now().Unix()),
272
- Object: "chat.completion",
273
- Created: time.Now().Unix(),
274
- Model: reverseMapModelName(mapModelName(originalModel)),
275
- Choices: []OpenAIChoice{
276
- {
277
- Message: Message{
278
- Role: "assistant",
279
- Content: fullResponse.String(),
280
- },
281
- Index: 0,
282
- FinishReason: "stop",
283
- },
284
- },
285
- }
286
-
287
- w.Header().Set("Content-Type", "application/json")
288
- if err := json.NewEncoder(w).Encode(openAIResp); err != nil {
289
- http.Error(w, "Error encoding response", http.StatusInternalServerError)
290
- return
291
- }
292
  }
293
 
294
  func handleStreamingResponse(w http.ResponseWriter, youReq *http.Request) {
295
- client := &http.Client{}
296
- resp, err := client.Do(youReq)
297
- if err != nil {
298
- http.Error(w, err.Error(), http.StatusInternalServerError)
299
- return
300
- }
301
- defer resp.Body.Close()
302
-
303
- w.Header().Set("Content-Type", "text/event-stream")
304
- w.Header().Set("Cache-Control", "no-cache")
305
- w.Header().Set("Connection", "keep-alive")
306
-
307
- scanner := bufio.NewScanner(resp.Body)
308
- for scanner.Scan() {
309
- line := scanner.Text()
310
-
311
- if strings.HasPrefix(line, "event: youChatToken") {
312
- scanner.Scan()
313
- data := scanner.Text()
314
-
315
- var token YouChatResponse
316
- json.Unmarshal([]byte(strings.TrimPrefix(data, "data: ")), &token)
317
-
318
- openAIResp := OpenAIStreamResponse{
319
- ID: "chatcmpl-" + fmt.Sprintf("%d", time.Now().Unix()),
320
- Object: "chat.completion.chunk",
321
- Created: time.Now().Unix(),
322
- Model: reverseMapModelName(mapModelName(originalModel)),
323
- Choices: []Choice{
324
- {
325
- Delta: Delta{
326
- Content: token.YouChatToken,
327
- },
328
- Index: 0,
329
- FinishReason: "",
330
- },
331
- },
332
- }
333
-
334
- respBytes, _ := json.Marshal(openAIResp)
335
- fmt.Fprintf(w, "data: %s\n\n", string(respBytes))
336
- w.(http.Flusher).Flush()
337
- }
338
- }
339
  }
340
 
341
  func main() {
342
- http.HandleFunc("/", Handler)
343
- fmt.Println("Server starting on :7860...")
344
- if err := http.ListenAndServe(":7860", nil); err != nil {
345
- fmt.Printf("Error starting server: %v\n", err)
346
- }
347
  }
 
1
  package main
2
 
3
  import (
4
+ "bufio"
5
+ "encoding/json"
6
+ "fmt"
7
+ "net/http"
8
+ "strings"
9
+ "time"
10
  )
11
 
12
  type YouChatResponse struct {
13
+ YouChatToken string `json:"youChatToken"`
14
  }
15
 
16
  type OpenAIStreamResponse struct {
17
+ ID string `json:"id"`
18
+ Object string `json:"object"`
19
+ Created int64 `json:"created"`
20
+ Model string `json:"model"`
21
+ Choices []Choice `json:"choices"`
22
  }
23
 
24
  type Choice struct {
25
+ Delta Delta `json:"delta"`
26
+ Index int `json:"index"`
27
+ FinishReason string `json:"finish_reason"`
28
  }
29
 
30
  type Delta struct {
31
+ Content string `json:"content"`
32
  }
33
 
34
  type OpenAIRequest struct {
35
+ Messages []Message `json:"messages"`
36
+ Stream bool `json:"stream"`
37
+ Model string `json:"model"`
38
  }
39
 
40
  type Message struct {
41
+ Role string `json:"role"`
42
+ Content string `json:"content"`
43
  }
44
 
45
  type OpenAIResponse struct {
46
+ ID string `json:"id"`
47
+ Object string `json:"object"`
48
+ Created int64 `json:"created"`
49
+ Model string `json:"model"`
50
+ Choices []OpenAIChoice `json:"choices"`
51
  }
52
 
53
  type OpenAIChoice struct {
54
+ Message Message `json:"message"`
55
+ Index int `json:"index"`
56
+ FinishReason string `json:"finish_reason"`
57
+ }
58
+
59
+ type ModelResponse struct {
60
+ Object string `json:"object"`
61
+ Data []ModelDetail `json:"data"`
62
+ }
63
+
64
+ type ModelDetail struct {
65
+ ID string `json:"id"`
66
+ Object string `json:"object"`
67
+ Created int64 `json:"created"`
68
+ OwnedBy string `json:"owned_by"`
69
  }
70
 
 
71
  var modelMap = map[string]string{
72
  "deepseek-reasoner": "deepseek_r1",
73
  "deepseek-chat": "deepseek_v3",
 
94
  "gemini-2-flash": "gemini_2_flash",
95
  "gemini-1.5-flash": "gemini_1_5_flash",
96
  "gemini-1.5-pro": "gemini_1_5_pro",
97
+ "databricks-dbrx-instruct": "databricks_dbrx_instruct",
98
  "qwen-2.5-72b": "qwen2p5_72b",
99
  "qwen-2.5-coder-32b": "qwen2p5_coder_32b",
100
  "command-r-plus": "command_r_plus",
 
103
  }
104
 
105
  func getReverseModelMap() map[string]string {
106
+ reverse := make(map[string]string, len(modelMap))
107
+ for k, v := range modelMap {
108
+ reverse[v] = k
109
+ }
110
+ return reverse
111
  }
112
 
113
  func mapModelName(openAIModel string) string {
114
+ if mappedModel, exists := modelMap[openAIModel]; exists {
115
+ return mappedModel
116
+ }
117
+ return "deepseek_v3"
118
  }
119
 
120
  func reverseMapModelName(youModel string) string {
121
+ reverseMap := getReverseModelMap()
122
+ if mappedModel, exists := reverseMap[youModel]; exists {
123
+ return mappedModel
124
+ }
125
+ return "deepseek-chat"
126
  }
127
 
128
  var originalModel string
129
 
130
  func Handler(w http.ResponseWriter, r *http.Request) {
131
+ // 新增模型列表接口
132
+ if r.URL.Path == "/hf/v1/models" {
133
+ w.Header().Set("Content-Type", "application/json")
134
+ w.Header().Set("Access-Control-Allow-Origin", "*")
135
+ w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
136
+ w.Header().Set("Access-Control-Allow-Headers", "*")
137
+
138
+ if r.Method == "OPTIONS" {
139
+ w.WriteHeader(http.StatusOK)
140
+ return
141
+ }
142
+
143
+ models := make([]ModelDetail, 0, len(modelMap))
144
+ created := time.Now().Unix()
145
+ for modelID := range modelMap {
146
+ models = append(models, ModelDetail{
147
+ ID: modelID,
148
+ Object: "model",
149
+ Created: created,
150
+ OwnedBy: "organization-owner",
151
+ })
152
+ }
153
+
154
+ response := ModelResponse{
155
+ Object: "list",
156
+ Data: models,
157
+ }
158
+
159
+ json.NewEncoder(w).Encode(response)
160
+ return
161
+ }
162
+
163
+ // 原有逻辑保持不变
164
+ if r.URL.Path != "/hf/v1/chat/completions" {
165
+ w.Header().Set("Content-Type", "application/json")
166
+ json.NewEncoder(w).Encode(map[string]string{
167
+ "status": "You2Api Service Running...",
168
+ "message": "MoLoveSze...",
169
+ })
170
+ return
171
+ }
172
+
173
+ w.Header().Set("Access-Control-Allow-Origin", "*")
174
+ w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
175
+ w.Header().Set("Access-Control-Allow-Headers", "*")
176
+
177
+ if r.Method == "OPTIONS" {
178
+ w.WriteHeader(http.StatusOK)
179
+ return
180
+ }
181
+
182
+ authHeader := r.Header.Get("Authorization")
183
+ if !strings.HasPrefix(authHeader, "Bearer ") {
184
+ http.Error(w, "Missing or invalid authorization header", http.StatusUnauthorized)
185
+ return
186
+ }
187
+ dsToken := strings.TrimPrefix(authHeader, "Bearer ")
188
+
189
+ var openAIReq OpenAIRequest
190
+ if err := json.NewDecoder(r.Body).Decode(&openAIReq); err != nil {
191
+ http.Error(w, "Invalid request body", http.StatusBadRequest)
192
+ return
193
+ }
194
+
195
+ originalModel = openAIReq.Model
196
+ lastMessage := openAIReq.Messages[len(openAIReq.Messages)-1].Content
197
+ var chatHistory []map[string]interface{}
198
+ for _, msg := range openAIReq.Messages {
199
+ chatMsg := map[string]interface{}{
200
+ "question": msg.Content,
201
+ "answer": "",
202
+ }
203
+ if msg.Role == "assistant" {
204
+ chatMsg["question"] = ""
205
+ chatMsg["answer"] = msg.Content
206
+ }
207
+ chatHistory = append(chatHistory, chatMsg)
208
+ }
209
+
210
+ chatHistoryJSON, _ := json.Marshal(chatHistory)
211
+
212
+ youReq, _ := http.NewRequest("GET", "https://you.com/api/streamingSearch", nil)
213
+
214
+ q := youReq.URL.Query()
215
+ q.Add("q", lastMessage)
216
+ q.Add("page", "1")
217
+ q.Add("count", "10")
218
+ q.Add("safeSearch", "Moderate")
219
+ q.Add("mkt", "zh-HK")
220
+ q.Add("enable_worklow_generation_ux", "true")
221
+ q.Add("domain", "youchat")
222
+ q.Add("use_personalization_extraction", "true")
223
+ q.Add("pastChatLength", fmt.Sprintf("%d", len(chatHistory)-1))
224
+ q.Add("selectedChatMode", "custom")
225
+ q.Add("selectedAiModel", mapModelName(openAIReq.Model))
226
+ q.Add("enable_agent_clarification_questions", "true")
227
+ q.Add("use_nested_youchat_updates", "true")
228
+ q.Add("chat", string(chatHistoryJSON))
229
+ youReq.URL.RawQuery = q.Encode()
230
+
231
+ youReq.Header = http.Header{
232
+ "sec-ch-ua-platform": {"Windows"},
233
+ "Cache-Control": {"no-cache"},
234
+ "sec-ch-ua": {`"Not(A:Brand";v="99", "Microsoft Edge";v="133", "Chromium";v="133"`},
235
+ "sec-ch-ua-bitness": {"64"},
236
+ "sec-ch-ua-model": {""},
237
+ "sec-ch-ua-mobile": {"?0"},
238
+ "sec-ch-ua-arch": {"x86"},
239
+ "sec-ch-ua-full-version": {"133.0.3065.39"},
240
+ "Accept": {"text/event-stream"},
241
+ "User-Agent": {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0"},
242
+ "sec-ch-ua-platform-version": {"19.0.0"},
243
+ "Sec-Fetch-Site": {"same-origin"},
244
+ "Sec-Fetch-Mode": {"cors"},
245
+ "Sec-Fetch-Dest": {"empty"},
246
+ "Host": {"you.com"},
247
+ }
248
+
249
+ cookies := getCookies(dsToken)
250
+ var cookieStrings []string
251
+ for name, value := range cookies {
252
+ cookieStrings = append(cookieStrings, fmt.Sprintf("%s=%s", name, value))
253
+ }
254
+ youReq.Header.Add("Cookie", strings.Join(cookieStrings, ";"))
255
+
256
+ if !openAIReq.Stream {
257
+ handleNonStreamingResponse(w, youReq)
258
+ return
259
+ }
260
+
261
+ handleStreamingResponse(w, youReq)
262
  }
263
 
264
  func getCookies(dsToken string) map[string]string {
265
+ return map[string]string{
266
+ "guest_has_seen_legal_disclaimer": "true",
267
+ "youchat_personalization": "true",
268
+ "DS": dsToken,
269
+ "you_subscription": "youpro_standard_year",
270
+ "youpro_subscription": "true",
271
+ "ai_model": "deepseek_r1",
272
+ "youchat_smart_learn": "true",
273
+ }
274
  }
275
 
276
  func handleNonStreamingResponse(w http.ResponseWriter, youReq *http.Request) {
277
+ client := &http.Client{
278
+ Timeout: 60 * time.Second,
279
+ }
280
+ resp, err := client.Do(youReq)
281
+ if err != nil {
282
+ http.Error(w, err.Error(), http.StatusInternalServerError)
283
+ return
284
+ }
285
+ defer resp.Body.Close()
286
+
287
+ var fullResponse strings.Builder
288
+ scanner := bufio.NewScanner(resp.Body)
289
+
290
+ buf := make([]byte, 0, 64*1024)
291
+ scanner.Buffer(buf, 1024*1024)
292
+
293
+ for scanner.Scan() {
294
+ line := scanner.Text()
295
+ if strings.HasPrefix(line, "event: youChatToken") {
296
+ scanner.Scan()
297
+ data := scanner.Text()
298
+ if !strings.HasPrefix(data, "data: ") {
299
+ continue
300
+ }
301
+ var token YouChatResponse
302
+ if err := json.Unmarshal([]byte(strings.TrimPrefix(data, "data: ")), &token); err != nil {
303
+ continue
304
+ }
305
+ fullResponse.WriteString(token.YouChatToken)
306
+ }
307
+ }
308
+
309
+ if scanner.Err() != nil {
310
+ http.Error(w, "Error reading response", http.StatusInternalServerError)
311
+ return
312
+ }
313
+
314
+ openAIResp := OpenAIResponse{
315
+ ID: "chatcmpl-" + fmt.Sprintf("%d", time.Now().Unix()),
316
+ Object: "chat.completion",
317
+ Created: time.Now().Unix(),
318
+ Model: reverseMapModelName(mapModelName(originalModel)),
319
+ Choices: []OpenAIChoice{
320
+ {
321
+ Message: Message{
322
+ Role: "assistant",
323
+ Content: fullResponse.String(),
324
+ },
325
+ Index: 0,
326
+ FinishReason: "stop",
327
+ },
328
+ },
329
+ }
330
+
331
+ w.Header().Set("Content-Type", "application/json")
332
+ if err := json.NewEncoder(w).Encode(openAIResp); err != nil {
333
+ http.Error(w, "Error encoding response", http.StatusInternalServerError)
334
+ return
335
+ }
336
  }
337
 
338
  func handleStreamingResponse(w http.ResponseWriter, youReq *http.Request) {
339
+ client := &http.Client{}
340
+ resp, err := client.Do(youReq)
341
+ if err != nil {
342
+ http.Error(w, err.Error(), http.StatusInternalServerError)
343
+ return
344
+ }
345
+ defer resp.Body.Close()
346
+
347
+ w.Header().Set("Content-Type", "text/event-stream")
348
+ w.Header().Set("Cache-Control", "no-cache")
349
+ w.Header().Set("Connection", "keep-alive")
350
+
351
+ scanner := bufio.NewScanner(resp.Body)
352
+ for scanner.Scan() {
353
+ line := scanner.Text()
354
+
355
+ if strings.HasPrefix(line, "event: youChatToken") {
356
+ scanner.Scan()
357
+ data := scanner.Text()
358
+
359
+ var token YouChatResponse
360
+ json.Unmarshal([]byte(strings.TrimPrefix(data, "data: ")), &token)
361
+
362
+ openAIResp := OpenAIStreamResponse{
363
+ ID: "chatcmpl-" + fmt.Sprintf("%d", time.Now().Unix()),
364
+ Object: "chat.completion.chunk",
365
+ Created: time.Now().Unix(),
366
+ Model: reverseMapModelName(mapModelName(originalModel)),
367
+ Choices: []Choice{
368
+ {
369
+ Delta: Delta{
370
+ Content: token.YouChatToken,
371
+ },
372
+ Index: 0,
373
+ FinishReason: "",
374
+ },
375
+ },
376
+ }
377
+
378
+ respBytes, _ := json.Marshal(openAIResp)
379
+ fmt.Fprintf(w, "data: %s\n\n", string(respBytes))
380
+ w.(http.Flusher).Flush()
381
+ }
382
+ }
383
  }
384
 
385
  func main() {
386
+ http.HandleFunc("/", Handler)
387
+ fmt.Println("Server starting on :7860...")
388
+ if err := http.ListenAndServe(":7860", nil); err != nil {
389
+ fmt.Printf("Error starting server: %v\n", err)
390
+ }
391
  }