adityaxess's picture
Deploy 24/7 DeepSeek Proxy Server
aedcabb
Raw History Blame Contribute Delete
6.21 kB
"""
FastAPI Server Application for DeepSeek Proxy.
Provides OpenAI-Compatible REST API endpoints and Tab Management endpoints.
"""
import time
import uuid
from typing import List, Optional, Union
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from server.model_resolver import resolve_model, DEFAULT_MODEL_NAME
from server.tab_manager import tab_manager
from server.cdp_client import send_chat_completion
app = FastAPI(
title="DeepSeek Proxy API Server",
description="Bridge server for DeepSeek models with tab selection & automatic default model selection.",
version="1.0.0"
)
# --- Pydantic Data Models ---
class ChatMessage(BaseModel):
role: str = "user"
content: str
class ChatCompletionRequest(BaseModel):
model: Optional[str] = Field(default=None, description="Model name. Defaults to 'DeepSeek-V3 Standard' if omitted or empty.")
messages: List[ChatMessage]
chat_session_id: Optional[str] = Field(default=None, description="Optional tab session ID override.")
stream: Optional[bool] = False
class TabSelectRequest(BaseModel):
chat_session_id: str
# --- API Routes ---
@app.get("/health")
async def health_check():
active_tab = await tab_manager.get_active_session()
return {
"status": "online",
"active_tab_session_id": active_tab,
"default_model": DEFAULT_MODEL_NAME
}
@app.get("/v1/models")
async def list_models():
return {
"object": "list",
"data": [
{"id": "DeepSeek-V3 Standard", "object": "model", "owned_by": "deepseek", "is_default": True},
{"id": "DeepSeek-R1", "object": "model", "owned_by": "deepseek", "is_default": False},
{"id": "DeepSeek-V3 + R1", "object": "model", "owned_by": "deepseek", "is_default": False},
{"id": "DeepSeek Web Search", "object": "model", "owned_by": "deepseek", "is_default": False},
{"id": "DeepSeek Vision (DeepSeek-VL / Janus)", "object": "model", "owned_by": "deepseek", "is_default": False},
{"id": "deepseek-vision", "object": "model", "owned_by": "deepseek", "is_default": False},
{"id": "deepseek-vl", "object": "model", "owned_by": "deepseek", "is_default": False},
{"id": "deepseek-janus-pro", "object": "model", "owned_by": "deepseek", "is_default": False}
]
}
@app.get("/v1/tabs")
async def get_tabs():
"""Returns list of previous chat session tabs and highlights active tab."""
active_id = await tab_manager.get_active_session()
previous_tabs = await tab_manager.list_available_tabs()
return {
"active_session_id": active_id,
"tabs": previous_tabs
}
@app.post("/v1/tab/select")
async def select_tab(req: TabSelectRequest):
"""Switches active session tab to the requested chat_session_id."""
sid = await tab_manager.set_active_session(req.chat_session_id)
return {
"status": "success",
"message": f"Switched to tab session: {sid}",
"active_session_id": sid
}
@app.post("/v1/tab/new")
async def create_new_tab():
"""Opens a brand new chat session tab."""
sid = await tab_manager.initialize(use_new_tab=True)
return {
"status": "success",
"message": "Opened new chat session tab.",
"active_session_id": sid
}
@app.post("/v1/chat/completions")
async def chat_completions(req: ChatCompletionRequest):
"""
OpenAI-Compatible Chat Completions Endpoint.
If model is unspecified, auto-selects 'DeepSeek-V3 Standard'.
"""
if not req.messages:
raise HTTPException(status_code=400, detail="Messages array cannot be empty.")
# Get last user prompt
prompt = req.messages[-1].content
# Resolve Model (Defaults to DeepSeek-V3 Standard if model is None or empty)
model_cfg = resolve_model(req.model)
resolved_model_name = model_cfg["resolved_name"]
# Determine Tab / Session ID
if req.chat_session_id:
session_id = req.chat_session_id
else:
session_id = await tab_manager.get_active_session()
parent_msg_id = tab_manager.get_parent_message_id(session_id)
print(f"\n📩 API Request Received:")
print(f" Model Specified: '{req.model}' -> Resolved: '{resolved_model_name}' (Default: {model_cfg['was_auto_selected']})")
print(f" Tab Session ID: '{session_id}' (Parent Msg ID: {parent_msg_id})")
print(f" Prompt: '{prompt}'")
try:
# Execute prompt via CDP inside browser
result = await send_chat_completion(
chat_session_id=session_id,
prompt=prompt,
model_config=model_cfg,
parent_message_id=parent_msg_id
)
response_text = result.get("response_text", "")
next_parent_msg_id = result.get("parent_message_id")
if next_parent_msg_id:
tab_manager.update_parent_message_id(session_id, next_parent_msg_id)
# Build OpenAI Compatible Response
cmpl_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
created_ts = int(time.time())
return {
"id": cmpl_id,
"object": "chat.completion",
"created": created_ts,
"model": resolved_model_name,
"model_resolution": {
"requested": req.model,
"resolved": resolved_model_name,
"is_default_fallback": model_cfg["was_auto_selected"]
},
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": response_text
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": len(prompt.split()),
"completion_tokens": len(response_text.split()),
"total_tokens": len(prompt.split()) + len(response_text.split())
},
"chat_session_id": session_id
}
except Exception as e:
print(f"❌ Error executing chat completion: {e}")
raise HTTPException(status_code=500, detail=f"DeepSeek execution error: {str(e)}")