ラベル Python の投稿を表示しています。 すべての投稿を表示
ラベル Python の投稿を表示しています。 すべての投稿を表示

2026年1月14日水曜日

AI エージェントを作ってみた感想

AI エージェントを作ってみた感想

これまでにBotはいくつか作っていました

https://blog.kakakikikeke.com/2025/10/no-life-no-bot.html

それもエージェントと言えばエージェントなのかもしれませんがもう少しエンジニアっぽい AI エージェントを作ってみたので感想やらつらつら残しておきます

作ったもの

  • 不正プロセス監視エージェント
  • 不正ログ監視エージェント
  • 株価予測エージェント

不正プロセス監視エージェントのソースコード

#!/usr/bin/env python3
import json
import os
import subprocess
import time
from collections import deque

from google import genai
from slack_sdk import WebClient

GEMINI_API_KEY = "xxx"
SLACK_TOKEN = "xoxb-xxx"
SLACK_CHANNEL = "#general"
CUSTOM_BASE_URL = "https://your-llm-domain/endpoint"

# バッチ処理の設定
BATCH_MODE = (
    os.getenv("BATCH_MODE", "true").lower() == "true"
)  # デフォルトはバッチモード
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "5"))  # 一度に判定するプロセス数
BATCH_TIMEOUT = int(os.getenv("BATCH_TIMEOUT", "10"))  # タイムアウト時間(秒)
MONITOR_INTERVAL = int(os.getenv("MONITOR_INTERVAL", "30"))  # プロセス取得間隔(秒)

print(f"Mode: {'BATCH' if BATCH_MODE else 'SINGLE'}")
print(
    f"BATCH_SIZE: {BATCH_SIZE}, BATCH_TIMEOUT: {BATCH_TIMEOUT}s, MONITOR_INTERVAL: {MONITOR_INTERVAL}s"
)

client = genai.Client(
    api_key=GEMINI_API_KEY,
    http_options=genai.types.HttpOptions(base_url=CUSTOM_BASE_URL),
)

slack = WebClient(token=SLACK_TOKEN)

# 既に通知済みのプロセスを追跡(重複通知を避けるため)
notified_processes = set()


# --- プロセス情報取得 ---
def get_processes():
    """
    ps コマンドでシステム上の全プロセスを取得する。
    戻り値: [{"pid": "...", "user": "...", "cpu": "...", "mem": "...", "cmd": "..."}, ...]
    """
    try:
        # aux フラグで詳細情報を取得
        cmd = ["ps", "aux"]
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            check=True,
        )

        processes = []
        lines = result.stdout.strip().split("\n")

        # ヘッダースキップ
        for line in lines[1:]:
            parts = line.split()
            if len(parts) >= 11:
                processes.append(
                    {
                        "user": parts[0],
                        "pid": parts[1],
                        "cpu": parts[2],
                        "mem": parts[3],
                        "vsz": parts[4],
                        "rss": parts[5],
                        "cmd": " ".join(parts[10:]),
                    }
                )

        return processes

    except Exception as e:
        print(f"Error getting processes: {e}")
        return []


# --- LLM にプロセスの異常判定を依頼 ---
def analyze_process_single(process_info: dict) -> bool:
    """
    単一のプロセスを LLM で判定する。
    怪しいなら True を返す。
    """
    prompt = f"""
あなたは Linux サーバーのセキュリティ監視 AI です。
以下のプロセス情報が不審かどうか、以下の形式で答えてください。

プロセス情報:
- PID: {process_info['pid']}
- ユーザー: {process_info['user']}
- CPU使用率: {process_info['cpu']}%
- メモリ使用率: {process_info['mem']}%
- VSZ: {process_info['vsz']}
- RSS: {process_info['rss']}
- コマンド: {process_info['cmd']}

判断:
- 不審なら "SUSPICIOUS"
- そうでなければ "OK"

通常のシステムプロセス(kernel threads、systemd関連など)は OK と判定してください。
考察や理由は出力しないでください。
"""

    response = client.models.generate_content(
        model="gemini-2.5-pro",
        contents=prompt,
    )

    if response.text is None:
        print("No response text from LLM")
        return False

    result_text = response.text.strip().upper()
    return "SUSPICIOUS" in result_text


def analyze_processes_batch(processes: list) -> dict:
    """
    複数のプロセスを一度に LLM で判定する。
    戻り値: {pid: bool} の辞書
    """
    if not processes:
        return {}

    # プロセス情報をまとめてプロンプト作成
    processes_text = "\n".join(
        [
            f"{i+1}. PID: {p['pid']}, User: {p['user']}, CPU: {p['cpu']}%, Mem: {p['mem']}%, Cmd: {p['cmd']}"
            for i, p in enumerate(processes)
        ]
    )

    prompt = f"""
あなたは Linux サーバーのセキュリティ監視 AI です。
以下のプロセス情報が不審かどうか、それぞれを判定してください。

プロセス一覧:
{processes_text}

判定結果を以下の JSON フォーマットで出力してください:
{{
  "1": "OK",
  "2": "SUSPICIOUS",
  "3": "OK",
  ...
}}

JSONのキーはプロセス番号、値は "SUSPICIOUS" または "OK" です。
通常のシステムプロセス(kernel threads、systemd関連など)は OK と判定してください。
"""

    response = client.models.generate_content(
        model="gemini-2.5-pro",
        contents=prompt,
    )

    if response.text is None:
        print("No response text from LLM")
        return {p["pid"]: False for p in processes}

    # JSON を抽出して解析
    result_dict = {}
    try:
        # レスポンスから JSON を抽出
        json_str = response.text
        # JSONブロックの開始と終了を探す
        start_idx = json_str.find("{")
        end_idx = json_str.rfind("}") + 1
        if start_idx >= 0 and end_idx > start_idx:
            json_str = json_str[start_idx:end_idx]
            parsed = json.loads(json_str)

            # プロセスごとに判定結果をマッピング
            for idx, process in enumerate(processes, 1):
                result = parsed.get(str(idx), "OK").upper()
                result_dict[process["pid"]] = "SUSPICIOUS" in result
        else:
            # JSON が見つからない場合は全て False
            result_dict = {p["pid"]: False for p in processes}
    except json.JSONDecodeError as e:
        print(f"JSON parse error: {e}")
        result_dict = {p["pid"]: False for p in processes}

    return result_dict


