XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Adding embedding support using huggingface to app.py

596e1d89
chatgpt-tricks <143020293+chatgpt-tricks@users.noreply.github.com>
提交于

代码差异

1 个文件 +66 -2
Modified interference/app.py +66 -2
@@ -3,7 +3,7 @@ import random
3 3 import string
4 4 import time
5 5 from typing import Any
6
6 import requests
7 7 from flask import Flask, request
8 8 from flask_cors import CORS
9 9
@@ -88,9 +88,73 @@ def chat_completions():
88 88 return app.response_class(streaming(), mimetype="text/event-stream")
89 89
90 90
91 #Get the embedding from huggingface
92 def get_embedding(input_text, token):
93 huggingface_token = token
94 embedding_model = "sentence-transformers/all-mpnet-base-v2"
95 max_token_length = 500
96
97 # Load the tokenizer for the "all-mpnet-base-v2" model
98 tokenizer = AutoTokenizer.from_pretrained(embedding_model)
99 # Tokenize the text and split the tokens into chunks of 500 tokens each
100 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
103 # Initialize an empty list
104 embeddings = []
105
106 # Create embeddings for each chunk
107 for chunk in token_chunks:
108 # Convert the chunk tokens back to text
109 chunk_text = tokenizer.convert_tokens_to_string(chunk)
110
111 # 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
116 # 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 # Parse the response and extract the embedding
120 chunk_embedding = response.json()
121 # Append the embedding to the list
122 embeddings.append(chunk_embedding)
123
124 #averaging all the embeddings
125 #this isn't very effective
126 #someone a better idea?
127 num_embeddings = len(embeddings)
128 average_embedding = [sum(x) / num_embeddings for x in zip(*embeddings)]
129 embedding = average_embedding
130 return embedding
131
132
133 @app.route("/embeddings", methods=["POST"])
134 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)
139 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 }
154
91 155 def main():
92 156 app.run(host="0.0.0.0", port=1337, debug=True)
93 157
94 158
95 159 if __name__ == "__main__":
96 main()
160 main()