Update app.py
Browse files167 unmodified lines168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232167 unmodified linesraise HTTPException(status_code=500, detail="Custom API key not configured.")async def custom_api_streamer():executor = ThreadPoolExecutor(max_workers=1)client = Nonetry:logger.info("Sending request to Custom API for /chat.")def create_stream():nonlocal clientclient = openai.OpenAI(api_key=custom_api_key_secret,base_url=custom_api_base_url,timeout=30.0)return client.chat.completions.create(model=custom_api_model,temperature=payload.temperature,messages=[{"role": "user", "content": payload.message}],stream=True)# Run the blocking call in a threadstream = await asyncio.get_event_loop().run_in_executor(executor, create_stream)def process_chunk():try:for chunk in stream:content_to_yield = Noneif hasattr(chunk.choices[0].delta, "reasoning_content") and chunk.choices[0].delta.reasoning_content:content_to_yield = chunk.choices[0].delta.reasoning_contentelif chunk.choices[0].delta and chunk.choices[0].delta.content:content_to_yield = chunk.choices[0].delta.contentif content_to_yield:yield content_to_yieldexcept Exception as e:logger.error(f"Error processing stream chunk: {e}")yield f"Error processing stream: {str(e)}"# Process chunks in the thread poolloop = asyncio.get_event_loop()chunks = await loop.run_in_executor(executor, lambda: list(process_chunk()))for chunk in chunks:yield chunkexcept Exception as e:logger.error(f"Error during Custom API call for /chat: {e}", exc_info=True)yield f"Error processing with Custom API: {str(e)}"finally:# Cleanupif client:try:client.close()except Exception as cleanup_error:logger.warning(f"Error closing OpenAI client: {cleanup_error}")executor.shutdown(wait=False)return StreamingResponse(custom_api_streamer(),media_type="text/plain",headers={"Cache-Control": "no-cache",167 unmodified lines168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225167 unmodified linesraise HTTPException(status_code=500, detail="Custom API key not configured.")async def custom_api_streamer():client = Nonetry:logger.info("Sending request to Custom API for /chat.")# Use AsyncOpenAI with proper configurationfrom openai import AsyncOpenAIclient = AsyncOpenAI(api_key=custom_api_key_secret,base_url=custom_api_base_url,timeout=60.0 # Longer timeout for gemma3:27b model)stream = await client.chat.completions.create(model=custom_api_model,temperature=payload.temperature,messages=[{"role": "user", "content": payload.message}],stream=True)async for chunk in stream:try:# Exact same logic as your working codeif hasattr(chunk.choices[0].delta, "reasoning_content") and chunk.choices[0].delta.reasoning_content:yield chunk.choices[0].delta.reasoning_contentelif chunk.choices[0].delta.content is not None: # Handle None explicitlyyield chunk.choices[0].delta.contentexcept (IndexError, AttributeError) as e:# Skip malformed chunks silently (some APIs send empty chunks)continueexcept Exception as e:logger.warning(f"Skipping chunk due to error: {e}")continueexcept Exception as e:logger.error(f"Error during Custom API call for /chat: {e}", exc_info=True)# Handle specific connection errors with retry suggestionif "peer closed connection" in str(e) or "incomplete chunked read" in str(e):yield "Connection interrupted. Please try again."else:yield f"Error processing with Custom API: {str(e)}"finally:if client:try:await client.close()except Exception as cleanup_error:logger.warning(f"Error closing OpenAI client: {cleanup_error}")return StreamingResponse(custom_api_streamer(),media_type="text/plain",headers={"Cache-Control": "no-cache",
app.py+34-41