# --- Slack 通知 ---
def notify(process_info: dict):
    message = f"""
:rotating_light: *Suspicious process detected!*
PID: {process_info['pid']}
User: {process_info['user']}
CPU: {process_info['cpu']}% | Mem: {process_info['mem']}%
Command: {process_info['cmd']}
"""
    slack.chat_postMessage(channel=SLACK_CHANNEL, text=message)


# --- フィルタリング関数 ---
def should_check_process(process_info: dict) -> bool:
    """
    監視対象外のプロセスをフィルタリング
    """
    cmd = process_info["cmd"]
    user = process_info["user"]

    # self プロセスは除外
    if "process_monitor_agent" in cmd:
        return False

    # root 関連の明らかに安全なプロセスは除外
    safe_keywords = [
        "kernel",
        "[",
        "]",
        "systemd",
        "sshd",
        "agetty",
        "bash",
        "sh",
        "grep",
        "ps",
        "vim",
        "nano",
        "sudo",
        "root",
        "ls -l",
        "sd-pam",
        "unbound",
        "cron",
        "sleep",
        "less",
        "/sbin/init",
        "canonical-livepatch",
        "snapd",
        "ubuntu-advantage/timer.py",
        "multipathd",
        "journalctl",
        "bpftrace",
        # 開発ツール関連
        "tmux",
        "mysqld",
        "redis-server",
        "code-server",
        "mosquitto",
        "ollama",
        "nginx",
        # postfix 関連
        "pickup -l -t unix -u -c",
        "tlsmgr -l -t unix -u -c",
        "qmgr -l -t unix -u",
        "/usr/lib/postfix/sbin/master",
        # docker 関連
        "dockerd",
        "docker-proxy",
        # apt 関連
        "apt-get",
        "packagekitd",
        "/usr/lib/update-notifier/apt-check",
        "tar -df alternatives.tar.0 -C /var/lib/dpkg alternatives",
        # EDR 関連
        "cbram",
        "cybereason-sensor",
        "cybereason-activeconsole",
    ]
    if any(keyword in cmd for keyword in safe_keywords):
        return False

    return True


# --- プロセス監視メイン処理 ---
def monitor_processes():
    """
    定期的にプロセスを取得して監視
    """
    print("Process monitor started.")

    if BATCH_MODE:
        # バッチモード
        monitor_processes_batch()
    else:
        # 単発モード
        monitor_processes_single()


def monitor_processes_single():
    """単発モード: 各プロセスを即座に判定"""
    while True:
        try:
            processes = get_processes()

            # フィルタリング
            filtered_processes = [p for p in processes if should_check_process(p)]

            for process in filtered_processes:
                try:
                    suspicious = analyze_process_single(process)
                    if suspicious:
                        pid = process["pid"]
                        if pid not in notified_processes:
                            print(f"[!] Suspicious process: {process}")
                            notify(process)
                            notified_processes.add(pid)
                    else:
                        print(f"[OK] {process['cmd']}")

                except Exception as e:
                    print(f"Error analyzing process: {e}")

            time.sleep(MONITOR_INTERVAL)

        except Exception as e:
            print(f"Error in monitor loop: {e}")
            time.sleep(MONITOR_INTERVAL)


def monitor_processes_batch():
    """バッチモード: プロセスをバッチでまとめて判定"""
    process_buffer = deque()
    last_batch_time = time.time()

    while True:
        try:
            current_time = time.time()
            processes = get_processes()

            # フィルタリング
            filtered_processes = [p for p in processes if should_check_process(p)]

            # バッファに追加
            for process in filtered_processes:
                process_buffer.append(process)

            # バッチ処理の条件: BATCH_SIZE に達したか、BATCH_TIMEOUT を超えたか
            should_process = len(process_buffer) >= BATCH_SIZE or (
                len(process_buffer) > 0
                and current_time - last_batch_time >= BATCH_TIMEOUT
            )

            if should_process or current_time - last_batch_time >= MONITOR_INTERVAL:
                try:
                    # バッファ内のプロセスを一度に処理
                    processes_to_process = list(process_buffer)
                    process_buffer.clear()
                    last_batch_time = current_time

                    if processes_to_process:
                        results = analyze_processes_batch(processes_to_process)

                        for process in processes_to_process:
                            pid = process["pid"]
                            is_suspicious = results.get(pid, False)

                            if is_suspicious:
                                if pid not in notified_processes:
                                    print(f"[!] Suspicious process: {process}")
                                    notify(process)
                                    notified_processes.add(pid)
                            else:
                                print(f"[OK] {process['cmd']}")

                except Exception as e:
                    print(f"Error analyzing processes: {e}")

            time.sleep(1)  # CPU負荷を減らすため1秒待機

        except Exception as e:
            print(f"Fatal error: {e}")
            time.sleep(MONITOR_INTERVAL)


