Update app.py
Browse files3 unmodified lines456789156 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142153 unmodified linesimport uuidfrom datetime import datetime, timezonefrom typing import Optional, Dict, Anyfrom fastapi import FastAPI, HTTPException, Body, BackgroundTasks, Pathfrom fastapi.responses import StreamingResponse156 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 for proper async handlingfrom openai import AsyncOpenAIclient = AsyncOpenAI(api_key=custom_api_key_secret,base_url=custom_api_base_url,timeout=30.0 # Add timeout to prevent hanging connections)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: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 (IndexError, AttributeError) as e:logger.warning(f"Skipping malformed chunk: {e}")continueexcept 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:# Ensure proper cleanup of the clientif client:try:await client.close()except Exception as cleanup_error:logger.warning(f"Error closing OpenAI client: {cleanup_error}")return StreamingResponse(custom_api_streamer(),3 unmodified lines4567891011156 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282293 unmodified linesimport uuidfrom datetime import datetime, timezonefrom typing import Optional, Dict, Anyimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom fastapi import FastAPI, HTTPException, Body, BackgroundTasks, Pathfrom fastapi.responses import StreamingResponse156 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(),
app.py+42-28