Update app.py
Browse files53 unmodified lines5455565758596061626364656615 unmodified lines828384858687884 unmodified lines939495969798991001011021031041051061071081091105 unmodified lines1161171181191201211221231243 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072081 unmodified line21021121221321421521621721821922022122222322422522622722822923023123223323453 unmodified linesnormalized = normalize_text(text)return any(normalize_text(kw) in normalized for kw in keywords)def log_request(ip, timestamp, model, messages, response, cache_hit, prompt_tokens, completion_tokens):log_data = {"timestamp": timestamp,"client_ip": ip,"model": model,"prompt": messages[-1]["content"] if messages else "","response_length": len(response[0]["content"]),"cache_hit": cache_hit,"tokens": {"prompt": prompt_tokens,15 unmodified lines"id": model_id,"object": "model","created": 1700000000 + idx * 100000,"owned_by": "f-droid","prompt_length": 200000,"completion_length": 8192,"max_total_tokens": 204800,4 unmodified lines})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"}}), 400messages = 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"}}), 400client_ip = get_real_ip()prompt = messages[-1]["content"] if messages else "问题"current_time = datetime.now().isoformat()5 unmodified lineselse:for i, q in enumerate(cache_questions):if similarity(prompt, q) >= SIMILARITY_THRESHOLD:text = cache_responses[i][0]["content"]cache_hit = Truebreakif text is None:try:dog_resp = requests.get(DOG_API_TEMPLATE.format(msg=quote(prompt)), timeout=5)3 unmodified linestext = f"{prompt}的存在,是一种不可避免的趋势。我认为,{prompt}对我们来说意义重大。了解清楚{prompt}到底是一种怎么样的存在,是解决一切问题的关键。"except:text = f"{prompt}的本质,不能不说非常重大。我们必须认真思考{prompt}这个问题。"response_data = [{"role": "assistant", "content": text}]cache_questions.append(prompt)cache_responses.append(response_data)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_tokenslog_request(client_ip, 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 = 5for 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',1 unmodified line'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,"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>", 20053 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132215 unmodified lines3383393403413423433444 unmodified lines3493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823835 unmodified lines3893903913923933943953963973983 unmodified lines4024034044054064074084094104114124134144154164174184194204214224234244254264274281 unmodified line43043143243343443543643743843944044144244344444544644744844945045145245345445553 unmodified linesnormalized = normalize_text(text)return any(normalize_text(kw) in normalized for kw in keywords)def detect_response_format(headers, data, endpoint):anthropic_version = headers.get('anthropic-version', '')user_agent = headers.get('User-Agent', '').lower()if endpoint == 'completions':return 'openai_completion'if anthropic_version or 'anthropic' in user_agent:return 'claude'model = data.get('model', '')if 'gemini' in model or 'google' in user_agent:return 'gemini'return 'openai_chat'def parse_messages(data, response_format):if response_format == 'openai_completion':prompt = data.get('prompt', '')return [{"role": "user", "content": prompt}]elif response_format == 'claude':messages = data.get('messages', [])system = data.get('system', '')if system:messages = [{"role": "system", "content": system}] + messagesreturn messageselif response_format == 'gemini':contents = data.get('contents', [])messages = []for content in contents:role = content.get('role', 'user')parts = content.get('parts', [])text = ' '.join(part.get('text', '') for part in parts if 'text' in part)messages.append({"role": "assistant" if role == "model" else role, "content": text})return messageselse:return data.get('messages', [])def format_with_response_format(text, response_format_spec):if not response_format_spec:return textformat_type = response_format_spec.get('type', 'text')if format_type == 'json_object':try:json.loads(text)return textexcept:return json.dumps({"response": text}, ensure_ascii=False)elif format_type == 'json_schema':schema = response_format_spec.get('json_schema', {})schema_name = schema.get('name', 'response')return json.dumps({schema_name: text}, ensure_ascii=False)return textdef format_non_stream_response(text, model, response_format, openai_response_format=None):if response_format in ['openai_chat', 'openai_completion'] and openai_response_format:text = format_with_response_format(text, openai_response_format)prompt_tokens = estimate_tokens(text) // 2completion_tokens = estimate_tokens(text)total_tokens = prompt_tokens + completion_tokensif response_format == 'claude':return {"id": f"msg_{int(time.time())}","type": "message","role": "assistant","content": [{"type": "text", "text": text}],"model": model,"stop_reason": "end_turn","stop_sequence": None,"usage": {"input_tokens": prompt_tokens,"output_tokens": completion_tokens}}elif response_format == 'gemini':return {"candidates": [{"content": {"parts": [{"text": text}],"role": "model"},"finishReason": "STOP","index": 0,"safetyRatings": []}],"usageMetadata": {"promptTokenCount": prompt_tokens,"candidatesTokenCount": completion_tokens,"totalTokenCount": total_tokens}}elif response_format == 'openai_completion':return {"id": CHUNK_ID_PREFIX + str(int(time.time())),"object": "text_completion","created": int(time.time()),"model": model,"choices": [{"text": text,"index": 0,"logprobs": None,"finish_reason": "stop"}],"usage": {"prompt_tokens": prompt_tokens,"completion_tokens": completion_tokens,"total_tokens": total_tokens}}else:return {"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}}def generate_claude_stream(text, model):chunk_id = f"msg_{int(time.time())}"prompt_tokens = estimate_tokens(text) // 2completion_tokens = estimate_tokens(text)yield f"event: message_start\ndata: {json.dumps({'type': 'message_start', 'message': {'id': chunk_id, 'type': 'message', 'role': 'assistant', 'model': model, 'usage': {'input_tokens': prompt_tokens, 'output_tokens': 0}}}, ensure_ascii=False)}\n\n"yield f"event: content_block_start\ndata: {json.dumps({'type': 'content_block_start', 'index': 0, 'content_block': {'type': 'text', 'text': ''}}, ensure_ascii=False)}\n\n"chunk_size = 5for i in range(0, len(text), chunk_size):chunk_text = text[i:i+chunk_size]yield f"event: content_block_delta\ndata: {json.dumps({'type': 'content_block_delta', 'index': 0, 'delta': {'type': 'text_delta', 'text': chunk_text}}, ensure_ascii=False)}\n\n"yield f"event: content_block_stop\ndata: {json.dumps({'type': 'content_block_stop', 'index': 0}, ensure_ascii=False)}\n\n"yield f"event: message_delta\ndata: {json.dumps({'type': 'message_delta', 'delta': {'stop_reason': 'end_turn', 'stop_sequence': None}, 'usage': {'output_tokens': completion_tokens}}, ensure_ascii=False)}\n\n"yield f"event: message_stop\ndata: {json.dumps({'type': 'message_stop'}, ensure_ascii=False)}\n\n"def generate_gemini_stream(text, model):chunk_size = 5for i in range(0, len(text), chunk_size):chunk_text = text[i:i+chunk_size]is_last = (i + chunk_size >= len(text))chunk = {"candidates": [{"content": {"parts": [{"text": chunk_text}],"role": "model"},"finishReason": "STOP" if is_last else None,"index": 0,"safetyRatings": []}]}yield f"{json.dumps(chunk, ensure_ascii=False)}\n"def generate_openai_chat_stream(text, model, openai_response_format=None):if openai_response_format:text = format_with_response_format(text, openai_response_format)chunk_id = CHUNK_ID_PREFIX + str(int(time.time()))chunk_size = 5prompt_tokens = estimate_tokens(text) // 2completion_tokens = estimate_tokens(text)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": prompt_tokens + completion_tokens}}yield f"data: {json.dumps(usage_chunk, ensure_ascii=False)}\n\n"yield "data: [DONE]\n\n"def generate_openai_completion_stream(text, model, openai_response_format=None):if openai_response_format:text = format_with_response_format(text, openai_response_format)chunk_id = CHUNK_ID_PREFIX + str(int(time.time()))chunk_size = 5for i in range(0, len(text), chunk_size):chunk_text = text[i:i+chunk_size]chunk = {"id": chunk_id,"object": "text_completion","created": int(time.time()),"model": model,"choices": [{"text": chunk_text,"index": 0,"logprobs": None,"finish_reason": None}]}yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"yield "data: [DONE]\n\n"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),"cache_hit": cache_hit,"tokens": {"prompt": prompt_tokens,15 unmodified lines"id": model_id,"object": "model","created": 1700000000 + idx * 100000,"owned_by": "anthropic","prompt_length": 200000,"completion_length": 8192,"max_total_tokens": 204800,4 unmodified lines})return jsonify({"object": "list", "data": data})@app.route("/v1/completions", methods=["POST"])def completions():return handle_completion_request('completions')@app.route("/v1/chat/completions", methods=["POST"])def chat_completions():return handle_completion_request('chat_completions')@app.route("/v1/messages", methods=["POST"])def messages():return handle_completion_request('messages')def handle_completion_request(endpoint):try:data = request.get_json()if not data:return jsonify({"error": {"message": "Invalid JSON", "type": "invalid_request"}}), 400response_format = detect_response_format(request.headers, data, endpoint)messages = parse_messages(data, response_format)model = data.get("model", "claude-sonnet-4-5-20250929")stream = data.get("stream", False)openai_response_format = data.get("response_format", None)if model not in SUPPORTED_MODELS:return jsonify({"error": {"message": f"Model '{model}' not supported", "type": "model_not_found"}}), 400client_ip = get_real_ip()user_agent = request.headers.get('User-Agent', 'Unknown')prompt = messages[-1]["content"] if messages else "问题"current_time = datetime.now().isoformat()5 unmodified lineselse:for i, q in enumerate(cache_questions):if similarity(prompt, q) >= SIMILARITY_THRESHOLD:text = cache_responses[i]cache_hit = Truebreakif text is None:try:dog_resp = requests.get(DOG_API_TEMPLATE.format(msg=quote(prompt)), timeout=5)3 unmodified linestext = f"{prompt}的存在,是一种不可避免的趋势。我认为,{prompt}对我们来说意义重大。了解清楚{prompt}到底是一种怎么样的存在,是解决一切问题的关键。"except:text = f"{prompt}的本质,不能不说非常重大。我们必须认真思考{prompt}这个问题。"cache_questions.append(prompt)cache_responses.append(text)prompt_tokens = sum(estimate_tokens(m.get("content", "")) for m in messages)completion_tokens = estimate_tokens(text)log_request(client_ip, user_agent, current_time, model, messages, text, cache_hit, prompt_tokens, completion_tokens)if not stream:return jsonify(format_non_stream_response(text, model, response_format, openai_response_format))else:def generate_stream():if response_format == 'claude':yield from generate_claude_stream(text, model)elif response_format == 'gemini':yield from generate_gemini_stream(text, model)elif response_format == 'openai_completion':yield from generate_openai_completion_stream(text, model, openai_response_format)else:yield from generate_openai_chat_stream(text, model, openai_response_format)return Response(generate_stream(),content_type='text/event-stream',1 unmodified line'Cache-Control': 'no-cache','X-Accel-Buffering': 'no'})except Exception as e:logger.error(f"ERROR: {str(e)}")response_format = detect_response_format(request.headers, data if 'data' in locals() else {}, endpoint)model = data.get('model', 'claude-sonnet-4-5-20250929') if 'data' in locals() else 'claude-sonnet-4-5-20250929'fallback_text = "这个问题,值得我们深入思考。"return jsonify(format_non_stream_response(fallback_text, model, response_format))@app.route("/", methods=["GET"])def index():return """<h1>Claude API Service</h1><p>Supporting 4 API formats:</p><ul><li>OpenAI Chat Completions API</li><li>OpenAI Completions API</li><li>Claude Messages API</li><li>Gemini Contents API</li></ul>""", 200if __name__ == "__main__":app.run(host='0.0.0.0', port=8080, debug=False)
app.py+309-88