ローカルLLMにワークフローを作らせる
This commit is contained in:
9
.gitignore
vendored
9
.gitignore
vendored
@@ -3,6 +3,15 @@
|
||||
variables/
|
||||
resources/
|
||||
|
||||
# Environment / secrets
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# Python
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# wmill CLI
|
||||
wmill-lock.yaml
|
||||
|
||||
|
||||
31
CLAUDE.md
31
CLAUDE.md
@@ -24,7 +24,8 @@
|
||||
windmill_workflow/
|
||||
├── flows/ # フロー定義JSON
|
||||
│ ├── system_heartbeat.flow.json # Windmill自己診断フロー
|
||||
│ └── shiraou_notification.flow.json # 白皇集落 変更通知フロー
|
||||
│ ├── shiraou_notification.flow.json # 白皇集落 変更通知フロー
|
||||
│ └── mail_filter.flow.json # メールフィルタリングフロー
|
||||
├── docs/
|
||||
│ └── shiraou/ # 白皇集落営農組合関連ドキュメント
|
||||
│ ├── 19_windmill_通知ワークフロー連携仕様.md # API仕様書
|
||||
@@ -43,6 +44,7 @@ windmill_workflow/
|
||||
|------|------|-------------|
|
||||
| `f/app_custom/system_heartbeat` | Windmill自己診断 | なし(手動) |
|
||||
| `f/shiraou/shiraou_notification` | 白皇集落営農 変更通知 | 5分毎(JST) |
|
||||
| `f/mail/mail_filter` | メールフィルタリング(IMAP→LLM→LINE) | 10分毎(JST)予定 |
|
||||
| `u/antigravity/git_sync` | Git同期 | 30分毎 |
|
||||
|
||||
## wm-api.sh コマンド一覧
|
||||
@@ -88,7 +90,34 @@ git push origin main
|
||||
| `u/admin/LINE_CHANNEL_ACCESS_TOKEN` | ✅ | LINE Messaging APIトークン |
|
||||
| `u/admin/LINE_TO` | ✅ | LINE通知先ID(ユーザーまたはグループ) |
|
||||
| `u/admin/SHIRAOU_LAST_CHECKED_AT` | ❌ | 前回確認時刻(ワークフローが自動更新) |
|
||||
| `u/admin/KEINASYSTEM_API_KEY` | ✅ | Keinasystem MAIL_API_KEY(.envと同じ値) |
|
||||
| `u/admin/KEINASYSTEM_API_URL` | ❌ | `https://keinafarm.net` |
|
||||
| `u/admin/GEMINI_API_KEY` | ✅ | Google Gemini API キー(LLM判定用) |
|
||||
| `u/admin/GMAIL_IMAP_USER` | ✅ | GmailアカウントのIMAPユーザー名(メールアドレス) |
|
||||
| `u/admin/GMAIL_IMAP_PASSWORD` | ✅ | GmailのアプリパスワードIMAPパスワード) |
|
||||
| `u/admin/MAIL_FILTER_GMAIL_LAST_UID` | ❌ | Gmail最終処理UID(ワークフローが自動更新) |
|
||||
| `u/admin/HOTMAIL_IMAP_USER` | ✅ | Hotmail IMAPユーザー名(有効化時に登録) |
|
||||
| `u/admin/HOTMAIL_IMAP_PASSWORD` | ✅ | Hotmail IMAPパスワード(有効化時に登録) |
|
||||
| `u/admin/MAIL_FILTER_HOTMAIL_LAST_UID` | ❌ | Hotmail最終処理UID(有効化時に登録) |
|
||||
| `u/admin/XSERVER_IMAP_USER` | ✅ | Xserver IMAPユーザー名(有効化時に登録) |
|
||||
| `u/admin/XSERVER_IMAP_PASSWORD` | ✅ | Xserver IMAPパスワード(有効化時に登録) |
|
||||
| `u/admin/MAIL_FILTER_XSERVER_LAST_UID` | ❌ | Xserver最終処理UID(有効化時に登録) |
|
||||
|
||||
## マスタードキュメント
|
||||
|
||||
- [白皇集落 Windmill通知ワークフロー](docs/shiraou/20_マスタードキュメント_Windmill通知ワークフロー編.md)
|
||||
|
||||
## メールフィルタリング — アカウント有効化手順
|
||||
|
||||
Gmail → Hotmail → Xserver の順で段階的に有効化する。
|
||||
|
||||
### Gmail 初期設定
|
||||
1. GoogleアカウントでIMAPを有効化(Googleアカウント設定 → セキュリティ → アプリパスワード)
|
||||
2. Windmill Variables に `GMAIL_IMAP_USER`, `GMAIL_IMAP_PASSWORD` を登録
|
||||
3. フローを手動実行(初回: 既存メールスキップ、最大UIDを記録)
|
||||
4. スケジュール登録(10分毎)
|
||||
|
||||
### Hotmail/Xserver 追加時
|
||||
1. Windmill Variables に対応する変数を登録
|
||||
2. `flows/mail_filter.flow.json` の該当アカウントの `"enabled": false` を `true` に変更
|
||||
3. フローを DELETE → POST で再デプロイ
|
||||
|
||||
15
autonomous_windmill/.env.example
Normal file
15
autonomous_windmill/.env.example
Normal file
@@ -0,0 +1,15 @@
|
||||
# Windmill 接続設定
|
||||
WINDMILL_URL=https://windmill.keinafarm.net
|
||||
WINDMILL_TOKEN=your_token_here
|
||||
WINDMILL_WORKSPACE=admins
|
||||
|
||||
# Ollama 設定
|
||||
OLLAMA_URL=http://localhost:11434
|
||||
OLLAMA_MODEL=qwen2.5-coder:14b
|
||||
|
||||
# 動作設定
|
||||
DEV_PATH_PREFIX=f/dev
|
||||
MAX_RETRIES=3
|
||||
MAX_JSON_RETRIES=2
|
||||
POLL_INTERVAL=5
|
||||
POLL_MAX_COUNT=30
|
||||
22
autonomous_windmill/config.py
Normal file
22
autonomous_windmill/config.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""設定値の一元管理。環境変数 or .env ファイルから読み込む。"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(Path(__file__).parent / ".env")
|
||||
|
||||
WINDMILL_URL = os.environ.get("WINDMILL_URL", "https://windmill.keinafarm.net")
|
||||
WINDMILL_TOKEN = os.environ.get("WINDMILL_TOKEN", "")
|
||||
WINDMILL_WORKSPACE = os.environ.get("WINDMILL_WORKSPACE", "admins")
|
||||
|
||||
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434")
|
||||
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5-coder:14b")
|
||||
|
||||
DEV_PATH_PREFIX = os.environ.get("DEV_PATH_PREFIX", "f/dev")
|
||||
MAX_RETRIES = int(os.environ.get("MAX_RETRIES", "3"))
|
||||
MAX_JSON_RETRIES = int(os.environ.get("MAX_JSON_RETRIES", "2"))
|
||||
POLL_INTERVAL = int(os.environ.get("POLL_INTERVAL", "5"))
|
||||
POLL_MAX_COUNT = int(os.environ.get("POLL_MAX_COUNT", "30"))
|
||||
|
||||
if not WINDMILL_TOKEN:
|
||||
raise EnvironmentError("WINDMILL_TOKEN が設定されていません。.env ファイルを確認してください。")
|
||||
148
autonomous_windmill/controller.py
Normal file
148
autonomous_windmill/controller.py
Normal file
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
自律ループ制御。全体のオーケストレーションのみを行う。
|
||||
|
||||
Usage:
|
||||
python controller.py <flow_name> <task_description>
|
||||
|
||||
Example:
|
||||
python controller.py hello_world "print Hello World in Python"
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from config import DEV_PATH_PREFIX, MAX_RETRIES, MAX_JSON_RETRIES
|
||||
from state_manager import State, is_duplicate, register_hash
|
||||
from validator import validate
|
||||
from windmill_client import create_flow, update_flow, flow_exists, run_flow
|
||||
from job_poller import poll_until_done, JobTimeout
|
||||
from llm_interface import generate_flow, fix_flow
|
||||
|
||||
|
||||
def _log(prefix: str, msg: str) -> None:
|
||||
print(f"{prefix} {msg}", flush=True)
|
||||
|
||||
|
||||
def run(task_description: str, flow_name: str) -> bool:
|
||||
"""
|
||||
自律ループを実行する。
|
||||
|
||||
Returns:
|
||||
True = 成功, False = 失敗
|
||||
"""
|
||||
# パス制限: f/dev/* のみ(controller 側で強制)
|
||||
flow_path = f"{DEV_PATH_PREFIX}/{flow_name}"
|
||||
state = State(retry_count=MAX_RETRIES)
|
||||
is_first = True
|
||||
json_fail_count = 0
|
||||
|
||||
_log("[START]", f"タスク: {task_description}")
|
||||
_log("[START]", f"フローパス: {flow_path}")
|
||||
|
||||
while state.retry_count > 0:
|
||||
attempt = MAX_RETRIES - state.retry_count + 1
|
||||
prefix = f"[試行 {attempt}/{MAX_RETRIES}]"
|
||||
|
||||
# ── 1. LLM 生成 ─────────────────────────────────────────
|
||||
_log(prefix, "フロー生成中...")
|
||||
if is_first:
|
||||
raw = generate_flow(task_description)
|
||||
else:
|
||||
prev_json = json.dumps(state.current_flow, ensure_ascii=False)
|
||||
raw = fix_flow(prev_json, state.last_error or "")
|
||||
|
||||
# ── 2 & 3. JSON 検証 ─────────────────────────────────────
|
||||
try:
|
||||
flow_dict = validate(raw)
|
||||
json_fail_count = 0
|
||||
_log(prefix, "JSON検証: OK")
|
||||
except ValueError as e:
|
||||
_log(prefix, f"JSON検証: NG - {e}")
|
||||
json_fail_count += 1
|
||||
if json_fail_count >= MAX_JSON_RETRIES:
|
||||
_log(prefix, f"JSON検証 {MAX_JSON_RETRIES} 回連続失敗 → リトライ消費")
|
||||
state.retry_count -= 1
|
||||
state.last_error = str(e)
|
||||
json_fail_count = 0
|
||||
is_first = False
|
||||
continue
|
||||
|
||||
# ── 5. ハッシュ比較 ──────────────────────────────────────
|
||||
if is_duplicate(state, flow_dict):
|
||||
_log("[STOP]", "同一JSON検出 → 即停止")
|
||||
return False
|
||||
|
||||
register_hash(state, flow_dict)
|
||||
|
||||
# ── 6. create / update ───────────────────────────────────
|
||||
summary = flow_dict["summary"]
|
||||
value = flow_dict["value"]
|
||||
try:
|
||||
if flow_exists(flow_path):
|
||||
update_flow(flow_path, summary, value)
|
||||
_log(prefix, f"フロー更新: {flow_path}")
|
||||
else:
|
||||
create_flow(flow_path, summary, value)
|
||||
_log(prefix, f"フロー作成: {flow_path}")
|
||||
except Exception as e:
|
||||
_log(prefix, f"フロー送信エラー: {e}")
|
||||
state.retry_count -= 1
|
||||
state.last_error = str(e)
|
||||
is_first = False
|
||||
continue
|
||||
|
||||
# API 送信成功直後に current_flow を更新(run 前・失敗時は更新しない)
|
||||
state.current_flow = flow_dict
|
||||
|
||||
# ── 7. run ──────────────────────────────────────────────
|
||||
try:
|
||||
job_id = run_flow(flow_path)
|
||||
state.job_id = job_id
|
||||
_log(prefix, f"ジョブ実行: {job_id}")
|
||||
except Exception as e:
|
||||
_log(prefix, f"ジョブ起動エラー: {e}")
|
||||
state.retry_count -= 1
|
||||
state.last_error = str(e)
|
||||
is_first = False
|
||||
continue
|
||||
|
||||
# ── 8. ジョブ完了待ち ────────────────────────────────────
|
||||
_log(prefix, "ジョブ完了待ち...")
|
||||
try:
|
||||
success, logs = poll_until_done(job_id)
|
||||
except JobTimeout as e:
|
||||
_log(prefix, f"タイムアウト: {e}")
|
||||
state.retry_count -= 1
|
||||
state.last_error = "タイムアウト"
|
||||
state.last_logs = None
|
||||
is_first = False
|
||||
continue
|
||||
|
||||
state.last_logs = logs
|
||||
|
||||
# ── 9. ステータス判定 ────────────────────────────────────
|
||||
if success:
|
||||
_log(prefix, "実行結果: SUCCESS")
|
||||
_log("[最終]", "状態: 成功")
|
||||
return True
|
||||
else:
|
||||
excerpt = logs[:300] if logs else "(ログなし)"
|
||||
_log(prefix, "実行結果: FAILURE")
|
||||
_log(prefix, f"エラー内容: {excerpt}")
|
||||
state.retry_count -= 1
|
||||
state.last_error = logs or "不明なエラー"
|
||||
is_first = False
|
||||
|
||||
_log("[最終]", f"状態: {MAX_RETRIES} 回失敗で停止")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: python controller.py <flow_name> <task_description>")
|
||||
print("Example: python controller.py hello_world 'print Hello World in Python'")
|
||||
sys.exit(1)
|
||||
|
||||
_flow_name = sys.argv[1]
|
||||
_task = " ".join(sys.argv[2:])
|
||||
|
||||
ok = run(_task, _flow_name)
|
||||
sys.exit(0 if ok else 1)
|
||||
48
autonomous_windmill/job_poller.py
Normal file
48
autonomous_windmill/job_poller.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""ジョブ完了待ちポーリング。Windmill の success フィールドで判定する。"""
|
||||
import time
|
||||
from windmill_client import get_job, get_job_logs
|
||||
from config import POLL_INTERVAL, POLL_MAX_COUNT
|
||||
|
||||
|
||||
class JobTimeout(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def poll_until_done(job_id: str) -> tuple[bool, str]:
|
||||
"""
|
||||
ジョブが完了するまでポーリングする。
|
||||
|
||||
判定優先順位:
|
||||
1. success is False → 失敗(即返却)
|
||||
2. success is True → 成功(即返却)
|
||||
3. それ以外 → 継続待機
|
||||
|
||||
ログ文字列は主判定に使わない(誤検知防止)。
|
||||
|
||||
Returns:
|
||||
(success: bool, logs: str)
|
||||
Raises:
|
||||
JobTimeout: POLL_MAX_COUNT * POLL_INTERVAL 秒以内に完了しなかった場合
|
||||
"""
|
||||
for _ in range(POLL_MAX_COUNT):
|
||||
job = get_job(job_id)
|
||||
success = job.get("success")
|
||||
|
||||
if success is False:
|
||||
logs = get_job_logs(job_id)
|
||||
# result.error があればログに付加(ログが空でもエラー詳細を取得できる)
|
||||
result_error = job.get("result", {}) or {}
|
||||
error_detail = result_error.get("error", {}) or {}
|
||||
error_msg = error_detail.get("message", "")
|
||||
if error_msg and error_msg not in (logs or ""):
|
||||
logs = f"{logs}\n[result.error] {error_msg}".strip()
|
||||
return False, logs
|
||||
|
||||
if success is True:
|
||||
logs = get_job_logs(job_id)
|
||||
return True, logs
|
||||
|
||||
time.sleep(POLL_INTERVAL)
|
||||
|
||||
timeout_sec = POLL_MAX_COUNT * POLL_INTERVAL
|
||||
raise JobTimeout(f"ジョブ {job_id} が {timeout_sec} 秒以内に完了しませんでした")
|
||||
99
autonomous_windmill/llm_interface.py
Normal file
99
autonomous_windmill/llm_interface.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""Ollama へのプロンプト送信と JSON 抽出。"""
|
||||
import json
|
||||
import re
|
||||
import httpx
|
||||
from config import OLLAMA_URL, OLLAMA_MODEL
|
||||
|
||||
_SYSTEM_PROMPT = """\
|
||||
あなたはWindmillフロー生成AIです。
|
||||
以下のルールを必ず守ってください:
|
||||
- JSONのみ出力すること
|
||||
- Markdownのコードブロック(```)は使わない
|
||||
- 説明文・コメントは一切出力しない
|
||||
- フィールド順は必ず summary → value の順にすること
|
||||
- 出力するJSONは必ず以下のスキーマに従うこと:
|
||||
|
||||
{
|
||||
"summary": "<タスクを一言で表す英語の説明>",
|
||||
"value": {
|
||||
"modules": [
|
||||
{
|
||||
"id": "a",
|
||||
"value": {
|
||||
"type": "rawscript",
|
||||
"language": "python3",
|
||||
"content": "<タスクを実行するPython3コード>",
|
||||
"input_transforms": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
【必須ルール】
|
||||
- content のコードは必ず def main(): で始めること(Windmillのエントリーポイント)
|
||||
- main() がない場合は AttributeError になるため絶対に省略しないこと
|
||||
- content の内容はユーザーのタスク説明に従って書くこと(テンプレートをそのままコピーしないこと)
|
||||
- content 内の改行は \\n でエスケープすること(リテラル改行を入れると JSON パースエラーになる)
|
||||
- modules.id は a, b, c... の連番。追加フィールド禁止。
|
||||
|
||||
【出力例1】タスク: 「おはよう」と表示する
|
||||
{"summary":"Print greeting","value":{"modules":[{"id":"a","value":{"type":"rawscript","language":"python3","content":"def main():\\n print('おはよう')","input_transforms":{}}}]}}
|
||||
|
||||
【出力例2】タスク: 1から5までの数字を表示する
|
||||
{"summary":"Print numbers 1 to 5","value":{"modules":[{"id":"a","value":{"type":"rawscript","language":"python3","content":"def main():\\n for i in range(1, 6):\\n print(i)","input_transforms":{}}}]}}
|
||||
|
||||
【出力例3】タスク: 現在の日時を表示する
|
||||
{"summary":"Display current datetime","value":{"modules":[{"id":"a","value":{"type":"rawscript","language":"python3","content":"def main():\\n from datetime import datetime\\n print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))","input_transforms":{}}}]}}\
|
||||
"""
|
||||
|
||||
|
||||
def _chat(messages: list[dict]) -> str:
|
||||
resp = httpx.post(
|
||||
f"{OLLAMA_URL}/api/chat",
|
||||
json={
|
||||
"model": OLLAMA_MODEL,
|
||||
"messages": messages,
|
||||
"stream": False,
|
||||
"options": {"temperature": 0.1, "top_p": 0.9},
|
||||
},
|
||||
timeout=120,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
raw = resp.json()["message"]["content"].strip()
|
||||
return _extract_json(raw)
|
||||
|
||||
|
||||
def _extract_json(raw: str) -> str:
|
||||
"""LLM がコードブロックで囲んでしまった場合でも JSON 部分を取り出す。"""
|
||||
# ```json ... ``` または ``` ... ``` を除去
|
||||
match = re.search(r"```(?:json)?\s*([\s\S]+?)\s*```", raw)
|
||||
if match:
|
||||
return match.group(1).strip()
|
||||
return raw
|
||||
|
||||
|
||||
def generate_flow(task_description: str) -> str:
|
||||
"""初回生成:タスク説明からフロー JSON を生成する。"""
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": f"以下のフローをJSON形式で生成してください。\n要件: {task_description}"},
|
||||
]
|
||||
return _chat(messages)
|
||||
|
||||
|
||||
def fix_flow(previous_flow_json: str, error_log: str) -> str:
|
||||
"""リトライ生成:前回の JSON + エラーログから修正版を生成する。"""
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": (
|
||||
"前回のフロー実行でエラーが発生しました。修正したフローをJSON形式で出力してください。\n\n"
|
||||
f"--- 前回のフローJSON ---\n{previous_flow_json}\n\n"
|
||||
f"--- エラーログ ---\n{error_log}\n\n"
|
||||
"--- 修正指示 ---\n"
|
||||
"- 前回と同一のJSONは絶対に出力しないこと\n"
|
||||
"- エラーの原因箇所のみ修正すること\n"
|
||||
"- スキーマは変えないこと"
|
||||
)},
|
||||
]
|
||||
return _chat(messages)
|
||||
3
autonomous_windmill/requirements.txt
Normal file
3
autonomous_windmill/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
httpx
|
||||
jsonschema
|
||||
python-dotenv
|
||||
81
autonomous_windmill/run_gui.py
Normal file
81
autonomous_windmill/run_gui.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
GUIダイアログでフロー名とタスク説明を入力してから controller.py を起動する。
|
||||
VS Code タスクから呼び出す用。
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
|
||||
|
||||
def main() -> None:
|
||||
root = tk.Tk()
|
||||
root.title("Windmill フロー生成")
|
||||
root.resizable(True, True)
|
||||
|
||||
pad = {"padx": 12, "pady": 4}
|
||||
|
||||
# ── フロー名 ──────────────────────────────────
|
||||
tk.Label(root, text="フロー名", anchor="w").grid(
|
||||
row=0, column=0, sticky="ew", **pad
|
||||
)
|
||||
flow_var = tk.StringVar()
|
||||
flow_entry = tk.Entry(root, textvariable=flow_var, width=46)
|
||||
flow_entry.grid(row=1, column=0, sticky="ew", padx=12, pady=(0, 8))
|
||||
|
||||
# ── タスク説明 ────────────────────────────────
|
||||
tk.Label(root, text="タスク説明", anchor="w").grid(
|
||||
row=2, column=0, sticky="ew", **pad
|
||||
)
|
||||
task_text = tk.Text(root, width=46, height=8, wrap=tk.WORD)
|
||||
task_text.grid(row=3, column=0, sticky="nsew", padx=12, pady=(0, 8))
|
||||
|
||||
# ── ボタン ────────────────────────────────────
|
||||
btn_frame = tk.Frame(root)
|
||||
btn_frame.grid(row=4, column=0, sticky="e", padx=12, pady=(4, 12))
|
||||
|
||||
def on_cancel():
|
||||
root.destroy()
|
||||
sys.exit(0)
|
||||
|
||||
def on_run():
|
||||
flow_name = flow_var.get().strip()
|
||||
task_desc = task_text.get("1.0", tk.END).strip()
|
||||
|
||||
if not flow_name:
|
||||
messagebox.showwarning("入力エラー", "フロー名を入力してください。", parent=root)
|
||||
flow_entry.focus()
|
||||
return
|
||||
if not task_desc:
|
||||
messagebox.showwarning("入力エラー", "タスク説明を入力してください。", parent=root)
|
||||
task_text.focus()
|
||||
return
|
||||
|
||||
root.destroy()
|
||||
|
||||
# controller.py をカレントプロセスと置き換えて実行
|
||||
# → ターミナルにそのままログが流れる
|
||||
script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "controller.py")
|
||||
os.execv(sys.executable, [sys.executable, script, flow_name, task_desc])
|
||||
|
||||
tk.Button(btn_frame, text="キャンセル", width=10, command=on_cancel).pack(
|
||||
side=tk.LEFT, padx=(0, 6)
|
||||
)
|
||||
tk.Button(btn_frame, text="実行", width=10, command=on_run, default=tk.ACTIVE).pack(
|
||||
side=tk.LEFT
|
||||
)
|
||||
|
||||
# ── レイアウト調整 ────────────────────────────
|
||||
root.columnconfigure(0, weight=1)
|
||||
root.rowconfigure(3, weight=1)
|
||||
|
||||
# Enter キーで実行、Escape でキャンセル
|
||||
root.bind("<Return>", lambda _: on_run())
|
||||
root.bind("<Escape>", lambda _: on_cancel())
|
||||
|
||||
flow_entry.focus()
|
||||
root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
33
autonomous_windmill/state_manager.py
Normal file
33
autonomous_windmill/state_manager.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""State オブジェクトの管理とハッシュ比較。"""
|
||||
import json
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, Set
|
||||
|
||||
|
||||
@dataclass
|
||||
class State:
|
||||
retry_count: int = 3
|
||||
current_flow: Optional[dict] = None
|
||||
last_logs: Optional[str] = None
|
||||
last_error: Optional[str] = None
|
||||
flow_hashes: Set[str] = field(default_factory=set)
|
||||
job_id: Optional[str] = None
|
||||
|
||||
|
||||
def _canonical(flow_dict: dict) -> str:
|
||||
"""キー順を固定した JSON 文字列を返す(ハッシュ安定化)。"""
|
||||
return json.dumps(flow_dict, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
def compute_hash(flow_dict: dict) -> str:
|
||||
return hashlib.sha256(_canonical(flow_dict).encode()).hexdigest()
|
||||
|
||||
|
||||
def is_duplicate(state: State, flow_dict: dict) -> bool:
|
||||
"""過去に同一の JSON を出力済みかどうかを判定する。"""
|
||||
return compute_hash(flow_dict) in state.flow_hashes
|
||||
|
||||
|
||||
def register_hash(state: State, flow_dict: dict) -> None:
|
||||
state.flow_hashes.add(compute_hash(flow_dict))
|
||||
57
autonomous_windmill/validator.py
Normal file
57
autonomous_windmill/validator.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""LLM 出力の JSON 構文・スキーマ検証。"""
|
||||
import json
|
||||
import jsonschema
|
||||
|
||||
# LLM が出力すべき JSON の最小スキーマ
|
||||
_FLOW_SCHEMA = {
|
||||
"type": "object",
|
||||
"required": ["summary", "value"],
|
||||
"additionalProperties": False,
|
||||
"properties": {
|
||||
"summary": {"type": "string", "minLength": 1},
|
||||
"value": {
|
||||
"type": "object",
|
||||
"required": ["modules"],
|
||||
"properties": {
|
||||
"modules": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["id", "value"],
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"value": {
|
||||
"type": "object",
|
||||
"required": ["type", "language", "content"],
|
||||
"properties": {
|
||||
"type": {"type": "string"},
|
||||
"language": {"type": "string"},
|
||||
"content": {"type": "string"},
|
||||
"input_transforms": {"type": "object"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def validate(raw: str) -> dict:
|
||||
"""JSON 文字列を構文・スキーマ検証して dict を返す。失敗時は ValueError を投げる。"""
|
||||
# 構文チェック
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"JSON構文エラー: {e}")
|
||||
|
||||
# スキーマチェック
|
||||
try:
|
||||
jsonschema.validate(data, _FLOW_SCHEMA)
|
||||
except jsonschema.ValidationError as e:
|
||||
raise ValueError(f"JSONスキーマ不正: {e.message}")
|
||||
|
||||
return data
|
||||
50
autonomous_windmill/windmill_client.py
Normal file
50
autonomous_windmill/windmill_client.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""Windmill REST API の薄いラッパー。MCP は使わず直接 HTTPS で叩く。"""
|
||||
import httpx
|
||||
from config import WINDMILL_URL, WINDMILL_TOKEN, WINDMILL_WORKSPACE
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
return {"Authorization": f"Bearer {WINDMILL_TOKEN}"}
|
||||
|
||||
|
||||
def _api(path: str) -> str:
|
||||
return f"{WINDMILL_URL}/api/w/{WINDMILL_WORKSPACE}/{path}"
|
||||
|
||||
|
||||
def flow_exists(path: str) -> bool:
|
||||
resp = httpx.get(_api(f"flows/get/{path}"), headers=_headers(), timeout=30)
|
||||
return resp.status_code == 200
|
||||
|
||||
|
||||
def create_flow(path: str, summary: str, value: dict) -> None:
|
||||
payload = {"path": path, "summary": summary, "description": "", "value": value}
|
||||
resp = httpx.post(_api("flows/create"), headers=_headers(), json=payload, timeout=30)
|
||||
resp.raise_for_status()
|
||||
|
||||
|
||||
def update_flow(path: str, summary: str, value: dict) -> None:
|
||||
# 正しいエンドポイントは /flows/update/{path}(/flows/edit/ は404になる)
|
||||
payload = {"path": path, "summary": summary, "description": "", "value": value}
|
||||
resp = httpx.post(_api(f"flows/update/{path}"), headers=_headers(), json=payload, timeout=30)
|
||||
resp.raise_for_status()
|
||||
|
||||
|
||||
def run_flow(path: str) -> str:
|
||||
"""フローを実行して job_id を返す。"""
|
||||
resp = httpx.post(_api(f"jobs/run/f/{path}"), headers=_headers(), json={}, timeout=30)
|
||||
resp.raise_for_status()
|
||||
return resp.text.strip().strip('"')
|
||||
|
||||
|
||||
def get_job(job_id: str) -> dict:
|
||||
"""ジョブの状態を取得する。success フィールド: True=成功, False=失敗, None=実行中。"""
|
||||
resp = httpx.get(_api(f"jobs_u/get/{job_id}"), headers=_headers(), timeout=30)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def get_job_logs(job_id: str) -> str:
|
||||
resp = httpx.get(_api(f"jobs_u/getlogs/{job_id}"), headers=_headers(), timeout=30)
|
||||
if resp.status_code == 200:
|
||||
return resp.text
|
||||
return ""
|
||||
27
flows/mail_filter.flow.json
Normal file
27
flows/mail_filter.flow.json
Normal file
File diff suppressed because one or more lines are too long
83
test_imap.py
Normal file
83
test_imap.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
IMAP接続診断スクリプト
|
||||
使い方: python test_imap.py
|
||||
"""
|
||||
import imaplib
|
||||
import ssl
|
||||
import getpass
|
||||
|
||||
HOST = "outlook.office365.com"
|
||||
PORT = 993
|
||||
USER = "akiracraftworl@infoseek.jp"
|
||||
|
||||
print(f"IMAP診断: {HOST}:{PORT}")
|
||||
print(f"ユーザー: {USER}")
|
||||
print()
|
||||
|
||||
# --- Step 1: SSL接続テスト(認証なし)---
|
||||
print("[1] SSL接続テスト...")
|
||||
try:
|
||||
ssl_ctx = ssl.create_default_context()
|
||||
mail = imaplib.IMAP4_SSL(HOST, PORT, ssl_context=ssl_ctx)
|
||||
print(" ✓ SSL接続成功")
|
||||
except Exception as e:
|
||||
print(f" ❌ SSL接続失敗: {e}")
|
||||
exit(1)
|
||||
|
||||
# --- Step 2: サーバーの認証方式を確認 ---
|
||||
print("[2] サーバー対応認証方式を確認...")
|
||||
try:
|
||||
typ, caps_data = mail.capability()
|
||||
caps = caps_data[0].decode() if caps_data and caps_data[0] else ""
|
||||
print(f" CAPABILITY: {caps}")
|
||||
|
||||
if "AUTH=PLAIN" in caps or "AUTH=LOGIN" in caps:
|
||||
print(" ✓ 基本認証(パスワード)が使えます")
|
||||
basic_auth_supported = True
|
||||
else:
|
||||
basic_auth_supported = False
|
||||
|
||||
if "AUTH=XOAUTH2" in caps or "AUTH=OAUTHBEARER" in caps:
|
||||
print(" ⚠ モダン認証(OAuth2)が必要な可能性があります")
|
||||
|
||||
if not basic_auth_supported:
|
||||
print(" ❌ 基本認証は対応していません → OAuth2が必要です")
|
||||
mail.logout()
|
||||
exit(1)
|
||||
except Exception as e:
|
||||
print(f" CAPABILITY取得エラー: {e}")
|
||||
|
||||
# --- Step 3: ログインテスト ---
|
||||
print("[3] ログインテスト...")
|
||||
password = getpass.getpass(" パスワードを入力: ")
|
||||
|
||||
try:
|
||||
mail.login(USER, password)
|
||||
print(" ✓ ログイン成功!")
|
||||
|
||||
mail.select("INBOX")
|
||||
_, data = mail.uid("SEARCH", None, "ALL")
|
||||
uids = data[0].split() if data[0] else []
|
||||
print(f" ✓ INBOX: {len(uids)}件")
|
||||
mail.logout()
|
||||
print()
|
||||
print("✅ 成功!Windmillに登録できます。")
|
||||
|
||||
except imaplib.IMAP4.error as e:
|
||||
err = str(e)
|
||||
print(f" ❌ ログイン失敗: {err}")
|
||||
print()
|
||||
if "disabled" in err.lower() or "imap" in err.lower():
|
||||
print(" 原因: IMAPが無効化されています")
|
||||
print(" 対処: https://outlook.live.com → 設定 → メールの同期 → IMAPを有効化")
|
||||
elif "AUTHENTICATE" in err or "XOAUTH" in err:
|
||||
print(" 原因: モダン認証(OAuth2)が必要です")
|
||||
else:
|
||||
print(" 原因1: パスワードが間違っている")
|
||||
print(" 原因2: IMAPが無効(Outlook.com設定を再確認)")
|
||||
print(" 原因3: モダン認証が必要")
|
||||
print()
|
||||
print(" 確認してください:")
|
||||
print(" → https://outlook.live.com にこのメアドとパスワードでログインできますか?")
|
||||
except Exception as e:
|
||||
print(f" ❌ エラー: {type(e).__name__}: {e}")
|
||||
Reference in New Issue
Block a user