chatバックエンド側(Python (Flask + PostgreSQL + OpenAI))の作り込み1

chat() の中で  
認証チェックを追加  
DBにユーザーの入力を保存  
OpenAI API や HuggingFace API を呼んで応答を生成  
生成した応答をDBに保存して返却

### step.0 テーブル作成

CREATE TABLE chat_messages (
    id SERIAL PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL,
    message TEXT NOT NULL,
    reply TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

### step.1 パッケージインストール
$ install flask psycopg2-binary openai

### step.2 Python (Flask + PostgreSQL + OpenAI)

from flask import Flask, request, Response
import json
import psycopg2
import os
from openai import OpenAI

app = Flask(__name__)

DB_CONFIG = {
    "dbname": os.getenv("DB_NAME"),
    "user": os.getenv("DB_USER"),
    "password": os.getenv("DB_PASSWORD"),
    "host": os.getenv("DB_HOST", "localhost"),
    "port": os.getenv("DB_PORT", 5432)
}


def get_db_connection():
    try:
        conn = psycopg2.connect(**DB_CONFIG)
        return conn
    except Exception as e:
        print(f"Database connection error: {e}")
        return None

@app.route("/chat", methods=["POST"])
def chat():
    try:
        data = request.get_json()

        user_id = data.get("user_id")
        message = data.get("message")

        if not user_id or not message:
            return Response(json.dumps({"error": "user_id and message are required"}), status=400, content_type="application/json; charset=utf-8")

        conn = get_db_connection()
        cur = conn.cursor()

        cur.execute(
            "INSERT INTO chat_messages (user_id, message) VALUES (%s, %s) RETURNING id;",
            (user_id, message)
        )
        chat_id = cur.fetchone()[0]

        client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
        completion = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages = [
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": message}
            ]
        )
        api_reply = completion.choices[0].message.content

        cur.execute(
            "UPDATE chat_messages SET reply = %s WHERE id = %s;",
            (api_reply, chat_id)
        )
        conn.commit()
        cur.close()
        conn.close()
        

        response_json = json.dumps({"reply": api_reply}, ensure_ascii=False)
        return Response(response_json, content_type="application/json; charset=utf-8")

    except Exception as e:
        error_json = json.dumps({"error": str(e)}, ensure_ascii=False)
        return Response(error_json, status=400, content_type="application/json; charset=utf-8")


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

$ curl -X POST http://127.0.0.1:5000/chat -H “Content-Type: application/json” -d ‘{“user_id”: “12345”, “message”: “おはよう!”}’
{“reply”: “おはようございます!元気ですか?何かお手伝いできることがありますか?”}

おおお

flaskでバックエンドを構築する

フロントエンドからデータを受け取るところを記述する
jsonをpostすると、jsonのレスポンスが返ってくる

from flask import Flask, request, Response
import json

app = Flask(__name__)

@app.route("/chat", methods=["POST"])
def chat():
    try:
        data = request.get_json()

        user_id = data.get("user_id")
        message = data.get("message")

        # ここで認証チェック、DBアクセス、AIモデルの呼び出しなどを行う
        # ここではダミーの応答を返す

        ai_reply = f"ユーザ({user_id})のメッセージを受け取りました: {message}"

        response_json = json.dumps({"reply": ai_reply}, ensure_ascii=False)
        return Response(response_json, content_type="application/json; charset=utf-8")

    except Exception as e:
        error_json = json.dumps({"error": str(e)}, ensure_ascii=False)
        return Response(error_json, status=400, content_type="application/json; charset=utf-8")


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

$ curl -X POST http://127.0.0.1:5000/chat -H “Content-Type: application/json” -d ‘{“user_id”: “12345”, “message”: “おはよう!”}’
{“reply”: “ユーザ(12345)のメッセージを受け取りました: おはよう!”}

この chat() の中で 以下も書いていく。
– 認証チェックを追加  
– DBにユーザーの入力を保存  
– OpenAI API や HuggingFace API を呼んで応答を生成  
– 生成した応答をDBに保存して返却

ChatGPT-4oとGPT5の違い

ChatGTP-4oがマルチモーダルAI実用化であったのに対し、ChatGPT5はは「思考するAI」「動けるAI」へ進化

#### ChatGPT-4o
– モデル構造 : テキスト・音声・画像を統合した「マルチモーダルモデル」
– モデルの選択 : 手動選択(GPT-4o, o3など)
– 応答速度(音声) : 平均320ms, 自然な会話速度
– 記憶機能(メモリ) : 一部記憶あり
– 外部連携機能 : なし

