tianlong12
commited on
Commit
•
bd06cc8
1
Parent(s):
ecaf86a
Update main.py
Browse files
main.py
CHANGED
@@ -1,103 +1,107 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
import random
|
4 |
-
import asyncio
|
5 |
import requests
|
6 |
-
from
|
7 |
-
|
8 |
-
from pydantic import BaseModel
|
9 |
-
from typing import List, Optional, Union
|
10 |
-
|
11 |
-
app = FastAPI()
|
12 |
-
|
13 |
-
class ChatCompletionMessage(BaseModel):
|
14 |
-
role: str
|
15 |
-
content: str
|
16 |
-
|
17 |
-
class ChatCompletionRequest(BaseModel):
|
18 |
-
model: str
|
19 |
-
messages: List[ChatCompletionMessage]
|
20 |
-
temperature: Optional[float] = 1.0
|
21 |
-
max_tokens: Optional[int] = None
|
22 |
-
stream: Optional[bool] = False
|
23 |
|
24 |
-
|
25 |
-
id: str
|
26 |
-
object: str
|
27 |
-
created: int
|
28 |
-
model: str
|
29 |
-
choices: List[dict]
|
30 |
-
usage: dict
|
31 |
|
32 |
def generate_random_ip():
|
33 |
return f"{random.randint(1,255)}.{random.randint(0,255)}.{random.randint(0,255)}.{random.randint(0,255)}"
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
"
|
39 |
-
"
|
40 |
-
"
|
41 |
-
"
|
|
|
|
|
|
|
|
|
42 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
# 将消息列表转换为单个字符串,保留对话历史
|
45 |
-
conversation = "\n".join([f"{msg
|
46 |
|
47 |
# 添加指导语
|
48 |
conversation += "\n请关注并回复user最近的消息并避免总结对话历史的回答"
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
"text": conversation,
|
52 |
"endpoint": "openAI",
|
53 |
"model": model
|
54 |
}
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
body = await request.json()
|
72 |
-
chat_request = ChatCompletionRequest(**body)
|
73 |
-
|
74 |
-
# 传递整个消息历史到API
|
75 |
-
api_response = await fetch_response(chat_request.messages, chat_request.model)
|
76 |
-
|
77 |
-
content = api_response.get("response", "")
|
78 |
-
|
79 |
-
if chat_request.stream:
|
80 |
-
return StreamingResponse(stream_response(content), media_type="text/event-stream")
|
81 |
else:
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
"
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
}
|
102 |
-
|
103 |
-
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import sseclient
|
|
|
|
|
3 |
import requests
|
4 |
+
from flask import Flask, request, Response, stream_with_context
|
5 |
+
import random
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
def generate_random_ip():
|
10 |
return f"{random.randint(1,255)}.{random.randint(0,255)}.{random.randint(0,255)}.{random.randint(0,255)}"
|
11 |
|
12 |
+
def format_openai_response(content, finish_reason=None):
|
13 |
+
return {
|
14 |
+
"id": "chatcmpl-123",
|
15 |
+
"object": "chat.completion.chunk",
|
16 |
+
"created": 1677652288,
|
17 |
+
"model": "gpt-4o",
|
18 |
+
"choices": [{
|
19 |
+
"delta": {"content": content} if content else {"finish_reason": finish_reason},
|
20 |
+
"index": 0,
|
21 |
+
"finish_reason": finish_reason
|
22 |
+
}]
|
23 |
}
|
24 |
+
|
25 |
+
@app.route('/hf/v1/chat/completions', methods=['POST'])
|
26 |
+
def chat_completions():
|
27 |
+
data = request.json
|
28 |
+
messages = data.get('messages', [])
|
29 |
+
stream = data.get('stream', False)
|
30 |
+
|
31 |
+
if not messages:
|
32 |
+
return {"error": "No messages provided"}, 400
|
33 |
|
34 |
# 将消息列表转换为单个字符串,保留对话历史
|
35 |
+
conversation = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])
|
36 |
|
37 |
# 添加指导语
|
38 |
conversation += "\n请关注并回复user最近的消息并避免总结对话历史的回答"
|
39 |
+
|
40 |
+
model = data.get('model', 'gpt-4o')
|
41 |
+
|
42 |
+
original_api_url = 'https://chatpro.ai-pro.org/api/ask/openAI'
|
43 |
+
headers = {
|
44 |
+
'content-type': 'application/json',
|
45 |
+
'X-Forwarded-For': generate_random_ip(),
|
46 |
+
'origin': 'https://chatpro.ai-pro.org',
|
47 |
+
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
|
48 |
+
}
|
49 |
+
payload = {
|
50 |
"text": conversation,
|
51 |
"endpoint": "openAI",
|
52 |
"model": model
|
53 |
}
|
54 |
|
55 |
+
def generate():
|
56 |
+
last_content = ""
|
57 |
+
response = requests.post(original_api_url, headers=headers, json=payload, stream=True)
|
58 |
+
client = sseclient.SSEClient(response)
|
59 |
+
|
60 |
+
for event in client.events():
|
61 |
+
if event.data.startswith('{"text":'):
|
62 |
+
data = json.loads(event.data)
|
63 |
+
new_content = data['text'][len(last_content):]
|
64 |
+
last_content = data['text']
|
65 |
+
|
66 |
+
if new_content:
|
67 |
+
yield f"data: {json.dumps(format_openai_response(new_content))}\n\n"
|
68 |
+
|
69 |
+
elif '"final":true' in event.data:
|
70 |
+
yield f"data: {json.dumps(format_openai_response('', 'stop'))}\n\n"
|
71 |
+
yield "data: [DONE]\n\n"
|
72 |
+
break
|
73 |
|
74 |
+
if stream:
|
75 |
+
return Response(stream_with_context(generate()), content_type='text/event-stream')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
else:
|
77 |
+
full_response = ""
|
78 |
+
for chunk in generate():
|
79 |
+
if chunk.startswith("data: ") and not chunk.strip() == "data: [DONE]":
|
80 |
+
response_data = json.loads(chunk[6:])
|
81 |
+
if 'choices' in response_data and response_data['choices']:
|
82 |
+
delta = response_data['choices'][0].get('delta', {})
|
83 |
+
if 'content' in delta:
|
84 |
+
full_response += delta['content']
|
85 |
+
|
86 |
+
return {
|
87 |
+
"id": "chatcmpl-123",
|
88 |
+
"object": "chat.completion",
|
89 |
+
"created": 1677652288,
|
90 |
+
"model": model,
|
91 |
+
"choices": [{
|
92 |
+
"index": 0,
|
93 |
+
"message": {
|
94 |
+
"role": "assistant",
|
95 |
+
"content": full_response
|
96 |
+
},
|
97 |
+
"finish_reason": "stop"
|
98 |
+
}],
|
99 |
+
"usage": {
|
100 |
+
"prompt_tokens": 0,
|
101 |
+
"completion_tokens": 0,
|
102 |
+
"total_tokens": 0
|
103 |
}
|
104 |
+
}
|
105 |
+
|
106 |
+
if __name__ == '__main__':
|
107 |
+
app.run(debug=True, port=5000)
|