Update api/utils.py
Browse files54 unmodified lines5556575859601 unmodified line6263646566676869707172737475767778792 unmodified lines82838485868788899091922 unmodified lines95969798991001011021031041051061071081091101113 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714854 unmodified lines# Process streaming response with headers from config.pyasync def process_streaming_response(request: ChatRequest):request_id = f"chatcmpl-{uuid.uuid4()}"logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")1 unmodified linetrending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})model_prefix = MODEL_PREFIXES.get(request.model, "")headers_api_chat = get_headers_api_chat(BASE_URL)# Delay for 'o1-preview' model if necessaryif request.model == 'o1-preview':delay_seconds = random.randint(1, 60)logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Request ID: {request_id})")await asyncio.sleep(delay_seconds)h_value = await getHid()if not h_value:logger.error("Failed to retrieve h-value for validation.")raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")json_data = {"agentMode": agent_mode,2 unmodified lines"clickedForceWebSearch": False,"codeModelMode": True,"githubToken": None,"id": request_id,"isChromeExt": False,"isMicMode": False,"maxTokens": request.max_tokens,"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],"mobileClient": False,"playgroundTemperature": request.temperature,"playgroundTopP": request.top_p,2 unmodified lines"userId": None,"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),"userSystemPrompt": None,"validated": h_value,"visitFromDelta": False,"webSearchModePrompt": False,"imageGenerationMode": False,}advertisement_added = False # Track if advertisement is already addedasync with httpx.AsyncClient() as client:try:async with client.stream("POST", f"{BASE_URL}/api/chat", headers=headers_api_chat, json=json_data, timeout=100) as response:response.raise_for_status()timestamp = int(datetime.now().timestamp())3 unmodified linesif content.startswith("$@$v=undefined-rv1$@$"):content = content[21:] # Remove unwanted prefixif BLOCKED_MESSAGE in content:logger.info(f"Blocked message detected in response for Request ID {request_id}.")content = content.replace(BLOCKED_MESSAGE, '').strip()if not content:continue # Skip empty contentcleaned_content = strip_model_prefix(content, model_prefix)# Yield cleaned chunk as part of the streamyield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"# Append advertisement as a separate chunk, if applicableif ADVERTISEMENT_TEXT and not advertisement_added:yield f"data: {json.dumps(create_chat_completion_data(ADVERTISEMENT_TEXT, request.model, timestamp))}\n\n"advertisement_added = True# Yield final chunk indicating the end of the streamyield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"yield "data: [DONE]\n\n"except httpx.HTTPStatusError as e:logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")raise HTTPException(status_code=e.response.status_code, detail=str(e))except httpx.RequestError as e:logger.error(f"Request error occurred for Request ID {request_id}: {e}")raise HTTPException(status_code=500, detail=str(e))# Process non-streaming response with headers from config.pyasync def process_non_streaming_response(request: ChatRequest):request_id = f"chatcmpl-{uuid.uuid4()}"54 unmodified lines555657585960611 unmodified line6364656667686970717273747576777879808182838485862 unmodified lines89909192939495969798991001012 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261273 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117254 unmodified lines# Process streaming response with headers from config.pyasync def process_streaming_response(request: ChatRequest):# Generate a unique ID for this requestrequest_id = f"chatcmpl-{uuid.uuid4()}"logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")1 unmodified linetrending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})model_prefix = MODEL_PREFIXES.get(request.model, "")# Adjust headers_api_chat since referer_url is removedheaders_api_chat = get_headers_api_chat(BASE_URL)if request.model == 'o1-preview':delay_seconds = random.randint(1, 60)logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' "f"(Request ID: {request_id})")await asyncio.sleep(delay_seconds)# Fetch the h-value for the 'validated' fieldh_value = await getHid()if not h_value:logger.error("Failed to retrieve h-value for validation.")raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")json_data = {"agentMode": agent_mode,2 unmodified lines"clickedForceWebSearch": False,"codeModelMode": True,"githubToken": None,"id": None, # Using request_id instead of chat_id"isChromeExt": False,"isMicMode": False,"maxTokens": request.max_tokens,"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],"mobileClient": False,"playgroundTemperature": request.temperature,"playgroundTopP": request.top_p,2 unmodified lines"userId": None,"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),"userSystemPrompt": None,"validated": h_value, # Dynamically set the validated field"visitFromDelta": False,"webSearchModePrompt": False,"imageGenerationMode": False, # Added this line}response_content = "" # Variable to hold the full response contentadvertisement_added = False # Track if advertisement is addedasync with httpx.AsyncClient() as client:try:async with client.stream("POST",f"{BASE_URL}/api/chat",headers=headers_api_chat,json=json_data,timeout=100,) as response:response.raise_for_status()timestamp = int(datetime.now().timestamp())3 unmodified linesif content.startswith("$@$v=undefined-rv1$@$"):content = content[21:] # Remove unwanted prefix# Remove blocked message if presentif BLOCKED_MESSAGE in content:logger.info(f"Blocked message detected in response for Request ID {request_id}.")content = content.replace(BLOCKED_MESSAGE, '').strip()if not content:continue # Skip if content is empty after removal# Clean up the contentcleaned_content = strip_model_prefix(content, model_prefix)# Add the chunk to the full response contentresponse_content += cleaned_content# Yield the cleaned chunk as part of the streamyield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"# After all chunks are processed, append the advertisement text at the end if it's not already includedif ADVERTISEMENT_TEXT and not advertisement_added:response_content += "\n\n" + ADVERTISEMENT_TEXT # Line break added hereadvertisement_added = True# Now yield the final chunk with the advertisement text appended at the endyield f"data: {json.dumps(create_chat_completion_data(response_content, request.model, timestamp, 'stop'))}\n\n"# Add the final "done" markeryield "data: [DONE]\n\n"except httpx.HTTPStatusError as e:logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")raise HTTPException(status_code=e.response.status_code, detail=str(e))except httpx.RequestError as e:logger.error(f"Error occurred during request for Request ID {request_id}: {e}")raise HTTPException(status_code=500, detail=str(e))# Process non-streaming response with headers from config.pyasync def process_non_streaming_response(request: ChatRequest):request_id = f"chatcmpl-{uuid.uuid4()}"
api/utils.py+40-16