File size: 11,675 Bytes
b50abc0
 
 
 
 
 
 
 
 
43cdeef
 
b59c7b9
b50abc0
b59c7b9
 
b50abc0
77af3d8
 
 
 
fd28e64
b50abc0
77af3d8
 
b50abc0
 
 
fd28e64
b50abc0
fd28e64
 
b50abc0
fd28e64
 
43cdeef
fd28e64
 
1e29b58
21089da
 
 
 
 
 
 
 
 
 
 
b50abc0
 
fd28e64
b50abc0
43cdeef
 
 
 
 
 
 
b50abc0
fd28e64
 
b59c7b9
 
fd28e64
b59c7b9
fd28e64
b59c7b9
 
b50abc0
fd28e64
 
43cdeef
77af3d8
 
 
 
b50abc0
 
 
 
 
 
 
 
 
77af3d8
 
 
 
 
 
43cdeef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77af3d8
 
43cdeef
 
 
 
 
 
 
 
 
 
 
 
 
 
fd28e64
b59c7b9
77af3d8
b59c7b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77af3d8
 
b59c7b9
 
 
 
fd28e64
77af3d8
fd28e64
 
77af3d8
fd28e64
77af3d8
d80a70b
b59c7b9
 
77af3d8
b59c7b9
 
 
 
 
 
 
 
 
 
 
77af3d8
b59c7b9
 
b50abc0
b59c7b9
43cdeef
b59c7b9
77af3d8
43cdeef
b50abc0
fd28e64
77af3d8
 
b50abc0
 
77af3d8
b50abc0
fd28e64
43cdeef
 
 
a649779
fd28e64
 
 
 
 
 
 
 
 
 
 
 
 
 
77af3d8
 
fd28e64
 
 
 
 
 
 
 
 
 
b1161c6
fd28e64
 
77af3d8
fd28e64
 
 
 
 
 
 
 
 
b59c7b9
fd28e64
b50abc0
43cdeef
 
 
 
 
77af3d8
 
43cdeef
fd28e64
77af3d8
fd28e64
 
 
 
 
77af3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd28e64
 
77af3d8
fd28e64
77af3d8
fd28e64
 
 
 
 
43cdeef
 
 
 
 
 
b50abc0
 
43cdeef
b50abc0
 
43cdeef
b50abc0
 
 
fd28e64
 
 
 
 
 
 
 
b50abc0
 
 
 
 
 
 
 
 
 
 
 
 
 
332aafb
77af3d8
 
 
 
332aafb
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import json
import logging
import os
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional

import httpx
import uvicorn
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import StreamingResponse, Response

# ==============================
# Configuration and Setup
# ==============================

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,  # Set to DEBUG for detailed logs
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Load environment variables from .env file
load_dotenv()

# Initialize FastAPI app
app = FastAPI()

# Constants and configurations
BASE_URL = "https://aichatonlineorg.erweima.ai/aichatonline"
APP_SECRET = os.getenv("APP_SECRET", "666")
ACCESS_TOKEN = os.getenv("SD_ACCESS_TOKEN", "")
headers = {    
    'accept': '*/*',
    'accept-language': 'en-US,en;q=0.9',
    'authorization': f'Bearer {ACCESS_TOKEN}',
    'cache-control': 'no-cache',
    'origin': 'chrome-extension://difoiogjjojoaoomphldepapgpbgkhkb',
    'pragma': 'no-cache',
    'priority': 'u=1, i',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'none',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36', 
}

# Define allowed models
ALLOWED_MODELS = [
    {"id": "claude-3.5-sonnet", "name": "claude-3.5-sonnet"},
    {"id": "claude-3-opus", "name": "claude-3-opus"},
    {"id": "gemini-1.5-pro", "name": "gemini-1.5-pro"},
    {"id": "gpt-4o", "name": "gpt-4o"},
    {"id": "o1-preview", "name": "o1-preview"},
    {"id": "o1-mini", "name": "o1-mini"},
    {"id": "gpt-4o-mini", "name": "gpt-4o-mini"},
]

# Configure CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins; restrict if necessary
    allow_credentials=True,
    allow_methods=["*"],  # Allow all HTTP methods
    allow_headers=["*"],  # Allow all headers
)

# Security configuration
security = HTTPBearer()

# ==============================
# Pydantic Models
# ==============================

class Message(BaseModel):
    role: str
    content: str

class ChatRequest(BaseModel):
    model: str
    messages: List[Message]
    stream: Optional[bool] = False

# ==============================
# Helper Functions
# ==============================

def simulate_data(content: str, model: str) -> Dict[str, Any]:
    """Simulate chunked response data."""
    return {
        "id": f"chatcmpl-{uuid.uuid4()}",
        "object": "chat.completion.chunk",
        "created": int(datetime.now().timestamp()),
        "model": model,
        "choices": [
            {
                "index": 0,
                "delta": {"content": content, "role": "assistant"},
                "finish_reason": None,
            }
        ],
        "usage": None,
    }

def stop_data(content: str, model: str) -> Dict[str, Any]:
    """Simulate the final chunk indicating the end of the response."""
    return {
        "id": f"chatcmpl-{uuid.uuid4()}",
        "object": "chat.completion.chunk",
        "created": int(datetime.now().timestamp()),
        "model": model,
        "choices": [
            {
                "index": 0,
                "delta": {"content": content, "role": "assistant"},
                "finish_reason": "stop",
            }
        ],
        "usage": None,
    }