if __name__ == "__main__":
    while True:
        try:
            monitor_processes()
        except Exception as e:
            print(f"Fatal error: {e}, restarting in 5 seconds...")
            time.sleep(5)

これを systemd 配下で動作させています

簡単に流れの紹介

  1. ps aux の結果を取得
  2. LLM (gemini) に投げて各プロセスが怪しいか判定してもらう
  3. 怪しい場合は Slack に通知

他のログ監視も同じような仕組みです
株価予測エージェントは上記の流れとだいぶ違うのは違うのですが LLM に過去の株価情報を渡して予測してもらうだけです

感想

以下不正プロセス監視エージェントを使ってみた感想や所感です

お金がかかるので呼び出し方を工夫しなければならない

  • LLM にわたす情報を複数行にまとめて API をコールする
  • 1行ずつだと時間もかかるしお金もかかる
  • ローカル LLM が一つの解決策だがそれなりのマシンスペックは必要

判断するまでの速度

  • API (ネットワーク) + LLM の推論の時間が必ずかかるので判断までに数秒かかる
  • 完全なリアルタイムを実現するのは難しい
  • 一瞬で消えてしまうプロセスをキャッチできないケースがある
  • 速度もローカル LLM で解決できそうだが結局高スペックマシンでもそれなりの推論時間がかかるので数ミリ秒レベルのレスポンス速度は期待できない

精度が曖昧

  • 本当にアウトな場合のテストができない
  • アウトじゃないけどアウトと判定してしまう
  • アウトじゃないプロセスは無視するような仕組みが必要になる (コード内参照)
  • それ(特定のプロセス無視/ホワイトリスト形式)でいいのかという問題もある (同一プロセス名だと攻撃されても検知できなくなる)
  • 前はセーフだったけど次はアウトにしちゃう
  • 「怪しい」という LLM への命令が曖昧すぎるが故の過剰検知とハレーション

そもそもAI エージェントの具体的なユースケースは

  • 人間には難しい「判断」や「解釈」が必要なタスク+状況に応じて行動を変える仕事
  • ログから「人間レベルの洞察」を出す
  • 毎日の情報を「読む → 取捨選択 → 解釈 → 提案」する
  • インシデント予兆検知
  • コードのレポート・改善案
  • などなど、とにかく得意なのは「判断」と「解釈」あと「生成」

(現状は)何かに特化した AI エージェントしか作れない

  • 本当にやりたいことは「何でも」やってくれる汎用 AI エージェント
  • でも現状はやりたいことだけをやってくれる特化 AI エージェントしか作れない
  • もっというと「やりたいこと」すら AI エージェントが見つけて勝手にやってほしい
  • 特化エージェントを組み合わせて汎用っぽく見せかける

AI を使わなくてもいい問題

  • 今回作成した AI エージェントのようなログ監視やプロセス監視の製品はある
  • 判断が静的 (特定の文字列を含む場合にアラート/CPUが90%以上になったらなど) だがそれで十分なケースが多い

そもそも「AI エージェント」の定義は

  • 広義には「人の代わりに作業をやってくれるツール」だと思っている
  • 自分は今回のようなプロセス版のエージェントも VSCode の Copilot Chat のようなエディタもエージェントだと思っている
  • エージェントにもいろいろなタイプがあるので言葉に惑わされてはいけない

既製品を使ってもいい

ブースティング

  • 複数の LLM に判断させてその結果で最終的な判断をする
  • エヴァンゲリオンのマギシステム的なイメージ
  • ただしお金が倍々に増えていくので注意

最後に

AI もあるので AI エージェント自体を作ることは非常に簡単ですが本当に有用なものを作るのは難しいと言うか無くても何とかなるというのが正直なところです

株価予測エージェントは評価機能もあるので評価の結果が良ければ実践投入してどうなるか試してみようかなと思います
売買も自動でできると更に良いかなと思っています

2025年10月1日水曜日

ボットは絵も動画もブログも作成できるようになった

ボットは絵も動画もブログも作成できるようになった

人生とはボットを育てることなのかもしれない

これまで

https://blog.kakakikikeke.com/2025/04/kakakikikeke-die-twice.html

自分のツイートを学習させて自分っぽいツイートができるようになりました

アカウント

https://x.com/kakakikikekebot

現在のボットにできること

2025/09/26 現在ボットは成長し以下ができるようになりました

  • ツイートをする
  • ブログを書く
  • 絵を書く
  • ショート動画を作る

以下それぞれの仕組みを詳細に説明します

共通点

  • 動作マシンはローカルの M2 Pro mac mini
  • バックエンドでは「CPU50%のマイニング」「Ollamaサーバの起動」「SD-webui」が稼働している
  • 生成時は MPS にすべて対応しているものを採用
  • Python で実装
  • 生成時間は動画以外数分で完了 (絵、文章系)

