Update api_mode.py
Browse files- api_mode.py +85 -85
api_mode.py
CHANGED
|
@@ -1,86 +1,86 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
from flask import Flask, render_template, request, jsonify
|
| 4 |
-
from flask_cors import CORS
|
| 5 |
-
import requests
|
| 6 |
-
from dotenv import load_dotenv
|
| 7 |
-
|
| 8 |
-
# Загружаем переменные окружения
|
| 9 |
-
load_dotenv()
|
| 10 |
-
|
| 11 |
-
app = Flask(__name__)
|
| 12 |
-
CORS(app)
|
| 13 |
-
|
| 14 |
-
# Проверяем наличие API ключа
|
| 15 |
-
API_KEY = os.getenv("MISTRAL_API_KEY")
|
| 16 |
-
API_URL = os.getenv("MISTRAL_API_URL", "https://api.mistral.ai/v1/")
|
| 17 |
-
|
| 18 |
-
# Функция для генерации ответа через API
|
| 19 |
-
def generate_response_api(prompt, max_length=1024):
|
| 20 |
-
if not API_KEY:
|
| 21 |
-
return "Ошибка: API ключ не найден. Пожалуйста, добавьте MISTRAL_API_KEY в файл .env"
|
| 22 |
-
|
| 23 |
-
headers = {
|
| 24 |
-
"Authorization": f"Bearer {API_KEY}",
|
| 25 |
-
"Content-Type": "application/json"
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
data = {
|
| 29 |
-
"model": "mistral-medium", # или другая доступная модель
|
| 30 |
-
"messages": [
|
| 31 |
-
{"role": "user", "content": prompt}
|
| 32 |
-
],
|
| 33 |
-
"max_tokens": max_length,
|
| 34 |
-
"temperature": 0.7,
|
| 35 |
-
"top_p": 0.9
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
try:
|
| 39 |
-
response = requests.post(f"{API_URL}chat/completions", headers=headers, json=data)
|
| 40 |
-
response.raise_for_status()
|
| 41 |
-
result = response.json()
|
| 42 |
-
return result["choices"][0]["message"]["content"]
|
| 43 |
-
except Exception as e:
|
| 44 |
-
return f"Ошибка при обращении к API: {str(e)}"
|
| 45 |
-
|
| 46 |
-
# Маршруты
|
| 47 |
-
@app.route('/')
|
| 48 |
-
def index():
|
| 49 |
-
return render_template('index.html')
|
| 50 |
-
|
| 51 |
-
@app.route('/api/chat', methods=['POST'])
|
| 52 |
-
def chat():
|
| 53 |
-
data = request.json
|
| 54 |
-
prompt = data.get('prompt', '')
|
| 55 |
-
|
| 56 |
-
if not prompt:
|
| 57 |
-
return jsonify({"error": "Пустой запрос"}), 400
|
| 58 |
-
|
| 59 |
-
try:
|
| 60 |
-
response = generate_response_api(prompt)
|
| 61 |
-
return jsonify({"response": response})
|
| 62 |
-
except Exception as e:
|
| 63 |
-
return jsonify({"error": str(e)}), 500
|
| 64 |
-
|
| 65 |
-
@app.route('/api/code', methods=['POST'])
|
| 66 |
-
def code():
|
| 67 |
-
data = request.json
|
| 68 |
-
prompt = data.get('prompt', '')
|
| 69 |
-
language = data.get('language', 'python')
|
| 70 |
-
|
| 71 |
-
if not prompt:
|
| 72 |
-
return jsonify({"error": "Пустой запрос"}), 400
|
| 73 |
-
|
| 74 |
-
# Добавляем контекст для генерации кода
|
| 75 |
-
code_prompt = f"Напиши код на языке {language} для решения следующей задачи: {prompt}"
|
| 76 |
-
|
| 77 |
-
try:
|
| 78 |
-
response = generate_response_api(code_prompt)
|
| 79 |
-
return jsonify({"code": response})
|
| 80 |
-
except Exception as e:
|
| 81 |
-
return jsonify({"error": str(e)}), 500
|
| 82 |
-
|
| 83 |
-
if __name__ == '__main__':
|
| 84 |
-
print("🚀 Запуск
|
| 85 |
-
print("⚠️ Убедитесь, что вы добавили MISTRAL_API_KEY в файл .env")
|
| 86 |
app.run(debug=True, port=5000)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from flask import Flask, render_template, request, jsonify
|
| 4 |
+
from flask_cors import CORS
|
| 5 |
+
import requests
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
# Загружаем переменные окружения
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
app = Flask(__name__)
|
| 12 |
+
CORS(app)
|
| 13 |
+
|
| 14 |
+
# Проверяем наличие API ключа
|
| 15 |
+
API_KEY = os.getenv("MISTRAL_API_KEY")
|
| 16 |
+
API_URL = os.getenv("MISTRAL_API_URL", "https://api.mistral.ai/v1/")
|
| 17 |
+
|
| 18 |
+
# Функция для генерации ответа через API
|
| 19 |
+
def generate_response_api(prompt, max_length=1024):
|
| 20 |
+
if not API_KEY:
|
| 21 |
+
return "Ошибка: API ключ не найден. Пожалуйста, добавьте MISTRAL_API_KEY в файл .env"
|
| 22 |
+
|
| 23 |
+
headers = {
|
| 24 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 25 |
+
"Content-Type": "application/json"
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
data = {
|
| 29 |
+
"model": "mistral-medium", # или другая доступная модель
|
| 30 |
+
"messages": [
|
| 31 |
+
{"role": "user", "content": prompt}
|
| 32 |
+
],
|
| 33 |
+
"max_tokens": max_length,
|
| 34 |
+
"temperature": 0.7,
|
| 35 |
+
"top_p": 0.9
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
response = requests.post(f"{API_URL}chat/completions", headers=headers, json=data)
|
| 40 |
+
response.raise_for_status()
|
| 41 |
+
result = response.json()
|
| 42 |
+
return result["choices"][0]["message"]["content"]
|
| 43 |
+
except Exception as e:
|
| 44 |
+
return f"Ошибка при обращении к API: {str(e)}"
|
| 45 |
+
|
| 46 |
+
# Маршруты
|
| 47 |
+
@app.route('/')
|
| 48 |
+
def index():
|
| 49 |
+
return render_template('index.html')
|
| 50 |
+
|
| 51 |
+
@app.route('/api/chat', methods=['POST'])
|
| 52 |
+
def chat():
|
| 53 |
+
data = request.json
|
| 54 |
+
prompt = data.get('prompt', '')
|
| 55 |
+
|
| 56 |
+
if not prompt:
|
| 57 |
+
return jsonify({"error": "Пустой запрос"}), 400
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
response = generate_response_api(prompt)
|
| 61 |
+
return jsonify({"response": response})
|
| 62 |
+
except Exception as e:
|
| 63 |
+
return jsonify({"error": str(e)}), 500
|
| 64 |
+
|
| 65 |
+
@app.route('/api/code', methods=['POST'])
|
| 66 |
+
def code():
|
| 67 |
+
data = request.json
|
| 68 |
+
prompt = data.get('prompt', '')
|
| 69 |
+
language = data.get('language', 'python')
|
| 70 |
+
|
| 71 |
+
if not prompt:
|
| 72 |
+
return jsonify({"error": "Пустой запрос"}), 400
|
| 73 |
+
|
| 74 |
+
# Добавляем контекст для генерации кода
|
| 75 |
+
code_prompt = f"Напиши код на языке {language} для решения следующей задачи: {prompt}"
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
response = generate_response_api(code_prompt)
|
| 79 |
+
return jsonify({"code": response})
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return jsonify({"error": str(e)}), 500
|
| 82 |
+
|
| 83 |
+
if __name__ == '__main__':
|
| 84 |
+
print("🚀 Запуск AI Assistant в режиме API")
|
| 85 |
+
print("⚠️ Убедитесь, что вы добавили MISTRAL_API_KEY в файл .env")
|
| 86 |
app.run(debug=True, port=5000)
|