def create_chat_completion_data(content: str, model: str, finish_reason: Optional[str] = None) -> Dict[str, Any]:
    """Create a structured chat completion data chunk."""
    return {
        "id": f"chatcmpl-{uuid.uuid4()}",
        "object": "chat.completion.chunk",
        "created": int(datetime.now().timestamp()),
        "model": model,
        "choices": [
            {
                "index": 0,
                "delta": {"content": content, "role": "assistant"},
                "finish_reason": finish_reason,
            }
        ],
        "usage": None,
    }

def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str:
    """Verify the provided APP_SECRET."""
    if credentials.credentials != APP_SECRET:
        raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
    return credentials.credentials

def replace_escaped_newlines(input_string: str) -> str:
    """Replace escaped newline characters with actual newlines."""
    return input_string.replace("\\n", "\n")

# ==============================
# API Endpoints
# ==============================

@app.options("/hf/v1/chat/completions")
async def chat_completions_options():
    """Handle CORS preflight requests."""
    return Response(
        status_code=200,
        headers={
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST, OPTIONS",
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
        },
    )

@app.get("/hf/v1/models")
async def list_models():
    """List all allowed models."""
    return {"object": "list", "data": ALLOWED_MODELS}

@app.post("/hf/v1/chat/completions")
async def chat_completions(
    request: ChatRequest, app_secret: str = Depends(verify_app_secret)
):
    """Handle chat completion requests."""
    logger.info(f"Received chat completion request for model: {request.model}")

    # Validate model
    allowed_model_ids = [model['id'] for model in ALLOWED_MODELS]
    if request.model not in allowed_model_ids:
        raise HTTPException(
            status_code=400,
            detail=f"Model {request.model} is not allowed. Allowed models are: {', '.join(allowed_model_ids)}",
        )

    # Generate a UUID
    original_uuid = uuid.uuid4()
    uuid_str = str(original_uuid).replace("-", "")

    # Construct the payload to send to the external API
    json_data = {
        'prompt': "\n".join(
            [
                f"{'User' if msg.role == 'user' else 'Assistant'}: {msg.content}"
                for msg in request.messages
            ]
        ),
        'stream': True,
        'app_name': 'ChitChat_Edge_Ext',
        'app_version': '4.28.0',
        'tz_name': 'Asia/Karachi',
        'cid': 'C092SEMXM9BJ',
        'model': request.model,
        'search': False,  # Disable search
        'auto_search': False,  # Disable auto_search
        'filter_search_history': False,
        'from': 'chat',
        'group_id': 'default',
        'chat_models': [],
        'files': [],
        'prompt_template': {
            'key': '',
            'attributes': {
                'lang': 'original',
            },
        },
        'tools': {
            'auto': [
                'search',  # Re-add search to maintain API expectations
                'text_to_image',
                'data_analysis',
            ],
        },
        'extra_info': {
            'origin_url': '',
            'origin_title': '',
        },
    }

    # Define the asynchronous generator for streaming responses
    async def generate():
        async with httpx.AsyncClient() as client:
            try:
                async with client.stream('POST', 'https://sider.ai/api/v3/completion/text', headers=headers, json=json_data, timeout=120.0) as response:
                    response.raise_for_status()
                    async for line in response.aiter_lines():
                        if line:
                            logger.debug(f"Raw line received: {line}")  # Log raw line
                        if line and ("[DONE]" not in line):
                            try:
                                # Remove 'data: ' prefix if present
                                if line.startswith("data: "):
                                    line_content = line[6:]
                                else:
                                    line_content = line
                                
                                # Log the content before parsing
                                logger.debug(f"Line content to parse: {line_content}")
                                
                                # Check if the line is not empty after stripping
                                if not line_content.strip():
                                    logger.warning("Received an empty line, skipping.")
                                    continue
                                
                                # Attempt to parse JSON
                                parsed_json = json.loads(line_content)
                                
                                # Ensure 'data' key exists
                                if "data" not in parsed_json:
                                    logger.error(f"'data' key not found in the response: {parsed_json}")
                                    continue
                                
                                content_data = parsed_json["data"]
                                
                                # Extract text content if available
                                text_content = content_data.get("text", "")
                                
                                # Yield the formatted data
                                yield f"data: {json.dumps(create_chat_completion_data(text_content, request.model))}\n\n"
                            except json.JSONDecodeError as e:
                                logger.error(f"JSON decode error: {e} | Line: {line_content}")
                                continue
                        else:
                            if line and "[DONE]" in line:
                                yield f"data: {json.dumps(create_chat_completion_data('', request.model, 'stop'))}\n\n"
                                yield "data: [DONE]\n\n"
            except httpx.HTTPStatusError as e:
                logger.error(f"HTTP error occurred: {e}")
                raise HTTPException(status_code=e.response.status_code, detail=str(e))
            except httpx.RequestError as e:
                logger.error(f"An error occurred while requesting: {e}")
                raise HTTPException(status_code=500, detail=str(e))

    if request.stream:
        logger.info("Streaming response")
        return StreamingResponse(generate(), media_type="text/event-stream")
    else:
        logger.info("Non-streaming response")
        full_response = ""
        async for chunk in generate():
            if chunk.startswith("data: ") and not chunk[6:].startswith("[DONE]"):
                try:
                    data = json.loads(chunk[6:])
                    if data["choices"][0]["delta"].get("content"):
                        full_response += data["choices"][0]["delta"]["content"]
                except json.JSONDecodeError as e:
                    logger.error(f"JSON decode error in non-streaming response: {e}")
                    continue

        return {
            "id": f"chatcmpl-{uuid.uuid4()}",
            "object": "chat.completion",
            "created": int(datetime.now().timestamp()),
            "model": request.model,
            "choices": [
                {
                    "index": 0,
                    "message": {"role": "assistant", "content": full_response},
                    "finish_reason": "stop",
                }
            ],
            "usage": None,
        }

# ==============================
# Entry Point
# ==============================

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)