ツイートをする

Twitter API + Ollama API (gemma3)

  • 自分のツイートを500件準備、そこから20件をプロンプトのコンテキストとして与える
  • ツイートを生成してもらうようなプロンプトを入力
  • レスポンスをパース、サニタイズなど調整してからツイート
  • ハッシュタグやリンクなどは含めないようにしている
  • プロンプトは以下
def build_prompt(past_tweets, sample_size=20):
    examples = "\n".join(random.sample(past_tweets, sample_size))
    return f"""以下は過去のツイートです:

----ここから過去のツイート----
{examples}
----ここまで過去のツイート----

これらの文体や話題を参考にして、あなたらしい新しいツイートを1つ生成してください。
日本語でかつ文章の意味がわかるような自然なツイートにしてください。
ツイートに「https://」から始まるようなURLは絶対に含めないでください。
ツイートの長さは50文字以内にしてください。
ツイートを作成した理由などは説明しないください、ツイートのみ生成してください。
"""

ブログを書く

Twitter API + Blogger API + Ollama (gemma3)

  • テーマを与えてそのテーマに基づいたブログ記事を書いてもらう
  • 出力は必ずHTMLになるようにプロンプトで調整、デフォルトがMarkdownっぽいので可能な限りMarkdownにならないようにする
  • テーマはランダムで100件保持、100件分のテーマを消費すると停止する
  • テーマはChatGPTに生成してもらっている
  • プロンプトは以下
def build_prompt_for_blog_post(theme):
    return f"""以下はブログ記事のテーマです。

----ここからテーマ----
{theme}
----ここまでテーマ----

このテーマを参考にして、あなたらしい新しいブログ記事を1つ生成してください。
ブログ記事内では Markdown 記法は使えません、Markdown 記法は自動で HTML に変換されません。絶対に Markdown 記法を使わないでください。
ブログ記事は Markdown 記法を使わずに生成してください。
ブログ記事内では HTML タグが使えます。
コードなどシンタックスハイライトが必要な場合は HTML タグを使ってください。
ブログ記事に画像は含めないでください。
ブログ記事内に StyleSheet や CSS の記述を含めることは可能ですがブログ本体の StyleSheet や CSS に影響を与えないようにしてください。
ブログ記事を作成した理由などは説明しないください、ブログ記事の内容のみ生成してください。
"""

絵を書く

Twitter API + Stable Diffusion WebUI API (model はランダム)

  • SD-Web UI を API モードで起動してそれをコールする
  • SD-Web UI の命令はそのまま JSON のペイロードとして API に送信できるので楽
  • 生成された画像のサイズは896x1152
  • モデルは固定ではなく10個ほど保持しておりそれを順番に使用していくように Python 側で制御
  • プロンプトもランダムになるようにしておりベース、性別、向き、服装、背景など要素ごとに毎回ランダムで生成するようにしている
def generate_prompt():
    # プロンプトの定義
    base = "masterpiece, best quality, ultra-detailed, 8k, cinematic lighting"
    gender = "".join(
        ("1 beautiful japanese young women, fair skin, light makeup, realistic face")
    )
    viewpoint = get_random_viewpoint()
    posing = get_random_posing()
    hair_cut = get_random_hair_cut()
    hair_color = get_random_hair_color()
    hair = f"{hair_color} {hair_cut}"
    face = get_random_face()
    background = get_random_backend()
    tops = get_random_tops()
    bottoms = get_random_bottoms()
    clothes = f"{tops}, {bottoms}"
    return "".join(
        f"{base}, {gender}, {viewpoint}, {posing}, {hair}, {face}, {background}, {clothes}",
    )

ショート動画を作る

Twitter API + Stable Diffusion WebUI API + LTX-Video (txv-2b-0.9.8-distilled)

  • text-to-video ではなく image-to-video の手法
  • 先に SD-WebUI を使って画像を作成してもらう
  • その画像を使って LTX-Video で動画にする
  • 256x384の4秒動画を作成 (num_frames=121、frame_rate=30)
  • 4秒以上の動画を生成する場合は192x256にすれば生成できる
  • 本当は896x1152で生成したいがリソースが足りない
  • 動画の生成はほぼマシンリソースをすべて使うので生成前にマイニングおよび ollama の runner を停止している
  • 各種プロセスを停止しないとメモリが枯渇してほぼ100%クラッシュする
  • 1動画生成するのに20-60分ほどかかる
  • 生成時間にムラがありおそらく入力している画像の影響だと思われるが安定しない
  • LTX-Video をサブプロセスとしてコールしているのでその作りが微妙
def convert_image_to_video(
    img_filename: str, width: int, height: int, prompt: str = ""
) -> Optional[str]:
    # 環境変数からパスを取得、設定がなければデフォルト値を使用
    work_dir = os.getenv("LTX_WORK_DIR", "/Users/kakakikikeke/Documents/work/LTX-Video")
    img_dir = os.getenv("LTX_IMG_DIR", "/Users/kakakikikeke/data/repo/videobot")

    # 仮想環境の Python を直接指定
    venv_python = os.path.join(work_dir, "env", "bin", "python")

    # 実行コマンド
    command = f"""
    cd {work_dir} && \
    PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 \
    {venv_python} inference.py \
    --prompt "{prompt}" \
    --conditioning_media_paths {img_dir}/{img_filename} \
    --conditioning_start_frames 0 \
    --height {height} \
    --width {width} \
    --pipeline_config configs/ltxv-2b-0.9.8-distilled.yaml
    """

