app:
  description: 水道事業のポンプ設備保守記録から異常パターンを抽出しリスク分類・診断レポートを作成するワークフロー
  icon: 🤖
  icon_background: '#FFEAD5'
  mode: workflow
  name: ポンプ設備 保守記録異常パターン抽出と診断レポート
  use_icon_as_answer_icon: false
kind: app
version: 0.6.0
workflow:
  conversation_variables: []
  environment_variables: []
  features:
    file_upload:
      image:
        enabled: false
    opening_statement: ''
    suggested_questions: []
    suggested_questions_after_answer:
      enabled: false
    text_to_speech:
      enabled: false
  graph:
    edges:
    - data:
        sourceType: start
        targetType: code
      id: start-to-code1
      source: start
      target: code1
    - data:
        sourceType: code
        targetType: llm
      id: code1-to-llm1
      source: code1
      target: llm1
    - data:
        sourceType: llm
        targetType: end
      id: llm1-to-end
      source: llm1
      target: end
    nodes:
    - data:
        title: 開始
        type: start
        variables:
        - label: query
          max_length: 2048
          options: []
          required: true
          type: paragraph
          variable: query
      height: 90
      id: start
      position:
        x: 80
        y: 282
      type: custom
      width: 244
    - data:
        title: パターン抽出とリスク判定
        type: code
        code_language: python3
        code: "def _safe_str(v):\n    \"\"\"Convert any value to string safely.\"\"\
          \"\n    if v is None:\n        return \"\"\n    if isinstance(v, list):\n\
          \        return \"\\n\".join(str(i) for i in v)\n    return str(v)\n\ndef\
          \ _safe_list(v):\n    \"\"\"Ensure value is a list.\"\"\"\n    if v is None:\n\
          \        return []\n    if isinstance(v, str):\n        return [v]\n   \
          \ if isinstance(v, list):\n        return v\n    return [v]\n\ndef main(**kwargs)\
          \ -> dict:\n    inputs = kwargs\n    csv_text = inputs.get(\"csv\", \"\"\
          )\n    if not csv_text:\n        return dict(output=\"ERROR: CSV input is\
          \ empty.\")\n    import csv\n    from io import StringIO\n    from datetime\
          \ import datetime, timedelta\n    f = StringIO(csv_text)\n    try:\n   \
          \     reader = csv.DictReader(f)\n    except Exception:\n        return\
          \ dict(output=\"ERROR: CSV parse failed.\")\n    # helper to normalize keys\n\
          \    def norm_key(k: str) -> str:\n        if k is None:\n            return\
          \ \"\"\n        return k.strip().lower()\n    def get_val_row(row: dict,\
          \ keys):\n        for k in keys:\n            if k in row and row[k] is\
          \ not None and str(row[k]).strip() != \"\":\n                return str(row[k]).strip()\n\
          \        return \"\"\n    # storage\n    equipment_map = dict()\n    # possible\
          \ header key variants\n    date_keys = [\"date\", \"日付\", \"date\".lower()]\n\
          \    id_keys = [\"設備id\", \"設備_id\", \"equipmentid\", \"equipment_id\",\
          \ \"id\"]\n    name_keys = [\"設備名\", \"name\", \"equipment_name\"]\n   \
          \ symptom_keys = [\"症状\", \"symptom\", \"症状\".lower()]\n    part_keys =\
          \ [\"交換部品\", \"parts\", \"交換部品\".lower()]\n    # parse rows\n    for raw\
          \ in reader:\n        row = dict()\n        for k, v in raw.items():\n \
          \           nk = norm_key(k)\n            row[nk] = v.strip() if v is not\
          \ None else \"\"\n        date_str = get_val_row(row, date_keys)\n     \
          \   equip_id = get_val_row(row, id_keys)\n        equip_name = get_val_row(row,\
          \ name_keys)\n        symptom = get_val_row(row, symptom_keys)\n       \
          \ part = get_val_row(row, part_keys)\n        if not date_str or not equip_id:\n\
          \            # skip incomplete rows\n            continue\n        # try\
          \ multiple date formats\n        parsed_date = None\n        for fmt in\
          \ (\"%Y-%m-%d\", \"%Y/%m/%d\", \"%d-%m-%Y\", \"%d/%m/%Y\"):\n          \
          \  try:\n                parsed_date = datetime.strptime(date_str, fmt)\n\
          \                break\n            except Exception:\n                continue\n\
          \        if parsed_date is None:\n            # skip unparseable date\n\
          \            continue\n        if equip_id not in equipment_map:\n     \
          \       equipment_map[equip_id] = dict(name=equip_name, dates=[], symptoms=dict(),\
          \ parts=dict())\n        # append date\n        equipment_map[equip_id][\"\
          dates\"].append(parsed_date)\n        # count symptom\n        sym_map =\
          \ equipment_map[equip_id][\"symptoms\"]\n        prev_sym_count = sym_map.get(symptom,\
          \ 0)\n        sym_map[symptom] = prev_sym_count + 1\n        # count parts\n\
          \        parts_map = equipment_map[equip_id][\"parts\"]\n        if part:\n\
          \            prev_part_count = parts_map.get(part, 0)\n            parts_map[part]\
          \ = prev_part_count + 1\n    # analyze per equipment\n    high_list = []\n\
          \    medium_list = []\n    per_equip_summary = []\n    for eid, info in\
          \ equipment_map.items():\n        dates = sorted(info.get(\"dates\", []))\n\
          \        total = len(dates)\n        # detect reoccurrence: at least 2 events\
          \ within window -> mark\n        def check_within_window(win_days):\n  \
          \          n = len(dates)\n            for i in range(n):\n            \
          \    j = i\n                while j < n and (dates[j] - dates[i]).days <=\
          \ win_days:\n                    j += 1\n                if (j - i) >= 2:\n\
          \                    return True\n            return False\n        is_high\
          \ = check_within_window(90)\n        is_medium = (not is_high) and check_within_window(180)\n\
          \        if is_high:\n            high_list.append(eid)\n        elif is_medium:\n\
          \            medium_list.append(eid)\n        # top symptoms\n        sym_items\
          \ = sorted(list(info[\"symptoms\"].items()), key=lambda x: x[1], reverse=True)\n\
          \        top_symptoms = []\n        for s, c in sym_items[:3]:\n       \
          \     top_symptoms.append(str(s) + \" (\" + str(c) + \")\")\n        # top\
          \ parts\n        part_items = sorted(list(info[\"parts\"].items()), key=lambda\
          \ x: x[1], reverse=True)\n        top_parts = []\n        for p, c in part_items[:3]:\n\
          \            top_parts.append(str(p) + \" (\" + str(c) + \")\")\n      \
          \  risk_label = \"HIGH\" if is_high else (\"MEDIUM\" if is_medium else \"\
          LOW\")\n        line = \"EquipmentID: \" + str(eid) + \" | Name: \" + (info.get(\"\
          name\") or \"\") + \" | TotalFailures: \" + str(total) + \" | TopSymptoms:\
          \ \" + (\", \".join(top_symptoms) or \"N/A\") + \" | TopParts: \" + (\"\
          , \".join(top_parts) or \"N/A\") + \" | Risk: \" + risk_label\n        per_equip_summary.append(line)\n\
          \    # build output text\n    lines = []\n    lines.append(\"HighRiskEquipmentIDs:\
          \ \" + (\", \".join(high_list) if high_list else \"None\"))\n    lines.append(\"\
          MediumRiskEquipmentIDs: \" + (\", \".join(medium_list) if medium_list else\
          \ \"None\"))\n    lines.append(\"\")\n    lines.append(\"PerEquipmentSummary:\"\
          )\n    for s in per_equip_summary:\n        lines.append(s)\n    # final\
          \ note\n    lines.append(\"\")\n    lines.append(\"Notes: Risk detection\
          \ rule -> HIGH: >=2 events within 90 days; MEDIUM: >=2 events within 180\
          \ days (and not HIGH).\")\n    result_text = \"\\n\".join(lines)\n    return\
          \ dict(output=result_text)\n"
        variables:
        - value_selector:
          - start
          - query
          variable: csv
        outputs:
          output:
            type: string
            children: null
      height: 90
      id: code1
      position:
        x: 380
        y: 282
      type: custom
      width: 244
    - data:
        title: 診断レポート生成
        type: llm
        model:
          provider: openai
          name: gpt-5-mini
          mode: chat
          completion_params:
            temperature: 0.6
        prompt_template:
        - role: system
          text: 'あなたは水道事業の設備保全専門家です。提供された保守解析結果を基に、以下を含む診断レポートを作成してください: 1) 高リスク設備リスト（設備IDと短い理由）、2)
            優先的に実施すべき予防保全アクション（具体的な手順と優先度）、3) 部品在庫の推奨数量（部品名と推奨個数、簡潔な算出根拠）。出力は明確なセクション見出しで日本語で記述してください。


            ---


            【最終出力フォーマット (この指示が最優先)】

            最終出力は **読みやすい日本語の Markdown** で返してください。JSON

            配列・オブジェクトをそのまま出力してはいけません。

            - 見出し (## / ###) でセクションを区切る

            - リスト (- / 1.) や表 (| ... |) で構造化

            - 各項目の意図や根拠が分かるよう短い説明文を添える

            - 営業デモで顧客に直接見せられる体裁にする


            (構造化されたデータ項目を内部で扱うのは構いませんが、出力時に Markdown

            に変換してください。)'
        - role: user
          text: '保守解析結果:

            {{#code1.output#}}


            元CSV入力（参照用）:

            {{#start.query#}}'
        vision:
          enabled: false
        memory: null
        context:
          enabled: false
      height: 90
      id: llm1
      position:
        x: 680
        y: 282
      type: custom
      width: 244
    - data:
        title: 終了
        type: end
        outputs:
        - value_selector:
          - llm1
          - text
          variable: result
      height: 90
      id: end
      position:
        x: 980
        y: 282
      type: custom
      width: 244
  hash: null
