Spaces:
Sleeping
Sleeping
Update app.py
Browse files10 unmodified lines11121314151617181920217 unmodified lines2930313233343536373839404 unmodified lines45464748495051522 unmodified lines555657585960611 unmodified line636465666768697071727374757677787980818283848586878889909110 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414510 unmodified lines# 1 · Initialization & Constantsclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())MODEL_DETAILS = {# ... same details as before ...}_env = os.getenv("OPENAI_MODEL_LIST", "gpt-4o,gpt-4o-mini,gpt-3.5-turbo")ALL_MODELS = [m for m in _env.split(",") if m in MODEL_DETAILS] or list(MODEL_DETAILS.keys())DEFAULT_MAX_CONTEXT = MODEL_DETAILS[ALL_MODELS[0]]["max_context"]BUFFER_TOKENS, DEFAULT_REPLY_MAX, TEMPERATURE = 500, 2048, 0.37 unmodified linesreturn len(enc.encode(text))def trim_conversation(convo: List[Dict], model: str, max_context: int) -> List[Dict]:if not convo: return []kept, total = [convo[0]], count_tokens(convo[0]["content"], model)for msg in reversed(convo[1:]):t = count_tokens(msg["content"], model)if total + t + BUFFER_TOKENS > max_context: breakkept.insert(1, msg); total += treturn kept# 3 · Streaming API Helper4 unmodified linestry:trimmed = trim_conversation(convo, m, MODEL_DETAILS[m]["max_context"])stream = client.chat.completions.create(model=m, messages=trimmed, max_tokens=max_rep,temperature=TEMPERATURE, stream=True)reply = ""for chunk in stream:2 unmodified linesyield reply, None, mreturnexcept Exception as e:last_exc = e; continueraise last_exc or RuntimeError("All models failed.")# 4 · Gradio Chat Functions1 unmodified linedef chat_stream(user_msg: str, history: List[Tuple[str,str]], sys_prompt: str,sel_model: str, ctx: int, rep: int, file) -> Tuple:if not user_msg and not file:yield history, '', '⚠️ Enter prompt or upload file.', None; returnif not client.api_key:yield history+[('', '❌ API KEY MISSING')], '', '🚨 Set API_KEY', None; returncontent = ''if file:with open(file.name) as f: content = f.read()user_msg += f"\n\n---FILE---\n{content}"convo = [{'role':'system','content':sys_prompt}]for u,a in history: convo += [{'role':'user','content':u},{'role':'assistant','content':a}]convo.append({'role':'user','content':user_msg}); history.append((user_msg,''))yield history, '', f'⏳ Connecting to {sel_model}...', Nonemodels = [sel_model]+[m for m in ALL_MODELS if m!=sel_model]acc = ''try:for part,_,m in safe_chat_stream(convo,ctx,rep,models):acc=part; history[-1]=(user_msg,acc)yield history,'',f'💡 Streaming {m}...',Noneyield history,'','✅ Complete',Noneexcept Exception as e:history[-1]=(user_msg,f'❌ {e}')yield history,'',f'🚫 Error: {e}',Nonedef clear_chat(): return [], '', '🔄 Reset.', None, None# 5 · Ultra Synthwave CSS & JSCSS = """10 unmodified lines"""JS = """// Dark mode & sundocument.documentElement.classList.add('dark');var sun=document.createElement('div');sun.id='sun';document.body.appendChild(sun);// Matrix rainvar c=document.createElement('canvas');c.id='matrix';document.body.appendChild(c);var ctx=c.getContext('2d');c.width=innerWidth;c.height=innerHeight;var cols=c.width/20;var drops=[];for(var x=0;x<cols;x++)drops[x]=1;function draw(){ctx.fillStyle='rgba(0,0,0,0.05)';ctx.fillRect(0,0,c.width,c.height);ctx.fillStyle='#0f0';ctx.font='20px monospace';for(var i=0;i<drops.length;i++){var text=String.fromCharCode(0x30A0+Math.random()*96);ctx.fillText(text,i*20,drops[i]*20);if(drops[i]*20>c.height||Math.random()>0.975)drops[i]=0;drops[i]++;}}setInterval(draw,50);// Flicker effectsetInterval(()=>document.body.style.opacity=Math.random()>0.95?0.9:1,100);"""theme=gr.themes.Base(primary_hue=gr.themes.Color("#0ff","#0ee","#0dd","#0cc","#0bb"),neutral_hue=gr.themes.Color("#000","#111","#222","#333","#444"))with gr.Blocks(title="JadeGPT Synthwave Ultra",theme=theme,analytics_enabled=False) as demo:gr.HTML(f"""<style>{CSS}</style><script>{JS}</script><div id='title'>🌃 JADEGPT ULTRA</div>""")status=gr.Markdown('🏙️ SYSTEM ONLINE',elem_id='status')with gr.Tab('⚡ Chat'):sys=gr.Textbox('You are JadeGPT... Ultra Mode.',lines=2)chat=gr.Chatbot([],height=400)with gr.Row():inp=gr.Textbox(placeholder='Jack into the mainframe...')send=gr.Button('TRANSMIT',variant='primary')clear=gr.Button('RESET',variant='secondary')with gr.Tab('⚙️ Settings'):mdl=gr.Dropdown(ALL_MODELS,value=ALL_MODELS[0],label='Model')ctx=gr.Slider(1000,DEFAULT_MAX_CONTEXT,256,value=DEFAULT_MAX_CONTEXT,label='Context')rep=gr.Slider(100,4096,100,value=DEFAULT_REPLY_MAX,label='Max Reply')send.click(chat_stream,[inp,chat,sys,mdl,ctx,rep,None],[chat,inp,status])inp.submit(chat_stream,[inp,chat,sys,mdl,ctx,rep,None],[chat,inp,status])clear.click(clear_chat,[],[chat,inp,status])demo.launch()10 unmodified lines1112131415161718192021222324252627282930317 unmodified lines3940414243444546474849505152534 unmodified lines58596061626364656667682 unmodified lines71727374757677781 unmodified line808182838485868788899091929394959697989910010110210310410510610710810911011111211310 unmodified lines12412512612710 unmodified lines# 1 · Initialization & Constantsclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())MODEL_DETAILS: Dict[str, Dict] = {"gpt-4o": {"input_price": 5.00, "output_price": 15.00, "max_context": 128_000, "description": "OpenAI's most capable and cost-effective multimodal model."},"gpt-4o-mini": {"input_price": 0.15, "output_price": 0.60, "max_context": 128_000, "description": "Highly affordable and fast, suitable for simpler tasks."},"o3": {"input_price": 2.00, "output_price": 8.00, "max_context": 200_000, "description": "Designed for complex reasoning and step-by-step problem-solving."},"o3-pro": {"input_price": 20.00, "output_price": 80.00, "max_context": 200_000, "description": "Premium reasoning model for high-stakes tasks, higher accuracy."},"o4-mini": {"input_price": 1.10, "output_price": 4.40, "max_context": 200_000, "description": "Balanced multimodal model, good for image+text on a budget."},"gpt-4-32k": {"input_price": 0.06, "output_price": 0.12, "max_context": 32_768, "description": "Larger context GPT-4 model (older generation)."},"gpt-4": {"input_price": 0.03, "output_price": 0.06, "max_context": 8_192, "description": "Original GPT-4 model (older generation)."},"gpt-3.5-turbo": {"input_price": 0.001, "output_price": 0.002,"max_context": 16_385, "description": "Cost-effective, fast, and good for general-purpose tasks."},}_env = os.getenv("OPENAI_MODEL_LIST", "gpt-4o,gpt-4o-mini,gpt-3.5-turbo")ALL_MODELS: List[str] = [m.strip() for m in _env.split(",") if m.strip() in MODEL_DETAILS]if not ALL_MODELS:ALL_MODELS = list(MODEL_DETAILS.keys())DEFAULT_MAX_CONTEXT = MODEL_DETAILS[ALL_MODELS[0]]["max_context"]BUFFER_TOKENS, DEFAULT_REPLY_MAX, TEMPERATURE = 500, 2048, 0.37 unmodified linesreturn len(enc.encode(text))def trim_conversation(convo: List[Dict], model: str, max_context: int) -> List[Dict]:if not convo:return []kept, total = [convo[0]], count_tokens(convo[0]["content"], model)for msg in reversed(convo[1:]):t = count_tokens(msg["content"], model)if total + t + BUFFER_TOKENS > max_context:breakkept.insert(1, msg)total += treturn kept# 3 · Streaming API Helper4 unmodified linestry:trimmed = trim_conversation(convo, m, MODEL_DETAILS[m]["max_context"])stream = client.chat.completions.create(model=m,messages=trimmed,max_tokens=max_rep,temperature=TEMPERATURE,stream=True,)reply = ""for chunk in stream:2 unmodified linesyield reply, None, mreturnexcept Exception as e:last_exc = econtinueraise last_exc or RuntimeError("All models failed.")# 4 · Gradio Chat Functions1 unmodified linedef chat_stream(user_msg: str, history: List[Tuple[str,str]], sys_prompt: str,sel_model: str, ctx: int, rep: int, file) -> Tuple:if not user_msg and not file:yield history, '', '⚠️ Enter prompt or upload file.', Nonereturnif not client.api_key:yield history + [('', '❌ API KEY MISSING')], '', '🚨 Set API_KEY', Nonereturnif file:with open(file.name, 'r', encoding='utf-8') as f:content = f.read()user_msg += f"\n\n---FILE UPLOAD---\n{content}"convo = [{'role': 'system', 'content': sys_prompt}]for u, a in history:convo += [{'role': 'user', 'content': u}, {'role': 'assistant', 'content': a}]convo.append({'role': 'user', 'content': user_msg})history.append((user_msg, ''))yield history, '', f'⏳ Connecting to {sel_model}...', Nonemodels = [sel_model] + [m for m in ALL_MODELS if m != sel_model]try:for part, _, m in safe_chat_stream(convo, ctx, rep, models):history[-1] = (user_msg, part)yield history, '', f'💡 Streaming {m}...', Noneyield history, '', '✅ Complete', Noneexcept Exception as e:history[-1] = (user_msg, f'❌ {e}')yield history, '', f'🚫 Error: {e}', Nonedef clear_chat():return [], '', '🔄 Reset.', None, None# 5 · Ultra Synthwave CSS & JSCSS = """10 unmodified lines"""JS = """// Dark mode & sun...
app.py+49-67