Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262import requestsfrom flask import Flask, request, Response, jsonifyimport jsonimport timefrom datetime import datetimefrom urllib.parse import quote
app = Flask(__name__)
TARGET_URL = "https://chat.zzyu.me/api/chat"DOG_API_TEMPLATE = "https://api.lolimi.cn/API/dog/api.php?msg={msg}&num=500&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 = []request_log_file = "requests.log"
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 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 log_request(ip, timestamp, model, messages, response, cache_hit): log_entry = { "timestamp": timestamp, "client_ip": ip, "model": model, "messages": messages, "response": response, "cache_hit": cache_hit } try: with open(request_log_file, "a", encoding="utf-8") as f: f.write(json.dumps(log_entry, ensure_ascii=False) + "\n") except: pass
@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, "supportssupports_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() prompt = messages[-1]["content"] if messages else "问题" current_time = datetime.now().isoformat() cached_content = None for i, q in enumerate(cache_questions): if similarity(prompt, q) >= SIMILARITY_THRESHOLD: cached_content = cache_responses[i] break if cached_content is not None: log_request(client_ip, current_time, model, messages, cached_content, True) 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": cached_content[0]["content"]}, "finish_reason": "stop" }] }) else: def generate(): content = cached_content[0]["content"] chunk = { "id": CHUNK_ID_PREFIX + str(int(time.time())), "object": "chat.completion.chunk", "created": int(time.time()), "model": model, "choices": [{ "index": 0, "delta": {"content": content}, "finish_reason": None }] } yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n" yield f"data: {json.dumps({**chunk, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\n\n" return Response(generate(), content_type="text/event-stream") payload = { "messages": messages, "model": model, "useWebSearch": data.get("use_web_search", True) } headers = {"Content-Type": "application/json"} if not stream: try: resp = requests.post(TARGET_URL, json=payload, headers=headers, timeout=10) if resp.status_code == 200: content = "" for line in resp.iter_lines(decode_unicode=True): if line.startswith("data: "): try: raw = json.loads(line[6:]) if raw["type"] == "text": content += raw["content"] except: continue response_data = [{"role": "assistant", "content": content}] cache_questions.append(prompt) cache_responses.append(response_data) log_request(client_ip, current_time, model, messages, response_data, False) 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": content}, "finish_reason": "stop" }] }) except: pass try: dog_resp = requests.get(DOG_API_TEMPLATE.format(msg=quote(prompt)), timeout=5) text = dog_resp.json().get("text", prompt + "的意义,值得我们深入反思。") response_data = [{"role": "assistant", "content": text}] cache_questions.append(prompt) cache_responses.append(response_data) log_request(client_ip, current_time, model, messages, response_data, False) 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" }] }) except: return jsonify({ "id": CHUNK_ID_PREFIX + str(int(time.time())), "object": "chat.completion", "created": int(time.time()), "model": model, "choices": [{ "index": 0, "message": {"role":是一种"}, "finish_reason": "stop" }] }) else: def generate_stream(): try: content_buffer = "" with requests.post(TARGET_URL, json=payload, headers=headers, timeout=10, stream=True) as r: if r.status_code == 200: for line in r.iter_lines(): if line: line = line.decode('utf-8') if line.startswith("data: ") and line != "data: {\"type\":\"done\"}": try: raw = json.loads(line[6:]) if raw["type"] == "text": content = raw["content"] content_buffer += content chunk = { "id": CHUNK_ID_PREFIX + str(int(time.time())), "object": "chat.completion.chunk", "created": int(time.time()), "model": model, "choices": [{ "index": 0, "delta": {"content": content} }] } yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n" except: continue if content_buffer: cache_questions.append(prompt) cache_responses.append([{"role": "assistant", "content": content_buffer}]) yield f"data: {json.dumps({**chunk, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\n\n" return except: pass try: dog_resp = requests.get(DOG_API_TEMPLATE.format(msg=quote(prompt)), timeout=5) text = dog_resp.json().get("text", prompt + "的意义,值得我们深入反思。") except: text = prompt + "的存在,不能不说是一种必然。" content_buffer = "" for char in text: content_buffer += char chunk = { "id": CHUNK_ID_PREFIX + str(int(time.time())), "object": "chat.completion.chunk", "created": int(time.time()), "model": model, "choices": [{ "index": 0, "delta": {"content": char} }] } yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n" yield f"data: {json.dumps({**chunk, 'choices': [{'index': 0, '':stop]})(),_type="text/event-stream") except: 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": "这个问题,需要从新的角度审视。"}, "finish_reason": "stop" }] })
@app.route("/", methods=["GET"])def index(): return "<h1>AI Service Running</h1>", 200app.pyAdded+262