Niansuh commited on
Commit
8c786ae
·
verified ·
1 Parent(s): 7e50448

Update api/utils.py

Browse files
Files changed (1) hide show
  1. api/utils.py +102 -67
api/utils.py CHANGED
@@ -1,22 +1,30 @@
1
  from datetime import datetime
2
- from http.client import HTTPException
3
  import json
4
  from typing import Any, Dict, Optional
5
  import uuid
6
 
7
  import httpx
8
- from api import validate
9
- from api.config import MODEL_MAPPING, headers, AGENT_MODE, TRENDING_AGENT_MODE
10
- from fastapi import Depends, security
11
- from fastapi.security import HTTPAuthorizationCredentials
12
 
13
- from api.config import APP_SECRET, BASE_URL
 
 
 
 
 
 
 
 
14
  from api.models import ChatRequest
15
 
16
  from api.logger import setup_logger
17
 
18
  logger = setup_logger(__name__)
19
 
 
 
 
20
  def create_chat_completion_data(
21
  content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
22
  ) -> Dict[str, Any]:
@@ -35,26 +43,46 @@ def create_chat_completion_data(
35
  "usage": None,
36
  }
37
 
38
- def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
39
  if credentials.credentials != APP_SECRET:
 
40
  raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
 
41
  return credentials.credentials
42
 
43
  def message_to_dict(message):
 
 
 
 
 
 
44
  if isinstance(message.content, str):
45
- return {"role": message.role, "content": message.content}
46
- elif isinstance(message.content, list) and len(message.content) == 2:
47
- return {
48
- "role": message.role,
49
- "content": message.content[0]["text"],
50
- "data": {
51
- "imageBase64": message.content[1]["image_url"]["url"],
52
- "fileText": "",
53
- "title": "snapshot",
54
- },
55
- }
 
 
 
 
 
 
 
 
 
56
  else:
57
- return {"role": message.role, "content": message.content}
 
 
 
58
 
59
  async def process_streaming_response(request: ChatRequest):
60
  agent_mode = AGENT_MODE.get(request.model, {})
@@ -85,8 +113,8 @@ async def process_streaming_response(request: ChatRequest):
85
  "clickedForceWebSearch": False,
86
  "visitFromDelta": False,
87
  "mobileClient": False,
88
- "userSelectedModel": MODEL_MAPPING.get(request.model, request.model), # Added default
89
- "validated": validate.getHid()
90
  }
91
 
92
  async with httpx.AsyncClient() as client:
@@ -96,31 +124,31 @@ async def process_streaming_response(request: ChatRequest):
96
  f"{BASE_URL}/api/chat",
97
  headers=headers,
98
  json=json_data,
99
- timeout=100,
100
  ) as response:
101
  response.raise_for_status()
 
102
  async for line in response.aiter_lines():
103
- timestamp = int(datetime.now().timestamp())
104
  if line:
105
- content = line + "\n"
106
  if "https://www.blackbox.ai" in content:
107
  validate.getHid(True)
108
  content = "hid已刷新,重新对话即可\n"
109
  yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
110
  break
111
  if content.startswith("$@$v=undefined-rv1$@$"):
112
- yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
113
- else:
114
- yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
115
 
 
116
  yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
117
  yield "data: [DONE]\n\n"
118
  except httpx.HTTPStatusError as e:
119
- logger.error(f"HTTP error occurred: {e}")
120
- raise HTTPException(status_code=e.response.status_code, detail=str(e))
121
  except httpx.RequestError as e:
122
- logger.error(f"Error occurred during request: {e}")
123
- raise HTTPException(status_code=500, detail=str(e))
124
 
125
  async def process_non_streaming_response(request: ChatRequest):
126
  agent_mode = AGENT_MODE.get(request.model, {})
@@ -151,41 +179,48 @@ async def process_non_streaming_response(request: ChatRequest):
151
  "clickedForceWebSearch": False,
152
  "visitFromDelta": False,
153
  "mobileClient": False,
154
- "userSelectedModel": MODEL_MAPPING.get(request.model, request.model), # Added default
155
- "validated": validate.getHid()
156
  }
157
 
158
- full_response = ""
159
- async with httpx.AsyncClient() as client:
160
- try:
161
- async with client.stream(
162
- method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
163
- ) as response:
164
- response.raise_for_status()
165
- async for chunk in response.aiter_text():
166
- full_response += chunk
167
- except httpx.HTTPStatusError as e:
168
- logger.error(f"HTTP error occurred: {e}")
169
- raise HTTPException(status_code=e.response.status_code, detail=str(e))
170
- except httpx.RequestError as e:
171
- logger.error(f"Error occurred during request: {e}")
172
- raise HTTPException(status_code=500, detail=str(e))
173
- if "https://www.blackbox.ai" in full_response:
174
- validate.getHid(True)
175
- full_response = "hid已刷新,重新对话即可"
176
- if full_response.startswith("$@$v=undefined-rv1$@$"):
177
- full_response = full_response[21:]
178
- return {
179
- "id": f"chatcmpl-{uuid.uuid4()}",
180
- "object": "chat.completion",
181
- "created": int(datetime.now().timestamp()),
182
- "model": request.model,
183
- "choices": [
184
- {
185
- "index": 0,
186
- "message": {"role": "assistant", "content": full_response},
187
- "finish_reason": "stop",
188
- }
189
- ],
190
- "usage": None,
191
- }
 
 
 
 
 
 
 
 
1
  from datetime import datetime
 
2
  import json
3
  from typing import Any, Dict, Optional
4
  import uuid
5
 
6
  import httpx
7
+ from fastapi import Depends, HTTPException
8
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
 
 
9
 