今後追加したい機能

  • 音楽の作成
    • AudioGen
    • RVC
  • 長めの動画
    • 今のマシンだと画像サイズを落としてフレーム数を上げるしかない
    • もっと軽量なモデルを探す
    • 本当はWan2.2やVeo3レベルの動画を生成したい
  • 俳句
    • gemma3 でプロントプト換えるだけ
  • 音楽+動画
    • 上記で生成した音楽と動画を何かしらで組み合わせる
    • 最終形はこれなのかもしれない
  • 昔の写真や自分で書いた絵を動画にしたい
    • 過去の復元
    • 手書きの絵 -> アニメ化 -> 動画化
  • NanoBanana 連携
    • 有料だとかなり強力
    • というかお金を使う前提ならローカルで全部動かさないで Google AI Studo API や Colab でガンガン動かして高品質、高画質、長尺コンテンツを作りまくれる
    • ただマネタイズ考えないと大変なことなりそう
    • 動画にするだけならVeo3でもいける

課題

  • Twitter API Free プランの上限
    • 500ツイート/1日にほぼ当たっている
    • 有料プランにすれば解決するがどうするか
    • コンテキスト(メディア系、テキスト系)にアカウントを分割するか、管理は面倒になる
  • Ollama で動作させるモデル
    • gemma3 はだいぶ軽量なので動作する
    • gpt-oss のような大規模LLMは動作しない (動作はするがスワップだらけでかなり遅くなる)
    • openhermes など試したがハッシュタグや無駄に絵文字を使うのでやめたりした
    • いいモデルを探すのが難しい
  • プロンプトだけで制御するのには限界がある
    • 含めないでと命令しても含めてくる
    • モデルに合ったプロンプトを調整しなければいけないのが辛いのでなんとかしたい (プロンプト最適化など)
  • プロンプトのパターン追加
    • テーマなど手動の部分があるので自動化したい
    • 絵を描く際のプロンプトのランダム抽出の候補を追加する
    • そもそも完全ランダムにする方法を考える
  • 絶望的にマシンスペックが足りない
    • やはり AppleSilliocn だとかなり辛い
    • 基本は RTX などの CUDA が使えるグラボがあることが前提 (xformers動作など)
    • 動画生成は特に VRAM を消費するので VRAM モリモリのグラボがないと厳しい (Wan2.2など)
  • ディスクも足りない
    • ローカルにモデルを置きまくっているのでディスクが枯渇する

最後に

多少の知識はいるが生成系は本当に楽な時代になった

2025年9月10日水曜日

NanoBanana の API を試す

NanoBanana の API を試す

ちゃんとこういうテック記事も投稿しないとダメだなと思い試しました
Python を使っています

環境

  • macOS 15.6.1
  • Python 3.12.11
    • google-genai==1.35.0
    • pillow==11.3.0

準備

必要なライブラリをインストールします

  • pipenv install google-genai
  • pipenv install pillow

google-generativeai は Deprecated なので注意してください
google-genai を使いましょう

API キーの取得

Google AI Studio (ここ)から生成しましょう

サンプルコード

比較的新しめの技術に関しては AI 先生に聞いても教えてくれないから公式ドキュメントを見るのが一番なんですよね

ファイルをアップロードして変換してもらうだけの簡単なスクリプトなのでリファクタなどはしていません

xxx の部分は上記で取得した API キーを入力してください

from io import BytesIO

from google import genai
from PIL import Image

client = genai.Client(api_key="xxx")

prompt = """
  背景を宇宙に変更してください。
"""
image = Image.open("reforg.jpeg")

# チャットクライアントの作成
chat = client.chats.create(model="gemini-2.5-flash-image-preview")
# イメージとプロンプトの送信
response = chat.send_message([prompt, image])

# 結果(テキストと画像)の取得、一応 pyright のエラーも対応
if response.candidates is None:
    raise

if response.candidates[0].content is None:
    raise

parts = response.candidates[0].content.parts
if parts is not None:
    for i, part in enumerate(parts):
        if part.text is not None:
            print(part.text)
        elif part.inline_data is not None and part.inline_data.data is not None:
            image = Image.open(BytesIO(part.inline_data.data))
            image.save(f"generated_image_{i}.png")

で入力した画像がこれで

出力された画像が以下です

すばらしい
特にレスポンスの速さがすばらしい

最後に

Google AI Studio の UI からだと制限があったりしてうまく画像が生成されないことがあるようなのでそんな場合は API を使いましょう

ただこれだとチャットというよりかは一問一答の会話なのでチャット的な感じでインタラクティブな感じにしたいのであればもう少し手を加える筆意ようがありそうです

それでもこれが無料で使えるのは本当に素晴らしいことだと思います

参考サイト

2023年7月4日火曜日

nifcloud sdk for python でカスタムヘッダを設定する方法

nifcloud sdk for python でカスタムヘッダを設定する方法

nifcloud sdk for python は botocore を使っているので botocore レベルでヘッダをカスタムする必要があります

環境

  • Python 3.11.3
  • nifcloud sdk for python 1.6.0

サンプルコード

