Update api/utils.py
Browse files10 unmodified lines111213141516179 unmodified lines2728293031323334353637389 unmodified lines4849505152535438 unmodified lines939495969798991001011021031041051061071081091101115 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501517 unmodified lines1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992001 unmodified line20220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326410 unmodified linesfrom api.config import (MODEL_MAPPING,get_headers_api_chat,get_headers_chat,BASE_URL,AGENT_MODE,TRENDING_AGENT_MODE,9 unmodified lineslogger = setup_logger(__name__)# Helper function to create a random alphanumeric chat IDdef generate_chat_id(length: int = 7) -> str:characters = string.ascii_letters + string.digitsreturn ''.join(random.choices(characters, k=length))# Helper function to create chat completion datadef create_chat_completion_data(content: str,9 unmodified lines"choices": [{"index": 0,"delta": {"content": content, "role": "assistant"},"finish_reason": finish_reason,}],38 unmodified lines# Function to get the correct referer URL for loggingdef get_referer_url(chat_id: str, model: str) -> str:"""Generate the referer URL based on specific models listed in MODEL_REFERERS."""if model in MODEL_REFERERS:return f"{BASE_URL}/chat/{chat_id}?model={model}"return BASE_URL# Process streaming response with headers from config.pyasync def process_streaming_response(request: ChatRequest):chat_id = generate_chat_id()referer_url = get_referer_url(chat_id, request.model)logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")agent_mode = AGENT_MODE.get(request.model, {})5 unmodified linesif request.model == 'o1-preview':delay_seconds = random.randint(1, 60)logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Chat ID: {chat_id})")await asyncio.sleep(delay_seconds)json_data = {"agentMode": agent_mode,"clickedAnswer2": False,"clickedAnswer3": False,"clickedForceWebSearch": False,"codeModelMode": True,"githubToken": None,"id": 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,"previewToken": None,"trendingAgentMode": trending_agent_mode,"userId": None,"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),"userSystemPrompt": None,# Use validate.getHid() for the 'validated' field"validated": validate.getHid(),"visitFromDelta": False,}async with httpx.AsyncClient() as client:7 unmodified lines) as response:response.raise_for_status()async for line in response.aiter_lines():timestamp = int(datetime.now().timestamp())if line:content = line + "\n"if "https://www.blackbox.ai" in content:# Refresh hid and inform the uservalidate.getHid(True)content = "The HID has been refreshed; please try again.\n"yield (f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n")breakif content.startswith("$@$v=undefined-rv1$@$"):content = content[21:]cleaned_content = strip_model_prefix(content, model_prefix)yield (f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n")yield (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 Chat ID {chat_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 Chat ID {chat_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):chat_id = generate_chat_id()referer_url = get_referer_url(chat_id, request.model)logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")agent_mode = AGENT_MODE.get(request.model, {})1 unmodified linemodel_prefix = MODEL_PREFIXES.get(request.model, "")headers_api_chat = get_headers_api_chat(referer_url)headers_chat = get_headers_chat(referer_url,next_action=str(uuid.uuid4()),next_router_state_tree=json.dumps([""]),)if request.model == 'o1-preview':delay_seconds = random.randint(20, 60)logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Chat ID: {chat_id})")await asyncio.sleep(delay_seconds)json_data = {"agentMode": agent_mode,"clickedAnswer2": False,"clickedAnswer3": False,"clickedForceWebSearch": False,"codeModelMode": True,"githubToken": None,"id": 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,"previewToken": None,"trendingAgentMode": trending_agent_mode,"userId": None,"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),"userSystemPrompt": None,# Use validate.getHid() for the 'validated' field"validated": validate.getHid(),"visitFromDelta": False,}full_response = ""async with httpx.AsyncClient() as client:try:async with client.stream(method="POST",url=f"{BASE_URL}/api/chat",headers=headers_api_chat,json=json_data,) as response:response.raise_for_status()async for chunk in response.aiter_text():full_response += chunkexcept httpx.HTTPStatusError as e:logger.error(f"HTTP error occurred for Chat ID {chat_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 Chat ID {chat_id}: {e}")raise HTTPException(status_code=500, detail=str(e))if "https://www.blackbox.ai" in full_response:10 unmodified lines1112131415169 unmodified lines2627282930319 unmodified lines4142434445464738 unmodified lines86878889909192939495969798991001011021035 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401417 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901 unmodified line19219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424510 unmodified linesfrom api.config import (MODEL_MAPPING,get_headers_api_chat,BASE_URL,AGENT_MODE,TRENDING_AGENT_MODE,9 unmodified lineslogger = setup_logger(__name__)# Helper function to create chat completion datadef create_chat_completion_data(content: str,9 unmodified lines"choices": [{"index": 0,"delta": {"content": content},"finish_reason": finish_reason,}],38 unmodified lines# Function to get the correct referer URL for loggingdef get_referer_url(model: str) -> str:"""Generate the referer URL based on specific models listed in MODEL_REFERERS."""if model in MODEL_REFERERS:return f"{BASE_URL}/chat?model={model}"return BASE_URL# Process streaming response with headers from config.pyasync def process_streaming_response(request: ChatRequest):referer_url = get_referer_url(request.model)logger.info(f"Model: {request.model} - URL: {referer_url}")agent_mode = AGENT_MODE.get(request.model, {})5 unmodified linesif request.model == 'o1-preview':delay_seconds = random.randint(1, 60)logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview'")await asyncio.sleep(delay_seconds)json_data = {"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],"previewToken": None,"userId": None,"codeModelMode": True,"agentMode": agent_mode,"trendingAgentMode": trending_agent_mode,"isMicMode": False,"userSystemPrompt": None,"maxTokens": request.max_tokens,"playgroundTopP": request.top_p,"playgroundTemperature": request.temperature,"isChromeExt": False,"githubToken": None,"clickedAnswer2": False,"clickedAnswer3": False,"clickedForceWebSearch": False,"visitFromDelta": False,"mobileClient": False,"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),"validated": validate.getHid(),}async with httpx.AsyncClient() as client:7 unmodified lines) as response:response.raise_for_status()async for line in response.aiter_lines():if line:# Process the line as per the Blackbox API response formatif "https://www.blackbox.ai" in line:# Refresh hid and inform the uservalidate.getHid(True)content = "The HID has been refreshed; please try again."yield (f"data: {json.dumps(create_chat_completion_data(content, request.model, int(datetime.now().timestamp())))}\n\n")breakif line.startswith("$@$v=undefined-rv1$@$"):line = line[21:]cleaned_content = strip_model_prefix(line, model_prefix)# Yield the data in the format expected by the clientyield (f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, int(datetime.now().timestamp())))}\n\n")# Signal that the response is completeyield (f"data: {json.dumps(create_chat_completion_data('', request.model, int(datetime.now().timestamp()), 'stop'))}\n\n")yield "data: [DONE]\n\n"except httpx.HTTPStatusError as e:logger.error(f"HTTP error occurred: {e}")raise HTTPException(status_code=e.response.status_code, detail=str(e))except httpx.RequestError as e:logger.error(f"Error occurred during request: {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):referer_url = get_referer_url(request.model)logger.info(f"Model: {request.model} - URL: {referer_url}")agent_mode = AGENT_MODE.get(request.model, {})1 unmodified linemodel_prefix = MODEL_PREFIXES.get(request.model, "")headers_api_chat = get_headers_api_chat(referer_url)if request.model == 'o1-preview':delay_seconds = random.randint(20, 60)logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview'")await asyncio.sleep(delay_seconds)json_data = {"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],"previewToken": None,"userId": None,"codeModelMode": True,"agentMode": agent_mode,"trendingAgentMode": trending_agent_mode,"isMicMode": False,"userSystemPrompt": None,"maxTokens": request.max_tokens,"playgroundTopP": request.top_p,"playgroundTemperature": request.temperature,"isChromeExt": False,"githubToken": None,"clickedAnswer2": False,"clickedAnswer3": False,"clickedForceWebSearch": False,"visitFromDelta": False,"mobileClient": False,"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),"validated": validate.getHid(),}full_response = ""async with httpx.AsyncClient() as client:try:response = await client.post(url=f"{BASE_URL}/api/chat",headers=headers_api_chat,json=json_data,)response.raise_for_status()full_response = response.textexcept httpx.HTTPStatusError as e:logger.error(f"HTTP error occurred: {e}")raise HTTPException(status_code=e.response.status_code, detail=str(e))except httpx.RequestError as e:logger.error(f"Error occurred during request: {e}")raise HTTPException(status_code=500, detail=str(e))if "https://www.blackbox.ai" in full_response:
api/utils.py+58-77