10
+ from api import validate
11
+ from api.config import (
12
+ MODEL_MAPPING,
13
+ headers,
14
+ AGENT_MODE,
15
+ TRENDING_AGENT_MODE,
16
+ APP_SECRET,
17
+ BASE_URL,
18
+ )
19
  from api.models import ChatRequest
20
 
21
  from api.logger import setup_logger
22
 
23
  logger = setup_logger(__name__)
24
 
25
+ # Initialize the HTTPBearer security scheme
26
+ bearer_scheme = HTTPBearer()
27
+
28
  def create_chat_completion_data(
29
  content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
30
  ) -> Dict[str, Any]:
 
43
  "usage": None,
44
  }
45
 
46
+ def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
47
  if credentials.credentials != APP_SECRET:
48
+ logger.warning("Invalid APP_SECRET provided.")
49
  raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
50
+ logger.debug("APP_SECRET verified successfully.")
51
  return credentials.credentials
52
 
53
  def message_to_dict(message):
54
+ """
55
+ Convert a message object to a dictionary suitable for the API request.
56
+ Handles different content types gracefully.
57
+ """
58
+ message_dict = {"role": message.role}
59
+
60
  if isinstance(message.content, str):
61
+ message_dict["content"] = message.content
62
+ elif isinstance(message.content, list):
63
+ # Handle list content more robustly
64
+ try:
65
+ if len(message.content) >= 2:
66
+ # Assuming the first element has 'text' and the second has 'image_url'
67
+ text_content = message.content[0].get("text", "")
68
+ image_url = message.content[1].get("image_url", {}).get("url", "")
69
+ message_dict["content"] = text_content
70
+ message_dict["data"] = {
71
+ "imageBase64": image_url,
72
+ "fileText": "",
73
+ "title": "snapshot",
74
+ }
75
+ else:
76
+ # Fallback if the list doesn't have expected structure
77
+ message_dict["content"] = json.dumps(message.content)
78
+ except (AttributeError, KeyError, TypeError) as e:
79
+ logger.error(f"Error parsing message content: {e}")
80
+ message_dict["content"] = "Invalid message format."
81
  else:
82
+ # Fallback for unexpected content types
83
+ message_dict["content"] = str(message.content)
84
+
85
+ return message_dict
86
 
87
  async def process_streaming_response(request: ChatRequest):
88
  agent_mode = AGENT_MODE.get(request.model, {})
 
113
  "clickedForceWebSearch": False,
114
  "visitFromDelta": False,
115
  "mobileClient": False,
116
+ "userSelectedModel": MODEL_MAPPING.get(request.model),
117
+ "validated": validate.getHid(),
118
  }
119
 
120
  async with httpx.AsyncClient() as client:
 
124
  f"{BASE_URL}/api/chat",
125
  headers=headers,
126
  json=json_data,
127
+ timeout=httpx.Timeout(100.0),
128
  ) as response:
129
  response.raise_for_status()
130
+ timestamp = int(datetime.now().timestamp())
131
  async for line in response.aiter_lines():
 
132
  if line:
133
+ content = line.strip() + "\n"
134
  if "https://www.blackbox.ai" in content:
135
  validate.getHid(True)
136
  content = "hid已刷新,重新对话即可\n"
137
  yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
138
  break
139
  if content.startswith("$@$v=undefined-rv1$@$"):
140
+ content = content[21:]
141
+ yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
 
142
 
143
+ # Indicate the end of the stream
144
  yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
145
  yield "data: [DONE]\n\n"
146
  except httpx.HTTPStatusError as e:
147
+ logger.error(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")
148
+ raise HTTPException(status_code=e.response.status_code, detail="Error from upstream service.")
149
  except httpx.RequestError as e:
150
+ logger.error(f"Request error occurred: {e}")
151
+ raise HTTPException(status_code=500, detail="Internal server error.")
152
 
153
  async def process_non_streaming_response(request: ChatRequest):
154
  agent_mode = AGENT_MODE.get(request.model, {})
 
179
  "clickedForceWebSearch": False,
180
  "visitFromDelta": False,
181
  "mobileClient": False,
182
+ "userSelectedModel": MODEL_MAPPING.get(request.model),
183
+ "validated": validate.getHid(),
184
  }
185
 
186
+ try:
187
+ async with httpx.AsyncClient() as client:
188
+ response = await client.post(
189
+ f"{BASE_URL}/api/chat",
190
+ headers=headers,
191
+ json=json_data,
192
+ timeout=httpx.Timeout(100.0),
193
+ )
194
+ response.raise_for_status()
195
+ full_response = response.text
196
+
197
+ # Process the full response
198
+ if "https://www.blackbox.ai" in full_response:
199
+ validate.getHid(True)
200
+ full_response = "hid已刷新,重新对话即可"
201
+ if full_response.startswith("$@$v=undefined-rv1$@$"):
202
+ full_response = full_response[21:]
203
+
204
+ return {
205
+ "id": f"chatcmpl-{uuid.uuid4()}",
206
+ "object": "chat.completion",
207
+ "created": int(datetime.now().timestamp()),
208
+ "model": request.model,
209
+ "choices": [
210
+ {
211
+ "index": 0,
212
+ "message": {"role": "assistant", "content": full_response},
213
+ "finish_reason": "stop",
214
+ }
215
+ ],
216
+ "usage": None,
217
+ }
218
+ except httpx.HTTPStatusError as e:
219
+ logger.error(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")
220
+ raise HTTPException(status_code=e.response.status_code, detail="Error from upstream service.")
221
+ except httpx.RequestError as e:
222
+ logger.error(f"Request error occurred: {e}")
223
+ raise HTTPException(status_code=500, detail="Internal server error.")
224
+ except Exception as e:
225
+ logger.error(f"Unexpected error: {e}")
226
+ raise HTTPException(status_code=500, detail="Internal server error.")