2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChatGPTのAPIが出たので作ってみた

Last updated at Posted at 2023-03-02

概要

忙しいので明日の夜に説明を書きます。

ソースコード

FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "aiapp.py"]

requirements.txt
aiohttp==3.8.4
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
certifi==2022.12.7
charset-normalizer==3.0.1
click==8.1.3
Flask==2.1.2
frozenlist==1.3.3
idna==3.4
importlib-metadata==6.0.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.2
multidict==6.0.4
openai==0.27.0
requests==2.28.2
tqdm==4.64.1
urllib3==1.26.14
Werkzeug==2.2.3
yarl==1.8.2
zipp==3.15.0

templates/index.html
<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <style>
        #result div {
            text-align: left !important;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <h1 class="text-center mb-4">{{ message }}</h1>
                <form id="create-text-form" action="{{ url_for('create_text') }}" method="POST">
                    <div class="form-group">
                        <label for="api_key">API Key:</label>
                        <input type="text" class="form-control" id="api_key" name="api_key" required>
                    </div>
                    <div class="form-group">
                        <label for="message">Message:</label>
                        <textarea class="form-control" id="message" name="message" rows="3" required></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
                <div id="loading" class="text-center mt-3" style="display:none;">Loading...</div>
                <pre id="result" class="text-left mt-3"></pre>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $('#create-text-form').submit(function(event) {
                event.preventDefault();
                $('#loading').show();
                $('#result').empty();
                $.post('/create_text', $(this).serialize(), function(data) {
                $('#loading').hide();
                var message = data.message.replace(/\n/g, '<br>');
                $('#result').html('AI message: ' + message);
                });
            });
        });

    </script>
</body>
</html>


aiapp.py
from flask import Flask, render_template, jsonify, request, escape, Markup
import time
import openai
import json


app = Flask(__name__)

def text_generate(api_key=None, message=None):
    openai.api_key = api_key
    res = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
                {"role": "user", "content": message},
            ]
    )
    generated_text = res["choices"][0]["message"]["content"]
    return generated_text

@app.route('/', methods=['GET'])
def toppage():
    message = "Hello, Flask!"
    return render_template('index.html', message=message)

@app.route('/create_text', methods=['POST'])
def create_text():
    api_key = request.form['api_key']
    message = request.form['message']
    # Run AI model to generate message
    generated_text = text_generate(api_key=api_key, message=message)
    generated_text = escape(generated_text)
    return jsonify({'message': generated_text})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5001)


起動コマンド

docker build -t flask-app .
docker run -p 5001:5001 flask-app
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?