Update api/utils.py
Browse files- api/utils.py +160 -158
api/utils.py
CHANGED
@@ -1,158 +1,160 @@
|
|
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.config import MODEL_MAPPING, headers
|
9 |
-
from fastapi import Depends, security
|
10 |
-
from fastapi.security import HTTPAuthorizationCredentials
|
11 |
-
|
12 |
-
from api.config import APP_SECRET, BASE_URL
|
13 |
-
from api.models import ChatRequest
|
14 |
-
|
15 |
-
from api.logger import setup_logger
|
16 |
-
|
17 |
-
logger = setup_logger(__name__)
|
18 |
-
|
19 |
-
|
20 |
-
def create_chat_completion_data(
|
21 |
-
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
22 |
-
) -> Dict[str, Any]:
|
23 |
-
return {
|
24 |
-
"id": f"chatcmpl-{uuid.uuid4()}",
|
25 |
-
"object": "chat.completion.chunk",
|
26 |
-
"created": timestamp,
|
27 |
-
"model": model,
|
28 |
-
"choices": [
|
29 |
-
{
|
30 |
-
"index": 0,
|
31 |
-
"delta": {"content": content, "role": "assistant"},
|
32 |
-
"finish_reason": finish_reason,
|
33 |
-
}
|
34 |
-
],
|
35 |
-
"usage": None,
|
36 |
-
}
|
37 |
-
|
38 |
-
|
39 |
-
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
40 |
-
if credentials.credentials != APP_SECRET:
|
41 |
-
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
|
42 |
-
return credentials.credentials
|
43 |
-
|
44 |
-
|
45 |
-
def message_to_dict(message):
|
46 |
-
if isinstance(message.content, str):
|
47 |
-
return {"role": message.role, "content": message.content}
|
48 |
-
elif isinstance(message.content, list) and len(message.content) == 2:
|
49 |
-
return {
|
50 |
-
"role": message.role,
|
51 |
-
"content": message.content[0]["text"],
|
52 |
-
"data": {
|
53 |
-
"imageBase64": message.content[1]["image_url"]["url"],
|
54 |
-
"fileText": "",
|
55 |
-
"title": "snapshoot",
|
56 |
-
},
|
57 |
-
}
|
58 |
-
else:
|
59 |
-
return {"role": message.role, "content": message.content}
|
60 |
-
|
61 |
-
|
62 |
-
async def process_streaming_response(request: ChatRequest):
|
63 |
-
json_data = {
|
64 |
-
"messages": [message_to_dict(msg) for msg in request.messages],
|
65 |
-
"previewToken": None,
|
66 |
-
"userId": None,
|
67 |
-
"codeModelMode": True,
|
68 |
-
"agentMode": {},
|
69 |
-
"trendingAgentMode": {},
|
70 |
-
"isMicMode": False,
|
71 |
-
"userSystemPrompt": None,
|
72 |
-
"maxTokens": request.max_tokens,
|
73 |
-
"playgroundTopP": request.top_p,
|
74 |
-
"playgroundTemperature": request.temperature,
|
75 |
-
"isChromeExt": False,
|
76 |
-
"githubToken": None,
|
77 |
-
"clickedAnswer2": False,
|
78 |
-
"clickedAnswer3": False,
|
79 |
-
"clickedForceWebSearch": False,
|
80 |
-
"visitFromDelta": False,
|
81 |
-
"mobileClient": False,
|
82 |
-
"
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
yield "data:
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
"
|
118 |
-
"
|
119 |
-
"
|
120 |
-
"
|
121 |
-
"
|
122 |
-
"
|
123 |
-
"
|
124 |
-
"
|
125 |
-
"
|
126 |
-
"
|
127 |
-
"
|
128 |
-
"
|
129 |
-
"
|
130 |
-
"
|
131 |
-
"
|
132 |
-
"
|
133 |
-
"
|
134 |
-
"
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
"
|
149 |
-
"
|
150 |
-
"
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
"
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
|
|
|
|
|
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.config import MODEL_MAPPING, headers
|
9 |
+
from fastapi import Depends, security
|
10 |
+
from fastapi.security import HTTPAuthorizationCredentials
|
11 |
+
|
12 |
+
from api.config import APP_SECRET, BASE_URL
|
13 |
+
from api.models import ChatRequest
|
14 |
+
|
15 |
+
from api.logger import setup_logger
|
16 |
+
|
17 |
+
logger = setup_logger(__name__)
|
18 |
+
|
19 |
+
|
20 |
+
def create_chat_completion_data(
|
21 |
+
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
22 |
+
) -> Dict[str, Any]:
|
23 |
+
return {
|
24 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
25 |
+
"object": "chat.completion.chunk",
|
26 |
+
"created": timestamp,
|
27 |
+
"model": model,
|
28 |
+
"choices": [
|
29 |
+
{
|
30 |
+
"index": 0,
|
31 |
+
"delta": {"content": content, "role": "assistant"},
|
32 |
+
"finish_reason": finish_reason,
|
33 |
+
}
|
34 |
+
],
|
35 |
+
"usage": None,
|
36 |
+
}
|
37 |
+
|
38 |
+
|
39 |
+
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
40 |
+
if credentials.credentials != APP_SECRET:
|
41 |
+
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
|
42 |
+
return credentials.credentials
|
43 |
+
|
44 |
+
|
45 |
+
def message_to_dict(message):
|
46 |
+
if isinstance(message.content, str):
|
47 |
+
return {"role": message.role, "content": message.content}
|
48 |
+
elif isinstance(message.content, list) and len(message.content) == 2:
|
49 |
+
return {
|
50 |
+
"role": message.role,
|
51 |
+
"content": message.content[0]["text"],
|
52 |
+
"data": {
|
53 |
+
"imageBase64": message.content[1]["image_url"]["url"],
|
54 |
+
"fileText": "",
|
55 |
+
"title": "snapshoot",
|
56 |
+
},
|
57 |
+
}
|
58 |
+
else:
|
59 |
+
return {"role": message.role, "content": message.content}
|
60 |
+
|
61 |
+
|
62 |
+
async def process_streaming_response(request: ChatRequest):
|
63 |
+
json_data = {
|
64 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
65 |
+
"previewToken": None,
|
66 |
+
"userId": None,
|
67 |
+
"codeModelMode": True,
|
68 |
+
"agentMode": {},
|
69 |
+
"trendingAgentMode": {},
|
70 |
+
"isMicMode": False,
|
71 |
+
"userSystemPrompt": None,
|
72 |
+
"maxTokens": request.max_tokens,
|
73 |
+
"playgroundTopP": request.top_p,
|
74 |
+
"playgroundTemperature": request.temperature,
|
75 |
+
"isChromeExt": False,
|
76 |
+
"githubToken": None,
|
77 |
+
"clickedAnswer2": False,
|
78 |
+
"clickedAnswer3": False,
|
79 |
+
"clickedForceWebSearch": False,
|
80 |
+
"visitFromDelta": False,
|
81 |
+
"mobileClient": False,
|
82 |
+
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
83 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
84 |
+
}
|
85 |
+
|
86 |
+
async with httpx.AsyncClient() as client:
|
87 |
+
try:
|
88 |
+
async with client.stream(
|
89 |
+
"POST",
|
90 |
+
f"{BASE_URL}/api/chat",
|
91 |
+
headers=headers,
|
92 |
+
json=json_data,
|
93 |
+
timeout=100,
|
94 |
+
) as response:
|
95 |
+
response.raise_for_status()
|
96 |
+
async for line in response.aiter_lines():
|
97 |
+
timestamp = int(datetime.now().timestamp())
|
98 |
+
if line:
|
99 |
+
content = line + "\n"
|
100 |
+
if content.startswith("$@$v=undefined-rv1$@$"):
|
101 |
+
yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
|
102 |
+
else:
|
103 |
+
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
|
104 |
+
|
105 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
106 |
+
yield "data: [DONE]\n\n"
|
107 |
+
except httpx.HTTPStatusError as e:
|
108 |
+
logger.error(f"HTTP error occurred: {e}")
|
109 |
+
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
110 |
+
except httpx.RequestError as e:
|
111 |
+
logger.error(f"Error occurred during request: {e}")
|
112 |
+
raise HTTPException(status_code=500, detail=str(e))
|
113 |
+
|
114 |
+
|
115 |
+
async def process_non_streaming_response(request: ChatRequest):
|
116 |
+
json_data = {
|
117 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
118 |
+
"previewToken": None,
|
119 |
+
"userId": None,
|
120 |
+
"codeModelMode": True,
|
121 |
+
"agentMode": {},
|
122 |
+
"trendingAgentMode": {},
|
123 |
+
"isMicMode": False,
|
124 |
+
"userSystemPrompt": None,
|
125 |
+
"maxTokens": request.max_tokens,
|
126 |
+
"playgroundTopP": request.top_p,
|
127 |
+
"playgroundTemperature": request.temperature,
|
128 |
+
"isChromeExt": False,
|
129 |
+
"githubToken": None,
|
130 |
+
"clickedAnswer2": False,
|
131 |
+
"clickedAnswer3": False,
|
132 |
+
"clickedForceWebSearch": False,
|
133 |
+
"visitFromDelta": False,
|
134 |
+
"mobileClient": False,
|
135 |
+
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
136 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
137 |
+
}
|
138 |
+
full_response = ""
|
139 |
+
async with httpx.AsyncClient() as client:
|
140 |
+
async with client.stream(
|
141 |
+
method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
|
142 |
+
) as response:
|
143 |
+
async for chunk in response.aiter_text():
|
144 |
+
full_response += chunk
|
145 |
+
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
146 |
+
full_response = full_response[21:]
|
147 |
+
return {
|
148 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
149 |
+
"object": "chat.completion",
|
150 |
+
"created": int(datetime.now().timestamp()),
|
151 |
+
"model": request.model,
|
152 |
+
"choices": [
|
153 |
+
{
|
154 |
+
"index": 0,
|
155 |
+
"message": {"role": "assistant", "content": full_response},
|
156 |
+
"finish_reason": "stop",
|
157 |
+
}
|
158 |
+
],
|
159 |
+
"usage": None,
|
160 |
+
}
|