Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234569 unmodified lines16171819202122232425267 unmodified lines34353637383940414243444546474849506 unmodified lines57585960616263646566676 unmodified lines74757677787980818210 unmodified lines9394959697989914 unmodified lines1141151161171181191201211221231241251261271281 unmodified line1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591607 unmodified lines168169170171172173"""app.py β Advanced Chatbot with Model Selector, Context & Reply Token Sliders(OpenAI Python SDK β₯1.0.0)"""import os9 unmodified linesenv_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)7 unmodified linestokens = [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:6 unmodified lines)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:6 unmodified linesexcept 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(10 unmodified linesif not client.api_key:return 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})14 unmodified lineshistory.append((user_message, reply))return 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""")1 unmodified linemodel_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=("You are an expert software engineer specializing in Python and C#. ""Provide detailed, production-grade answers and include code snippets when appropriate."),label="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,7 unmodified lines],outputs=[chatbot, user_input])if __name__ == "__main__":demo.launch()1234569 unmodified lines16171819202122232425267 unmodified lines34353637383940414243444546474849506 unmodified lines57585960616263646566676 unmodified lines74757677787980818210 unmodified lines9394959697989914 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391 unmodified line1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002017 unmodified lines209210211212213214215216217218"""app.py β Cool Coding Assistant with Model Selector, Context/Reply Sliders, Examples & Clear Chat(OpenAI Python SDK β₯1.0.0 + Gradio 5.34.1 + tiktoken)"""import os9 unmodified linesenv_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()]# βββ Configuration βββDEFAULT_MAX_CONTEXT = 32768 # tokensBUFFER_TOKENS = 500 # reserved for the modelβs replyDEFAULT_REPLY_MAX = 2048 # tokens for the answerTEMPERATURE = 0.3 # creativity vs determinismdef count_tokens(text: str, model: str) -> int:enc = tiktoken.encoding_for_model(model)7 unmodified linestokens = [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) # remove oldest userconvo.pop(1) # remove corresponding 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]):"""1) Try each model in model_list in order.2) On model-not-found: skip to next.3) On context-length error: trim history & retry same model once."""last_exc = Nonefor model in model_list:6 unmodified lines)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 β trim & retryif "context length" in msg or "maximum context length" in msg:trimmed = trim_conversation(convo.copy(), model, max_context)try:6 unmodified linesexcept Exception as e2:last_exc = e2continue# other errors β bubble upraise# none succeededraise last_exc or RuntimeError("All models failed in safe_chat()")def chat_handler(10 unmodified linesif not client.api_key:return history, "β OPENAI_API_KEY not set."# Build conversation payloadconvo = [{"role":"system","content":system_prompt}]for u, b in history or []:convo.append({"role":"user", "content":u})14 unmodified lineshistory.append((user_message, reply))return history, ""def clear_chat_handler() -> list:"""Clear all previous chat messages."""return []# βββ Gradio UI βββwith gr.Blocks(title="π€ CodeBot: Your Cool Coding Assistant",theme=gr.themes.SoftDark()) as demo:gr.Markdown("""## CodeBotA stylish coding assistant with:- **Model selector**: pick your LLM- **Context slider**: control how much history to keep- **Reply slider**: set max response length- **Examples**: load sample coding questions- **Clear Chat**: reset conversation anytime- **Sliding-window**: auto-drop oldest history when over limit""")1 unmodified linemodel_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")# Example questionsexamples = ["How do I implement quicksort in Python?","Show me a C# example using LINQ to group items.","Explain async/await in Python with sample code.","How to connect to SQL Server using C#?"]with gr.Row():example_dropdown = gr.Dropdown(choices=examples,label="π‘ Examples")example_btn = gr.Button("π₯ Load Example")example_btn.click(fn=lambda q: q or "",inputs=[example_dropdown],outputs=[gr.update(component_id="user_input")])system_txt = gr.Textbox(lines=3,value=("You are CodeBot, an expert software engineer specializing in Python and C#. ""Provide detailed, production-grade answers including runnable code snippets."),label="π» System Prompt")chatbot = gr.Chatbot(value=[("", "π Hello! I'm CodeBot. How can I help you with code today?")],label="π¬ Conversation",height=500)user_input = gr.Textbox(placeholder="Type your question or paste code here...",label="π Your Message",elem_id="user_input")with gr.Row():send_btn = gr.Button("π Send")clear_btn = gr.Button("ποΈ Clear Chat", variant="secondary")send_btn.click(fn=chat_handler,7 unmodified lines],outputs=[chatbot, user_input])clear_btn.click(fn=clear_chat_handler,outputs=[chatbot])if __name__ == "__main__":demo.launch()
app.py+76-31