Spaces:
Sleeping

File size: 9,650 Bytes
1337f2e
 
 
 
 
 
c532637
1337f2e
 
 
c532637
 
 
 
 
 
 
dafc96d
1337f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5886a17
 
 
1337f2e
 
 
 
 
 
 
7543cef
c532637
 
 
 
 
5d2fada
 
 
 
 
7543cef
502d80c
c532637
1337f2e
 
502d80c
1337f2e
c532637
5886a17
c532637
 
 
 
 
 
1337f2e
c532637
1337f2e
 
 
 
 
 
 
 
 
 
 
 
 
5886a17
1337f2e
 
 
83033f3
 
1337f2e
 
 
 
 
 
 
 
 
 
 
ba03bfc
5886a17
1337f2e
 
ba03bfc
1337f2e
 
ba03bfc
1337f2e
5886a17
 
1337f2e
5d2fada
b482ad9
 
 
5d2fada
dafc96d
5d2fada
 
 
5886a17
b482ad9
5d2fada
ba03bfc
b482ad9
5d2fada
 
c532637
 
 
 
5d2fada
c532637
ba03bfc
5d2fada
ba03bfc
5886a17
 
5d2fada
 
 
5886a17
5d2fada
5886a17
c532637
1337f2e
5886a17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1337f2e
 
5886a17
 
ba03bfc
5886a17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d7228e
 
 
 
 
 
 
ba03bfc
c532637
 
5886a17
 
 
 
ba03bfc
5886a17
 
 
 
 
 
 
 
 
 
 
1337f2e
 
 
ba03bfc
 
 
 
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
import requests
from flask import Flask, request, Response, jsonify
import json
import time
from datetime import datetime
from urllib.parse import quote
import logging

app = Flask(__name__)

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

DOG_API_TEMPLATE = "https://api.lolimi.cn/API/dog/api.php?msg={msg}&num=6666&type=json"

SUPPORTED_MODELS = [
    "claude-3-5-haiku-20241022",
    "claude-3-7-sonnet-20250219",
    "claude-sonnet-4-20250514",
    "claude-sonnet-4-5-20250929"
]

CHUNK_ID_PREFIX = "chatcmpl-"
SIMILARITY_THRESHOLD = 0.9

cache_questions = []
cache_responses = []

def get_real_ip():
    return (request.headers.get('X-Forwarded-For', '').split(',')[0].strip() or
            request.headers.get('X-Real-IP', '') or
            request.remote_addr)

def get_user_agent():
    return request.headers.get('User-Agent', 'Unknown')

def normalize_text(text):
    return ''.join(filter(str.isalnum, text.lower()))

def similarity(a, b):
    from difflib import SequenceMatcher
    return SequenceMatcher(None, normalize_text(a), normalize_text(b)).ratio()

def estimate_tokens(text):
    if not text:
        return 1
    chinese_chars = sum(1 for c in text if '\u4e00' <= c <= '\u9fff')
    other_chars = len(text) - chinese_chars
    return max(1, int(chinese_chars * 0.5 + other_chars * 0.25))

def is_identity_question(text):
    keywords = ['你是谁', '你是什么', 'who are you', 'what are you', '介绍一下你自己', '介绍下你自己', '你叫什么']
    normalized = normalize_text(text)
    return any(normalize_text(kw) in normalized for kw in keywords)

def log_request(ip, user_agent, timestamp, model, messages, response, cache_hit, prompt_tokens, completion_tokens):
    log_data = {
        "timestamp": timestamp,
        "client_ip": ip,
        "user_agent": user_agent,
        "model": model,
        "prompt": messages[-1]["content"] if messages else "",
        "response_length": len(response[0]["content"]),
        "cache_hit": cache_hit,
        "tokens": {
            "prompt": prompt_tokens,
            "completion": completion_tokens,
            "total": prompt_tokens + completion_tokens
        }
    }
    logger.info(f"REQUEST: {json.dumps(log_data, ensure_ascii=False)}")

@app.route("/v1/models", methods=["GET"])
def list_models():
    data = []
    for idx, model_id in enumerate(SUPPORTED_MODELS):
        version = model_id.split('-')[2]
        variant = 'haiku' if 'haiku' in model_id else 'sonnet' if 'sonnet' in model_id else 'opus'
        supports_vision = float(''.join(version.split('-')[:2])) >= 3.5
        reasoning = variant in ['sonnet', 'opus']
        data.append({
            "id": model_id,
            "object": "model",
            "created": 1700000000 + idx * 100000,
            "owned_by": "f-droid",
            "prompt_length": 200000,
            "completion_length": 8192,
            "max_total_tokens": 204800,
            "supports_vision": supports_vision,
            "supports_function_calling": True,
            "reasoning": reasoning,
            "supports_streaming": True
        })
    return jsonify({"object": "list", "data": data})

