Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,11 @@
|
|
1 |
-
from
|
|
|
2 |
import requests
|
3 |
import json
|
4 |
import os
|
|
|
5 |
|
6 |
-
app =
|
7 |
|
8 |
# 环境变量配置
|
9 |
STATUS_URL = os.environ.get("STATUS_URL", "https://duckduckgo.com/duckchat/v1/status")
|
@@ -14,153 +16,151 @@ USER_AGENT = os.environ.get("USER_AGENT", "Mozilla/5.0 (Macintosh; Intel Mac OS
|
|
14 |
COOKIE = os.environ.get("COOKIE", "dcm=3; s=l; bf=1") # 从环境变量获取 Cookie
|
15 |
|
16 |
DEFAULT_HEADERS = {
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
}
|
32 |
|
33 |
SUPPORTED_MODELS = ["o3-mini", "gpt-4o-mini", "claude-3-haiku-20240307", "meta-llama/Llama-3.3-70B-Instruct-Turbo"]
|
34 |
|
35 |
-
def get_vqd():
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
def duckduckgo_chat(model, messages):
|
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 |
-
@app.
|
88 |
-
def chat_completions():
|
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 |
-
if __name__ == '__main__':
|
166 |
-
app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException, Request
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
import requests
|
4 |
import json
|
5 |
import os
|
6 |
+
import time
|
7 |
|
8 |
+
app = FastAPI()
|
9 |
|
10 |
# 环境变量配置
|
11 |
STATUS_URL = os.environ.get("STATUS_URL", "https://duckduckgo.com/duckchat/v1/status")
|
|
|
16 |
COOKIE = os.environ.get("COOKIE", "dcm=3; s=l; bf=1") # 从环境变量获取 Cookie
|
17 |
|
18 |
DEFAULT_HEADERS = {
|
19 |
+
"User-Agent": USER_AGENT,
|
20 |
+
"Accept": "text/event-stream",
|
21 |
+
"Accept-Language": "en-US,en;q=0.5",
|
22 |
+
"Accept-Encoding": "gzip, deflate, br",
|
23 |
+
"Referer": REFERER,
|
24 |
+
"Content-Type": "application/json",
|
25 |
+
"Origin": ORIGIN,
|
26 |
+
"Connection": "keep-alive",
|
27 |
+
"Cookie": COOKIE,
|
28 |
+
"Sec-Fetch-Dest": "empty",
|
29 |
+
"Sec-Fetch-Mode": "cors",
|
30 |
+
"Sec-Fetch-Site": "same-origin",
|
31 |
+
"Pragma": "no-cache",
|
32 |
+
"TE": "trailers",
|
33 |
}
|
34 |
|
35 |
SUPPORTED_MODELS = ["o3-mini", "gpt-4o-mini", "claude-3-haiku-20240307", "meta-llama/Llama-3.3-70B-Instruct-Turbo"]
|
36 |
|
37 |
+
async def get_vqd():
|
38 |
+
"""获取 DuckDuckGo Chat 的 VQD 值。"""
|
39 |
+
headers = {**DEFAULT_HEADERS, "x-vqd-accept": "1"}
|
40 |
+
try:
|
41 |
+
response = requests.get(STATUS_URL, headers=headers)
|
42 |
+
response.raise_for_status() # 抛出 HTTPError,如果状态码不是 200
|
43 |
+
vqd = response.headers.get("x-vqd-4")
|
44 |
+
if not vqd:
|
45 |
+
raise ValueError("x-vqd-4 header 在响应中未找到。")
|
46 |
+
return vqd
|
47 |
+
except requests.exceptions.RequestException as e:
|
48 |
+
raise HTTPException(status_code=500, detail=f"HTTP 请求失败: {e}")
|
49 |
+
except ValueError as e:
|
50 |
+
raise HTTPException(status_code=500, detail=str(e))
|
51 |
+
|
52 |
+
async def duckduckgo_chat(model, messages):
|
53 |
+
"""与 DuckDuckGo Chat 进行交互。"""
|
54 |
+
try:
|
55 |
+
x_vqd_4 = await get_vqd()
|
56 |
+
|
57 |
+
chat_headers = {
|
58 |
+
**DEFAULT_HEADERS,
|
59 |
+
"x-vqd-4": x_vqd_4,
|
60 |
+
}
|
61 |
+
|
62 |
+
body = json.dumps({
|
63 |
+
"model": model,
|
64 |
+
"messages": messages,
|
65 |
+
})
|
66 |
+
|
67 |
+
response = requests.post(CHAT_URL, headers=chat_headers, data=body, stream=True)
|
68 |
+
response.raise_for_status()
|
69 |
+
|
70 |
+
full_message = ""
|
71 |
+
for line in response.iter_lines():
|
72 |
+
if line:
|
73 |
+
decoded_line = line.decode('utf-8')
|
74 |
+
if decoded_line.startswith("data: "):
|
75 |
+
try:
|
76 |
+
json_data = json.loads(decoded_line[5:])
|
77 |
+
full_message += json_data.get("message", "")
|
78 |
+
except json.JSONDecodeError as e:
|
79 |
+
print(f"JSON 解析错误: {e}, 行: {decoded_line}")
|
80 |
+
pass # 忽略解析错误
|
81 |
+
|
82 |
+
return full_message
|
83 |
+
|
84 |
+
except requests.exceptions.RequestException as e:
|
85 |
+
raise HTTPException(status_code=500, detail=f"HTTP 请求失败: {e}")
|
86 |
+
except Exception as e:
|
87 |
+
raise HTTPException(status_code=500, detail=f"聊天过程中发生错误: {e}")
|
88 |
+
|
89 |
+
@app.post("/v1/chat/completions")
|
90 |
+
async def chat_completions(request: Request):
|
91 |
+
try:
|
92 |
+
body = await request.json()
|
93 |
+
if not body:
|
94 |
+
raise HTTPException(status_code=400, detail="无效的请求体")
|
95 |
+
|
96 |
+
model = body.get("model", "o3-mini")
|
97 |
+
if model not in SUPPORTED_MODELS:
|
98 |
+
raise HTTPException(status_code=400, detail=f"模型 \"{model}\" 不支持。支持的模型有: {', '.join(SUPPORTED_MODELS)}.")
|
99 |
+
|
100 |
+
messages = body.get("messages")
|
101 |
+
if not messages:
|
102 |
+
raise HTTPException(status_code=400, detail="未提供任何消息内容")
|
103 |
+
|
104 |
+
# 处理 system 消息
|
105 |
+
system_message = next((msg for msg in messages if msg.get("role") == "system"), None)
|
106 |
+
system_prompt = f"你将扮演一个{system_message['content']}.\n" if system_message else ""
|
107 |
+
|
108 |
+
# 提取历史消息并格式化
|
109 |
+
history_messages = "\n".join(
|
110 |
+
f"{msg['role']}: {msg['content']}"
|
111 |
+
for msg in messages
|
112 |
+
if msg.get("role") != "system" and msg != messages[-1]
|
113 |
+
)
|
114 |
+
|
115 |
+
# 提取最后一条用户消息
|
116 |
+
last_user_message = messages[-1]
|
117 |
+
current_question = last_user_message["content"] if last_user_message.get("role") == "user" else ""
|
118 |
+
|
119 |
+
# 构建合并后的消息
|
120 |
+
combined_message_content = f"{system_prompt}以下是历史对话记录:\n{history_messages}\n用户当前提问:{current_question}"
|
121 |
+
combined_message = {"role": "user", "content": combined_message_content}
|
122 |
+
|
123 |
+
# 发送单条消息
|
124 |
+
response_text = await duckduckgo_chat(model, [combined_message])
|
125 |
+
|
126 |
+
# 构建 OpenAI 风格的响应
|
127 |
+
openai_response = {
|
128 |
+
"id": f"chatcmpl-{int(time.time() * 1000)}", # 生成唯一 ID
|
129 |
+
"object": "chat.completion",
|
130 |
+
"created": int(time.time()),
|
131 |
+
"model": model,
|
132 |
+
"choices": [
|
133 |
+
{
|
134 |
+
"message": {
|
135 |
+
"role": "assistant",
|
136 |
+
"content": response_text,
|
137 |
+
},
|
138 |
+
"finish_reason": "stop",
|
139 |
+
"index": 0,
|
140 |
+
},
|
141 |
+
],
|
142 |
+
"usage": {
|
143 |
+
"prompt_tokens": 0,
|
144 |
+
"completion_tokens": 0,
|
145 |
+
"total_tokens": 0
|
146 |
+
},
|
147 |
+
}
|
148 |
+
|
149 |
+
return JSONResponse(content=openai_response)
|
150 |
+
|
151 |
+
except HTTPException as e:
|
152 |
+
raise e # 重新抛出 HTTPException,以便 FastAPI 处理
|
153 |
+
except Exception as e:
|
154 |
+
print(f"API 错误: {e}")
|
155 |
+
raise HTTPException(status_code=500, detail=f"服务器内部错误: {e}")
|
156 |
+
|
157 |
+
@app.exception_handler(HTTPException)
|
158 |
+
async def http_exception_handler(request: Request, exc: HTTPException):
|
159 |
+
return JSONResponse(
|
160 |
+
status_code=exc.status_code,
|
161 |
+
content={"detail": exc.detail},
|
162 |
+
)
|
163 |
+
|
164 |
+
@app.get("/")
|
165 |
+
async def greet_json():
|
166 |
+
return {"Hello": "World!"}
|
|
|
|