メインコンテンツへスキップ
見出し画像

ロリポップレンタルサーバでPythonを動かす:ChatGPTの実装

    ※ 2023/12/24時点の調査結果
    Webアプリを作りたいけどAWSは料金が高いので、ロリポップレンタルサーバにPython/Flaskで構築したときの記録です。
    ロリポップレンタルサーバの話やサーバの設定についてはこちらをご覧ください。

    https://note.com/cryptoscore/n/nc0f1f7a63de2


    ゴール=ChatGPTに質問する

    前回で、「HTMLのインプットボックスに入力した文字をPythonに渡して、一意のIDをHTMLに返す」という処理が入りました。
    この部分を応用して、「インプットボックスに入力した文字をPythonに渡して、そこでGPTに質問し、回答をHTMLに返す」というようにしたいと思います。

    前回の記事


    準備1:ロリポップレンタルサーバにopenaiをpip

    SSHでロリポップサーバに入り込み、openaiをpipしましょう。ついでにdotenvも。dotenvは、APIキーを環境変数に入れ込む便利関数です。

    pip3 install -U openai
    pip3 install -U python-dotenv

    ご参考:SSHでのサーバ入り方などが詳しく乗っている記事

    準備2:openaiのAPIキーを発行

    こちらはいろんなところで記事が出ていると思います。以下のOpenAI-APIのサイトにログインし、左側のサイドバーの「API keys」から発行できます。

    準備3:.envファイルの作成

    「.env」というテキストファイルを作り、その中に発行したAPIキーを入れます。****** のところに、発行したAPIキーを貼り付けます。

    OPENAI_API_KEY='************'

    保存したら、ロリポップサーバにアップロードしましょう。ファイル構成は以下のようになります。

    test-flask/
    ├templates/
    │ ┗index.html
    ├ .htaccess
    ├ app.py
    ├ index.cgi
    ├ .env

    Pythonのコーディング

    最初のほう(impot uuidの後)に、以下を入れます。

    from dotenv import load_dotenv
    load_dotenv() #OpenAIのAPIキーをセット
    
    from openai import OpenAI
    client = OpenAI()

    そして、recievingdata関数のところを以下のように書き換えます。「#--- chat gpt -----」というところと、★マークがついているところが変更箇所です。前回はテキストファイルにunique_idを書き込んでいましたが、ChatGPTの返答を出力するように変えています。また、HTMLに返答を渡しています。

    @app.route('/submit', methods=['POST'])
    def recievingdata():
        text = request.form['text']
        unique_id = str(uuid.uuid4())
        filename = f"{unique_id}.txt" 
    
        #--- chat gpt -------#
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": text},
            ]
        )
        res_txt = response.choices[0].message.content
        #--------------------#
    
        try:
            with open(filename, 'w') as file:
                file.write(res_txt) #★
            return jsonify(success=True, user_id=unique_id, response=res_txt) #★
        except Exception as e:
            return jsonify(success=False, error=str(e))
    


    ご参考:OpenAIが出している記事(文書生成)


    HTMLのコーディング

    1行(星のついている行)だけ修正します。responseも画面に表示するようにしています。

    if (json.success) {
        document.getElementById("result").innerHTML = "Success! Your ID: " + json.user_id + ". response= " + json.response; //★
        userId = json.user_id;
    else {
        document.getElementById("result").innerHTML = "Failed: " + json.error;
    }
    


    app.pyとtemplates/index.htmlをサーバにアップロードして、試してみてください。例えば「大谷翔平の誕生日は?」と入れて、「〇月×日です」と帰ってくれば成功です。

    プログラムの全文

    最後に、app.pyの全文を載せておきます。index.htmlは1行修正しているだけなので割愛。

    app.py

    import os
    from flask import Flask, render_template, request, jsonify
    import uuid
    from dotenv import load_dotenv
    load_dotenv()
    
    from openai import OpenAI
    client = OpenAI()
    
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/submit', methods=['POST'])
    def recievingdata():
        text = request.form['text']
        unique_id = str(uuid.uuid4())
        filename = f"{unique_id}.txt"
    
        #chat gpt
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": text},
            ]
        )
        res_txt = response.choices[0].message.content
    
        try:
            with open(filename, 'w') as file:
                file.write(res_txt)
            return jsonify(success=True, user_id=unique_id, response=res_txt)
        except Exception as e:
            return jsonify(success=False, error=str(e))
        
    
    
    @app.route('/recieve_id', methods=['POST'])
    def recieve_id():
        user_id = request.form['user_id']
        filename = f"{user_id}.txt"
        if os.path.exists(filename):
            with open(filename, 'r') as file:
                content = file.read()
            return jsonify(success=True, content=content)
        else:
            return jsonify(success=False, error="File not found.")
    
    if __name__ == '__main__':
        app.run(debug=True)
    




     
     
    データサイエンスが本業ですが、最近生成AI関連にはまり、生成AIを使ったWebアプリ構築に精力を注いでいます。Pythonは慣れていますがインフラまわりやフロント(Webページ)開発などは全く知識がないので、逆に新たに知ることが多く、その辺を記事にまとめていこうと思います。

    あなたへのおすすめ