File size: 7,259 Bytes
2717776
 
 
67d2cfe
2717776
 
 
 
 
 
67d2cfe
e51b490
2717776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e51b490
 
 
 
 
 
 
 
 
 
 
 
 
2717776
e51b490
 
2717776
 
 
 
e51b490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bc6a18
 
 
 
 
 
e51b490
 
 
 
 
 
 
 
 
 
2717776
e51b490
 
 
 
 
 
 
 
 
 
4bc6a18
 
 
 
 
 
 
 
 
 
e51b490
 
 
 
 
2717776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
927c01a
2717776
7fa3c43
 
 
 
 
 
 
 
 
 
 
 
 
 
2717776
 
67d2cfe
7fa3c43
2717776
 
 
 
 
 
 
 
 
82dcd64
1df46ea
977fbaf
1df46ea
7fa3c43
1df46ea
 
5780e3c
1df46ea
ba9e5b2
5780e3c
1df46ea
 
 
 
977fbaf
1df46ea
 
67d2cfe
 
977fbaf
67d2cfe
 
1df46ea
 
 
 
 
 
 
5780e3c
67d2cfe
977fbaf
 
 
67d2cfe
 
 
977fbaf
 
67d2cfe
 
977fbaf
 
2717776
67d2cfe
 
 
2717776
 
1df46ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
927c01a
1df46ea
 
 
67d2cfe
2717776
67d2cfe
2717776
814ba4e
67d2cfe
2717776
 
67d2cfe
 
 
2717776
67d2cfe
2717776
 
 
 
67d2cfe
 
2717776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814ba4e
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"sync"
	"time"
)

type OpenAIRequest struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
	Stream   bool      `json:"stream"`
}

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type DeepSeekResponse struct {
	Code      int    `json:"code"`
	Msg       string `json:"msg"`
	Message   string `json:"message"`
	APISource string `json:"api_source"`
}

