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)

Cisco Packet Tracerで演習を行う_1

Cisco Packet Tracerにsign upして、以下のページからinstallします。
https://www.netacad.com/resources/lab-downloads?courseLang=ja-JP
Packet Tracer 8.2.2 MacOS 64bit

### PC2台をクロスケーブルで接続してPing確認
① PCを2台配置する
下部の【End Devices】→【PC】をクリック
作業エリアに2台ドラッグ&ドロップ

② ケーブルで接続する
下部の【Connections】を選択
黄色の【クロスケーブル(Copper Cross-Over)】を選ぶ
PC0 → FastEthernet0 をクリック
PC1 → FastEthernet0 をクリック

③ IPアドレスを設定する
PC0 をクリック →【Desktop】タブ →【IP Configuration】
IP address: 192.168.1.1
Subnet mask: 自動で 255.255.255.0 に設定される
PC1 も同様に設定
IP address: 192.168.1.2
Subnet mask: 同じく 255.255.255.0

④ Pingを実行して確認
PC0 をクリック →【Desktop】タブ →【Command Prompt】
ping 192.168.1.2 と入力して送信

Cisco Packet Tracer PC Command Line 1.0
C:\>ping 192.168.1.2

Pinging 192.168.1.2 with 32 bytes of data:

Reply from 192.168.1.2: bytes=32 time=1ms TTL=128
Reply from 192.168.1.2: bytes=32 time=1ms TTL=128
Reply from 192.168.1.2: bytes=32 time<1ms TTL=128 Reply from 192.168.1.2: bytes=32 time<1ms TTL=128 Ping statistics for 192.168.1.2: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 1ms, Average = 0ms おおおおおお、本の勉強とは違って、なかなか面白い ### スイッチ2960を入れる場合 ステップ1:デバイスの配置 Packet Tracer の下部「End Devices」→「PC-PT」を選んで作業エリアに2台配置(PC0、PC1) 「Switching」→「2960」を選んで中央に1台配置(SW1) 🔹 ステップ2:ケーブル接続 左下の「Connections(雷アイコン)」をクリック [ストレートケーブル](Copper Straight-Through) を選択 以下のように接続: PC0 の FastEthernet0 → SW1 の FastEthernet0/1 PC1 の FastEthernet0 → SW1 の FastEthernet0/2 ✅ ヒント: ポート番号(0/1、0/2)で使っているポートを確認できます。ケーブルをつなぐとLEDが緑に変わればリンクアップ成功。 🔹 ステップ3:IPアドレスの設定 PC0 をクリック → 【Desktop】タブ → 【IP Configuration】 IP Address: 192.168.1.1 Subnet Mask: 255.255.255.0(自動で入力されます) PC1 も同様に設定 IP Address: 192.168.1.2 Subnet Mask: 255.255.255.0 💡 デフォルトゲートウェイは未設定でOK(同一セグメント内なので) 🔹 ステップ4:Pingで通信確認 PC0 をクリック → 【Desktop】 → 【Command Prompt】 以下のコマンドを入力:ping 192.168.1.2 C:\>ping 192.168.1.2

Pinging 192.168.1.2 with 32 bytes of data:

Reply from 192.168.1.2: bytes=32 time=1ms TTL=128
Reply from 192.168.1.2: bytes=32 time<1ms TTL=128 Reply from 192.168.1.2: bytes=32 time<1ms TTL=128 Reply from 192.168.1.2: bytes=32 time<1ms TTL=128 Ping statistics for 192.168.1.2: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 1ms, Average = 0ms