Download app.py from venlacy0/Chat: direct link, hf CLI and curl.
- Browser
- Download file 9.65 kB
-
https://huggingface.co/spaces/venlacy0/Chat/resolve/main/app.py
- Command line
-
hf download hf://spaces/venlacy0/Chat/app.py
-
curl -L -o app.py https://huggingface.co/spaces/venlacy0/Chat/resolve/main/app.py
9.65 kB
| 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)}") | |
| 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}) | |
| 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 | |
| } | |
| }) | |
| def index(): | |
| return "<h1>AI Service Running</h1>", 200 | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=8080) |