update import project
Browse filesFiles changed (3)
222 unmodified lines2232242252262262272282291 unmodified line2312322332342342352362371 unmodified line239240241242242243244245222 unmodified lines response = client.chat.completions.create( model=get_real_model_id(_current_model['id']), messages=messages, max_tokens=4000, max_tokens=10000, temperature=0.1 ) changes_text = response.choices[0].message.content1 unmodified line response = client.chat.complete( model=get_real_model_id(_current_model['id']), messages=messages, max_tokens=4000, max_tokens=10000, temperature=0.1 ) changes_text = response.choices[0].message.content1 unmodified line completion = client.chat.completions.create( model=get_real_model_id(_current_model['id']), messages=messages, max_tokens=4000, max_tokens=10000, temperature=0.1 ) changes_text = completion.choices[0].message.content344 unmodified lines345346347348348349350351352353350351352353354355356357358359360361362363364365344 unmodified lines )
@app.get("/api/generate")@app.post("/api/generate")async def generate_code( query: str, language: str = "html", model_id: str = "openrouter/sherlock-dash-alpha", provider: str = "auto", request: CodeGenerationRequest, authorization: Optional[str] = Header(None)): """Generate code based on user query - returns streaming response""" # Dev mode: No authentication required - just use server's HF_TOKEN # In production, you would check real OAuth tokens here # Extract parameters from request body query = request.query language = request.language model_id = request.model_id provider = request.provider async def event_stream() -> AsyncGenerator[str, None]: """Stream generated code chunks""" # Use the model_id from outer scope96 unmodified lines9798991001001011021033 unmodified lines10710810911011111211311411511011711811912012112211111211311411511611711811912012112212312412512612712812912412512612712812913013113213313013113213513613713813914014114214314413313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120214820320420520696 unmodified lines } }
// Stream-based code generation using EventSource (Server-Sent Events) // Stream-based code generation using Fetch API with streaming (supports POST) generateCodeStream( request: CodeGenerationRequest, onChunk: (content: string) => void,3 unmodified lines // Build the URL correctly whether we have a base URL or not const baseUrl = API_URL || window.location.origin; const url = new URL('/api/generate', baseUrl); url.search = new URLSearchParams({ query: request.query, language: request.language, model_id: request.model_id, provider: request.provider, }).toString(); const eventSource = new EventSource(url.toString());
eventSource.onmessage = (event) => { try { const data = JSON.parse(event.data); console.log('[SSE] Received event:', data.type, data.content?.substring(0, 30)); let abortController = new AbortController(); let accumulatedCode = ''; let buffer = ''; // Buffer for incomplete SSE lines // Use fetch with POST to support large payloads fetch(url.toString(), { method: 'POST', headers: { 'Content-Type': 'application/json', ...(this.token ? { 'Authorization': `Bearer ${this.token}` } : {}), }, body: JSON.stringify(request), signal: abortController.signal, }) .then(async (response) => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } 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(); if (!response.body) { throw new Error('Response body is null'); } } catch (error) { console.error('Error parsing SSE data:', error); } };
eventSource.onerror = (error) => { console.error('EventSource error:', error); onError('Connection error occurred'); eventSource.close(); }; const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) { console.log('[Stream] Stream ended, total code length:', accumulatedCode.length); if (accumulatedCode) { onComplete(accumulatedCode); } break; } // Decode chunk and add to buffer buffer += decoder.decode(value, { stream: true }); // Process complete SSE messages (ending with \n\n) const messages = buffer.split('\n\n'); // Keep the last incomplete message in the buffer buffer = messages.pop() || ''; // Process each complete message for (const message of messages) { if (!message.trim()) continue; // Parse SSE format: "data: {...}" const lines = message.split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { try { const jsonStr = line.substring(6); const data = JSON.parse(jsonStr); console.log('[Stream] Received event:', data.type, data.content?.substring(0, 50)); if (data.type === 'chunk' && data.content) { accumulatedCode += data.content; onChunk(data.content); } else if (data.type === 'complete') { console.log('[Stream] Generation complete, total code length:', data.code?.length || accumulatedCode.length); // Use the complete code from the message if available, otherwise use accumulated const finalCode = data.code || accumulatedCode; onComplete(finalCode); return; // Exit the processing loop } else if (data.type === 'error') { console.error('[Stream] Error:', data.message); onError(data.message || 'Unknown error occurred'); return; // Exit the processing loop } } catch (error) { console.error('Error parsing SSE data:', error, 'Line:', line); } } } } } }) .catch((error) => { if (error.name === 'AbortError') { console.log('[Stream] Request aborted'); return; } console.error('[Stream] Fetch error:', error); onError(error.message || 'Connection error occurred'); });
// Return cleanup function return () => { eventSource.close(); abortController.abort(); }; }
anycoder_app/deploy.py+3-3
backend_api.py+8-5
frontend/src/lib/api.ts+89-34