interstellar_ai/py/api.py

62 lines
2 KiB
Python
Raw Normal View History

2024-09-19 09:41:00 +02:00
from flask import Flask, request, jsonify
2024-09-19 12:46:52 +02:00
from flask_cors import CORS
2024-09-19 09:41:00 +02:00
import ollama
2024-09-19 12:46:52 +02:00
import secrets
2024-09-19 09:41:00 +02:00
class AI:
@staticmethod
2024-09-19 16:24:16 +02:00
def process_local(model, messages, return_class, access_token):
2024-09-19 09:41:00 +02:00
stream = ollama.chat(
model=model,
2024-09-19 16:24:16 +02:00
messages=messages,
2024-09-19 09:41:00 +02:00
stream=True,
2024-09-19 16:24:16 +02:00
options={"temperature": 0},
2024-09-19 09:41:00 +02:00
)
for chunk in stream:
print(chunk['message']['content'])
return_class.ai_response[access_token] += chunk['message']['content']
class API:
def __init__(self):
self.app = Flask(__name__)
2024-09-19 12:46:52 +02:00
self.ai_response = {}
2024-09-19 09:41:00 +02:00
self.ai = AI()
2024-09-19 12:46:52 +02:00
CORS(self.app)
2024-09-19 09:41:00 +02:00
def run(self):
2024-09-19 09:44:54 +02:00
@self.app.route('/interstellar/api/ai_create', methods=['GET'])
2024-09-19 09:41:00 +02:00
def create_ai():
2024-09-19 12:46:52 +02:00
access_token = secrets.token_urlsafe(4096)
self.ai_response[access_token] = ""
return jsonify({'status': 200, 'access_token': access_token})
2024-09-19 09:41:00 +02:00
@self.app.route('/interstellar/api/ai_send', methods=['POST'])
def send_ai():
data = request.get_json()
2024-09-19 16:24:16 +02:00
messages = data.get('messages')
2024-09-19 09:41:00 +02:00
ai_model = data.get('ai_model')
access_token = data.get('access_token')
2024-09-19 12:46:52 +02:00
if access_token not in self.ai_response:
return jsonify({'status': 401, 'error': 'Invalid access token'})
2024-09-19 16:24:16 +02:00
self.ai.process_local(ai_model, messages, self, access_token)
2024-09-19 09:41:00 +02:00
return jsonify({'status': 200})
@self.app.route('/interstellar/api/ai_get', methods=['GET'])
def get_ai():
data = request.args.get('access_token')
2024-09-19 12:46:52 +02:00
if data not in self.ai_response:
return jsonify({'status': 401, 'error': 'Invalid access token'})
return jsonify({'status': 200, 'response': self.ai_response[data]})
2024-09-19 09:41:00 +02:00
2024-09-19 12:46:52 +02:00
ssl_context = ('cert.pem', 'key.pem')
self.app.run(debug=True, host='0.0.0.0', port=5000, ssl_context=ssl_context)
2024-09-19 09:41:00 +02:00
if __name__ == '__main__':
api = API()
api.run()
2024-09-19 12:46:52 +02:00