Niansuh commited on
Commit
56867b8
1 Parent(s): 96a234b

Update api/utils.py

Browse files
Files changed (1) hide show
  1. 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
- "userSelectedModel": MODEL_MAPPING.get(request.model),
83
- }
84
-
85
- async with httpx.AsyncClient() as client:
86
- try:
87
- async with client.stream(
88
- "POST",
89
- f"{BASE_URL}/api/chat",
90
- headers=headers,
91
- json=json_data,
92
- timeout=100,
93
- ) as response:
94
- response.raise_for_status()
95
- async for line in response.aiter_lines():
96
- timestamp = int(datetime.now().timestamp())
97
- if line:
98
- content = line + "\n"
99
- if content.startswith("$@$v=undefined-rv1$@$"):
100
- yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
101
- else:
102
- yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
103
-
104
- yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
105
- yield "data: [DONE]\n\n"
106
- except httpx.HTTPStatusError as e:
107
- logger.error(f"HTTP error occurred: {e}")
108
- raise HTTPException(status_code=e.response.status_code, detail=str(e))
109
- except httpx.RequestError as e:
110
- logger.error(f"Error occurred during request: {e}")
111
- raise HTTPException(status_code=500, detail=str(e))
112
-
113
-
114
- async def process_non_streaming_response(request: ChatRequest):
115
- json_data = {
116
- "messages": [message_to_dict(msg) for msg in request.messages],
117
- "previewToken": None,
118
- "userId": None,
119
- "codeModelMode": True,
120
- "agentMode": {},
121
- "trendingAgentMode": {},
122
- "isMicMode": False,
123
- "userSystemPrompt": None,
124
- "maxTokens": request.max_tokens,
125
- "playgroundTopP": request.top_p,
126
- "playgroundTemperature": request.temperature,
127
- "isChromeExt": False,
128
- "githubToken": None,
129
- "clickedAnswer2": False,
130
- "clickedAnswer3": False,
131
- "clickedForceWebSearch": False,
132
- "visitFromDelta": False,
133
- "mobileClient": False,
134
- "userSelectedModel": MODEL_MAPPING.get(request.model),
135
- }
136
- full_response = ""
137
- async with httpx.AsyncClient() as client:
138
- async with client.stream(
139
- method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
140
- ) as response:
141
- async for chunk in response.aiter_text():
142
- full_response += chunk
143
- if full_response.startswith("$@$v=undefined-rv1$@$"):
144
- full_response = full_response[21:]
145
- return {
146
- "id": f"chatcmpl-{uuid.uuid4()}",
147
- "object": "chat.completion",
148
- "created": int(datetime.now().timestamp()),
149
- "model": request.model,
150
- "choices": [
151
- {
152
- "index": 0,
153
- "message": {"role": "assistant", "content": full_response},
154
- "finish_reason": "stop",
155
- }
156
- ],
157
- "usage": None,
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
+ }