Update app.py
Browse files
app.py
CHANGED
|
@@ -160,75 +160,64 @@ async def direct_chat(payload: ChatPayload):
|
|
| 160 |
custom_api_key_secret = os.getenv("CUSTOM_API_SECRET_KEY")
|
| 161 |
custom_api_base_url = os.getenv("CUSTOM_API_BASE_URL", CUSTOM_API_BASE_URL_DEFAULT)
|
| 162 |
custom_api_model = os.getenv("CUSTOM_API_MODEL", CUSTOM_API_MODEL_DEFAULT)
|
| 163 |
-
|
| 164 |
if not custom_api_key_secret:
|
| 165 |
logger.error("Custom API key ('CUSTOM_API_SECRET_KEY') is not configured for /chat.")
|
| 166 |
raise HTTPException(status_code=500, detail="Custom API key not configured.")
|
| 167 |
-
|
| 168 |
-
client = openai.OpenAI(api_key=custom_api_key_secret, base_url=custom_api_base_url)
|
| 169 |
-
|
| 170 |
async def custom_api_streamer():
|
|
|
|
| 171 |
try:
|
| 172 |
logger.info("Sending request to Custom API for /chat.")
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
model=custom_api_model,
|
| 175 |
temperature=payload.temperature,
|
| 176 |
messages=[{"role": "user", "content": payload.message}],
|
| 177 |
stream=True
|
| 178 |
)
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
content_to_yield =
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
except Exception as e:
|
| 188 |
logger.error(f"Error during Custom API call for /chat: {e}", exc_info=True)
|
| 189 |
yield f"Error processing with Custom API: {str(e)}"
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
gemini_api_key_from_request = request.api_key
|
| 199 |
-
gemini_api_key_secret = os.getenv("GEMINI_API_KEY")
|
| 200 |
-
key_to_use = gemini_api_key_from_request or gemini_api_key_secret
|
| 201 |
-
|
| 202 |
-
if not key_to_use:
|
| 203 |
-
logger.error(f"[Task {task_id}] Gemini API Key missing for task submission.")
|
| 204 |
-
raise HTTPException(status_code=400, detail="Gemini API Key required.")
|
| 205 |
-
|
| 206 |
-
requested_model = request.gemini_model or DEFAULT_GEMINI_MODEL
|
| 207 |
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
"
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
"request_params": request.model_dump() # Store original request
|
| 216 |
-
}
|
| 217 |
-
|
| 218 |
-
background_tasks.add_task(
|
| 219 |
-
process_gemini_request_background,
|
| 220 |
-
task_id,
|
| 221 |
-
request.message,
|
| 222 |
-
request.url,
|
| 223 |
-
requested_model,
|
| 224 |
-
key_to_use
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
logger.info(f"[Task {task_id}] Task submitted to background processing.")
|
| 228 |
-
return TaskSubmissionResponse(
|
| 229 |
-
task_id=task_id,
|
| 230 |
-
status="PENDING",
|
| 231 |
-
task_detail_url=f"/gemini/task/{task_id}" # Provide the URL to poll
|
| 232 |
)
|
| 233 |
|
| 234 |
|
|
|
|
| 160 |
custom_api_key_secret = os.getenv("CUSTOM_API_SECRET_KEY")
|
| 161 |
custom_api_base_url = os.getenv("CUSTOM_API_BASE_URL", CUSTOM_API_BASE_URL_DEFAULT)
|
| 162 |
custom_api_model = os.getenv("CUSTOM_API_MODEL", CUSTOM_API_MODEL_DEFAULT)
|
| 163 |
+
|
| 164 |
if not custom_api_key_secret:
|
| 165 |
logger.error("Custom API key ('CUSTOM_API_SECRET_KEY') is not configured for /chat.")
|
| 166 |
raise HTTPException(status_code=500, detail="Custom API key not configured.")
|
| 167 |
+
|
|
|
|
|
|
|
| 168 |
async def custom_api_streamer():
|
| 169 |
+
client = None
|
| 170 |
try:
|
| 171 |
logger.info("Sending request to Custom API for /chat.")
|
| 172 |
+
|
| 173 |
+
# Use AsyncOpenAI for proper async handling
|
| 174 |
+
from openai import AsyncOpenAI
|
| 175 |
+
client = AsyncOpenAI(
|
| 176 |
+
api_key=custom_api_key_secret,
|
| 177 |
+
base_url=custom_api_base_url,
|
| 178 |
+
timeout=30.0 # Add timeout to prevent hanging connections
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
stream = await client.chat.completions.create(
|
| 182 |
model=custom_api_model,
|
| 183 |
temperature=payload.temperature,
|
| 184 |
messages=[{"role": "user", "content": payload.message}],
|
| 185 |
stream=True
|
| 186 |
)
|
| 187 |
+
|
| 188 |
+
async for chunk in stream:
|
| 189 |
+
try:
|
| 190 |
+
content_to_yield = None
|
| 191 |
+
if hasattr(chunk.choices[0].delta, "reasoning_content") and chunk.choices[0].delta.reasoning_content:
|
| 192 |
+
content_to_yield = chunk.choices[0].delta.reasoning_content
|
| 193 |
+
elif chunk.choices[0].delta and chunk.choices[0].delta.content:
|
| 194 |
+
content_to_yield = chunk.choices[0].delta.content
|
| 195 |
+
|
| 196 |
+
if content_to_yield:
|
| 197 |
+
yield content_to_yield
|
| 198 |
+
|
| 199 |
+
except (IndexError, AttributeError) as e:
|
| 200 |
+
logger.warning(f"Skipping malformed chunk: {e}")
|
| 201 |
+
continue
|
| 202 |
+
|
| 203 |
except Exception as e:
|
| 204 |
logger.error(f"Error during Custom API call for /chat: {e}", exc_info=True)
|
| 205 |
yield f"Error processing with Custom API: {str(e)}"
|
| 206 |
+
finally:
|
| 207 |
+
# Ensure proper cleanup of the client
|
| 208 |
+
if client:
|
| 209 |
+
try:
|
| 210 |
+
await client.close()
|
| 211 |
+
except Exception as cleanup_error:
|
| 212 |
+
logger.warning(f"Error closing OpenAI client: {cleanup_error}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
+
return StreamingResponse(
|
| 215 |
+
custom_api_streamer(),
|
| 216 |
+
media_type="text/plain",
|
| 217 |
+
headers={
|
| 218 |
+
"Cache-Control": "no-cache",
|
| 219 |
+
"Connection": "keep-alive",
|
| 220 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
)
|
| 222 |
|
| 223 |
|