Spaces:
Sleeping
Sleeping
Update app.py
Browse files69 unmodified lines7071727374758 unmodified lines84858687888990919293949569 unmodified lines# ββββββββββββββββββββββββββββββββdef safe_chat_stream(convo: list[dict], max_ctx: int, max_rep: int, models: list[str]):last_exc = Nonefor m in models:try:8 unmodified linesfor chunk in stream:delta = chunk.choices[0].delta.content or ""reply += deltayield reply, Noneusage = client.chat.completions.create(model=m,messages=convo + [{"role": "assistant", "content": reply}],max_tokens=0,).usageyield reply, usagereturnexcept Exception as e:69 unmodified lines707172737475768 unmodified lines85868788899091929394959697989910010110210310469 unmodified lines# ββββββββββββββββββββββββββββββββdef safe_chat_stream(convo: list[dict], max_ctx: int, max_rep: int, models: list[str]):"""Stream reply; after completion return usage safely (avoids max_tokens=0 bug)."""last_exc = Nonefor m in models:try:8 unmodified linesfor chunk in stream:delta = chunk.choices[0].delta.content or ""reply += deltayield reply, None # still streaming# --- Retrieve usage tokens in a way that never requests max_tokens=0 ---try:usage_resp = client.chat.completions.create(model=m,messages=convo + [{"role": "assistant", "content": reply}],max_tokens=1, # 0 can trigger 400 on some models/tierstemperature=0,)usage = usage_resp.usageexcept Exception:# fallback: estimate usage roughly if call above failsusage = Noneyield reply, usagereturnexcept Exception as e:
app.py+15-6