gpt4free/interference/app.py

163 lines
5.2 KiB
Python
Raw Normal View History

2023-06-24 01:47:00 +00:00
import json
2023-10-02 17:07:20 +00:00
import time
2023-06-24 01:47:00 +00:00
import random
2023-07-28 10:07:17 +00:00
import string
import requests
2023-10-02 17:07:20 +00:00
from typing import Any
from flask import Flask, request
from flask_cors import CORS
from transformers import AutoTokenizer
2023-10-02 17:07:20 +00:00
from g4f import ChatCompletion
2023-07-28 10:07:17 +00:00
2023-06-24 01:47:00 +00:00
app = Flask(__name__)
CORS(app)
2023-10-02 17:07:20 +00:00
@app.route('/chat/completions', methods=['POST'])
2023-06-24 01:47:00 +00:00
def chat_completions():
2023-10-02 17:07:20 +00:00
model = request.get_json().get('model', 'gpt-3.5-turbo')
stream = request.get_json().get('stream', False)
messages = request.get_json().get('messages')
2023-06-24 01:47:00 +00:00
2023-10-02 17:07:20 +00:00
response = ChatCompletion.create(model = model,
stream = stream, messages = messages)
2023-06-24 01:47:00 +00:00
2023-10-02 17:07:20 +00:00
completion_id = ''.join(random.choices(string.ascii_letters + string.digits, k=28))
2023-07-28 10:07:17 +00:00
completion_timestamp = int(time.time())
if not stream:
2023-06-24 01:47:00 +00:00
return {
2023-10-02 17:07:20 +00:00
'id': f'chatcmpl-{completion_id}',
'object': 'chat.completion',
'created': completion_timestamp,
'model': model,
'choices': [
2023-07-28 10:07:17 +00:00
{
2023-10-02 17:07:20 +00:00
'index': 0,
'message': {
'role': 'assistant',
'content': response,
2023-07-28 10:07:17 +00:00
},
2023-10-02 17:07:20 +00:00
'finish_reason': 'stop',
2023-07-28 10:07:17 +00:00
}
],
2023-10-02 17:07:20 +00:00
'usage': {
'prompt_tokens': None,
'completion_tokens': None,
'total_tokens': None,
2023-06-24 01:47:00 +00:00
},
}
2023-07-28 10:07:17 +00:00
def streaming():
for chunk in response:
2023-06-24 01:47:00 +00:00
completion_data = {
2023-10-02 17:07:20 +00:00
'id': f'chatcmpl-{completion_id}',
'object': 'chat.completion.chunk',
'created': completion_timestamp,
'model': model,
'choices': [
2023-06-24 01:47:00 +00:00
{
2023-10-02 17:07:20 +00:00
'index': 0,
'delta': {
'content': chunk,
2023-06-24 01:47:00 +00:00
},
2023-10-02 17:07:20 +00:00
'finish_reason': None,
2023-06-24 01:47:00 +00:00
}
2023-07-28 10:07:17 +00:00
],
2023-06-24 01:47:00 +00:00
}
2023-10-02 17:07:20 +00:00
content = json.dumps(completion_data, separators=(',', ':'))
yield f'data: {content}\n\n'
2023-06-24 01:47:00 +00:00
time.sleep(0.1)
2023-07-28 10:07:17 +00:00
end_completion_data: dict[str, Any] = {
2023-10-02 17:07:20 +00:00
'id': f'chatcmpl-{completion_id}',
'object': 'chat.completion.chunk',
'created': completion_timestamp,
'model': model,
'choices': [
2023-07-28 10:07:17 +00:00
{
2023-10-02 17:07:20 +00:00
'index': 0,
'delta': {},
'finish_reason': 'stop',
2023-07-28 10:07:17 +00:00
}
],
}
2023-10-02 17:07:20 +00:00
content = json.dumps(end_completion_data, separators=(',', ':'))
yield f'data: {content}\n\n'
2023-06-24 01:47:00 +00:00
2023-10-02 17:07:20 +00:00
return app.response_class(streaming(), mimetype='text/event-stream')
2023-06-24 01:47:00 +00:00
2023-10-02 17:07:20 +00:00
# Get the embedding from huggingface
def get_embedding(input_text, token):
huggingface_token = token
2023-10-02 17:07:20 +00:00
embedding_model = 'sentence-transformers/all-mpnet-base-v2'
max_token_length = 500
2023-10-02 17:07:20 +00:00
# Load the tokenizer for the 'all-mpnet-base-v2' model
tokenizer = AutoTokenizer.from_pretrained(embedding_model)
# Tokenize the text and split the tokens into chunks of 500 tokens each
tokens = tokenizer.tokenize(input_text)
2023-10-02 17:07:20 +00:00
token_chunks = [tokens[i:i + max_token_length]
for i in range(0, len(tokens), max_token_length)]
# Initialize an empty list
embeddings = []
# Create embeddings for each chunk
for chunk in token_chunks:
# Convert the chunk tokens back to text
chunk_text = tokenizer.convert_tokens_to_string(chunk)
# Use the Hugging Face API to get embeddings for the chunk
2023-10-02 17:07:20 +00:00
api_url = f'https://api-inference.huggingface.co/pipeline/feature-extraction/{embedding_model}'
headers = {'Authorization': f'Bearer {huggingface_token}'}
chunk_text = chunk_text.replace('\n', ' ')
# Make a POST request to get the chunk's embedding
2023-10-02 17:07:20 +00:00
response = requests.post(api_url, headers=headers, json={
'inputs': chunk_text, 'options': {'wait_for_model': True}})
# Parse the response and extract the embedding
chunk_embedding = response.json()
# Append the embedding to the list
embeddings.append(chunk_embedding)
2023-10-02 17:07:20 +00:00
# averaging all the embeddings
# this isn't very effective
# someone a better idea?
num_embeddings = len(embeddings)
average_embedding = [sum(x) / num_embeddings for x in zip(*embeddings)]
embedding = average_embedding
return embedding
2023-10-02 17:07:20 +00:00
@app.route('/embeddings', methods=['POST'])
def embeddings():
2023-10-02 17:07:20 +00:00
input_text_list = request.get_json().get('input')
input_text = ' '.join(map(str, input_text_list))
token = request.headers.get('Authorization').replace('Bearer ', '')
embedding = get_embedding(input_text, token)
return {
2023-10-02 17:07:20 +00:00
'data': [
{
'embedding': embedding,
'index': 0,
'object': 'embedding'
}
],
'model': 'text-embedding-ada-002',
'object': 'list',
'usage': {
'prompt_tokens': None,
'total_tokens': None
}
}
2023-08-31 11:32:23 +00:00
def main():
2023-10-02 17:07:20 +00:00
app.run(host='0.0.0.0', port=1337, debug=True)
2023-08-31 11:32:23 +00:00
2023-10-02 17:07:20 +00:00
if __name__ == '__main__':
2023-09-26 13:18:47 +00:00
main()