from nifcloud import session

def add_custom_header(request, **kwargs):
    request.headers['Custom-Header-1'] = 'Value-1'


class NifcloudClient:
    def __init__(self, region: str, access_key: str, secret_key) -> None:
        # 先にセッションを作成する
        custom_session = session.get_session()
        # 作成したセッションに対して before-send イベントに対してカスタムヘッダを設定するためのハンドラを登録する
        custom_session.register("before-send", add_custom_header)
        # custom_session を使ってクライアントを作る
        self.client = custom_session.create_client(
            "computing",
            region_name=region,
            nifcloud_access_key_id=access_key,  # type: ignore
            nifcloud_secret_access_key=secret_key,  # type: ignore
        )

動作確認したい場合は適当にエコーサーバとかを立てて endpoint_url を設定してリクエストの内容を覗いてみてください

参考URL

2018年7月13日金曜日

nifcloud-python-sdk で MagicMock を使う方法

概要

結構手こずったのでメモ
ポイントはどのモジュールに @patch を当てるのかとメソッドをモック化するときは return_value が必要な点かなと

環境

  • macOS 10.13.5
  • Python 3.6.5

テスト対象のコード

  • vim nif.py
from nifcloud import session

class Nif(object):
    def __init__(self):
        self.cli = session.get_session().create_client(
            "computing",
            region_name="jp-east-1",
            aws_access_key_id="xxxx",
            aws_secret_access_key="xxxx"
        )

    def desc(self):
        return self.cli.describe_security_groups()

これをテストします

普通にテストすると

  • vim test_nif.py
import unittest
from nif import Nif


class TestNifClass(unittest.TestCase):

    def test_desc(self):
        n = Nif()
        res = n.desc()
        print(res)


if __name__ == '__main__':
    unittest.main()
  • python3 -m unittest test_nif.py

で普通に describe_security_groups がコールされます

モック化してみる

先ほどのテストをモック化して describe_security_groups を呼ばないようにしてモックがレスポンスを返却するようにしてみます

import unittest
from nif import Nif
from unittest.mock import patch, MagicMock


class TestNifClass(unittest.TestCase):

    # @patch('nif.session.get_session')
    @patch('nifcloud.session.get_session')
    def test_get(self, mock):
        mock_res = MagicMock(return_value={'RequestId': 'xxxxxxx'})
        mock.return_value.create_client.return_value.describe_security_groups = mock_res
        n = Nif()
        res = n.desc()
        print(res)


if __name__ == '__main__':
    unittest.main()

ポイントは 2 つでパッチを当てるのは @patch('nifcloud.session.get_session') というのと describe_security_groups のレスポンスをモックから返却させるために mock.return_value.create_client.return_value.describe_security_groups = mock_res をしている点です

前者は @patch('nif.session.get_session') でも動作します
後者はメソッドに対してモックを割り当てるため return_value が必要です
get_sessioncreate_client もメソッドになります

とりあえずこれでテストするとレスポンスが以下のようにモックからのレスポンスに変わります

  • pipenv run python3 -m unittest test_nif.py
{'RequestId': 'xxxxxxx'}
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

最後に

Python3 の unittest.Mock は非常に便利なモックライブラリかなと思います
メソッドだけでなく属性やクラス全体をモック化することもできます
ただ、使い方が結構複雑なのでマスタするまでに多少の学習が必要かなと思います

2014年7月17日木曜日

pipのインストール方法

・easy_installでインストール
easy_install pip
※easy_installのインストール手順はこちら

・インストールスクリプトからインストール
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py

2014年5月15日木曜日

fabricやってみた

■環境
CentOS 5.10
Python 2.6.8
easy_install 0.6.45

easy_installのインストール方法
CentOS5系でのpythonのアップデート方法

■fabricインストール
easy_install fabric

■設定ファイル作成
touch fabfile.py
from fabric.api import run

def current_ls():
  run("ls")

■実行
fab -H 192.168.0.1,host1,host2 current_ls

上記の場合fabコマンドを実行したユーザの「192.168.0.1」でのログインパスワードを聞かれます
「host1」「host2」で同じパスワードを使用している場合は続けて聞かれませんが、パスワードが違う場合は再度パスワードの入力を求められます
[root@fabhost fabric]# fab -H 192.168.0.1,host1,host2 current_ls
[192.168.0.1] Executing task 'current_ls'
[192.168.0.1] run: ls
[192.168.0.1] Login password for 'root':

■設定ファイル内に認証情報を記載する方法
from fabric.api import run, env

def current_ls():
  env.password = 'hogehoge'
  run("ls")

ポイントは「env」をimportするのと「env.password」でパスワードを記載するところ
current_ls を実行した場合はenv.passwordで設定したパスワードでまずSSH認証を試みます
もし、認証できない場合は先ほどのようにパスワードを入力するように促されます

envには他にも鍵情報やユーザを設定することもできます
http://docs.fabfile.org/en/latest/usage/env.html

基本的な動作は以上で完了です
これだけで複数のサーバに同時にSSH実行することができるのでだいぶオペレーションが楽になります

■Tips
sudoをimportしてrunの代わりにsudoとするとrootユーザで実行できるようになります
env.passwordにsudoのパスワードを入力しておけば実行時に省略できます、記載しなかった場合は入力を求められます

