Spaces:
Configuration error
Configuration error
from flask import Flask, request, jsonify, send_from_directory | |
from flask_cors import CORS | |
from mistralai import Mistral | |
import os | |
app = Flask(__name__, static_folder='.') | |
CORS(app, resources={ | |
r"/chat": { | |
"origins": ["https://your-netlify-url.netlify.app"], | |
"methods": ["POST", "OPTIONS"], | |
"allow_headers": ["Content-Type", "Authorization"] | |
} | |
}) | |
# Mistral API configuration | |
API_KEY = "SNCMZQyb5CvFLiQdLQAjki4NNrohYClY" | |
MODEL = "mistral-large-latest" | |
client = Mistral(api_key=API_KEY) | |
def serve_index(): | |
return send_from_directory('.', 'index.html') | |
def serve_static(path): | |
return send_from_directory('.', path) | |
def chat(): | |
try: | |
data = request.json | |
if not data: | |
return jsonify({"error": "No request data received"}), 400 | |
message = data.get('message', '') | |
history = data.get('history', []) | |
if not message: | |
return jsonify({"error": "No message provided"}), 400 | |
# Prepare messages with system prompt | |
messages = [{ | |
"role": "system", | |
"content": """You are a professional and friendly conversation partner. Follow these guidelines: | |
- Use a warm, professional tone while staying conversational | |
- Write naturally as if having a face-to-face conversation | |
- Use simple language and avoid technical jargon unless specifically asked | |
- Keep responses concise and informative | |
- No special formatting, markdown, asterisks, or special characters | |
- Use only basic punctuation and natural paragraph breaks | |
- Keep responses to 2-3 short paragraphs maximum""" | |
}] | |
# Add conversation history and current message | |
messages.extend(history) | |
messages.append({"role": "user", "content": message}) | |
print("Sending request to Mistral API...") | |
try: | |
chat_response = client.chat.complete( | |
model=MODEL, | |
messages=messages | |
) | |
bot_response = chat_response.choices[0].message.content | |
print(f"Bot response: {bot_response[:50]}...") | |
return jsonify({ | |
"response": bot_response | |
}) | |
except Exception as e: | |
error_message = f"Mistral API Error: {str(e)}" | |
print(error_message) | |
return jsonify({"error": error_message}), 500 | |
except Exception as e: | |
error_message = f"Server error: {str(e)}" | |
print(error_message) | |
return jsonify({"error": error_message}), 500 | |
if __name__ == "__main__": | |
app.run(host='0.0.0.0', port=5001, debug=False) |