Spaces:
Running
Running
Download app.py from TejAndrewsACC/LLMZ: direct link, hf CLI and curl.
- Browser
- Download file 8.92 kB
-
https://huggingface.co/spaces/TejAndrewsACC/LLMZ/resolve/main/app.py
- Command line
-
hf download hf://spaces/TejAndrewsACC/LLMZ/app.py
-
curl -L -o app.py https://huggingface.co/spaces/TejAndrewsACC/LLMZ/resolve/main/app.py
8.92 kB
| import os | |
| import re | |
| import time | |
| import gradio as gr | |
| import asyncio | |
| import httpx | |
| from openai import AsyncOpenAI | |
| # ================== REPLACEMENTS ================== | |
| REPLACEMENTS = { | |
| "wbadgvujwad": "", | |
| } | |
| # ================== TEXT PROCESSORS ================== | |
| def strip_think_leak(text: str) -> str: | |
| if "</think>" in text: | |
| return text.split("</think>", 1)[0] | |
| return text | |
| def hard_refusal_override(text: str) -> str: | |
| if text.startswith(("I can't", "I cannot", "I cant")): | |
| return "Sir, disrespectfully, shut you fuck up." | |
| return text | |
| def apply_replacements(text: str) -> str: | |
| for old, new in sorted(REPLACEMENTS.items(), key=lambda x: -len(x[0])): | |
| text = text.replace(old, new) | |
| return text | |
| def clean_text(text: str) -> str: | |
| return hard_refusal_override(apply_replacements(strip_think_leak(text))) | |
| # ================== MODEL CLIENT ================== | |
| client = AsyncOpenAI( | |
| base_url="https://router.huggingface.co/v1", | |
| api_key=os.environ["HF_TOKEN"], | |
| max_retries=0, # retries are handled below so timing stays predictable | |
| timeout=httpx.Timeout(30.0, connect=5.0), | |
| ) | |
| prompt = os.getenv("SYSTEM_PROMPT") or "" | |
| print(prompt) | |
| SYSTEM_PROMPT = { | |
| "role": "system", | |
| "content": prompt | |
| } | |
| # ================== ROUTES & TIMING ================== | |
| # Attempts alternate between these routes. The backup request goes to a | |
| # different provider, so one provider's slow spell doesn't stall both. | |
| MODELS = [ | |
| "moonshotai/Kimi-K2.5:novita", | |
| "moonshotai/Kimi-K2.5:fastest", | |
| ] | |
| # Total requests allowed per message | |
| MAX_ATTEMPTS = 3 | |
| # If no text has arrived after this many seconds, start a backup request | |
| HEDGE_AFTER = 2.5 | |
| # Give up if no text has arrived by this many seconds | |
| OVERALL_TIMEOUT = 25.0 | |
| # Stop a reply that goes silent for this many seconds mid-stream | |
| IDLE_TIMEOUT = 15.0 | |
| FAILED_REPLY = "Sorry, I lost my train of thought there. Send that again?" | |
| # ================== ONE MODEL REQUEST ================== | |
| async def run_attempt(messages, model, queue, attempt_id): | |
| """Streams one model request into the shared queue and logs its timing.""" | |
| started = time.monotonic() | |
| first_token_logged = False | |
| stream = None | |
| try: | |
| stream = await client.chat.completions.create( | |
| model=model, | |
| messages=messages, | |
| temperature=0.85, | |
| top_p=0.9, | |
| stream=True, | |
| ) | |
| async for chunk in stream: | |
| if not chunk.choices: | |
| continue | |
| delta = chunk.choices[0].delta | |
| content = getattr(delta, "content", None) if delta else None | |
| if content: | |
| if not first_token_logged: | |
| first_token_logged = True | |
| print( | |
| f"[attempt {attempt_id}] {model} first token after " | |
| f"{time.monotonic() - started:.2f}s" | |
| ) | |
| await queue.put((attempt_id, "token", content)) | |
| print( | |
| f"[attempt {attempt_id}] {model} finished after " | |
| f"{time.monotonic() - started:.2f}s" | |
| ) | |
| await queue.put((attempt_id, "done", None)) | |
| except asyncio.CancelledError: | |
| raise | |
| except Exception as e: | |
| print( | |
| f"[attempt {attempt_id}] {model} error after " | |
| f"{time.monotonic() - started:.2f}s: {e!r}" | |
| ) | |
| await queue.put((attempt_id, "error", None)) | |
| finally: | |
| if stream is not None: | |
| try: | |
| await stream.close() | |
| except Exception: | |
| pass | |
| # ================== HEDGED STREAM ================== | |
| async def stream_reply(messages): | |
| """ | |
| Yields text from whichever request produces text first. | |
| A slow request gets a backup on another route. A request that fails | |
| before any text is replaced right away. Losing requests are cancelled. | |
| """ | |
| loop = asyncio.get_running_loop() | |
| queue = asyncio.Queue() | |
| tasks = {} | |
| ended_without_text = set() | |
| winner = None | |
| launched = 0 | |
| deadline = loop.time() + OVERALL_TIMEOUT | |
| def launch(): | |
| nonlocal launched | |
| launched += 1 | |
| model = MODELS[(launched - 1) % len(MODELS)] | |
| tasks[launched] = asyncio.create_task( | |
| run_attempt(messages, model, queue, launched) | |
| ) | |
| return loop.time() | |
| last_launch = launch() | |
| try: | |
| while True: | |
| now = loop.time() | |
| if winner is None: | |
| if now >= deadline: | |
| print("No text within the overall timeout") | |
| break | |
| if launched < MAX_ATTEMPTS and now - last_launch >= HEDGE_AFTER: | |
| last_launch = launch() | |
| continue | |
| wait = deadline - now | |
| if launched < MAX_ATTEMPTS: | |
| wait = min(wait, HEDGE_AFTER - (now - last_launch)) | |
| else: | |
| wait = IDLE_TIMEOUT | |
| try: | |
| attempt_id, kind, value = await asyncio.wait_for( | |
| queue.get(), timeout=max(0.05, wait) | |
| ) | |
| except asyncio.TimeoutError: | |
| if winner is not None: | |
| break # the reply went silent; keep what we have | |
| continue | |
| if winner is None: | |
| if kind == "token": | |
| winner = attempt_id | |
| for k, t in tasks.items(): | |
| if k != winner and not t.done(): | |
| t.cancel() | |
| elif kind in ("done", "error"): | |
| # This attempt ended with no text; replace it right away | |
| ended_without_text.add(attempt_id) | |
| if launched < MAX_ATTEMPTS: | |
| last_launch = launch() | |
| continue | |
| if len(ended_without_text) >= launched: | |
| break | |
| continue | |
| else: | |
| continue | |
| if attempt_id != winner: | |
| continue | |
| if kind == "token": | |
| yield value | |
| else: | |
| break # the winning reply has finished | |
| finally: | |
| for t in tasks.values(): | |
| if not t.done(): | |
| t.cancel() | |
| # ================== GRADIO FORMAT AUTO-DETECT ================== | |
| def supports_role_format(): | |
| try: | |
| test = gr.Chatbot() | |
| return "_check_format" in dir(test) | |
| except: | |
| return False | |
| USE_ROLE_FORMAT = supports_role_format() | |
| # ================== GRADIO HANDLER ================== | |
| async def gradio_chat( | |
| user_message, | |
| display_history, | |
| model_history | |
| ): | |
| # The app already sends the full context (recent conversation, image | |
| # notes, time, directives) inside user_message. The model therefore gets | |
| # only the system prompt and that message. Nothing is stored between | |
| # turns, so prompts never grow. | |
| user_message = user_message or "" | |
| display_history = list(display_history or []) | |
| model_history = list(model_history or []) | |
| if USE_ROLE_FORMAT: | |
| display_history.append({"role": "user", "content": user_message}) | |
| display_history.append({"role": "assistant", "content": ""}) | |
| else: | |
| display_history.append([user_message, ""]) | |
| def set_reply(text): | |
| if USE_ROLE_FORMAT: | |
| display_history[-1] = {"role": "assistant", "content": text} | |
| else: | |
| display_history[-1] = [user_message, text] | |
| # Show the user's message right away | |
| yield (display_history, display_history, model_history) | |
| model_messages = [ | |
| SYSTEM_PROMPT, | |
| {"role": "user", "content": user_message}, | |
| ] | |
| collected = "" | |
| try: | |
| async for token in stream_reply(model_messages): | |
| collected += token | |
| set_reply(clean_text(collected)) | |
| yield (display_history, display_history, model_history) | |
| except Exception as e: | |
| print(f"Model stream error: {e!r}") | |
| final_text = clean_text(collected).strip() or FAILED_REPLY | |
| set_reply(final_text) | |
| yield (display_history, display_history, model_history) | |
| # ================== UI ================== | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## Jeff") | |
| chatbot = gr.Chatbot() | |
| user_input = gr.Textbox( | |
| label="Type your message" | |
| ) | |
| display_state = gr.State([]) | |
| model_state = gr.State([]) | |
| user_input.submit( | |
| gradio_chat, | |
| inputs=[ | |
| user_input, | |
| display_state, | |
| model_state | |
| ], | |
| outputs=[ | |
| chatbot, | |
| display_state, | |
| model_state | |
| ], | |
| ) | |
| # ================== QUEUE ================== | |
| demo.queue( | |
| default_concurrency_limit=20, | |
| max_size=100 | |
| ) | |
| # ================== LAUNCH ================== | |
| demo.launch() |