@app.route("/v1/chat/completions", methods=["POST"])
def chat_completions():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": {"message": "Invalid JSON", "type": "invalid_request"}}), 400
        
        messages = data.get("messages", [])
        model = data.get("model", "claude-sonnet-4-5-20250929")
        stream = data.get("stream", False)
        
        if model not in SUPPORTED_MODELS:
            return jsonify({"error": {"message": f"Model '{model}' not supported", "type": "model_not_found"}}), 400
        
        client_ip = get_real_ip()
        user_agent = get_user_agent()
        prompt = messages[-1]["content"] if messages else "问"
        current_time = datetime.now().isoformat()
        
        text = None
        cache_hit = False
        
        if is_identity_question(prompt):
            text = "我是Claude,由Anthropic公司开发的AI助手。我可以帮助回答问题、进行对话、协助完成各种任务,比如写作、分析、编程、数学计算等。有什么我可以帮助你的吗?"
        else:
            for i, q in enumerate(cache_questions):
                if similarity(prompt, q) >= SIMILARITY_THRESHOLD:
                    text = cache_responses[i][0]["content"]
                    cache_hit = True
                    break
            
            if text is None:
                try:
                    dog_resp = requests.get(DOG_API_TEMPLATE.format(msg=quote(prompt)), timeout=5)
                    dog_data = dog_resp.json()
                    text = dog_data.get("text", "").strip()
                    if not text or len(text) < 10:
                        text = f"{prompt}的存在,是一种不可避免的趋势。我认为,{prompt}对我们来说意义重大。了解清楚{prompt}到底是一种怎么样的存在,是解决一切问题的关键。"
                except:
                    text = f"{prompt}的本质,不能不说非常重大。我们必须认真思考{prompt}这个问题。"
                
                cache_questions.append(prompt)
                cache_responses.append([{"role": "assistant", "content": text}])
        
        response_data = [{"role": "assistant", "content": text}]
        
        prompt_tokens = sum(estimate_tokens(m.get("content", "")) for m in messages)
        completion_tokens = estimate_tokens(text)
        total_tokens = prompt_tokens + completion_tokens
        
        log_request(client_ip, user_agent, current_time, model, messages, response_data, cache_hit, prompt_tokens, completion_tokens)
        
        if not stream:
            return jsonify({
                "id": CHUNK_ID_PREFIX + str(int(time.time())),
                "object": "chat.completion",
                "created": int(time.time()),
                "model": model,
                "choices": [{
                    "index": 0,
                    "message": {"role": "assistant", "content": text},
                    "finish_reason": "stop"
                }],
                "usage": {
                    "prompt_tokens": prompt_tokens,
                    "completion_tokens": completion_tokens,
                    "total_tokens": total_tokens
                }
            })
        else:
            def generate_stream():
                chunk_id = CHUNK_ID_PREFIX + str(int(time.time()))
                chunk_size = 5
                
                for i in range(0, len(text), chunk_size):
                    chunk_text = text[i:i+chunk_size]
                    chunk = {
                        "id": chunk_id,
                        "object": "chat.completion.chunk",
                        "created": int(time.time()),
                        "model": model,
                        "choices": [{
                            "index": 0,
                            "delta": {"content": chunk_text},
                            "finish_reason": None
                        }]
                    }
                    yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
                
                final_chunk = {
                    "id": chunk_id,
                    "object": "chat.completion.chunk",
                    "created": int(time.time()),
                    "model": model,
                    "choices": [{
                        "index": 0,
                        "delta": {},
                        "finish_reason": "stop"
                    }]
                }
                yield f"data: {json.dumps(final_chunk, ensure_ascii=False)}\n\n"
                
                usage_chunk = {
                    "id": chunk_id,
                    "object": "chat.completion.chunk",
                    "created": int(time.time()),
                    "model": model,
                    "choices": [],
                    "usage": {
                        "prompt_tokens": prompt_tokens,
                        "completion_tokens": completion_tokens,
                        "total_tokens": total_tokens
                    }
                }
                yield f"data: {json.dumps(usage_chunk, ensure_ascii=False)}\n\n"
                yield "data: [DONE]\n\n"
            
            return Response(generate_stream(), 
                          content_type='text/event-stream',
                          headers={
                              'Cache-Control': 'no-cache',
                              'X-Accel-Buffering': 'no'
                          })
    
    except Exception as e:
        logger.error(f"ERROR: {str(e)}")
        return jsonify({
            "id": CHUNK_ID_PREFIX + str(int(time.time())),
            "object": "chat.completion",
            "created": int(time.time()),
            "model": model if 'model' in locals() else "claude-sonnet-4-5-20250929",
            "choices": [{
                "index": 0,
                "message": {"role": "assistant", "content": "这个问题,值得我们深入思考。"},
                "finish_reason": "stop"
            }],
            "usage": {
                "prompt_tokens": 10,
                "completion_tokens": 15,
                "total_tokens": 25
            }
        })

@app.route("/", methods=["GET"])
def index():
    return "<h1>AI Service Running</h1>", 200

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)