update import project
Browse filesFiles changed (3)
222 unmodified lines2232242252262272282291 unmodified line2312322332342352362371 unmodified line239240241242243244245222 unmodified linesresponse = client.chat.completions.create(model=get_real_model_id(_current_model['id']),messages=messages,max_tokens=4000,temperature=0.1)changes_text = response.choices[0].message.content1 unmodified lineresponse = client.chat.complete(model=get_real_model_id(_current_model['id']),messages=messages,max_tokens=4000,temperature=0.1)changes_text = response.choices[0].message.content1 unmodified linecompletion = client.chat.completions.create(model=get_real_model_id(_current_model['id']),messages=messages,max_tokens=4000,temperature=0.1)changes_text = completion.choices[0].message.content222 unmodified lines2232242252262272282291 unmodified line2312322332342352362371 unmodified line239240241242243244245222 unmodified linesresponse = client.chat.completions.create(model=get_real_model_id(_current_model['id']),messages=messages,max_tokens=10000,temperature=0.1)changes_text = response.choices[0].message.content1 unmodified lineresponse = client.chat.complete(model=get_real_model_id(_current_model['id']),messages=messages,max_tokens=10000,temperature=0.1)changes_text = response.choices[0].message.content1 unmodified linecompletion = client.chat.completions.create(model=get_real_model_id(_current_model['id']),messages=messages,max_tokens=10000,temperature=0.1)changes_text = completion.choices[0].message.content
344 unmodified lines345346347348349350351352353354355356357358359360361362344 unmodified lines)@app.get("/api/generate")async def generate_code(query: str,language: str = "html",model_id: str = "openrouter/sherlock-dash-alpha",provider: str = "auto",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 hereasync def event_stream() -> AsyncGenerator[str, None]:"""Stream generated code chunks"""# Use the model_id from outer scope344 unmodified lines345346347348349350351352353354355356357358359360361362363364365344 unmodified lines)@app.post("/api/generate")async def generate_code(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 bodyquery = request.querylanguage = request.languagemodel_id = request.model_idprovider = request.providerasync def event_stream() -> AsyncGenerator[str, None]:"""Stream generated code chunks"""# Use the model_id from outer scope
96 unmodified lines9798991001011021033 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015196 unmodified lines}}// Stream-based code generation using EventSource (Server-Sent Events)generateCodeStream(request: CodeGenerationRequest,onChunk: (content: string) => void,3 unmodified lines// Build the URL correctly whether we have a base URL or notconst 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));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();}} catch (error) {console.error('Error parsing SSE data:', error);}};eventSource.onerror = (error) => {console.error('EventSource error:', error);onError('Connection error occurred');eventSource.close();};// Return cleanup functionreturn () => {eventSource.close();};}96 unmodified lines9798991001011021033 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520696 unmodified lines}}// 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 notconst baseUrl = API_URL || window.location.origin;const url = new URL('/api/generate', baseUrl);let abortController = new AbortController();let accumulatedCode = '';let buffer = ''; // Buffer for incomplete SSE lines// Use fetch with POST to support large payloadsfetch(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 (!response.body) {throw new Error('Response body is null');}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 bufferbuffer += 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 bufferbuffer = messages.pop() || '';// Process each complete messagefor (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 accumulatedconst 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 functionreturn () => {abortController.abort();};}
anycoder_app/deploy.py+3-3
backend_api.py+8-5
frontend/src/lib/api.ts+89-34