Fix OpenRouter streaming: Use OpenAI client with proper headers
Browse filesIssue: Streaming not working with OpenRouter models
Root cause: Using InferenceClient instead of OpenAI client for OpenRouter
Fix:
- Use OpenAI client directly for OpenRouter (as per their docs)
- Add required headers: HTTP-Referer and X-Title for OpenRouter ranking
- Remove artificial 0.01s delay - use asyncio.sleep(0) for immediate flush
- Add detailed logging every 10 chunks to track streaming progress
- Log when streaming starts and total chunks/chars at completion
OpenRouter streaming now works correctly:
✅ Uses base_url='https://openrouter.ai/api/v1'
✅ Includes HTTP-Referer and X-Title headers
✅ Streams immediately with no artificial delays
✅ Logs: 'Starting to stream...', 'Streamed N chunks', 'Completed'
✅ Works with all openrouter/ prefixed models
Example streaming flow:
1. User sends request
2. Backend logs: '[Generate] Starting to stream from openrouter/sherlock-dash-alpha...'
3. Chunks arrive: '[Generate] Streamed 10 chunks, 250 chars total'
4. Frontend receives each chunk immediately via SSE
5. Monaco editor updates in real-time
6. Backend logs: '[Generate] Completed with 147 chunks, total length: 3241'
376 unmodified lines37737837938038138238338438538645 unmodified lines4324334344354364376 unmodified lines4444454464474484494501 unmodified line452453454455456457458459376 unmodified lines# Determine which provider/API to use based on model IDif actual_model_id.startswith("openrouter/"):# OpenRouter models - use via OpenAI-compatible APIapi_key = os.getenv("OPENROUTER_API_KEY") or os.getenv("HF_TOKEN")client = InferenceClient(api_key=api_key, provider="openai", base_url="https://openrouter.ai/api/v1")# Keep the model_id as-is for OpenRouterelif actual_model_id == "MiniMaxAI/MiniMax-M2":# MiniMax M2 via HuggingFace with Novita providerhf_token = os.getenv("HF_TOKEN")45 unmodified lines)chunk_count = 0for chunk in stream:# Check if choices array has elements before accessingif (hasattr(chunk, 'choices') and6 unmodified linesgenerated_code += contentchunk_count += 1# Send chunk as Server-Sent Eventevent_data = json.dumps({"type": "chunk","content": content,1 unmodified line})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)}")376 unmodified lines37737837938038138238338438538638738838939039139239339445 unmodified lines4404414424434444454464476 unmodified lines4544554564574584594604614624634641 unmodified line466467468469470471472473376 unmodified lines# Determine which provider/API to use based on model IDif actual_model_id.startswith("openrouter/"):# OpenRouter models - use OpenAI client directlyfrom openai import OpenAIapi_key = os.getenv("OPENROUTER_API_KEY") or os.getenv("HF_TOKEN")client = OpenAI(base_url="https://openrouter.ai/api/v1",api_key=api_key,default_headers={"HTTP-Referer": "https://huggingface.co/spaces/akhaliq/anycoder","X-Title": "AnyCoder"})print(f"[Generate] Using OpenRouter with model: {actual_model_id}")elif actual_model_id == "MiniMaxAI/MiniMax-M2":# MiniMax M2 via HuggingFace with Novita providerhf_token = os.getenv("HF_TOKEN")45 unmodified lines)chunk_count = 0print(f"[Generate] Starting to stream from {actual_model_id}...")for chunk in stream:# Check if choices array has elements before accessingif (hasattr(chunk, 'choices') and6 unmodified linesgenerated_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,1 unmodified line})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)}")