Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151162 unmodified lines11912012112212312412512 unmodified lines138139140141142143144145146"""app.py β Advanced Chatbot with Automatic Long-Input Handling"""import osimport asyncioimport gradio as grimport openaiimport tiktoken# Alias the right exception class (your SDK uses BadRequestError for invalidβrequest)try:# if your install still has openai.error, this will workfrom openai.error import InvalidRequestErrorexcept ImportError:# otherwise, BadRequestError covers context-length errorsfrom openai import BadRequestError as InvalidRequestError# ConfigurationMODEL_NAME = "gpt-4-32k"MAX_CONTEXT_TOKENS = 32768SUMMARY_MAX_TOKENS = 1024REPLY_MAX_TOKENS = 2048TEMPERATURE = 0.3BUFFER_TOKENS = 500 # reserved for the modelβs reply# Load your keyopenai.api_key = os.getenv("OPENAI_API_KEY", "").strip()def 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_tokens: int, model: str = MODEL_NAME) -> list[str]:words, chunks, current = text.split(), [], []for w in words:current.append(w)if count_tokens(" ".join(current), model) >= max_tokens:last = current.pop()chunks.append(" ".join(current))current = [last]if current:chunks.append(" ".join(current))return chunksasync def summarize_chunk(chunk: str) -> str:resp = await openai.ChatCompletion.acreate(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_TOKENS,temperature=0.0,)return resp.choices[0].message.content.strip()def safe_chat_completion(convo: list[dict], max_tokens: int):"""Try once, catch context-length, summarize last user message, retry."""try:return openai.ChatCompletion.create(model=MODEL_NAME,messages=convo,max_tokens=max_tokens,temperature=TEMPERATURE)except InvalidRequestError as e:err = str(e)if "maximum context length" not in err:raise # some other bad request error# calculate tokens used by everything except the last user messageused = count_tokens("".join(m["content"] for m in convo[:-1]), MODEL_NAME)allowed_for_user = MAX_CONTEXT_TOKENS - used - BUFFER_TOKENSif allowed_for_user < 100:raise RuntimeError("Input too large, even after trimming.")# chunk & summarizelast = convo[-1]["content"]chunks = chunk_text(last, allowed_for_user // 2, MODEL_NAME)summaries = asyncio.get_event_loop().run_until_complete(asyncio.gather(*(summarize_chunk(c) for c in chunks)))convo[-1]["content"] = " ".join(summaries)# retry oncereturn openai.ChatCompletion.create(model=MODEL_NAME,messages=convo,max_tokens=max_tokens,temperature=TEMPERATURE)def chat_handler(user_message: str,history: list[tuple[str, str]],system_prompt: str) -> tuple[list[tuple[str, str]], str]:if not user_message.strip():return history, ""if not openai.api_key:return history, "β OPENAI_API_KEY not set."# build convoconvo = [{"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_completion(convo, max_tokens=REPLY_MAX_TOKENS)reply = resp.choices[0].message.contentexcept Exception as e:reply = f"β OpenAI error: {e}"2 unmodified lineshistory.append((user_message, reply))return history, ""# --- Gradio UI ---with gr.Blocks(title="π€ Advanced Chatbot (Long-Input Safe)") as demo:gr.Markdown("""12 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,1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131142 unmodified lines11711811912012112212312 unmodified lines136137138139140141142143144"""app.py β Advanced Chatbot with Automatic Long-Input Handling(OpenAI Python SDK β₯1.0.0)"""import osimport asyncioimport gradio as grimport 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)if count_tokens(" ".join(cur), model) >= max_toks:last = cur.pop()chunks.append(" ".join(cur))cur = [last]if cur:chunks.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,history: list[tuple[str,str]],system_prompt: str) -> 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."# 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)reply = resp.choices[0].message.contentexcept Exception as e:reply = f"β OpenAI error: {e}"2 unmodified lineshistory.append((user_message, reply))return history, ""# βββ Gradio UI βββwith gr.Blocks(title="π€ Advanced Chatbot (Long-Input Safe)") as demo:gr.Markdown("""12 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,
app.py+58-60