「--」を使用すると指定したコマンドをfabfile.pyを書かずとも実行できます、以下のような感じです
fab -H 192.168.0.1 -- ls

2013年11月27日水曜日

【python】easy_installでインストールしたパッケージの一覧を確認する方法

python2.6の場合

cat /usr/lib/python2.6/site-packages/easy-install.pth

2.4の場合は「python2.6」->「python2.4」に変更すれば確認可能です

easy_installはpythonのバージョンごとにインストールしているパッケージを管理しているため、2.6でインストールしたパッケージは2.4でもインストールしないと使用することはできません

2013年11月26日火曜日

pythonのバージョンをアップデートするとyumが動かなくなるときの対応

■環境
CentOS 5.9
python 2.4.3 -> 2.6.8

■エラー内容
There was a problem importing one of the Python modules
required to run yum. The error leading to this problem was:

No module named yum

Please install a package which provides this module, or
verify that the module is installed correctly.

It's possible that the above module doesn't match the
current version of Python, which is:
2.6.8 (unknown, Nov 7 2012, 14:47:45)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)]

If you cannot solve this problem yourself, please go to
the yum faq at:
http://wiki.linux.duke.edu/YumFaq

■対処方法
emacs /usr/bin/yum
上記のファイルの先頭部分を変更
#!/usr/bin/python
↓
#!/usr/bin/python2.4
明示的に2.4のバージョンのpythonを使うように変更しましょう

2013年10月15日火曜日

【python】sphinxのインストールとサンプル動作まで

■環境
CentOS 5.9
python 2.6.8
sphinx 1.2b3

■各種インストール
1. easy_installインストール
wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py
Downloading http://pypi.python.org/packages/2.4/s/setuptools/setuptools-0.6c11-py2.4.egg
Processing setuptools-0.6c11-py2.4.egg
creating /usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg
Extracting setuptools-0.6c11-py2.4.egg to /usr/lib/python2.4/site-packages
Adding setuptools 0.6c11 to easy-install.pth file
Installing easy_install script to /usr/bin
Installing easy_install-2.4 script to /usr/bin

Installed /usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg
Processing dependencies for setuptools==0.6c11
Finished processing dependencies for setuptools==0.6c11

2. sphinxインストール
easy_install sphinx
Searching for sphinx
Reading http://pypi.python.org/simple/sphinx/
Best match: Sphinx 1.2b3
Downloading https://pypi.python.org/packages/source/S/Sphinx/Sphinx-1.2b3.tar.gz#md5=10d0bffdf01f0eddd57b9e0af0623457
Processing Sphinx-1.2b3.tar.gz
Writing /tmp/easy_install-VMYPoO/Sphinx-1.2b3/setup.cfg
Running Sphinx-1.2b3/setup.py -q bdist_egg --dist-dir /tmp/easy_install-VMYPoO/Sphinx-1.2b3/egg-dist-tmp-nTgP_U
warning: no files found matching 'README'
no previously-included directories found matching 'doc/_build'
Adding Sphinx 1.2b3 to easy-install.pth file
Installing sphinx-apidoc script to /usr/bin
Installing sphinx-build script to /usr/bin
Installing sphinx-quickstart script to /usr/bin
Installing sphinx-autogen script to /usr/bin

Installed /usr/lib/python2.6/site-packages/Sphinx-1.2b3-py2.6.egg
Processing dependencies for sphinx
Searching for Jinja2>=2.3
Reading http://pypi.python.org/simple/Jinja2/
Best match: Jinja2 2.7.1
Downloading https://pypi.python.org/packages/source/J/Jinja2/Jinja2-2.7.1.tar.gz#md5=282aed153e69f970d6e76f78ed9d027a
Processing Jinja2-2.7.1.tar.gz
Writing /tmp/easy_install-5UTFwS/Jinja2-2.7.1/setup.cfg
Running Jinja2-2.7.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-5UTFwS/Jinja2-2.7.1/egg-dist-tmp-ugTvwR
warning: no files found matching '*' under directory 'custom_fixers'
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no previously-included files matching '*.pyc' found under directory 'jinja2'
warning: no previously-included files matching '*.pyc' found under directory 'docs'
warning: no previously-included files matching '*.pyo' found under directory 'jinja2'
warning: no previously-included files matching '*.pyo' found under directory 'docs'
Adding Jinja2 2.7.1 to easy-install.pth file

Installed /usr/lib/python2.6/site-packages/Jinja2-2.7.1-py2.6.egg
Searching for docutils>=0.7
Reading http://pypi.python.org/simple/docutils/
Best match: docutils 0.11
Downloading https://pypi.python.org/packages/source/d/docutils/docutils-0.11.tar.gz#md5=20ac380a18b369824276864d98ec0ad6
warning: no files found matching 'MANIFEST'
warning: no files found matching '*' under directory 'extras'
warning: no previously-included files matching '.cvsignore' found under directory '*'
warning: no previously-included files matching '*.pyc' found under directory '*'
warning: no previously-included files matching '*~' found under directory '*'
warning: no previously-included files matching '.DS_Store' found under directory '*'
zip_safe flag not set; analyzing archive contents...
docutils.parsers.rst.directives.misc: module references __file__
docutils.writers.docutils_xml: module references __path__
docutils.writers.s5_html.__init__: module references __file__
docutils.writers.odf_odt.__init__: module references __file__
docutils.writers.html4css1.__init__: module references __file__
docutils.writers.pep_html.__init__: module references __file__
docutils.writers.latex2e.__init__: module references __file__
Adding docutils 0.11 to easy-install.pth file
Installing rst2html.py script to /usr/bin
Installing rst2s5.py script to /usr/bin
Installing rst2pseudoxml.py script to /usr/bin
Installing rst2latex.py script to /usr/bin
Installing rstpep2html.py script to /usr/bin
Installing rst2xetex.py script to /usr/bin
Installing rst2man.py script to /usr/bin
Installing rst2odt_prepstyles.py script to /usr/bin
Installing rst2xml.py script to /usr/bin
Installing rst2odt.py script to /usr/bin

