Spaces:
Running
Running
Update app.py
Browse files74 unmodified lines75767778798081159 unmodified lines2412422432442452462472 unmodified lines25025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332474 unmodified linescontinue# Check for Audiois_audio = not isinstance(content, list) and content["component"] == "audio"if is_audio:audio_path = content["value"]["path"]159 unmodified linestry:with httpx.Client(base_url=API_BASE_URL, timeout=120) as client:response = client.post("/chat/completions", json={"model": model_name,"messages": messages,"max_tokens": max_tokens,2 unmodified lines"stream": True,"repetition_penalty": 1.07,"stop_token_ids": [151665]})if response.status_code != 200:error_msg = f"❌ API Error {response.status_code}"if response.status_code == 404:error_msg += " - vLLM service not ready"elif response.status_code == 400:error_msg += " - Bad request"elif response.status_code == 500:error_msg += " - Model error"yield history, error_msgreturn# Process streaming responsebuffer = ""is_thinking = Truefor line in response.iter_lines():if not line:continue# Ensure line is string formatif isinstance(line, bytes):line = line.decode('utf-8')else:line = str(line)if line.startswith('data: '):data_str = line[6:]if data_str.strip() == '[DONE]':breaktry:data = json.loads(data_str)if 'choices' in data and len(data['choices']) > 0:delta = data['choices'][0].get('delta', {})if 'content' in delta:content = delta['content']buffer += contentif is_thinking:if "</think>" in buffer:is_thinking = Falseparts = buffer.split("</think>", 1)think_content = parts[0]response_content = parts[1]if think_content.startswith("<think>"):think_content = think_content[len("<think>"):].strip()# Update thinking messagehistory[-1].content = think_content# Add response messagehistory.append({"role": "assistant", "content": response_content})else:# Update thinking messagecurrent_think = bufferif current_think.startswith("<think>"):current_think = current_think[len("<think>"):]history[-1].content = current_thinkelse:# Already split, just update response messageparts = buffer.split("</think>", 1)response_content = parts[1]history[-1]["content"] = response_contentyield history, ""except json.JSONDecodeError:continueexcept httpx.ConnectError:yield history, "❌ Cannot connect to vLLM API"74 unmodified lines75767778798081159 unmodified lines2412422432442452462472482 unmodified lines25125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632774 unmodified linescontinue# Check for Audiois_audio = not isinstance(content, list) and content.get("component", None) == "audio"if is_audio:audio_path = content["value"]["path"]159 unmodified linestry:with httpx.Client(base_url=API_BASE_URL, timeout=120) as client:# Use client.stream for better streaming controlwith client.stream("POST", "/chat/completions", json={"model": model_name,"messages": messages,"max_tokens": max_tokens,2 unmodified lines"stream": True,"repetition_penalty": 1.07,"stop_token_ids": [151665]}) as response:if response.status_code != 200:error_msg = f"❌ API Error {response.status_code}"if response.status_code == 404:error_msg += " - vLLM service not ready"elif response.status_code == 400:error_msg += " - Bad request"elif response.status_code == 500:error_msg += " - Model error"yield history, error_msgreturn# Process streaming responsebuffer = ""is_thinking = Trueprint("[DEBUG] Start receiving stream...")for line in response.iter_lines():if not line:continue# Ensure line is string formatif isinstance(line, bytes):line = line.decode('utf-8')else:line = str(line)if line.startswith('data: '):data_str = line[6:]if data_str.strip() == '[DONE]':print("[DEBUG] Stream finished [DONE]")breaktry:data = json.loads(data_str)if 'choices' in data and len(data['choices']) > 0:delta = data['choices'][0].get('delta', {})if 'content' in delta:content = delta['content']buffer += contentif is_thinking:if "</think>" in buffer:is_thinking = Falseparts = buffer.split("</think>", 1)think_content = parts[0]response_content = parts[1]if think_content.startswith("<think>"):think_content = think_content[len("<think>"):].strip()# Update thinking messagehistory[-1].content = think_content# Add response messagehistory.append({"role": "assistant", "content": response_content})else:# Update thinking messagecurrent_think = bufferif current_think.startswith("<think>"):current_think = current_think[len("<think>"):]history[-1].content = current_thinkelse:# Already split, just update response messageparts = buffer.split("</think>", 1)response_content = parts[1]history[-1]["content"] = response_contentyield history, ""except json.JSONDecodeError:continueexcept httpx.ConnectError:yield history, "❌ Cannot connect to vLLM API"
app.py+72-69