1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AIがここまで来た:KAT-Devが“完璧なPythonスクリプト”を生成

Posted at

はじめに

夜のColab画面に、ふと思いました。
「JSONファイルのキーをアルファベット順に並べ替えたい。
でも、いちいちコードを書くのは面倒だな。」

そんな軽い気持ちで、AIにお願いしてみたのです。
──「JSONのキーを並べ替えるPythonスクリプトを書いてください。

返ってきたのは、完成された実用ツール。しかもエラー処理付き、CLI対応、UTF-8完全対応。まるで熟練エンジニアが一晩で仕上げたかのような完成度でした。

今回は、コード生成特化モデルKAT-Dev による
“自然言語 → 実行可能コード” の瞬間を紹介します。


KAT-Devの回答(そのまま実行可能)

返ってきたのは、なんと完全動作するスクリプトでした👇

#!/usr/bin/env python3
import json
import sys
import argparse
from typing import Any

def sort_json_keys(data: Any) -> Any:
    """JSONデータのキーをアルファベット順に並べ替える"""
    if isinstance(data, dict):
        return {k: sort_json_keys(v) for k, v in sorted(data.items())}
    elif isinstance(data, list):
        return [sort_json_keys(item) for item in data]
    else:
        return data

def main():
    parser = argparse.ArgumentParser(description='JSONファイルのキーをアルファベット順に並べ替える')
    parser.add_argument('--in', dest='input_file', default='input.json',
                       help='入力JSONファイルパス (デフォルト: input.json)')
    parser.add_argument('--out', dest='output_file', default='output.json',
                       help='出力JSONファイルパス (デフォルト: output.json)')
    
    args = parser.parse_args()
    
    try:
        # JSONファイル読み込み
        with open(args.input_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # キーを並べ替える
        sorted_data = sort_json_keys(data)
        
        # 結果を保存
        with open(args.output_file, 'w', encoding='utf-8') as f:
            json.dump(sorted_data, f, ensure_ascii=False, indent=2)
            
    except FileNotFoundError:
        print(f"エラー: ファイル '{args.input_file}' が見つかりません", file=sys.stderr)
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"エラー: JSONデコードに失敗しました: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"予期しないエラー: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    main()

コードの見どころ

ポイント 内容
再帰でのキーソート 辞書・配列のネストを完全に処理。構造理解が深い。
CLI設計が自然 argparse--in / --out 指定可能。実用レベル。
堅牢な例外処理 ファイル未発見、JSONデコード失敗、その他例外をカバー。
コメント&命名が丁寧 人間がそのままレビューに出せる品質。

つまり、
AIが1回で完璧なCLIツールを書いたということ。

しかもプロンプトはたった一行。
まるで「もう一人の自分が隣でペアプロしてくれた」ような感覚でした。

Colabで試すなら

# JSONサンプル作成
import json
sample = {"zebra": {"b": 1, "a": 2}, "apple": [{"y": 2, "x": 1}]}
with open("input.json", "w", encoding="utf-8") as f:
    json.dump(sample, f, ensure_ascii=False, indent=2)

# 実行
!python sort_json.py --in input.json --out output.json
!cat output.json

出力はすべてのキーが美しく整列してこうなります👇

{
  "apple": [
    {
      "x": 1,
      "y": 2
    }
  ],
  "zebra": {
    "a": 2,
    "b": 1
  }
}

実験手順(ColabでもOK)

必要ライブラリの準備

!pip install transformers accelerate torch

KAT-Devモデルをロード

from transformers import AutoTokenizer, AutoModelForCausalLM
model_name = "Kwaipilot/KAT-Dev"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")

自然言語で依頼

prompt = "JSONファイルを読み込み、キーをアルファベット順に並べ替えるPythonスクリプトを書いてください。CLI引数と例外処理も入れてください。"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=800)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

出力スクリプトを保存して実行

# 出力コードをファイルに保存
with open("sort_json.py", "w", encoding="utf-8") as f:
    f.write("""(↑のコード出力をここにペースト)""")

# テスト用JSONを作成
import json
sample = {"zebra": {"b": 1, "a": 2}, "apple": [{"y": 2, "x": 1}]}
with open("input.json", "w", encoding="utf-8") as f:
    json.dump(sample, f, ensure_ascii=False, indent=2)

# 実行
!python sort_json.py --in input.json --out output.json
!cat output.json

おすすめの用途

シーン 活用イメージ
🧮 データ整形スクリプトの自動生成 「CSVを読み込んで集計」「JSONをマージして整形」など、自然言語でコード生成。
💻 CLIツールの雛形作成 argparse付きのテンプレートを瞬時に生成して自分用に改造。
📚 教育・教材作成 「AIが書いたコード」を題材に、構造や例外処理を学習。
🧠 ペアプロAIとして利用 “AI同僚”として、ロジックやリファクタを会話しながら作成。

まとめ

KAT-Devは単なるコード生成AIではなく、「考えながら書ける」ペアプロAIに近い存在。自然言語で構造・入出力・エラーハンドリングを指定すると、人間が意図する“ちょうど良い形”でコードを出してくれます。

実験して感じたのは、

「もう、“書く”より“話す”ほうが早い。」

ということ。
コードを書く未来より、「AIに設計を伝える未来」が現実味を帯びています。

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

Twitter
Medium
GitHub

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?