Installed /usr/lib/python2.6/site-packages/docutils-0.11-py2.6.egg
Searching for Pygments>=1.2
Reading http://pypi.python.org/simple/Pygments/
Best match: Pygments 1.6
Downloading https://pypi.python.org/packages/2.6/P/Pygments/Pygments-1.6-py2.6.egg#md5=2584ae5795d01cefbff0744136df3f65
Processing Pygments-1.6-py2.6.egg
creating /usr/lib/python2.6/site-packages/Pygments-1.6-py2.6.egg
Extracting Pygments-1.6-py2.6.egg to /usr/lib/python2.6/site-packages
Adding Pygments 1.6 to easy-install.pth file
Installing pygmentize script to /usr/bin

Installed /usr/lib/python2.6/site-packages/Pygments-1.6-py2.6.egg
Searching for markupsafe
Reading http://pypi.python.org/simple/markupsafe/
Best match: MarkupSafe 0.18
Downloading https://pypi.python.org/packages/source/M/MarkupSafe/MarkupSafe-0.18.tar.gz#md5=f8d252fd05371e51dec2fe9a36890687
Processing MarkupSafe-0.18.tar.gz
Writing /tmp/easy_install-R1K6UA/MarkupSafe-0.18/setup.cfg
Running MarkupSafe-0.18/setup.py -q bdist_egg --dist-dir /tmp/easy_install-R1K6UA/MarkupSafe-0.18/egg-dist-tmp-Gp3OgU
Adding MarkupSafe 0.18 to easy-install.pth file

Installed /usr/lib/python2.6/site-packages/MarkupSafe-0.18-py2.6-linux-x86_64.egg
Finished processing dependencies for sphinx

上記のようになればインストール完了です

■サンプル作成
sphinx-quickstart
Welcome to the Sphinx 1.2b3 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]:

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/N) [n]:

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: test
> Author name(s): kakakikikeke

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version: 0.1
> Project release [0.1]:

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/N) [n]:

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/N) [n]:
> doctest: automatically test code snippets in doctest blocks (y/N) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/N) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]:
> coverage: checks for documentation coverage (y/N) [n]:
> pngmath: include math, rendered as PNG images (y/N) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/N) [n]:
> ifconfig: conditional inclusion of content based on config values (y/N) [n]:
> viewcode: include links to the source code of documented Python objects (y/N) [n]:

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (Y/n) [y]:
> Create Windows command file? (Y/n) [y]:

Creating file ./conf.py.
Creating file ./index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file ./index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

緑の部分で色付けした「プロジェクト名」「作者」「バージョン(開発バージョンとリリースバージョン)」の3つだけ適当に入力して後はEnterを入力で問題ありません
プロジェクトが作成できたらさっそくビルドします

make html
sphinx-build -b html -d _build/doctrees   . _build/html
Making output directory...
Running Sphinx v1.2b3
loading pickled environment... not yet created
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] index

looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index

writing additional files... genindex search
copying static files... done
copying extra files... dumping search index... done
dumping object inventory... done
build succeeded.

Build finished. The HTML pages are in _build/html.

_build/html配下に静的ファイルが生成されます
_build/html配下をapache等のDocumentRoot配下にコピーして確認してみます
EX)
cp -ipr _build/html/ /var/www/html/sphinxtest/

http:///localhost/sphinxtest
にアクセスして以下の画面が表示さればOKです

2013年6月2日日曜日

zipimport.ZipImportError: can't decompress data; zlib not available

yum -y install zlib*
したあとに再度pythonをconfigureしてmakeすれば幸せになれると思います

というかソースからインストールした場合ってyumでライブラリインストールしたあとは
再コンパイルしないとダメなのだろうか
あまりpythonは詳しくないのでわからない・・・

2013年6月1日土曜日

【CentOS6.3】python2.7.5をインストール

■コマンド
wget http://www.python.org/ftp/python/2.7.5/Python-2.7.5.tgz
tar xvfz Python-2.7.5.tgz
cd Python-2.7.5
yum -y install gcc zlib* openssl*
./configure
make
make test
make install

which python
cd /usr/local/bin/
rm python.back python2 python2-config python-config python
cd /usr/bin/
rm python2
mv python python2.6.6
ln -s /usr/local/bin/python2.7 python
python --version
vi /usr/bin/yum
冒頭のpythonへのパスを/usr/bin/python2.6.6に変更する
yum search python
yumができることを確認する

ポイントはyum installで、ソースからインストールするときはyumをインストールしてからでないとコンパイル後のpythonに反映されません
つまり、yumでモジュールをインストールしたあとは再コンパイルしないといけません