Spaces:
Runtime error
Runtime error
Update app.py
Browse files6 unmodified lines789101112139 unmodified lines232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110245 unmodified lines1481491501511526 unmodified lines# Load secretsPAYWALLS_API_KEY = os.environ.get("PAYWALLS_API_KEY")PAYWALLS_API_URL = os.environ.get("PAYWALLS_API_URL", "https://api.paywalls.ai/v1")HF_MODEL = "openai/gpt-oss-20b"# Free tier limitsFREE_MAX_TOKENS = 1509 unmodified lines}def check_paywall(user_id: str):headers = {"Authorization": f"Bearer {PAYWALLS_API_KEY}","X-Paywall-User": user_id}try:resp = requests.get(f"{PAYWALLS_API_URL}/user/connect?user={user_id}", headers=headers, timeout=10)resp.raise_for_status()data = resp.json()return data.get("connected", False), data.get('url', '')except Exception as e:print(f"[Paywall] Error: {e}")return False, ""def chat_completion(user_id, system_message, history, user_message, max_tokens, temperature, top_p):headers = {"Authorization": f"Bearer {PAYWALLS_API_KEY}","Content-Type": "application/json","X-Paywall-User": user_id}messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": user_message}]payload = {"model": HF_MODEL,"messages": messages,"stream": False,"user": user_id,"max_tokens": max_tokens,"temperature": temperature,"top_p": top_p}try:response = requests.post(f"{PAYWALLS_API_URL}/chat/completions", headers=headers, json=payload, timeout=60)response.raise_for_status()data = response.json()choices = data.get("choices", [])if choices:return choices[0]["message"]["content"]return "No response from model."except Exception as e:print(f"[Paywall] Error: {e}")return f"Error: {e}"def respond(message, history, style, max_tokens, temperature, top_p):user_id = "demo_user"is_premium, paywall_url = check_paywall(user_id)if not is_premium:max_tokens = min(max_tokens, FREE_MAX_TOKENS)if style != "neutral":return history + [{"role": "assistant", "content": f"🔒 Style customization requires premium. [Unlock here]({paywall_url})"}]# FREE TIER: Use direct Hugging Face APItry:from huggingface_hub import InferenceClientclient = InferenceClient()reply = client.chat_completion(messages=[{"role": "system", "content": STYLE_PRESETS["neutral"]}] + history + [{"role": "user", "content": message}],max_tokens=max_tokens,temperature=temperature).choices[0].message.contentreturn history + [{"role": "user", "content": message}, {"role": "assistant", "content": f"{reply}\n\n---\n_🆓 FREE_"}]except Exception as e:print(f"[Free Tier] Error: {e}")return history + [{"role": "assistant", "content": f"⚠️ Service temporarily unavailable. Error: {e}"}]# PREMIUM: Use Paywalls APIsystem_message = STYLE_PRESETS.get(style, STYLE_PRESETS["neutral"])reply = chat_completion(user_id, system_message, history, message, max_tokens, temperature, top_p)if "Error:" in reply:return history + [{"role": "assistant", "content": f"⚠️ {reply}"}]return history + [{"role": "user", "content": message}, {"role": "assistant", "content": f"{reply}\n\n---\n_✨ PREMIUM_"}]def export_conversation(history):user_id = "demo_user"45 unmodified linesexport_btn.click(export_conversation, [chatbot], [download_file, export_status])if __name__ == "__main__":demo.launch()```6 unmodified lines7891011129 unmodified lines22232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212345 unmodified lines1691701711726 unmodified lines# Load secretsPAYWALLS_API_KEY = os.environ.get("PAYWALLS_API_KEY")PAYWALLS_API_URL = os.environ.get("PAYWALLS_API_URL", "https://api.paywalls.ai/v1")# Free tier limitsFREE_MAX_TOKENS = 1509 unmodified lines}def check_paywall(user_id: str):"""Check if user has active premium subscription"""headers = {"Authorization": f"Bearer {PAYWALLS_API_KEY}"}try:resp = requests.get(f"{PAYWALLS_API_URL}/users/{user_id}", headers=headers, timeout=10)resp.raise_for_status()data = resp.json()# Check if user has active subscriptionis_connected = data.get("status") == "active" or data.get("connected", False)paywall_url = f"https://paywalls.ai/connect?api_key={PAYWALLS_API_KEY}&user={user_id}"return is_connected, paywall_urlexcept Exception as e:print(f"[Paywall] Check error: {e}")return False, f"https://paywalls.ai/connect?api_key={PAYWALLS_API_KEY}&user={user_id}"def free_tier_generation(system_message, history, user_message, max_tokens, temperature):"""Free tier using Hugging Face Inference API"""try:from huggingface_hub import InferenceClientclient = InferenceClient()messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": user_message}]reply = client.chat_completion(messages=messages,max_tokens=max_tokens,temperature=temperature).choices[0].message.contentreturn replyexcept Exception as e:print(f"[Free Tier] Error: {e}")return f"⚠️ Free tier service error: {str(e)}"def premium_generation(user_id, system_message, history, user_message, max_tokens, temperature, top_p):"""Premium tier using Paywalls proxy"""headers = {"Authorization": f"Bearer {PAYWALLS_API_KEY}","Content-Type": "application/json"}messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": user_message}]# Using Paywalls proxy endpoint - adjust model based on your Paywalls setuppayload = {"model": "gpt-3.5-turbo", # Use model available in your Paywalls account"messages": messages,"max_tokens": max_tokens,"temperature": temperature,"top_p": top_p,"user": user_id}try:response = requests.post(f"{PAYWALLS_API_URL}/chat/completions",headers=headers,json=payload,timeout=60)response.raise_for_status()data = response.json()if data.get("choices"):return data["choices"][0]["message"]["content"]return "No response from premium model."except requests.exceptions.HTTPError as e:print(f"[Premium] HTTP Error: {e.response.status_code} - {e.response.text}")return f"⚠️ Premium service error: {e.response.status_code}"except Exception as e:print(f"[Premium] Error: {e}")return f"⚠️ Premium service error: {str(e)}"def respond(message, history, style, max_tokens, temperature, top_p):user_id = "demo_user" # Replace with actual user sessionis_premium, paywall_url = check_paywall(user_id)# Check style restriction for free usersif not is_premium:max_tokens = min(max_tokens, FREE_MAX_TOKENS)if style != "neutral":return history + [{"role": "assistant", "content": f"🔒 Style customization requires premium. [Unlock here]({paywall_url})"}]system_message = STYLE_PRESETS.get(style, STYLE_PRESETS["neutral"])# Generate response based on tierif is_premium:reply = premium_generation(user_id, system_message, history, message, max_tokens, temperature, top_p)tier_badge = "✨ PREMIUM"else:reply = free_tier_generation(system_message, history, message, max_tokens, temperature)tier_badge = "🆓 FREE"full_reply = f"{reply}\n\n---\n_{tier_badge}_"return history + [{"role": "user", "content": message}, {"role": "assistant", "content": full_reply}]def export_conversation(history):user_id = "demo_user"45 unmodified linesexport_btn.click(export_conversation, [chatbot], [download_file, export_status])if __name__ == "__main__":demo.launch()
app.py+63-43