Fix streaming and use proper system prompts
Browse filesIssues fixed:
1. Streaming not working properly - code only appeared at the end
2. Not using language-specific prompts from prompts.py
Backend changes (backend_api.py):
- Import system prompts from anycoder_app/prompts.py
- Initialize Gradio and ComfyUI prompts on startup via docs_manager
- Use language-specific prompts (HTML, Gradio, Streamlit, React, etc.)
- Add proper system prompt selection based on language parameter
- Improve streaming with smaller sleep intervals (0.01s) for immediate flush
- Add chunk counting and logging for debugging
- Add detailed logging for prompt selection
Frontend changes (page.tsx, api.ts):
- Add console logging to track chunk reception
- Log SSE events for debugging
- Log buffer sizes and chunk lengths
- Track generation completion with total code length
This ensures:
✅ Proper language-specific prompts are used (HTML, Gradio, Streamlit, etc.)
✅ Streaming works immediately with chunks appearing in real-time
✅ Better debugging with console logs
✅ Backend properly flushes chunks to frontend
Files changed (3)
18 unmodified lines192021222324285 unmodified lines31031131231331431531631754 unmodified lines3723733743753763774 unmodified lines3823833843853863872 unmodified lines39039139239339439539618 unmodified linesfrom huggingface_hub import InferenceClientimport httpx# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [{"name": "Sherlock Dash Alpha", "id": "openrouter/sherlock-dash-alpha", "description": "Sherlock Dash Alpha model via OpenRouter"},285 unmodified lines# Track generated codegenerated_code = ""# Use a simple system promptsystem_prompt = "You are a helpful AI assistant that generates code based on user requirements. Generate clean, well-commented code."# Get the real model IDactual_model_id = selected_model["id"]54 unmodified linesstream=True)for chunk in stream:# Check if choices array has elements before accessingif (hasattr(chunk, 'choices') and4 unmodified lineschunk.choices[0].delta.content):content = chunk.choices[0].delta.contentgenerated_code += content# Send chunk as Server-Sent Eventevent_data = json.dumps({2 unmodified lines"timestamp": datetime.now().isoformat()})yield f"data: {event_data}\n\n"await asyncio.sleep(0) # Allow other tasks to run# Send completion eventcompletion_data = json.dumps({18 unmodified lines192021222324252627282930313233343536373839404142434445464748285 unmodified lines33433533633733833934034134234334434534634734834935035154 unmodified lines4064074084094104114124 unmodified lines4174184194204214224232 unmodified lines42642742842943043143243343443543618 unmodified linesfrom huggingface_hub import InferenceClientimport httpx# Import system prompts for code generationfrom anycoder_app.prompts import (HTML_SYSTEM_PROMPT,TRANSFORMERS_JS_SYSTEM_PROMPT,STREAMLIT_SYSTEM_PROMPT,REACT_SYSTEM_PROMPT,GRADIO_SYSTEM_PROMPT,JSON_SYSTEM_PROMPT,GENERIC_SYSTEM_PROMPT)# Initialize Gradio and ComfyUI prompts on startuptry:from anycoder_app.docs_manager import update_gradio_system_prompts, update_json_system_promptsprint("[Startup] Initializing Gradio and ComfyUI system prompts...")update_gradio_system_prompts()update_json_system_prompts()# Re-import to get updated promptsfrom anycoder_app.prompts import GRADIO_SYSTEM_PROMPT, JSON_SYSTEM_PROMPTprint("[Startup] System prompts initialized successfully")except Exception as e:print(f"[Startup] Warning: Could not initialize dynamic prompts: {e}")print("[Startup] Will use fallback prompts")# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [{"name": "Sherlock Dash Alpha", "id": "openrouter/sherlock-dash-alpha", "description": "Sherlock Dash Alpha model via OpenRouter"},285 unmodified lines# 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 real model IDactual_model_id = selected_model["id"]54 unmodified linesstream=True)chunk_count = 0for chunk in stream:# Check if choices array has elements before accessingif (hasattr(chunk, 'choices') and4 unmodified lineschunk.choices[0].delta.content):content = chunk.choices[0].delta.contentgenerated_code += contentchunk_count += 1# Send chunk as Server-Sent Eventevent_data = json.dumps({2 unmodified lines"timestamp": datetime.now().isoformat()})yield f"data: {event_data}\n\n"# Ensure immediate flush to clientawait asyncio.sleep(0.01) # Small delay to ensure flushingprint(f"[Generate] Completed with {chunk_count} chunks, total length: {len(generated_code)}")# Send completion eventcompletion_data = json.dumps({
78 unmodified lines79808182838478 unmodified lines// onChunk - Update code editor in real-time, NOT the chat(chunk: string) => {generatedCodeBuffer += chunk;setGeneratedCode(generatedCodeBuffer);},// onComplete78 unmodified lines798081828384858678 unmodified lines// onChunk - Update code editor in real-time, NOT the chat(chunk: string) => {generatedCodeBuffer += chunk;console.log('[Stream] Received chunk:', chunk.substring(0, 50), '... (length:', chunk.length, ')');console.log('[Stream] Buffer size:', generatedCodeBuffer.length);setGeneratedCode(generatedCodeBuffer);},// onComplete
118 unmodified lines119120121122123124125126127128129130131118 unmodified lineseventSource.onmessage = (event) => {try {const data = JSON.parse(event.data);if (data.type === 'chunk' && data.content) {onChunk(data.content);} else if (data.type === 'complete' && data.code) {onComplete(data.code);eventSource.close();} else if (data.type === 'error') {onError(data.message || 'Unknown error occurred');eventSource.close();}118 unmodified lines119120121122123124125126127128129130131132133134118 unmodified lineseventSource.onmessage = (event) => {try {const data = JSON.parse(event.data);console.log('[SSE] Received event:', data.type, data.content?.substring(0, 30));if (data.type === 'chunk' && data.content) {onChunk(data.content);} else if (data.type === 'complete' && data.code) {console.log('[SSE] Generation complete, total code length:', data.code.length);onComplete(data.code);eventSource.close();} else if (data.type === 'error') {console.error('[SSE] Error:', data.message);onError(data.message || 'Unknown error occurred');eventSource.close();}