Spaces:
Sleeping
Sleeping
Update app.py
Browse files123453 unmodified lines91011121314151617181920212223242526272829305 unmodified lines36373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293945 unmodified lines1001011021031041051061071081091101116 unmodified lines118119120121122123124125126127128129"""app.py – Advanced Chatbot with Automatic Long-Input Handling(OpenAI Python SDK ≥1.0.0)"""3 unmodified linesimport tiktokenfrom openai import OpenAI# Instantiate the new clientclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())# ConfigurationMODEL_NAME = "gpt-4-32k"MAX_CONTEXT = 32768SUMMARY_MAX = 1024REPLY_MAX = 2048TEMPERATURE = 0.3BUFFER_TOKENS = 500 # leave room for the model's answerdef count_tokens(text: str, model: str = MODEL_NAME) -> int:enc = tiktoken.encoding_for_model(model)return len(enc.encode(text))def chunk_text(text: str, max_toks: int, model: str = MODEL_NAME) -> list[str]:words, chunks, cur = text.split(), [], []for w in words:cur.append(w)5 unmodified lineschunks.append(" ".join(cur))return chunksasync def summarize_chunk(chunk: str) -> str:resp = await client.chat.completions.create(model=MODEL_NAME,messages=[{"role":"system", "content":"You are a concise summarizer."},{"role":"user", "content":f"Summarize this text briefly, preserving key details:\n\n{chunk}"}],max_tokens=SUMMARY_MAX,temperature=0.0,)return resp.choices[0].message.content.strip()def safe_chat(convo: list[dict], max_reply: int):"""1) Try a normal chat2) On context-length error, summarize only the last user message3) Retry once with the summaries in place"""try:return client.chat.completions.create(model=MODEL_NAME,messages=convo,max_tokens=max_reply,temperature=TEMPERATURE)except Exception as e:text = str(e).lower()if "context length" not in text and "maximum context length" not in text:# Not a token-limit issueraise# How many tokens have we used so far?used = count_tokens("".join(m["content"] for m in convo[:-1]), MODEL_NAME)allowed = MAX_CONTEXT - used - BUFFER_TOKENSif allowed < 100:raise RuntimeError("Even after trimming, input is too large.")# Chunk & summarize the last messagelast_msg = convo[-1]["content"]bits = chunk_text(last_msg, max_toks=allowed // 2, model=MODEL_NAME)summaries = asyncio.get_event_loop().run_until_complete(asyncio.gather(*(summarize_chunk(b) for b in bits)))convo[-1]["content"] = " ".join(summaries)# Retry oncereturn client.chat.completions.create(model=MODEL_NAME,messages=convo,max_tokens=max_reply,temperature=TEMPERATURE)def chat_handler(user_message: str,5 unmodified linesif not client.api_key:return history, "❌ OPENAI_API_KEY not set."# Build the full conversationconvo = [{"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, max_reply=REPLY_MAX)6 unmodified linesreturn history, ""# ——— Gradio UI ———with gr.Blocks(title="🤖 Advanced Chatbot (Long-Input Safe)") as demo:gr.Markdown("""# Advanced ChatbotPaste arbitrarily long code or text; the bot will auto-summarize overflow.Expert in Python & C# with production-grade answers.""")123453 unmodified lines9101112131415161718192021222324252627282930313233345 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121135 unmodified lines1191201211221231241251261271281291306 unmodified lines137138139140141142143144145146147148"""app.py – Advanced Chatbot with Multi-Model Fallback & Long-Input Safety(OpenAI Python SDK ≥1.0.0)"""3 unmodified linesimport tiktokenfrom openai import OpenAI# 1) Init OpenAI clientclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())# 2) Read prioritized model list from env (comma-separated)# Default: gpt-4-32k → gpt-4 → gpt-3.5-turbomodel_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()]# 3) Token-limit & summarization settingsMAX_CONTEXT = 32768 # e.g. for gpt-4-32kBUFFER_TOKENS = 500 # reserved for the model’s replySUMMARY_MAX = 1024 # each chunk’s summary limitREPLY_MAX = 2048 # tokens for the final answerTEMPERATURE = 0.3def count_tokens(text: str, model: str) -> int:enc = tiktoken.encoding_for_model(model)return len(enc.encode(text))def chunk_text(text: str, max_toks: int, model: str) -> list[str]:words, chunks, cur = text.split(), [], []for w in words:cur.append(w)5 unmodified lineschunks.append(" ".join(cur))return chunksasync def summarize_chunk(chunk: str, model: str) -> str:resp = await client.chat.completions.create(model=model,messages=[{"role":"system","content":"You are a concise summarizer."},{"role":"user", "content":f"Summarize this text briefly, preserving key details:\n\n{chunk}"}],max_tokens=SUMMARY_MAX,temperature=0.0)return resp.choices[0].message.content.strip()def safe_chat(convo: list[dict], max_reply: int):"""1) Try each model in MODELS in order2) On model_not_found → try next3) On context-length → summarize last user msg & retry that same model once"""last_exc = Nonefor model in MODELS:try:return client.chat.completions.create(model=model,messages=convo,max_tokens=max_reply,temperature=TEMPERATURE)except Exception as e:text = str(e).lower()# MODEL NOT FOUND → skip to nextif "does not exist" in text or "model_not_found" in text or "404" in text:last_exc = econtinue# CONTEXT-LENGTH ERROR → summarize + retry this same model onceif "maximum context length" in text or "context length" in text:used = count_tokens("".join(m["content"] for m in convo[:-1]), model)allowed = MAX_CONTEXT - used - BUFFER_TOKENSif allowed < 100:last_exc = RuntimeError("Input too large even after trimming.")break# chunk & summarize the last messagelast_msg = convo[-1]["content"]pieces = chunk_text(last_msg, allowed // 2, model)summaries = asyncio.get_event_loop().run_until_complete(asyncio.gather(*(summarize_chunk(p, model) for p in pieces)))convo[-1]["content"] = " ".join(summaries)# retry once on this modeltry:return client.chat.completions.create(model=model,messages=convo,max_tokens=max_reply,temperature=TEMPERATURE)except Exception as e2:last_exc = e2continue# any other error → bubble upraise# if none worked:raise last_exc or RuntimeError("All models failed in safe_chat()")def chat_handler(user_message: str,5 unmodified linesif not client.api_key:return history, "❌ OPENAI_API_KEY not set."# Build convo 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, max_reply=REPLY_MAX)6 unmodified linesreturn history, ""# ——— Gradio UI ———with gr.Blocks(title="🤖 Advanced Chatbot") as demo:gr.Markdown(f"**🔗 Models to try (in order):** {', '.join(MODELS)}")gr.Markdown("""Paste arbitrarily long code or text; the bot will auto-summarize overflow.It will also automatically fall back if a model isn’t available.""")
app.py+76-57