tianlong12 commited on
Commit
bd06cc8
1 Parent(s): ecaf86a

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +87 -83
main.py CHANGED
@@ -1,103 +1,107 @@
1
- import os
2
- import time
3
- import random
4
- import asyncio
5
  import requests
6
- from fastapi import FastAPI, HTTPException, Request
7
- from fastapi.responses import StreamingResponse
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
- class ChatCompletionResponse(BaseModel):
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
- async def fetch_response(messages: List[ChatCompletionMessage], model: str):
36
- your_api_url = "https://chatpro.ai-pro.org/api/ask/openAI"
37
- headers = {
38
- "content-type": "application/json",
39
- "X-Forwarded-For": generate_random_ip(),
40
- "origin": "https://chatpro.ai-pro.org",
41
- "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"
 
 
 
 
42
  }
 
 
 
 
 
 
 
 
 
43
 
44
  # 将消息列表转换为单个字符串,保留对话历史
45
- conversation = "\n".join([f"{msg.role}: {msg.content}" for msg in messages])
46
 
47
  # 添加指导语
48
  conversation += "\n请关注并回复user最近的消息并避免总结对话历史的回答"
49
-
50
- data = {
 
 
 
 
 
 
 
 
 
51
  "text": conversation,
52
  "endpoint": "openAI",
53
  "model": model
54
  }
55
 
56
- response = requests.post(your_api_url, headers=headers, json=data)
57
-
58
- if response.status_code != 200:
59
- raise HTTPException(status_code=response.status_code, detail="Error from upstream API")
60
-
61
- return response.json()
62
-
63
- async def stream_response(content: str):
64
- # Send the entire content as a single chunk
65
- yield f"data: {{'id': 'chatcmpl-{os.urandom(12).hex()}', 'object': 'chat.completion.chunk', 'created': 1677652288, 'model': 'gpt-3.5-turbo-0613', 'choices': [{'index': 0, 'delta': {{'content': '{content}'}}, 'finish_reason': None}]}}\n\n"
66
- yield f"data: {{'id': 'chatcmpl-{os.urandom(12).hex()}', 'object': 'chat.completion.chunk', 'created': 1677652288, 'model': 'gpt-3.5-turbo-0613', 'choices': [{'index': 0, 'delta': {{}}, 'finish_reason': 'stop'}]}}\n\n"
67
- yield 'data: [DONE]\n\n'
 
 
 
 
 
 
68
 
69
- @app.post("/hf/v1/chat/completions")
70
- async def chat_completions(request: Request):
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
- openai_response = ChatCompletionResponse(
83
- id="chatcmpl-" + os.urandom(12).hex(),
84
- object="chat.completion",
85
- created=int(time.time()),
86
- model=chat_request.model,
87
- choices=[
88
- {
89
- "index": 0,
90
- "message": {
91
- "role": "assistant",
92
- "content": content
93
- },
94
- "finish_reason": "stop"
95
- }
96
- ],
97
- usage={
98
- "prompt_tokens": sum(len(msg.content) for msg in chat_request.messages),
99
- "completion_tokens": len(content),
100
- "total_tokens": sum(len(msg.content) for msg in chat_request.messages) + len(content)
 
 
 
 
 
 
 
101
  }
102
- )
103
- return openai_response
 
 
 
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)