optimizations
Browse files62 unmodified lines6364656667686 unmodified lines757677787980285 unmodified lines36636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941018 unmodified lines42943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050162 unmodified linesprint("[Startup] System prompts initialization complete")# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [{"name": "Gemini 3.0 Pro", "id": "gemini-3.0-pro", "description": "Google Gemini 3.0 Pro via Poe with advanced reasoning"},6 unmodified lines{"name": "Qwen3 Max Preview", "id": "qwen3-max-preview", "description": "Qwen3 Max Preview via DashScope API"},]LANGUAGE_CHOICES = ["html", "gradio", "transformers.js", "streamlit", "comfyui", "react"]app = FastAPI(title="AnyCoder API", version="1.0.0")285 unmodified linesselected_model_id = model_idtry:# Find the selected modelselected_model = Nonefor model in AVAILABLE_MODELS:if model["id"] == selected_model_id:selected_model = modelbreakif not selected_model:selected_model = AVAILABLE_MODELS[0]selected_model_id = selected_model["id"]# Track generated codegenerated_code = ""# Select appropriate system prompt based on languageprompt_map = {"html": HTML_SYSTEM_PROMPT,"gradio": GRADIO_SYSTEM_PROMPT,"streamlit": STREAMLIT_SYSTEM_PROMPT,"transformers.js": TRANSFORMERS_JS_SYSTEM_PROMPT,"react": REACT_SYSTEM_PROMPT,"comfyui": JSON_SYSTEM_PROMPT,}system_prompt = prompt_map.get(language, GENERIC_SYSTEM_PROMPT.format(language=language))print(f"[Generate] Using {language} prompt for query: {query[:100]}...")# Get the client using backend_modelsprint(f"[Generate] Getting client for model: {selected_model_id}")client = get_inference_client(selected_model_id, provider)# Get the real model ID with provider suffixesactual_model_id = get_real_model_id(selected_model_id)print(f"[Generate] Using model ID: {actual_model_id}")# Prepare messagesmessages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"Generate a {language} application: {query}"}]# Stream the response18 unmodified lines)chunk_count = 0print(f"[Generate] Starting to stream from {actual_model_id}...")for chunk in stream:# Handle different response formatschunk_content = Noneif is_mistral_model(selected_model_id):# Mistral format: chunk.data.choices[0].delta.contentif (hasattr(chunk, "data") and chunk.data andhasattr(chunk.data, "choices") and chunk.data.choices andhasattr(chunk.data.choices[0], "delta") andhasattr(chunk.data.choices[0].delta, "content") andchunk.data.choices[0].delta.content is not None):chunk_content = chunk.data.choices[0].delta.contentelse:# OpenAI format: chunk.choices[0].delta.contentif (hasattr(chunk, 'choices') andchunk.choices andlen(chunk.choices) > 0 andhasattr(chunk.choices[0], 'delta') andhasattr(chunk.choices[0].delta, 'content') andchunk.choices[0].delta.content):chunk_content = chunk.choices[0].delta.contentif chunk_content:content = chunk_contentgenerated_code += contentchunk_count += 1# Log every 10th chunk to avoid spamif chunk_count % 10 == 0:print(f"[Generate] Streamed {chunk_count} chunks, {len(generated_code)} chars total")# Send chunk as Server-Sent Event - yield immediately for instant streamingevent_data = json.dumps({"type": "chunk","content": content,"timestamp": datetime.now().isoformat()})yield f"data: {event_data}\n\n"# Yield control to allow async processing - no artificial delayawait asyncio.sleep(0)print(f"[Generate] Completed with {chunk_count} chunks, total length: {len(generated_code)}")# Send completion eventcompletion_data = json.dumps({"type": "complete","code": generated_code,"timestamp": datetime.now().isoformat()})yield f"data: {completion_data}\n\n"except Exception as e:error_data = json.dumps({"type": "error","message": str(e),"timestamp": datetime.now().isoformat()})yield f"data: {error_data}\n\n"except Exception as e:error_data = json.dumps({"type": "error","message": f"Generation error: {str(e)}","timestamp": datetime.now().isoformat()})yield f"data: {error_data}\n\n"62 unmodified lines6364656667686970717273747576777879808182838485868788899091926 unmodified lines99100101102103104105106107108285 unmodified lines39439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542618 unmodified lines44544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450562 unmodified linesprint("[Startup] System prompts initialization complete")# Cache system prompts map for fast lookup (created once at startup)SYSTEM_PROMPT_CACHE = {"html": HTML_SYSTEM_PROMPT,"gradio": GRADIO_SYSTEM_PROMPT,"streamlit": STREAMLIT_SYSTEM_PROMPT,"transformers.js": TRANSFORMERS_JS_SYSTEM_PROMPT,"react": REACT_SYSTEM_PROMPT,"comfyui": JSON_SYSTEM_PROMPT,}# Client connection pool for reuse (thread-safe)import threading_client_pool = {}_client_pool_lock = threading.Lock()def get_cached_client(model_id: str, provider: str = "auto"):"""Get or create a cached API client for reuse"""cache_key = f"{model_id}:{provider}"with _client_pool_lock:if cache_key not in _client_pool:_client_pool[cache_key] = get_inference_client(model_id, provider)return _client_pool[cache_key]# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [{"name": "Gemini 3.0 Pro", "id": "gemini-3.0-pro", "description": "Google Gemini 3.0 Pro via Poe with advanced reasoning"},6 unmodified lines{"name": "Qwen3 Max Preview", "id": "qwen3-max-preview", "description": "Qwen3 Max Preview via DashScope API"},]# Cache model lookup for faster access (built after AVAILABLE_MODELS is defined)MODEL_CACHE = {model["id"]: model for model in AVAILABLE_MODELS}print(f"[Startup] ✅ Performance optimizations loaded: {len(SYSTEM_PROMPT_CACHE)} cached prompts, {len(MODEL_CACHE)} cached models, client pooling enabled")LANGUAGE_CHOICES = ["html", "gradio", "transformers.js", "streamlit", "comfyui", "react"]app = FastAPI(title="AnyCoder API", version="1.0.0")285 unmodified linesselected_model_id = model_idtry:# Fast model lookup using cacheselected_model = MODEL_CACHE.get(selected_model_id)if not selected_model:# Fallback to first available model (shouldn't happen often)selected_model = AVAILABLE_MODELS[0]selected_model_id = selected_model["id"]# Track generated codegenerated_code = ""# Fast system prompt lookup using cachesystem_prompt = SYSTEM_PROMPT_CACHE.get(language)if not system_prompt:# Format generic prompt only if neededsystem_prompt = GENERIC_SYSTEM_PROMPT.format(language=language)# Get cached client (reuses connections)client = get_cached_client(selected_model_id, provider)# Get the real model ID with provider suffixesactual_model_id = get_real_model_id(selected_model_id)# Prepare messages (optimized - no string concatenation in hot path)user_content = f"Generate a {language} application: {query}"messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": user_content}]# Stream the response18 unmodified lines)chunk_count = 0is_mistral = is_mistral_model(selected_model_id)# Optimized chunk processing - reduce attribute lookupsfor chunk in stream:chunk_content = Noneif is_mistral:# Mistral format: chunk.data.choices[0].delta.contenttry:if chunk.data and chunk.data.choices and chunk.data.choices[0].delta.content:chunk_content = chunk.data.choices[0].delta.contentexcept (AttributeError, IndexError):continueelse:# OpenAI format: chunk.choices[0].delta.contenttry:if chunk.choices and chunk.choices[0].delta.content:chunk_content = chunk.choices[0].delta.contentexcept (AttributeError, IndexError):continueif chunk_content:generated_code += chunk_contentchunk_count += 1# Send chunk immediately - optimized JSON serialization# Only yield control every 5 chunks to reduce overheadif chunk_count % 5 == 0:await asyncio.sleep(0)# Build event data efficientlyevent_data = json.dumps({"type": "chunk","content": chunk_content})yield f"data: {event_data}\n\n"# Send completion event (optimized - no timestamp in hot path)completion_data = json.dumps({"type": "complete","code": generated_code})yield f"data: {completion_data}\n\n"except Exception as e:error_data = json.dumps({"type": "error","message": str(e)})yield f"data: {error_data}\n\n"except Exception as e:error_data = json.dumps({"type": "error","message": f"Generation error: {str(e)}"})yield f"data: {error_data}\n\n"
backend_api.py+65-61