返回提交历史
Modified
interference/app.py
+86
-83
XFEstudio/gpt4free
~
23646b66
代码差异
1 个文件
+86
-83
@@ -1,104 +1,106 @@
1
1
import json
2
import time
2
3
import random
3
4
import string
4
import time
5
from typing import Any
6
5
import requests
7
from flask import Flask, request
8
from flask_cors import CORS
6
7
from typing import Any
8
from flask import Flask, request
9
from flask_cors import CORS
9
10
from transformers import AutoTokenizer
10
from g4f import ChatCompletion
11
from g4f import ChatCompletion
11
12
12
13
app = Flask(__name__)
13
14
CORS(app)
14
15
15
16
@app.route("/chat/completions", methods=["POST"])
16
@app.route('/chat/completions', methods=['POST'])
17
17
def chat_completions():
18
model = request.get_json().get("model", "gpt-3.5-turbo")
19
stream = request.get_json().get("stream", False)
20
messages = request.get_json().get("messages")
18
model = request.get_json().get('model', 'gpt-3.5-turbo')
19
stream = request.get_json().get('stream', False)
20
messages = request.get_json().get('messages')
21
21
22
response = ChatCompletion.create(model=model, stream=stream, messages=messages)
22
response = ChatCompletion.create(model = model,
23
stream = stream, messages = messages)
23
24
24
completion_id = "".join(random.choices(string.ascii_letters + string.digits, k=28))
25
completion_id = ''.join(random.choices(string.ascii_letters + string.digits, k=28))
25
26
completion_timestamp = int(time.time())
26
27
27
28
if not stream:
28
29
return {
29
"id": f"chatcmpl-{completion_id}",
30
"object": "chat.completion",
31
"created": completion_timestamp,
32
"model": model,
33
"choices": [
30
'id': f'chatcmpl-{completion_id}',
31
'object': 'chat.completion',
32
'created': completion_timestamp,
33
'model': model,
34
'choices': [
34
35
{
35
"index": 0,
36
"message": {
37
"role": "assistant",
38
"content": response,
36
'index': 0,
37
'message': {
38
'role': 'assistant',
39
'content': response,
39
40
},
40
"finish_reason": "stop",
41
'finish_reason': 'stop',
41
42
}
42
43
],
43
"usage": {
44
"prompt_tokens": None,
45
"completion_tokens": None,
46
"total_tokens": None,
44
'usage': {
45
'prompt_tokens': None,
46
'completion_tokens': None,
47
'total_tokens': None,
47
48
},
48
49
}
49
50
50
51
def streaming():
51
52
for chunk in response:
52
53
completion_data = {
53
"id": f"chatcmpl-{completion_id}",
54
"object": "chat.completion.chunk",
55
"created": completion_timestamp,
56
"model": model,
57
"choices": [
54
'id': f'chatcmpl-{completion_id}',
55
'object': 'chat.completion.chunk',
56
'created': completion_timestamp,
57
'model': model,
58
'choices': [
58
59
{
59
"index": 0,
60
"delta": {
61
"content": chunk,
60
'index': 0,
61
'delta': {
62
'content': chunk,
62
63
},
63
"finish_reason": None,
64
'finish_reason': None,
64
65
}
65
66
],
66
67
}
67
68
68
content = json.dumps(completion_data, separators=(",", ":"))
69
yield f"data: {content}\n\n"
69
content = json.dumps(completion_data, separators=(',', ':'))
70
yield f'data: {content}\n\n'
70
71
time.sleep(0.1)
71
72
72
73
end_completion_data: dict[str, Any] = {
73
"id": f"chatcmpl-{completion_id}",
74
"object": "chat.completion.chunk",
75
"created": completion_timestamp,
76
"model": model,
77
"choices": [
74
'id': f'chatcmpl-{completion_id}',
75
'object': 'chat.completion.chunk',
76
'created': completion_timestamp,
77
'model': model,
78
'choices': [
78
79
{
79
"index": 0,
80
"delta": {},
81
"finish_reason": "stop",
80
'index': 0,
81
'delta': {},
82
'finish_reason': 'stop',
82
83
}
83
84
],
84
85
}
85
content = json.dumps(end_completion_data, separators=(",", ":"))
86
yield f"data: {content}\n\n"
86
content = json.dumps(end_completion_data, separators=(',', ':'))
87
yield f'data: {content}\n\n'
87
88
88
return app.response_class(streaming(), mimetype="text/event-stream")
89
return app.response_class(streaming(), mimetype='text/event-stream')
89
90
90
91
91
#Get the embedding from huggingface
92
# Get the embedding from huggingface
92
93
def get_embedding(input_text, token):
93
94
huggingface_token = token
94
embedding_model = "sentence-transformers/all-mpnet-base-v2"
95
embedding_model = 'sentence-transformers/all-mpnet-base-v2'
95
96
max_token_length = 500
96
97
97
# Load the tokenizer for the "all-mpnet-base-v2" model
98
# Load the tokenizer for the 'all-mpnet-base-v2' model
98
99
tokenizer = AutoTokenizer.from_pretrained(embedding_model)
99
100
# Tokenize the text and split the tokens into chunks of 500 tokens each
100
101
tokens = tokenizer.tokenize(input_text)
101
token_chunks = [tokens[i:i + max_token_length] for i in range(0, len(tokens), max_token_length)]
102
token_chunks = [tokens[i:i + max_token_length]
103
for i in range(0, len(tokens), max_token_length)]
102
104
103
105
# Initialize an empty list
104
106
embeddings = []
@@ -109,52 +111,53 @@ def get_embedding(input_text, token):
109
111
chunk_text = tokenizer.convert_tokens_to_string(chunk)
110
112
111
113
# Use the Hugging Face API to get embeddings for the chunk
112
api_url = f"https://api-inference.huggingface.co/pipeline/feature-extraction/{embedding_model}"
113
headers = {"Authorization": f"Bearer {huggingface_token}"}
114
chunk_text = chunk_text.replace("\n", " ")
115
114
api_url = f'https://api-inference.huggingface.co/pipeline/feature-extraction/{embedding_model}'
115
headers = {'Authorization': f'Bearer {huggingface_token}'}
116
chunk_text = chunk_text.replace('\n', ' ')
117
116
118
# Make a POST request to get the chunk's embedding
117
response = requests.post(api_url, headers=headers, json={"inputs": chunk_text, "options": {"wait_for_model": True}})
118
119
response = requests.post(api_url, headers=headers, json={
120
'inputs': chunk_text, 'options': {'wait_for_model': True}})
121
119
122
# Parse the response and extract the embedding
120
123
chunk_embedding = response.json()
121
124
# Append the embedding to the list
122
125
embeddings.append(chunk_embedding)
123
126
124
#averaging all the embeddings
125
#this isn't very effective
126
#someone a better idea?
127
# averaging all the embeddings
128
# this isn't very effective
129
# someone a better idea?
127
130
num_embeddings = len(embeddings)
128
131
average_embedding = [sum(x) / num_embeddings for x in zip(*embeddings)]
129
132
embedding = average_embedding
130
133
return embedding
131
134
132
135
133
@app.route("/embeddings", methods=["POST"])
136
@app.route('/embeddings', methods=['POST'])
134
137
def embeddings():
135
input_text_list = request.get_json().get("input")
136
input_text = ' '.join(map(str, input_text_list))
137
token = request.headers.get('Authorization').replace("Bearer ", "")
138
embedding = get_embedding(input_text, token)
138
input_text_list = request.get_json().get('input')
139
input_text = ' '.join(map(str, input_text_list))
140
token = request.headers.get('Authorization').replace('Bearer ', '')
141
embedding = get_embedding(input_text, token)
142
139
143
return {
140
"data": [
141
{
142
"embedding": embedding,
143
"index": 0,
144
"object": "embedding"
145
}
146
],
147
"model": "text-embedding-ada-002",
148
"object": "list",
149
"usage": {
150
"prompt_tokens": None,
151
"total_tokens": None
152
}
153
}
144
'data': [
145
{
146
'embedding': embedding,
147
'index': 0,
148
'object': 'embedding'
149
}
150
],
151
'model': 'text-embedding-ada-002',
152
'object': 'list',
153
'usage': {
154
'prompt_tokens': None,
155
'total_tokens': None
156
}
157
}
154
158
155
159
def main():
156
app.run(host="0.0.0.0", port=1337, debug=True)
157
160
app.run(host='0.0.0.0', port=1337, debug=True)
158
161
159
if __name__ == "__main__":
162
if __name__ == '__main__':
160
163
main()