Update api/utils.py
Browse files2 unmodified lines345678910111210 unmodified lines2324252627282930317 unmodified lines394041424344451 unmodified line474849505152535455565758596061626364656667686970717273747576773 unmodified lines8182838485868788899091929394959697989910010110210310410510610710812 unmodified lines12112212312412512612710 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216316414 unmodified lines17918018118218318418510 unmodified lines1961971981992002012022032042052062072082092102112122132142152162 unmodified linesfrom typing import Any, Dict, Optionalimport httpximport aiohttp # Add this importfrom api.config import (DDG_API_ENDPOINT, # UpdatedDDG_STATUS_URL, # UpdatedMODEL_MAPPING,ALLOWED_MODELS,AGENT_MODE,10 unmodified lineslogger = setup_logger(__name__)# Remove Blackbox-specific functions and add DDG-specific functions# New DDG Integrationasync def get_ddg_vqd():status_url = DDG_STATUS_URL7 unmodified linestry:async with session.get(status_url, headers=headers) as response:if response.status == 200:return response.headers.get("x-vqd-4")else:logger.error(f"Error: Status code {response.status} when fetching VQD")return None1 unmodified linelogger.error(f"Error getting VQD: {e}")return Nonedef format_prompt(messages):"""Helper function to format messages into a prompt string."""return "\n".join([f"{msg.role}: {msg.content}" for msg in messages])def message_to_dict_ddg(message, model_prefix: Optional[str] = None):if isinstance(message.content, str):content = message.contentif model_prefix:content = f"{model_prefix} {content}"return {"role": message.role, "content": content}elif isinstance(message.content, list) and len(message.content) == 2:content = message.content[0]["text"]if model_prefix:content = f"{model_prefix} {content}"return {"role": message.role,"content": content,"data": {"imageBase64": message.content[1]["image_url"]["url"],"fileText": "","title": "snapshot",},}else:return {"role": message.role, "content": message.content}def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:"""Remove the model prefix from the response content if present."""3 unmodified lineslogger.debug("No prefix to strip from content.")return contentasync def process_ddg_streaming_response(request: ChatRequest):agent_mode = AGENT_MODE.get(request.model, {})trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})model_prefix = MODEL_PREFIXES.get(request.model, "")referer_path = MODEL_REFERERS.get(request.model, f"/?model={request.model}")referer_url = f"https://duckduckgo.com{referer_path}" # Updated BASE_URL# Update headers with dynamic Refererdynamic_headers = {'accept': 'text/event-stream','content-type': 'application/json','user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36','x-vqd-4': await get_ddg_vqd()}if not dynamic_headers['x-vqd-4']:raise HTTPException(status_code=500, detail="Failed to obtain VQD token")json_data = {"model": MODEL_MAPPING.get(request.model, request.model),"messages": [message_to_dict_ddg(msg, model_prefix=model_prefix) for msg in request.messages],# Add additional fields if required by DDG API}async with httpx.AsyncClient() as client:12 unmodified linescontent = lineif content.startswith("$@$v=undefined-rv1$@$"):content = content[21:]# Strip the model prefix from the response contentcleaned_content = strip_model_prefix(content, model_prefix)yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"10 unmodified linesagent_mode = AGENT_MODE.get(request.model, {})trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})model_prefix = MODEL_PREFIXES.get(request.model, "")referer_path = MODEL_REFERERS.get(request.model, f"/?model={request.model}")referer_url = f"https://duckduckgo.com{referer_path}" # Updated BASE_URL# Update headers with dynamic Refererdynamic_headers = {'accept': 'application/json','content-type': 'application/json','user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36','x-vqd-4': await get_ddg_vqd()}if not dynamic_headers['x-vqd-4']:raise HTTPException(status_code=500, detail="Failed to obtain VQD token")json_data = {"model": MODEL_MAPPING.get(request.model, request.model),"messages": [message_to_dict_ddg(msg, model_prefix=model_prefix) for msg in request.messages],# Add additional fields if required by DDG API}full_response = ""async with httpx.AsyncClient() as client:try:response = await client.post(14 unmodified linesif full_response.startswith("$@$v=undefined-rv1$@$"):full_response = full_response[21:]# Strip the model prefix from the full responsecleaned_full_response = strip_model_prefix(full_response, model_prefix)return {10 unmodified lines],"usage": None,}def create_chat_completion_data(content: str, model: str, timestamp: int, finish_reason: Optional[str] = None) -> Dict[str, Any]:return {"id": f"chatcmpl-{uuid.uuid4()}","object": "chat.completion.chunk","created": timestamp,"model": model,"choices": [{"index": 0,"delta": {"content": content, "role": "assistant"},"finish_reason": finish_reason,}],"usage": None,}2 unmodified lines345678910111210 unmodified lines2324252627287 unmodified lines363738394041424344451 unmodified line4748495051525354555657583 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311412 unmodified lines12712812913013113213310 unmodified lines14414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517614 unmodified lines19119219319419519610 unmodified lines2072082092 unmodified linesfrom typing import Any, Dict, Optionalimport httpximport aiohttpfrom api.config import (DDG_API_ENDPOINT,DDG_STATUS_URL,MODEL_MAPPING,ALLOWED_MODELS,AGENT_MODE,10 unmodified lineslogger = setup_logger(__name__)async def get_ddg_vqd():status_url = DDG_STATUS_URL7 unmodified linestry:async with session.get(status_url, headers=headers) as response:if response.status == 200:vqd = response.headers.get("x-vqd-4")if not vqd:logger.error("VQD token not found in response headers.")return vqdelse:logger.error(f"Error: Status code {response.status} when fetching VQD")return None1 unmodified linelogger.error(f"Error getting VQD: {e}")return Nonedef message_to_dict_ddg(message):if isinstance(message.content, str):return {"role": message.role, "content": message.content}else:# If DDG API does not support non-string content, raise an errorraise ValueError("Message content must be a string.")def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:"""Remove the model prefix from the response content if present."""3 unmodified lineslogger.debug("No prefix to strip from content.")return contentdef create_chat_completion_data(content: str, model: str, timestamp: int, finish_reason: Optional[str] = None) -> Dict[str, Any]:return {"id": f"chatcmpl-{uuid.uuid4()}","object": "chat.completion.chunk","created": timestamp,"model": model,"choices": [{"index": 0,"delta": {"content": content, "role": "assistant"},"finish_reason": finish_reason,}],"usage": None,}async def process_ddg_streaming_response(request: ChatRequest):agent_mode = AGENT_MODE.get(request.model, {})trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})model_prefix = MODEL_PREFIXES.get(request.model, "")# referer_path and referer_url are not required unless specified by DDG API# Obtain VQD tokenvqd = await get_ddg_vqd()if not vqd:raise HTTPException(status_code=500, detail="Failed to obtain VQD token")# Build headersdynamic_headers = {'accept': 'text/event-stream','content-type': 'application/json','user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36','x-vqd-4': vqd}# Construct message historytry:message_history = [message_to_dict_ddg(msg) for msg in request.messages]except ValueError as ve:logger.error(f"Invalid message format: {ve}")raise HTTPException(status_code=400, detail=str(ve))json_data = {"model": MODEL_MAPPING.get(request.model, request.model),"messages": message_history,}async with httpx.AsyncClient() as client:12 unmodified linescontent = lineif content.startswith("$@$v=undefined-rv1$@$"):content = content[21:]# No model_prefix handling as messages are correctly formattedcleaned_content = strip_model_prefix(content, model_prefix)yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"10 unmodified linesagent_mode = AGENT_MODE.get(request.model, {})trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})model_prefix = MODEL_PREFIXES.get(request.model, "")# referer_path and referer_url are not required unless specified by DDG API# Obtain VQD tokenvqd = await get_ddg_vqd()if not vqd:raise HTTPException(status_code=500, detail="Failed to obtain VQD token")# Build headersdynamic_headers = {'accept': 'application/json','content-type': 'application/json','user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36','x-vqd-4': vqd}# Construct message historytry:message_history = [message_to_dict_ddg(msg) for msg in request.messages]except ValueError as ve:logger.error(f"Invalid message format: {ve}")raise HTTPException(status_code=400, detail=str(ve))json_data = {"model": MODEL_MAPPING.get(request.model, request.model),"messages": message_history,}async with httpx.AsyncClient() as client:try:response = await client.post(14 unmodified linesif full_response.startswith("$@$v=undefined-rv1$@$"):full_response = full_response[21:]cleaned_full_response = strip_model_prefix(full_response, model_prefix)return {10 unmodified lines],"usage": None,}
api/utils.py+60-67