Update api/utils.py
Browse files- api/utils.py +135 -147
api/utils.py
CHANGED
@@ -4,25 +4,26 @@ import uuid
|
|
4 |
import asyncio
|
5 |
import random
|
6 |
import string
|
7 |
-
from typing import Any, Dict, Optional
|
8 |
|
9 |
import httpx
|
10 |
from fastapi import HTTPException
|
11 |
from api.config import (
|
|
|
|
|
|
|
12 |
MODEL_MAPPING,
|
13 |
get_headers_api_chat,
|
14 |
-
get_headers_chat,
|
15 |
BASE_URL,
|
16 |
-
AGENT_MODE,
|
17 |
-
TRENDING_AGENT_MODE,
|
18 |
-
MODEL_PREFIXES,
|
19 |
-
MODEL_REFERERS
|
20 |
)
|
21 |
-
from api.models import ChatRequest
|
22 |
from api.logger import setup_logger
|
23 |
|
24 |
logger = setup_logger(__name__)
|
25 |
|
|
|
|
|
|
|
26 |
# Helper function to create a random alphanumeric chat ID
|
27 |
def generate_chat_id(length: int = 7) -> str:
|
28 |
characters = string.ascii_letters + string.digits
|
@@ -47,11 +48,15 @@ def create_chat_completion_data(
|
|
47 |
"usage": None,
|
48 |
}
|
49 |
|
50 |
-
# Function to convert message to dictionary format, ensuring base64 data
|
51 |
-
def message_to_dict(message
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
55 |
if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
|
56 |
# Ensure base64 images are always included for all models
|
57 |
return {
|
@@ -65,163 +70,146 @@ def message_to_dict(message, model_prefix: Optional[str] = None):
|
|
65 |
}
|
66 |
return {"role": message.role, "content": content}
|
67 |
|
68 |
-
# Function to strip model prefix from content if present
|
69 |
-
def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
# Function to get the correct referer URL for logging
|
77 |
-
def get_referer_url(chat_id: str, model: str) -> str:
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
# Process streaming response with headers from config.py
|
84 |
-
async def process_streaming_response(request: ChatRequest):
|
85 |
chat_id = generate_chat_id()
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
"
|
102 |
-
"clickedAnswer2": False,
|
103 |
-
"clickedAnswer3": False,
|
104 |
-
"clickedForceWebSearch": False,
|
105 |
-
"codeModelMode": True,
|
106 |
-
"githubToken": None,
|
107 |
-
"id": chat_id,
|
108 |
-
"isChromeExt": False,
|
109 |
-
"isMicMode": False,
|
110 |
-
"maxTokens": request.max_tokens,
|
111 |
-
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
112 |
-
"mobileClient": False,
|
113 |
-
"playgroundTemperature": request.temperature,
|
114 |
-
"playgroundTopP": request.top_p,
|
115 |
-
"previewToken": None,
|
116 |
-
"trendingAgentMode": trending_agent_mode,
|
117 |
-
"userId": None,
|
118 |
-
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
119 |
-
"userSystemPrompt": None,
|
120 |
-
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
121 |
-
"visitFromDelta": False,
|
122 |
}
|
123 |
|
124 |
async with httpx.AsyncClient() as client:
|
125 |
try:
|
126 |
-
|
127 |
-
|
128 |
-
f"{BASE_URL}/api/chat",
|
129 |
headers=headers_api_chat,
|
130 |
-
json=
|
131 |
timeout=100,
|
132 |
-
)
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
except httpx.HTTPStatusError as e:
|
146 |
-
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
|
147 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
148 |
except httpx.RequestError as e:
|
149 |
-
logger.error(f"
|
150 |
raise HTTPException(status_code=500, detail=str(e))
|
151 |
|
152 |
# Process non-streaming response with headers from config.py
|
153 |
-
async def process_non_streaming_response(request: ChatRequest):
|
154 |
chat_id = generate_chat_id()
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
"agentMode": agent_mode,
|
172 |
-
"clickedAnswer2": False,
|
173 |
-
"clickedAnswer3": False,
|
174 |
-
"clickedForceWebSearch": False,
|
175 |
-
"codeModelMode": True,
|
176 |
-
"githubToken": None,
|
177 |
-
"id": chat_id,
|
178 |
-
"isChromeExt": False,
|
179 |
-
"isMicMode": False,
|
180 |
-
"maxTokens": request.max_tokens,
|
181 |
-
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
182 |
-
"mobileClient": False,
|
183 |
-
"playgroundTemperature": request.temperature,
|
184 |
-
"playgroundTopP": request.top_p,
|
185 |
-
"previewToken": None,
|
186 |
-
"trendingAgentMode": trending_agent_mode,
|
187 |
-
"userId": None,
|
188 |
-
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
189 |
-
"userSystemPrompt": None,
|
190 |
-
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
191 |
-
"visitFromDelta": False,
|
192 |
}
|
193 |
|
194 |
-
full_response = ""
|
195 |
async with httpx.AsyncClient() as client:
|
196 |
try:
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
except httpx.HTTPStatusError as e:
|
204 |
-
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
|
205 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
206 |
except httpx.RequestError as e:
|
207 |
-
logger.error(f"
|
208 |
raise HTTPException(status_code=500, detail=str(e))
|
209 |
-
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
210 |
-
full_response = full_response[21:]
|
211 |
-
|
212 |
-
cleaned_full_response = strip_model_prefix(full_response, model_prefix)
|
213 |
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
"usage": None,
|
227 |
-
}
|
|
|
4 |
import asyncio
|
5 |
import random
|
6 |
import string
|
7 |
+
from typing import Any, Dict, Optional, AsyncGenerator
|
8 |
|
9 |
import httpx
|
10 |
from fastapi import HTTPException
|
11 |
from api.config import (
|
12 |
+
models,
|
13 |
+
model_aliases,
|
14 |
+
ALLOWED_MODELS,
|
15 |
MODEL_MAPPING,
|
16 |
get_headers_api_chat,
|
|
|
17 |
BASE_URL,
|
|
|
|
|
|
|
|
|
18 |
)
|
19 |
+
from api.models import ChatRequest, Message
|
20 |
from api.logger import setup_logger
|
21 |
|
22 |
logger = setup_logger(__name__)
|
23 |
|
24 |
+
# Editee API endpoint
|
25 |
+
EDITE_API_ENDPOINT = "https://editee.com/submit/chatgptfree"
|
26 |
+
|
27 |
# Helper function to create a random alphanumeric chat ID
|
28 |
def generate_chat_id(length: int = 7) -> str:
|
29 |
characters = string.ascii_letters + string.digits
|
|
|
48 |
"usage": None,
|
49 |
}
|
50 |
|
51 |
+
# Function to convert message to dictionary format, ensuring base64 data
|
52 |
+
def message_to_dict(message: Message):
|
53 |
+
if isinstance(message.content, str):
|
54 |
+
content = message.content
|
55 |
+
elif isinstance(message.content, list) and isinstance(message.content[0], dict) and "text" in message.content[0]:
|
56 |
+
content = message.content[0]["text"]
|
57 |
+
else:
|
58 |
+
content = ""
|
59 |
+
|
60 |
if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
|
61 |
# Ensure base64 images are always included for all models
|
62 |
return {
|
|
|
70 |
}
|
71 |
return {"role": message.role, "content": content}
|
72 |
|
73 |
+
# Function to strip model prefix from content if present (Removed as MODEL_PREFIXES is removed)
|
74 |
+
# def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
75 |
+
# """Remove the model prefix from the response content if present."""
|
76 |
+
# if model_prefix and content.startswith(model_prefix):
|
77 |
+
# logger.debug(f"Stripping prefix '{model_prefix}' from content.")
|
78 |
+
# return content[len(model_prefix):].strip()
|
79 |
+
# return content
|
80 |
+
|
81 |
+
# Function to get the correct referer URL for logging (Removed as MODEL_REFERERS is removed)
|
82 |
+
# def get_referer_url(chat_id: str, model: str) -> str:
|
83 |
+
# """Generate the referer URL based on specific models listed in MODEL_REFERERS."""
|
84 |
+
# if model in MODEL_REFERERS:
|
85 |
+
# return f"{BASE_URL}/chat/{chat_id}?model={model}"
|
86 |
+
# return BASE_URL
|
87 |
+
|
88 |
+
# Function to resolve model aliases
|
89 |
+
def resolve_model(model: str) -> str:
|
90 |
+
if model in MODEL_MAPPING:
|
91 |
+
return model
|
92 |
+
elif model in model_aliases:
|
93 |
+
return model_aliases[model]
|
94 |
+
else:
|
95 |
+
logger.warning(f"Model '{model}' not recognized. Using default model '{default_model}'.")
|
96 |
+
return "claude" # default_model
|
97 |
|
98 |
# Process streaming response with headers from config.py
|
99 |
+
async def process_streaming_response(request: ChatRequest) -> AsyncGenerator[str, None]:
|
100 |
chat_id = generate_chat_id()
|
101 |
+
resolved_model = resolve_model(request.model)
|
102 |
+
# referer_url = get_referer_url(chat_id, resolved_model) # Removed
|
103 |
+
logger.info(f"Generated Chat ID: {chat_id} - Model: {resolved_model}")
|
104 |
+
|
105 |
+
# model_prefix = MODEL_PREFIXES.get(resolved_model, "") # Removed
|
106 |
+
|
107 |
+
headers_api_chat = get_headers_api_chat(BASE_URL) # Using BASE_URL as referer
|
108 |
+
|
109 |
+
# Removed agent mode and delay logic
|
110 |
+
|
111 |
+
prompt = format_prompt(request.messages)
|
112 |
+
data = {
|
113 |
+
"user_input": prompt,
|
114 |
+
"context": " ",
|
115 |
+
"template_id": "",
|
116 |
+
"selected_model": resolved_model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
}
|
118 |
|
119 |
async with httpx.AsyncClient() as client:
|
120 |
try:
|
121 |
+
response = await client.post(
|
122 |
+
EDITE_API_ENDPOINT,
|
|
|
123 |
headers=headers_api_chat,
|
124 |
+
json=data,
|
125 |
timeout=100,
|
126 |
+
)
|
127 |
+
response.raise_for_status()
|
128 |
+
response_data = response.json()
|
129 |
+
# Assuming response_data contains 'text' field
|
130 |
+
text = response_data.get('text', '')
|
131 |
+
timestamp = int(datetime.now().timestamp())
|
132 |
+
if text:
|
133 |
+
# cleaned_content = strip_model_prefix(text, model_prefix) # Removed
|
134 |
+
yield f"data: {json.dumps(create_chat_completion_data(text, resolved_model, timestamp))}\n\n"
|
135 |
+
|
136 |
+
# Indicate completion
|
137 |
+
yield f"data: {json.dumps(create_chat_completion_data('', resolved_model, timestamp, 'stop'))}\n\n"
|
138 |
+
yield "data: [DONE]\n\n"
|
139 |
except httpx.HTTPStatusError as e:
|
140 |
+
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e.response.status_code} - {e.response.text}")
|
141 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
142 |
except httpx.RequestError as e:
|
143 |
+
logger.error(f"Request error occurred for Chat ID {chat_id}: {e}")
|
144 |
raise HTTPException(status_code=500, detail=str(e))
|
145 |
|
146 |
# Process non-streaming response with headers from config.py
|
147 |
+
async def process_non_streaming_response(request: ChatRequest) -> Dict[str, Any]:
|
148 |
chat_id = generate_chat_id()
|
149 |
+
resolved_model = resolve_model(request.model)
|
150 |
+
# referer_url = get_referer_url(chat_id, resolved_model) # Removed
|
151 |
+
logger.info(f"Generated Chat ID: {chat_id} - Model: {resolved_model}")
|
152 |
+
|
153 |
+
# model_prefix = MODEL_PREFIXES.get(resolved_model, "") # Removed
|
154 |
+
|
155 |
+
headers_api_chat = get_headers_api_chat(BASE_URL) # Using BASE_URL as referer
|
156 |
+
|
157 |
+
# Removed agent mode and delay logic
|
158 |
+
|
159 |
+
prompt = format_prompt(request.messages)
|
160 |
+
data = {
|
161 |
+
"user_input": prompt,
|
162 |
+
"context": " ",
|
163 |
+
"template_id": "",
|
164 |
+
"selected_model": resolved_model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
}
|
166 |
|
|
|
167 |
async with httpx.AsyncClient() as client:
|
168 |
try:
|
169 |
+
response = await client.post(
|
170 |
+
EDITE_API_ENDPOINT,
|
171 |
+
headers=headers_api_chat,
|
172 |
+
json=data,
|
173 |
+
timeout=100,
|
174 |
+
)
|
175 |
+
response.raise_for_status()
|
176 |
+
response_data = response.json()
|
177 |
+
text = response_data.get('text', '')
|
178 |
+
# if text.startswith("$@$v=undefined-rv1$@$"):
|
179 |
+
# text = text[21:] # Removed
|
180 |
+
|
181 |
+
# cleaned_full_response = strip_model_prefix(text, model_prefix) # Removed
|
182 |
+
|
183 |
+
return {
|
184 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
185 |
+
"object": "chat.completion",
|
186 |
+
"created": int(datetime.now().timestamp()),
|
187 |
+
"model": resolved_model,
|
188 |
+
"choices": [
|
189 |
+
{
|
190 |
+
"index": 0,
|
191 |
+
"message": {"role": "assistant", "content": text},
|
192 |
+
"finish_reason": "stop",
|
193 |
+
}
|
194 |
+
],
|
195 |
+
"usage": None,
|
196 |
+
}
|
197 |
except httpx.HTTPStatusError as e:
|
198 |
+
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e.response.status_code} - {e.response.text}")
|
199 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
200 |
except httpx.RequestError as e:
|
201 |
+
logger.error(f"Request error occurred for Chat ID {chat_id}: {e}")
|
202 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
203 |
|
204 |
+
# Helper function to format prompt from messages
|
205 |
+
def format_prompt(messages: list[Message]) -> str:
|
206 |
+
# Implement the prompt formatting as per Editee's requirements
|
207 |
+
# Placeholder implementation
|
208 |
+
formatted_messages = []
|
209 |
+
for msg in messages:
|
210 |
+
if isinstance(msg.content, str):
|
211 |
+
formatted_messages.append(msg.content)
|
212 |
+
elif isinstance(msg.content, list):
|
213 |
+
text = msg.content[0].get("text", "")
|
214 |
+
formatted_messages.append(text)
|
215 |
+
return "\n".join(formatted_messages)
|
|
|
|