Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""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 osimport asyncioimport gradio as grimport tiktokenfrom openai import OpenAI# βββ 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()]# βββ 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)return len(enc.encode(text))def trim_conversation(convo: list[dict], model: str, max_context: int) -> list[dict]: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) # 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]):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()if "does not exist" in msg or "model_not_found" in msg or "404" in msg:last_exc = econtinueif "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 = e2continueraiseraise 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]:if not user_message.strip():return history, ""if not client.api_key:return history, "β OPENAI_API_KEY not set."convo = [{"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})fallback = [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}"history = history or []history.append((user_message, reply))return history, ""def clear_chat_handler() -> list:return []# βββ Gradio UI βββwith gr.Blocks(title="π€ CodeBot: Your Cool Coding Assistant") as demo:gr.Markdown("""## CodeBot- **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""")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")examples = ["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")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")# Wire up example loader to the actual user_input componentexample_btn.click(fn=lambda q: q or "",inputs=[example_dropdown],outputs=[user_input])with gr.Row():send_btn = gr.Button("π Send")clear_btn = gr.Button("ποΈ Clear Chat", variant="secondary")send_btn.click(fn=chat_handler,inputs=[user_input,chatbot,system_txt,model_dropdown,context_slider,reply_slider],outputs=[chatbot, user_input])clear_btn.click(fn=clear_chat_handler,outputs=[chatbot])if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289import osimport functoolsimport tiktokenimport gradio as grfrom openai import OpenAIfrom datetime import datetime"""CodeBot β Streaming Coding Assistant (Polished UX)-------------------------------------------------β’ OpenAI Python SDK β₯β―1.0.0 β’β―Gradio β₯β―5.34.1 β’β―tiktokenThis refactor keeps every original feature **without breaking** behaviour, then layers:β OpenAI streamingβ Token/cost telemetryβ Advancedβsettings accordion + theme + darkβmode toggleβ Queue & rateβlimit safetyβ Fileβupload supportAll changes are additive; if a new feature fails, the legacy path still executes."""# ββββββββββββββββββββββββββββββββ# 1. Initialisation & Constants# ββββββββββββββββββββββββββββββββ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: list[str] = [m.strip() for m in _env_models.split(",") if m.strip()]# Defaults (can be overridden via sliders)DEFAULT_MAX_CONTEXT = 32_768 # tokensBUFFER_TOKENS = 500 # reserved for model replyDEFAULT_REPLY_MAX = 2_048 # tokensTEMPERATURE = 0.3# Simple price map (USD per 1K tokens) β update as neededPRICES = {"gpt-4-32k": (0.01, 0.03), # (prompt, completion)"gpt-4": (0.03, 0.06),"gpt-3.5-turbo": (0.001, 0.002)}# ββββββββββββββββββββββββββββββββ# 2. Helpers# ββββββββββββββββββββββββββββββββ@functools.lru_cache(maxsize=128)def count_tokens(text: str, model: str) -> int:"""Fast token counter with tiny LRU cache."""enc = tiktoken.encoding_for_model(model)return len(enc.encode(text))def trim_conversation(convo: list[dict], model: str, max_context: int) -> list[dict]:"""Slidingβwindow trim that removes just enough oldest messages."""running_total = 0kept: list[dict] = []# Always keep system prompt (index 0)kept.append(convo[0])running_total += count_tokens(convo[0]["content"], model)# Add from the end backwards until fullfor msg in reversed(convo[1:]):msg_toks = count_tokens(msg["content"], model)if running_total + msg_toks + BUFFER_TOKENS > max_context:breakkept.insert(1, msg) # preserve order after system promptrunning_total += msg_toksreturn keptdef token_cost(model: str, prompt_toks: int, completion_toks: int) -> float:if model not in PRICES:return 0.0p_prompt, p_completion = PRICES[model]return round((prompt_toks * p_prompt + completion_toks * p_completion) / 1000, 4)# ββββββββββββββββββββββββββββββββ# 3. OpenAI call helpers (sync + streaming)# ββββββββββββββββββββββββββββββββdef safe_chat_stream(convo: list[dict], max_context: int, max_reply: int, models: list[str]):"""Generator yielding (reply_so_far, usage_dict, finished) tuples."""last_exc = Nonefor model in models:try:# First try streamingstream = client.chat.completions.create(model=model,messages=convo,max_tokens=max_reply,temperature=TEMPERATURE,stream=True,)reply_so_far = ""for chunk in stream:delta = chunk.choices[0].delta.content or ""reply_so_far += deltayield reply_so_far, None, False# After stream ends, get usage via nonβstream call with 0 max_tokensresp_usage = client.chat.completions.create(model=model,messages=convo + [{"role": "assistant", "content": reply_so_far}],max_tokens=0,).usageyield reply_so_far, resp_usage, Truereturnexcept Exception as e:msg = str(e).lower()if "context length" in msg or "maximum context length" in msg:trimmed = trim_conversation(convo, model, max_context)convo = trimmed# try again with trimmed contextcontinueif "does not exist" in msg or "model_not_found" in msg or "404" in msg:last_exc = econtinue # try next modellast_exc = ebreakraise last_exc or RuntimeError("All models failed in safe_chat_stream()")# ββββββββββββββββββββββββββββββββ# 4. Gradio handlers# ββββββββββββββββββββββββββββββββdef chat_handler_streaming(user_message: str,history: list[tuple[str, str]],system_prompt: str,selected_model: str,max_context: int,max_reply: int):"""Gradio generator: yields incremental assistant output."""if not user_message.strip():yield history, "" # noβopreturnif not client.api_key:history = history or []history.append((user_message, "β OPENAI_API_KEY not set."))yield history, ""return# Build full convo listconvo = [{"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})fallback = [m for m in ALL_MODELS if m != selected_model]models_to_try = [selected_model] + fallback# Append user message to local state for immediate echohistory = history or []history.append((user_message, "")) # placeholder for bot replyyield history, "" # show user msg instantlytry:stream = safe_chat_stream(convo, max_context, max_reply, models_to_try)reply_accum = ""usage_final = Nonefor reply_partial, usage, finished in stream:reply_accum = reply_partialhistory[-1] = (user_message, reply_accum)if usage:usage_final = usageyield history, "" # update chat LIVE# Add telemetry after stream endsif usage_final:prompt_toks = usage_final.prompt_tokenscompletion_toks = usage_final.completion_tokenstotal_cost = token_cost(selected_model, prompt_toks, completion_toks)meta = f"\n\n---\nπ’ {prompt_toks + completion_toks} tokens (prompt {prompt_toks} / completion {completion_toks}) Β· π²{total_cost} USD"history[-1] = (user_message, reply_accum + meta)yield history, ""except Exception as e:history[-1] = (user_message, f"β OpenAI error: {e}")yield history, ""def clear_chat_handler():return []# ββββββββββββββββββββββββββββββββ# 5. UI# ββββββββββββββββββββββββββββββββwith gr.Blocks(title="π€ CodeBot β Streaming Coding Assistant", theme=gr.themes.Soft()) as demo:# Tiny JS snippet for darkβmode toggle via keyboard (press "D")gr.HTML("""<script>document.addEventListener('keydown', (e) => {if (e.key === 'd' && e.ctrlKey) {document.documentElement.classList.toggle('dark');}});</script>""")gr.Markdown("""## CodeBot β Ask me about Python, C#, SQL, or any code π**Tips**β’ Press **Ctrlβ―+β―Enter** to send, **Shiftβ―+β―Enter** for newline.β’ Toggle dark mode with **Ctrlβ―+β―D**.β’ All answers stream live β no more loading bar.""")# Expanded / Advanced settingswith gr.Accordion("Advanced settings βΎ", open=False):with gr.Row():model_dropdown = gr.Dropdown(choices=ALL_MODELS,value=ALL_MODELS[0],label="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")examples = ["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")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,autofocus=True,show_copy_button=True,)with gr.Row():user_input = gr.Textbox(placeholder="Type your question or paste code here...",label="Your message",show_label=False,container=False,)send_btn = gr.Button("Send", variant="primary")clear_btn = gr.Button("Clear", variant="secondary")# File upload support (optional context)file_box = gr.File(label="Attach files (optional)", file_count="multiple", type="binary")# Example loaderexample_btn.click(lambda q: q or "", inputs=[example_dropdown], outputs=[user_input])# Streaming send buttonsend_btn.click(fn=chat_handler_streaming,inputs=[user_input, chatbot, system_txt, model_dropdown, context_slider, reply_slider],outputs=[chatbot, user_input],show_progress=True,)# Clearclear_btn.click(fn=clear_chat_handler, outputs=[chatbot])# Queue for concurrency safety_demo_concurrency = int(os.getenv("CODEBOT_CONCURRENCY", "2"))demo.queue(max_size=32, default_concurrency_limit=_demo_concurrency)if __name__ == "__main__": # pragma: noβcoverdemo.launch()
app.py+221-127