Spaces:
Sleeping
Sleeping
Commit
·
504d810
1
Parent(s):
56d3b84
fixed streaming
Browse files
main.py
CHANGED
|
@@ -134,25 +134,24 @@ async def chat_completions(
|
|
| 134 |
is_claude_or_gemini = "claude" in flowith_model_name.lower() or "gemini" in flowith_model_name.lower()
|
| 135 |
|
| 136 |
for msg in request.messages:
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
#
|
| 155 |
-
|
| 156 |
|
| 157 |
# 4. Construct Flowith Request Payload
|
| 158 |
flowith_payload = FlowithRequest(
|
|
@@ -168,11 +167,11 @@ async def chat_completions(
|
|
| 168 |
'accept': '*/*',
|
| 169 |
'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6,ja;q=0.5',
|
| 170 |
'authorization': FLOWITH_AUTH_TOKEN, # Send only the token, no "Bearer " prefix
|
| 171 |
-
'content-type': 'application/json',
|
|
|
|
| 172 |
'origin': 'https://flowith.net',
|
| 173 |
'priority': 'u=1, i',
|
| 174 |
'referer': 'https://flowith.net/',
|
| 175 |
-
'responsetype': 'stream', # Added - Was present in -H flags
|
| 176 |
'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
|
| 177 |
'sec-ch-ua-mobile': '?0',
|
| 178 |
'sec-ch-ua-platform': '"Windows"',
|
|
@@ -183,77 +182,122 @@ async def chat_completions(
|
|
| 183 |
}
|
| 184 |
|
| 185 |
# 6. Make Asynchronous Request to Flowith
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
try:
|
| 188 |
-
#
|
| 189 |
-
# Serialize payload manually for content=
|
| 190 |
payload_bytes = json.dumps(flowith_payload.dict()).encode('utf-8')
|
| 191 |
-
|
| 192 |
-
|
|
|
|
| 193 |
FLOWITH_API_URL,
|
| 194 |
-
content=payload_bytes,
|
| 195 |
headers=headers,
|
| 196 |
)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
#
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
# Try to parse as JSON
|
| 235 |
try:
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
except httpx.RequestError as exc:
|
| 246 |
print(f"Error requesting Flowith: {exc}")
|
| 247 |
raise HTTPException(status_code=503, detail=f"Error connecting to Flowith service: {exc}")
|
| 248 |
except HTTPException as http_exc:
|
| 249 |
-
|
| 250 |
-
|
| 251 |
except Exception as exc:
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
raise HTTPException(status_code=500, detail=f"Internal server error: {exc}")
|
| 257 |
|
| 258 |
|
| 259 |
# --- Models Endpoint ---
|
|
|
|
| 134 |
is_claude_or_gemini = "claude" in flowith_model_name.lower() or "gemini" in flowith_model_name.lower()
|
| 135 |
|
| 136 |
for msg in request.messages:
|
| 137 |
+
original_role = msg.role.lower() # Get original role
|
| 138 |
+
new_role = original_role # Start with original role
|
| 139 |
+
|
| 140 |
+
# Check for Claude/Gemini system message conversion based on *requested* model
|
| 141 |
+
is_claude_or_gemini_requested = "claude" in request.model.lower() or "gemini" in request.model.lower()
|
| 142 |
+
if is_claude_or_gemini_requested and original_role == "system":
|
| 143 |
+
new_role = "user"
|
| 144 |
+
# Check for non-standard roles (applies AFTER potential system->user conversion for C/G)
|
| 145 |
+
elif original_role not in {"user", "assistant", "system"}:
|
| 146 |
+
new_role = "user"
|
| 147 |
+
print(f"Warning: Converting non-standard role '{original_role}' to 'user' for model {request.model}")
|
| 148 |
+
|
| 149 |
+
# Append message with the determined new_role, but only if it's valid for Flowith
|
| 150 |
+
# Flowith only accepts 'user' and 'assistant'
|
| 151 |
+
if new_role in ["user", "assistant"]:
|
| 152 |
+
processed_messages.append(FlowithMessage(role=new_role, content=msg.content))
|
| 153 |
+
# else: # Log or skip roles that are still 'system' after processing
|
| 154 |
+
# print(f"Skipping message with final role '{new_role}' as it's not 'user' or 'assistant'. Original role: '{original_role}'")
|
|
|
|
| 155 |
|
| 156 |
# 4. Construct Flowith Request Payload
|
| 157 |
flowith_payload = FlowithRequest(
|
|
|
|
| 167 |
'accept': '*/*',
|
| 168 |
'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6,ja;q=0.5',
|
| 169 |
'authorization': FLOWITH_AUTH_TOKEN, # Send only the token, no "Bearer " prefix
|
| 170 |
+
'content-type': 'application/json',
|
| 171 |
+
'responsetype': 'stream', # Restore this header
|
| 172 |
'origin': 'https://flowith.net',
|
| 173 |
'priority': 'u=1, i',
|
| 174 |
'referer': 'https://flowith.net/',
|
|
|
|
| 175 |
'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
|
| 176 |
'sec-ch-ua-mobile': '?0',
|
| 177 |
'sec-ch-ua-platform': '"Windows"',
|
|
|
|
| 182 |
}
|
| 183 |
|
| 184 |
# 6. Make Asynchronous Request to Flowith
|
| 185 |
+
# Need time for simulated streaming chunks
|
| 186 |
+
import time
|
| 187 |
+
# Need JSONResponse
|
| 188 |
+
from fastapi.responses import JSONResponse
|
| 189 |
+
|
| 190 |
+
async with httpx.AsyncClient(timeout=300.0) as client:
|
| 191 |
try:
|
| 192 |
+
# Serialize payload manually
|
|
|
|
| 193 |
payload_bytes = json.dumps(flowith_payload.dict()).encode('utf-8')
|
| 194 |
+
|
| 195 |
+
# Make a non-streaming POST request to Flowith
|
| 196 |
+
response = await client.post(
|
| 197 |
FLOWITH_API_URL,
|
| 198 |
+
content=payload_bytes,
|
| 199 |
headers=headers,
|
| 200 |
)
|
| 201 |
+
|
| 202 |
+
# Check status code after receiving the full response
|
| 203 |
+
if response.status_code != 200:
|
| 204 |
+
try:
|
| 205 |
+
error_detail = response.text # Use .text for non-streaming
|
| 206 |
+
detail_msg = f"Flowith API Error ({response.status_code}): {error_detail}"
|
| 207 |
+
except Exception:
|
| 208 |
+
detail_msg = f"Flowith API Error ({response.status_code})"
|
| 209 |
+
raise HTTPException(status_code=response.status_code, detail=detail_msg)
|
| 210 |
+
|
| 211 |
+
# Attempt to parse the full response body as JSON
|
| 212 |
+
try:
|
| 213 |
+
flowith_data = response.json()
|
| 214 |
+
except json.JSONDecodeError as e:
|
| 215 |
+
print(f"Error decoding Flowith JSON response: {e}. Response text: {response.text[:200]}...")
|
| 216 |
+
raise HTTPException(status_code=502, detail=f"Invalid JSON response from Flowith: {e}")
|
| 217 |
+
|
| 218 |
+
# 7. Handle response based on *client's* request.stream preference
|
| 219 |
+
if not request.stream:
|
| 220 |
+
# Client wants non-streaming: Return the parsed Flowith data directly
|
| 221 |
+
return JSONResponse(content=flowith_data)
|
| 222 |
+
else:
|
| 223 |
+
# Client wants streaming: Simulate streaming from the complete response
|
| 224 |
+
# Client wants streaming: Simulate streaming word-by-word from the complete response
|
| 225 |
+
async def stream_generator() -> AsyncGenerator[str, None]:
|
| 226 |
+
# Ensure necessary imports are available (time, json, uuid are already imported)
|
| 227 |
+
# import time # Already imported around line 186
|
| 228 |
+
# import json # Already imported at top
|
| 229 |
+
# import uuid # Already imported at top
|
| 230 |
+
# import asyncio # Needed only if adding delay
|
| 231 |
+
|
| 232 |
+
chunk_id = f"chatcmpl-{uuid.uuid4()}"
|
| 233 |
+
model_name = request.model # Use the model requested by the client
|
| 234 |
+
|
| 235 |
+
# Extract full content safely
|
| 236 |
+
full_content = ""
|
|
|
|
|
|
|
| 237 |
try:
|
| 238 |
+
# Try the expected structure first
|
| 239 |
+
full_content = flowith_data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 240 |
+
if not full_content:
|
| 241 |
+
# Fallback: Check for other common fields
|
| 242 |
+
full_content = flowith_data.get("text", flowith_data.get("completion", ""))
|
| 243 |
+
|
| 244 |
+
if not full_content:
|
| 245 |
+
print(f"Warning: Could not extract content for streaming from Flowith response: {flowith_data}")
|
| 246 |
+
full_content = "" # Default to empty if extraction fails
|
| 247 |
+
|
| 248 |
+
except (AttributeError, IndexError, TypeError) as e:
|
| 249 |
+
print(f"Error extracting content for streaming: {e}. Data: {flowith_data}")
|
| 250 |
+
full_content = "" # Default to empty on error
|
| 251 |
+
|
| 252 |
+
# Define chunk size
|
| 253 |
+
chunk_size = 20
|
| 254 |
+
|
| 255 |
+
# Stream fixed-size chunks
|
| 256 |
+
for i in range(0, len(full_content), chunk_size):
|
| 257 |
+
content_piece = full_content[i:i + chunk_size]
|
| 258 |
+
chunk = {
|
| 259 |
+
"id": chunk_id,
|
| 260 |
+
"object": "chat.completion.chunk",
|
| 261 |
+
"created": int(time.time()), # New timestamp for each chunk
|
| 262 |
+
"model": model_name,
|
| 263 |
+
"choices": [{
|
| 264 |
+
"index": 0,
|
| 265 |
+
"delta": {"content": content_piece}, # Use the 20-char piece
|
| 266 |
+
"finish_reason": None
|
| 267 |
+
}]
|
| 268 |
+
}
|
| 269 |
+
yield f"data: {json.dumps(chunk)}\n\n"
|
| 270 |
+
# Optional delay for simulation
|
| 271 |
+
# await asyncio.sleep(0.01)
|
| 272 |
+
|
| 273 |
+
# Send the final chunk with finish_reason
|
| 274 |
+
final_chunk = {
|
| 275 |
+
"id": chunk_id,
|
| 276 |
+
"object": "chat.completion.chunk",
|
| 277 |
+
"created": int(time.time()), # Use a final timestamp
|
| 278 |
+
"model": model_name,
|
| 279 |
+
"choices": [{
|
| 280 |
+
"index": 0,
|
| 281 |
+
"delta": {}, # Empty delta for final chunk
|
| 282 |
+
"finish_reason": "stop" # Assume 'stop'
|
| 283 |
+
}]
|
| 284 |
+
}
|
| 285 |
+
yield f"data: {json.dumps(final_chunk)}\n\n"
|
| 286 |
+
yield "data: [DONE]\n\n"
|
| 287 |
+
|
| 288 |
+
return StreamingResponse(stream_generator(), media_type="text/event-stream")
|
| 289 |
|
| 290 |
except httpx.RequestError as exc:
|
| 291 |
print(f"Error requesting Flowith: {exc}")
|
| 292 |
raise HTTPException(status_code=503, detail=f"Error connecting to Flowith service: {exc}")
|
| 293 |
except HTTPException as http_exc:
|
| 294 |
+
# Re-raise HTTPExceptions (e.g., from status code check or JSON parsing)
|
| 295 |
+
raise http_exc
|
| 296 |
except Exception as exc:
|
| 297 |
+
print(f"Unexpected error during Flowith request/processing: {exc}")
|
| 298 |
+
import traceback
|
| 299 |
+
traceback.print_exc()
|
| 300 |
+
raise HTTPException(status_code=500, detail=f"Internal server error: {exc}")
|
|
|
|
| 301 |
|
| 302 |
|
| 303 |
# --- Models Endpoint ---
|