from flask import Flask, render_template, request, jsonify
import openai
import os

app = Flask(__name__)
conversation = []

# Set up OpenAI API credentials and model name
openai.api_key = "YOUR-API-KEY"
model_name = "gpt-3.5-turbo"
context = None

    
@app.route('/')
def index():
    return render_template('index.html')


@app.route('/get-response', methods=['POST'])
def get_response():
    global context
    global conversation
    user_message = request.form['message']
    conversation.append(('User', user_message))

    messages = []
    for conv in conversation:
        messages.append({"role": conv[0].lower(), "content": conv[1]})

    response = openai.ChatCompletion.create(
        model=model_name,
        messages=[
            {"role": "system","content":"あなたは私のアシスタントAIです"},
            {"role": "user", "content": user_message},
            {"role": "assistant", "content": ""}
        ]
    )

    message = response.choices[0]['message']['content']
    message = message.strip()

    conversation.append(("Assistant", message))
    context = "\n".join([f"{conv[0]}: {conv[1]}" for conv in conversation[-7:]])
    print(message)
    return jsonify({'message': message})


@app.route('/conversation')
def get_conversation():
    return jsonify(conversation)


if __name__ == '__main__':
    app.run(debug=True)