type OpenAIResponse struct {
	ID      string   `json:"id"`
	Object  string   `json:"object"`
	Created int64    `json:"created"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
}

type Choice struct {
	Index        int     `json:"index"`
	Message      Message `json:"message"`
	FinishReason string  `json:"finish_reason"`
}

type StreamChoice struct {
	Delta        StreamMessage `json:"delta"`
	Index        int           `json:"index"`
	FinishReason *string       `json:"finish_reason"`
}

type StreamMessage struct {
	Role    string `json:"role,omitempty"`
	Content string `json:"content,omitempty"`
}

type StreamResponse struct {
	ID      string         `json:"id"`
	Object  string         `json:"object"`
	Created int64          `json:"created"`
	Model   string         `json:"model"`
	Choices []StreamChoice `json:"choices"`
}

var (
	requestCount int64
	requestLog   []string
	lastMinute   time.Time
	rpm          int
	logMutex     sync.Mutex
)

func init() {
	lastMinute = time.Now()
	requestLog = make([]string, 0, 10000)
}

func main() {
	http.HandleFunc("/", handleStats)
	http.HandleFunc("/log", handleLogs)
	http.HandleFunc("/hf/v1/chat/completions", handleChat)
	log.Fatal(http.ListenAndServe(":7860", nil))
}

func handleStats(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	logMutex.Lock()
	currentRPM := rpm
	totalRequests := requestCount
	logMutex.Unlock()

	fmt.Fprintf(w, "总请求次数: %d\n每分钟请求数(RPM): %d", totalRequests, currentRPM)
}

func handleLogs(w http.ResponseWriter, r *http.Request) {
	auth := r.URL.Query().Get("auth")
	if auth != "smnet" {
		http.Error(w, "未授权访问", http.StatusUnauthorized)
		return
	}

	logMutex.Lock()
	logs := make([]string, len(requestLog))
	copy(logs, requestLog)
	logMutex.Unlock()

	for _, log := range logs {
		fmt.Fprintln(w, log)
	}
}

func handleChat(w http.ResponseWriter, r *http.Request) {
	logMutex.Lock()
	requestCount++
	now := time.Now()
	if now.Sub(lastMinute) >= time.Minute {
		rpm = 1
		lastMinute = now
	} else {
		rpm++
	}

	clientIP := r.Header.Get("X-Real-IP")
	if clientIP == "" {
		clientIP = r.Header.Get("X-Forwarded-For")
		if clientIP == "" {
			clientIP = r.RemoteAddr
		}
	}

	logEntry := fmt.Sprintf("[%s] IP:%s 新请求处理", now.Format("2006-01-02 15:04:05"), clientIP)
	if len(requestLog) >= 5000 {
		requestLog = requestLog[1:]
	}
	requestLog = append(requestLog, logEntry)
	logMutex.Unlock()

	if r.Method != http.MethodPost {
		log.Printf("错误: 不支持的请求方法 %s", r.Method)
		http.Error(w, "仅支持 POST 请求", http.StatusMethodNotAllowed)
		return
	}

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("错误: 读取请求失败 - %v", err)
		http.Error(w, "读取请求失败", http.StatusBadRequest)
		return
	}

	var openAIReq OpenAIRequest
	if err := json.Unmarshal(body, &openAIReq); err != nil {
		log.Printf("错误: 请求格式错误 - %v", err)
		http.Error(w, "请求格式错误", http.StatusBadRequest)
		return
	}

	log.Printf("用户问题: %s", openAIReq.Messages[len(openAIReq.Messages)-1].Content)

	var apiURL string
	var modelName string
	switch openAIReq.Model {
	case "claude-3-5-sonnet-latest":
		apiURL = "https://chat.pearktrue.cn/v1/chat/completions"
		modelName = "claude-3-5-sonnet-latest"
	case "deepseek-r1":
		apiURL = "https://chat.pearktrue.cn/v1/chat/completions"
		modelName = "deepseek-r1"
	default:
		apiURL = "https://chat.pearktrue.cn/v1/chat/completions"
		modelName = "deepseek-v3"
	}

	deepseekReq := map[string]interface{}{
		"messages": openAIReq.Messages,
		"stream":   true,
		"model":    modelName,
	}

	deepseekBody, err := json.Marshal(deepseekReq)
	if err != nil {
		log.Printf("错误: 构造请求失败 - %v", err)
		http.Error(w, "构造请求失败", http.StatusInternalServerError)
		return
	}

	maxRetries := 10
	var tryRequest func() (string, error)

	tryRequest = func() (string, error) {
		req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(deepseekBody))
		if err != nil {
			return "", fmt.Errorf("创建请求失败: %v", err)
		}
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Authorization", "Bearer sk-2b0fb98d9fcff00c26b753bfcfe2c60b")

		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			return "", fmt.Errorf("请求失败: %v", err)
		}
		defer resp.Body.Close()

		var fullMessage string
		scanner := bufio.NewScanner(resp.Body)

		for scanner.Scan() {
			line := scanner.Text()
			if openAIReq.Stream {
				_, err = fmt.Fprintf(w, "%s\n", line)
				if err != nil {
					return "", fmt.Errorf("写入流式响应失败: %v", err)
				}
				w.(http.Flusher).Flush()
			}

			if !strings.HasPrefix(line, "data: ") {
				continue
			}

			data := strings.TrimPrefix(line, "data: ")
			if data == "[DONE]" {
				break
			}

			var streamResp StreamResponse
			if err := json.Unmarshal([]byte(data), &streamResp); err != nil {
				continue
			}

			if len(streamResp.Choices) > 0 && streamResp.Choices[0].Delta.Content != "" {
				fullMessage += streamResp.Choices[0].Delta.Content
			}
		}

		if fullMessage == "" {
			return "", fmt.Errorf("收到空回复")
		}

		return fullMessage, nil
	}

	var fullMessage string
	var lastError error

	for i := 0; i < maxRetries; i++ {
		fullMessage, lastError = tryRequest()
		if lastError == nil {
			break
		}
		log.Printf("第 %d 次尝试失败: %v,准备重试", i+1, lastError)
		time.Sleep(time.Second * time.Duration(i+1))
	}

	if lastError != nil {
		log.Printf("错误: 所有重试都失败 - %v", lastError)
		http.Error(w, "服务暂时不可用", http.StatusServiceUnavailable)
		return
	}

	log.Printf("AI回答: %s", fullMessage)

	if !openAIReq.Stream {
		openAIResp := OpenAIResponse{
			ID:      "chatcmpl-" + generateRandomString(10),
			Object:  "chat.completion",
			Created: getCurrentTimestamp(),
			Model:   openAIReq.Model,
			Choices: []Choice{
				{
					Index: 0,
					Message: Message{
						Role:    "assistant",
						Content: fullMessage,
					},
					FinishReason: "stop",
				},
			},
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(openAIResp)
	}
}

func generateRandomString(length int) string {
	return "SomeApiResponse"
}

func getCurrentTimestamp() int64 {
	return time.Now().Unix()
}

func writeSSE(w http.ResponseWriter, data interface{}) error {
	jsonData, err := json.Marshal(data)
	if err != nil {
		http.Error(w, "JSON编码失败", http.StatusInternalServerError)
		return err
	}

	_, err = fmt.Fprintf(w, "data: %s\n\n", jsonData)
	if err != nil {
		http.Error(w, "写入响应失败", http.StatusInternalServerError)
		return err
	}

	return nil
}