#### ChatGPT-5
– モデル構造 : 複数の思考エンジンを自動で切り替える「統合システム+動的推論」
– モデルの選択 : 自動判定(Base/Thinking/Proにルーティング)
– 応答速度(音声) : 音声は4oベース、今後統合予定
– 記憶機能(メモリ) : 永続メモリ。過去の会話やユーザの好みを保持
– 外部連携機能 : Gmail、カレンダー、Drive等と直接連携可能

プロンプトの内容や難易度を自動解析し、最適な推論モデル(高速応答/深層思考)を選択
AIの性格を選べる

ソフトウェア開発、数学、多言語コード編集、マルチモーダル理解などあらゆる指標で賢くなった
プランはFree, Plus, Pro, Enterpriseなどあり

思考の質が自動最適化され、過去を覚える

Pythonで入力中の続きのコード生成AIをAPIで試す

フィボナッチ関数について、途中まで書いていて、その続きのコードをレスポンスとして返します。
ソースコードをapiに私、”complete this code”と指示を出しています。

from openai import OpenAI

client = OpenAI(api_key="sk-hoge****")

partial_code = """
def fibonacci(n):
    \"\"\"n番目までのフィボナッチ数列を返す関数.\"\"\"
    sequence = [0, 1]
"""

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are an expert Python programmer. Complete the given code without explanations, only code."},
        {"role": "user", "content": f"Complete this Python code:\n\n{partial_code}"}
    ],
    temperature=0.2,
)

print(response.choices[0].message.content)

$ python3 codegen_input.py
“`python
if n <= 0: return [] elif n == 1: return [0] elif n == 2: return sequence for i in range(2, n): next_value = sequence[-1] + sequence[-2] sequence.append(next_value) return sequence ``` Github Copilotではコメントからコード生成はグレーアウトされたコードで即時表示している。 これは特定の実行ボタンなどを押下しなくても表示しているので、Ajaxなど非同期で実行していると思われる。 入力中の続きのコード生成も同様 コメントを書き終えた時や、コードを打ち終えた時などにトリガーが発動される。

Pythonでコード型の生成AIをAPIで試す

from openai import OpenAI

client = OpenAI(api_key="sk-hoge****")

prompt = """
# Pythonで、与えられた文字列を逆順にして返す関数を作ってください
"""

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that writes clean Python code.."},
        {"role": "user", "content": prompt}
    ],
    temperature=0.2,
)

print(response.choices[0].message.content)

$ python3 codegen.py
もちろんです!以下は、与えられた文字列を逆順にして返すPythonの関数です。

“`python
def reverse_string(s):
return s[::-1]

# 使用例
input_string = “こんにちは”
reversed_string = reverse_string(input_string)
print(reversed_string) # 出力: はこんに
“`

この関数 `reverse_string` は、スライスを使って文字列を逆順にしています。`s[::-1]` は、文字列 `s` の全ての文字を逆順に取得します。

model, message, tempratureを指定してリクエストしていることがわかります。
なるほど

【Cisco Packet Tracer】ルーターを使ったVLAN間ルーティング

ルーターを使ったVLAN間ルーティング(Router-on-a-Stick構成)は、VLANで分離されたネットワーク同士を通信可能にする方法

switchの設定

Switch> enable
Switch# configure terminal

! VLANの作成
Switch(config)# vlan 10
Switch(config-vlan)# name VLAN10
Switch(config-vlan)# exit

Switch(config)# vlan 20
Switch(config-vlan)# name VLAN20
Switch(config-vlan)# exit

! ポートにVLANを割り当て
Switch(config)# interface range fa0/1 - 2
Switch(config-if-range)# switchport mode access
Switch(config-if-range)# switchport access vlan 10
Switch(config-if-range)# exit

Switch(config)# interface range fa0/3 - 4
Switch(config-if-range)# switchport mode access
Switch(config-if-range)# switchport access vlan 20
Switch(config-if-range)# exit

! ルーターに接続するポートをトランクに設定
Switch(config)# interface fa0/5
Switch(config-if)# switchport mode trunk
Switch(config-if)# exit

ルータの設定

Router> enable
Router# configure terminal

! サブインターフェース作成 VLAN10
Router(config)# interface g0/0.10
Router(config-subif)# encapsulation dot1Q 10
Router(config-subif)# ip address 192.168.10.1 255.255.255.0
Router(config-subif)# exit

