Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891 unmodified line11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192932 unmodified lines969798991001011021031041051061071081093 unmodified lines1131141151161171181191201211221231241251261271283 unmodified lines132133134135136137138139140141142143144145146147"""app.py β Advanced Chatbot with Sliding-Window Context Management(OpenAI Python SDK β₯1.0.0)"""import osimport gradio as grimport tiktokenfrom openai import OpenAI1 unmodified line# βββ Initialize OpenAI client βββclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())# βββ Model fallback list (highest quality first) βββ# Comma-separated in env, e.g. "gpt-4-32k,gpt-4,gpt-3.5-turbo"model_list = os.getenv("OPENAI_MODEL_LIST", "gpt-4-32k,gpt-4,gpt-3.5-turbo")MODELS = [m.strip() for m in model_list.split(",") if m.strip()]# βββ Configuration βββMAX_CONTEXT = 32768 # modelβs max context window (e.g. GPT-4-32k)BUFFER_TOKENS = 500 # reserved tokens for the replyREPLY_MAX = 2048 # max tokens in the answerTEMPERATURE = 0.3 # creativity vs. determinismdef count_tokens(text: str, model: str) -> int:"""Return the number of tokens for given text under specified model."""enc = tiktoken.encoding_for_model(model)return len(enc.encode(text))def trim_conversation(convo: list[dict], model: str) -> list[dict]:"""Slide the window: drop oldest user/assistant turnsuntil total tokens + buffer β€ MAX_CONTEXT."""# compute initial usagetokens = [count_tokens(m["content"], model) for m in convo]total = sum(tokens)# pop oldest turns (after system prompt) while over budgetwhile total + BUFFER_TOKENS > MAX_CONTEXT and len(convo) > 2:convo.pop(1) # remove oldest userconvo.pop(1) # remove that assistant replytokens = [count_tokens(m["content"], model) for m in convo]total = sum(tokens)return convodef safe_chat(convo: list[dict]):"""1) Try each model in MODELS in order.2) If model-not-found, skip to next.3) If context-length error, trim history and retry same model once."""last_exc = Nonefor model in MODELS:try:return client.chat.completions.create(model=model,messages=convo,max_tokens=REPLY_MAX,temperature=TEMPERATURE)except Exception as e:msg = str(e).lower()# model not found β fallbackif "does not exist" in msg or "model_not_found" in msg or "404" in msg:last_exc = econtinue# context-length error β trim & retryif "context length" in msg or "maximum context length" in msg:trimmed = trim_conversation(convo.copy(), model)try:return client.chat.completions.create(model=model,messages=trimmed,max_tokens=REPLY_MAX,temperature=TEMPERATURE)except Exception as e2:last_exc = e2continue# other errors β re-raiseraise# none succeededraise last_exc or RuntimeError("All models failed in safe_chat()")def chat_handler(user_message: str,history: list[tuple[str, str]],system_prompt: str) -> tuple[list[tuple[str, str]], str]:"""Gradio handler: builds convo, calls safe_chat, updates history."""if not user_message.strip():2 unmodified linesreturn history, "β OPENAI_API_KEY not set."# Build the conversation payloadconvo = [{"role": "system", "content": system_prompt}]for u, b in history or []:convo.append({"role": "user", "content": u})convo.append({"role": "assistant", "content": b})convo.append({"role": "user", "content": user_message})try:resp = safe_chat(convo)reply = resp.choices[0].message.contentexcept Exception as e:reply = f"β OpenAI error: {e}"3 unmodified linesreturn history, ""# βββ Gradio UI βββwith gr.Blocks(title="π€ Advanced Chatbot (Sliding-Window Context)") as demo:gr.Markdown("""# Advanced ChatbotThis bot preserves your newest input by **sliding** out the oldest historywhen you exceed the model's context windowβno summarization required.It also **automatically falls back** through multiple models if one isnβt available.""")system_txt = gr.Textbox(lines=3,value=(3 unmodified lineslabel="System Prompt")chatbot = gr.Chatbot(label="Conversation")user_input = gr.Textbox(placeholder="Type your message here...", label="You")send_btn = gr.Button("Send")send_btn.click(fn=chat_handler,inputs=[user_input, chatbot, system_txt],outputs=[chatbot, user_input])if __name__ == "__main__":demo.launch()123456789101 unmodified line12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990912 unmodified lines9495969798991001011021031041051061071081091101113 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471483 unmodified lines152153154155156157158159160161162163164165166167168169170171172173"""app.py β Advanced Chatbot with Model Selector, Context & Reply Token Sliders(OpenAI Python SDK β₯1.0.0)"""import osimport asyncioimport gradio as grimport tiktokenfrom openai import OpenAI1 unmodified line# βββ Initialize OpenAI client βββclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())# βββ Environment-configured model list (fallback order) βββenv_models = os.getenv("OPENAI_MODEL_LIST", "gpt-4-32k,gpt-4,gpt-3.5-turbo")ALL_MODELS = [m.strip() for m in env_models.split(",") if m.strip()]# βββ Default limits βββDEFAULT_MAX_CONTEXT = 32768 # tokensDEFAULT_REPLY_MAX = 2048 # tokensBUFFER_TOKENS = 500 # reserved for the modelβs answerTEMPERATURE = 0.3def count_tokens(text: str, model: str) -> int:enc = tiktoken.encoding_for_model(model)return len(enc.encode(text))def trim_conversation(convo: list[dict], model: str, max_context: int) -> list[dict]:"""Slide-window: drop the oldest user/assistant turns untiltotal tokens + BUFFER_TOKENS β€ max_context."""tokens = [count_tokens(m["content"], model) for m in convo]total = sum(tokens)while total + BUFFER_TOKENS > max_context and len(convo) > 2:convo.pop(1) # oldest userconvo.pop(1) # its assistant replytokens = [count_tokens(m["content"], model) for m in convo]total = sum(tokens)return convodef safe_chat(convo: list[dict], max_context: int, max_reply: int, model_list: list[str]):"""Try each model in model_list:- on model-not-found: skip to next- on context-length: trim history & retry same model once"""last_exc = Nonefor model in model_list:try:return client.chat.completions.create(model=model,messages=convo,max_tokens=max_reply,temperature=TEMPERATURE)except Exception as e:msg = str(e).lower()# Model unavailable β fallbackif "does not exist" in msg or "model_not_found" in msg or "404" in msg:last_exc = econtinue# Context-length error β slide window & retryif "context length" in msg or "maximum context length" in msg:trimmed = trim_conversation(convo.copy(), model, max_context)try:return client.chat.completions.create(model=model,messages=trimmed,max_tokens=max_reply,temperature=TEMPERATURE)except Exception as e2:last_exc = e2continue# Other errors β bubble upraise# All models failedraise last_exc or RuntimeError("All models failed in safe_chat()")def chat_handler(user_message: str,history: list[tuple[str, str]],system_prompt: str,selected_model: str,max_context: int,max_reply: int) -> tuple[list[tuple[str, str]], str]:"""Gradio handler: builds convo, calls safe_chat, updates history."""if not user_message.strip():2 unmodified linesreturn history, "β OPENAI_API_KEY not set."# Build the conversation payloadconvo = [{"role":"system","content":system_prompt}]for u, b in history or []:convo.append({"role":"user", "content":u})convo.append({"role":"assistant", "content":b})convo.append({"role":"user","content":user_message})# Prepare model list: user choice first, then the restfallback = [m for m in ALL_MODELS if m != selected_model]models_to_try = [selected_model] + fallbacktry:resp = safe_chat(convo, max_context, max_reply, models_to_try)reply = resp.choices[0].message.contentexcept Exception as e:reply = f"β OpenAI error: {e}"3 unmodified linesreturn history, ""# βββ Gradio UI βββwith gr.Blocks(title="π€ Advanced Chatbot") as demo:gr.Markdown("""# Advanced Chatbot- **Model selector**: pick any supported OpenAI model- **Context slider**: adjust how many tokens of history to keep- **Reply slider**: adjust maximum tokens in the answer- **Sliding-window**: oldest history drops automatically when over limit""")with gr.Row():model_dropdown = gr.Dropdown(choices=ALL_MODELS,value=ALL_MODELS[0],label="Choose Model")context_slider = gr.Slider(minimum=1000, maximum=DEFAULT_MAX_CONTEXT,step=256, value=DEFAULT_MAX_CONTEXT,label="Max Context Tokens")reply_slider = gr.Slider(minimum=100, maximum=8192,step=100, value=DEFAULT_REPLY_MAX,label="Max Reply Tokens")system_txt = gr.Textbox(lines=3,value=(3 unmodified lineslabel="System Prompt")chatbot = gr.Chatbot(label="Conversation")user_input = gr.Textbox(placeholder="Type your message here...", label="You")send_btn = gr.Button("Send")send_btn.click(fn=chat_handler,inputs=[user_input,chatbot,system_txt,model_dropdown,context_slider,reply_slider],outputs=[chatbot, user_input])if __name__ == "__main__":demo.launch()
app.py+75-49