Chrunos commited on
Commit
c2008cc
·
verified ·
1 Parent(s): d57c6f7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -54
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
- stream = client.chat.completions.create(
 
 
 
 
 
 
 
 
 
174
  model=custom_api_model,
175
  temperature=payload.temperature,
176
  messages=[{"role": "user", "content": payload.message}],
177
  stream=True
178
  )
179
- for chunk in stream:
180
- content_to_yield = None
181
- if hasattr(chunk.choices[0].delta, "reasoning_content") and chunk.choices[0].delta.reasoning_content:
182
- content_to_yield = chunk.choices[0].delta.reasoning_content
183
- elif chunk.choices[0].delta and chunk.choices[0].delta.content:
184
- content_to_yield = chunk.choices[0].delta.content
185
- if content_to_yield:
186
- yield content_to_yield
 
 
 
 
 
 
 
 
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
- return StreamingResponse(custom_api_streamer(), media_type="text/plain")
191
-
192
-
193
- @app.post("/gemini/submit_task", response_model=TaskSubmissionResponse)
194
- async def submit_gemini_task(request: GeminiTaskRequest, background_tasks: BackgroundTasks):
195
- task_id = str(uuid.uuid4())
196
- logger.info(f"Received Gemini task submission. Assigning Task ID: {task_id}. Message: '{request.message[:50]}...'")
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
- current_time = datetime.now(timezone.utc)
209
- tasks_db[task_id] = {
210
- "status": "PENDING",
211
- "result": None,
212
- "error": None,
213
- "submitted_at": current_time,
214
- "last_updated_at": current_time,
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