! サブインターフェース作成 VLAN20
Router(config)# interface g0/0.20
Router(config-subif)# encapsulation dot1Q 20
Router(config-subif)# ip address 192.168.20.1 255.255.255.0
Router(config-subif)# exit

! 物理インターフェースを有効化
Router(config)# interface g0/0
Router(config-if)# no shutdown
Router(config-if)# exit

pc0からVLANで分離されたpc2に接続できるようになる。
必要な通信は許可するというような時に活用する。

つまり、switch単体ではVLANを分離できるが、そのVLANを接続させるなどの制御にはルーターが必要

【Cisco Packet Tracer】VLANの設定

VLAN(Virtual LAN、仮想LAN)とは、物理的には同じネットワークに接続されている機器同士を、論理的に分割して異なるネットワークのように扱う技術です。

通常、同じスイッチ(L2スイッチ)に接続されたPCやサーバーは、すべて同じネットワーク(ブロードキャストドメイン)に属します。しかし、VLANを使うことで、同じスイッチ内でも異なるVLANに分けることができ、それぞれのVLANは独立したネットワークとして動作します。

Switch> enable
Switch# configure terminal

! VLANを作成
Switch(config)# vlan 10
Switch(config-vlan)# name VLAN10
Switch(config-vlan)# exit

Switch(config)# vlan 20
Switch(config-vlan)# name VLAN20
Switch(config-vlan)# exit

! ポートをVLANに割り当て
Switch(config)# interface range fa0/1 - 2
Switch(config-if-range)# switchport mode access
Switch(config-if-range)# switchport access vlan 10
Switch(config-if-range)# exit

Switch(config)# interface range fa0/3 - 4
Switch(config-if-range)# switchport mode access
Switch(config-if-range)# switchport access vlan 20
Switch(config-if-range)# exit

Switch(config)# exit
Switch#

comand promptからpingでpc2, pc3に疎通確認

なるほど、スイッチでネットワークを分離するのね。

【Azure】BlobStorageへPythonでアップロードする

$ install azure-storage-blob

Azureのストレージアカウントのセキュリティ&ネットワークのアクセスキーから接続文字列を取得する(キーの方ではない)

from azure.storage.blob import BlobServiceClient, ContentSettings

connection_string = "***"

blob_service_client = BlobServiceClient.from_connection_string(connection_string)

container_name = "images"
blob_name = "cat.jpg"
local_file_path = "cat.jpg"

container_cliient = blob_service_client.get_container_client(container_name)

with open(local_file_path, "rb") as data:
    container_cliient.upload_blob(
        name=blob_name,
        data=data,
        overwrite=True,
        content_settings=ContentSettings(content_type="image/jpeg")
    )

print(f"Blob '{blob_name}' uploaded to container '{container_name}' successfully.")

おおお、アップロードできるようになると、一段別のステージに行った感がありますね。
次はAzureSQLにも触っておきたい。

【Azure】BlobStorageからPythonでデータを取得する

前提条件:
Azureでストレージアカウントを作成し、その中にコンテナを作成、アクセスレベルをBlobの匿名アクセスを許可する。
そして、任意の画像をコンテナ内にアップロード。Pythonで読み込む際は、requestsを使用するだけ。

import requests

url = 'https://hoge.blob.core.windows.net/images/cat-9637984_640.jpg'
response = requests.get(url)

with open('downloaded_image.jpg', 'wb') as file:
    file.write(response.content)

print("Image downloaded successfully and saved as 'downloaded_image.jpg'.")

ストレージアカウントって概念に馴染みがないけど、操作自体は然程S3と変わらない。

transformer

import numpy as np 

# 3単語 4次元ベクトル
X = np.array([
    [1, 0, 1, 0],
    [0, 2, 0, 2],
    [1, 1, 1, 1]
])

W_q = np.random.rand(4, 2)
W_k = np.random.rand(4, 2)
W_v = np.random.rand(4, 2)

Q = X @ W_q
K = X @ W_k
V = X @ W_v

attention_scores = Q @ K.T

dk = Q.shape[-1]
attention_scores = attention_scores / np.sqrt(dk)

def softmax(x):
    e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
    return e_x / e_x.sum(axis=-1, keepdims=True)

attention_weights = softmax(attention_scores)

output = attention_weights @ V

print("Input X:\n", X)
print("\nAttention Weights:\n", attention_weights)
print("\nOutput:\n", output)