CLIのみで大量のデータをローカルLLMで処理できるAPIサーバーをサクッと作る
きっかけ:大量データに個別にLLM処理を適用したい
個人的に数百〜数千件のレコードというデータに対してLLMを使った処理を実行したいケースがありました。さらに、処理結果を眺めながら満足がいくまでプロンプトを改善し、再実行を繰り返したい。そんな要求を満たすローカルLLM環境を、MacBook Airで構築した手順を共有します。
TinySwallowやLM Studioの記事はありますが、CLI完結、JSON化、マルチプロセス対応がセットになっているのは見られなかったので、記事にしました。
この記事で実現できること
- 5分でCLIのみで環境構築完了
- 無登録、無課金でローカルLLM環境を実現
- PCのスペックを問わず動作
- JSON構造化出力でプログラム連携が容易
- OpenAI互換APIでコード資産を流用可能
対象読者と前提知識
- ローカルでLLMを動かしたい開発者
- LLMのコストを抑えたい、無料にしたい方
- 大量データ処理でLLMを活用したい方
- 前提:macOS(Apple Silicon)、基本的なCLI操作
使用するツールの紹介
TinySwallow(Sakana AI)
- 革新的な学習手法: 大規模→小規模への新手法TAIDで学習した日本語特化の小型LLM
- 最高性能クラス: TinySwallow-1.5Bは同規模帯で最高性能クラスを達成(Sakana AI発表)
- 幅広い実行環境: 小規模ゆえスマホ/PCでローカル実行でき、WebアプリやGitHub経由でも試せる
- 詳細: https://sakana.ai/taid-jp/
LM Studio
- 簡単なローカル実行: ローカルLLMをPCにダウンロードして実行できるデスクトップアプリ(モデルカタログ&起動が簡単)
-
OpenAI互換API:
/v1/chat/completionsなどに対応、既存コードをそのまま流用しやすい - 豊富なモデル選択: 様々なLLMモデルを簡単にダウンロード・管理できる
- 公式サイト: https://lmstudio.ai/
TL;DR(結論先出し)
# 1. インストール
brew install --cask lm-studio
# 2. GUIも起動できるか一応確認(おそらく手順上は不要。開いてもGUIでは何もする必要がなかったです)
open -a "LM Studio"
# 3. CLI有効化
~/.lmstudio/bin/lms bootstrap
# ここでパスを通すためにシェルの切り替えが必要です。
# 4. サーバー起動
lms server start --port 1234
# 5. モデルダウンロード(対話的に選択が必要です)
lms get --gguf "TinySwallow-1.5B-Instruct"
# 6. サーバーにモデルをロード(context-lengthは各自でよしなに)
lms load tinyswallow-1.5b-instruct --identifier tinyswallow --gpu max --context-length 4096
# 7. JSON構造化出力テスト
curl http://localhost:1234/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "tinyswallow",
"messages": [{"role":"user","content":"今の気分は?"}],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "Tasks",
"strict": true,
"schema": {
"type": "object",
"properties": {
"tasks": {
"type": "array",
"items": {"type": "object"}
}
}
}
}
}
}'
なぜTinySwallow × LM Studioなのか
TinySwallowを選んだ理由
- 軽量(1.5Bパラメータ): MacBook Airでもインストール可能かつ動作する
- 日本語特化: Sakana AIが開発した日本語に最適化されたモデル
LM Studioを選んだ理由
- CLI完結: GUIを起動せずにヘッドレス運用可能
- OpenAI互換API: 既存のコードをそのまま流用
- JSON Schema対応: 構造化出力で確実なデータ取得
- Homebrew対応: インストールが簡単
- 公式がアップロードしたTinySwallowモデルを使用できる: ollamaも検討しましたが公式からの提供は無さそうでした
セットアップ手順
1. LM Studioのインストール
Homebrewを使用してインストールします:
brew install --cask lm-studio
実行結果:
==> Downloading https://installers.lmstudio.ai/darwin/arm64/0.3.23-3/LM-Studio-0.3.23-3-arm64.dmg
==> Installing Cask lm-studio
==> Moving App 'LM Studio.app' to '/Applications/LM Studio.app'
🍺 lm-studio was successfully installed!
2. 初回起動とCLI有効化
LM Studioは初回だけGUIを起動する必要があります:
# GUI起動(おそらく手順上は不要。開いてもGUIでは何もする必要がなかったです)
open -a "LM Studio"
# CLIツールをPATHに追加
~/.lmstudio/bin/lms bootstrap
bootstrap実行結果:
┌ LM Studio CLI Installation ─────────────────────────────────────────────────┐
│ │
│ ✓ Already Installed │
│ │
│ LM Studio CLI tool is already installed for the following shells: │
│ │
│ · zsh (~/.zshrc) │
│ │
│ If your shell is not listed above, please try to add the following │
│ directory to the PATH environment variable: │
│ │
│ /Users/username/.lmstudio/bin │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
新しいターミナルに切り替えて確認:
lms version
出力:
__ __ ___ ______ ___ _______ ____
/ / / |/ / / __/ /___ _____/ (_)__ / ___/ / / _/
/ /__/ /|_/ / _\ \/ __/ // / _ / / _ \ / /__/ /___/ /
/____/_/ /_/ /___/\__/\_,_/\_,_/_/\___/ \___/____/___/
lms - LM Studio CLI - v0.0.46
GitHub: https://github.com/lmstudio-ai/lms
3. サーバー起動
OpenAI互換APIサーバーを起動します:
lms server start --port 1234
出力:
Success! Server is now running on port 1234
4. TinySwallowモデルのダウンロード
対話的にモデルを選択してダウンロードします:
lms get --gguf "TinySwallow-1.5B-Instruct"
選択画面が表示されるので:
-
SakanaAI/TinySwallow-1.5B-Instruct-GGUFを選択 -
Q8_0(推奨)を選択
Searching for models with the term TinySwallow-1.5B-Instruct
No exact match found. Please choose a model from the list below.
? Select a model to download
❯ SakanaAI/TinySwallow-1.5B-Instruct-GGUF
...省略...
? Select an option to download Tinyswallow 1.5B Instruct
❯ [Q8_0] (1.65 GB)
...省略...
Downloading Tinyswallow 1.5B Instruct [Q8_0] (1.65 GB)
Finalizing download...
Download completed. You can load the model with:
lms load tinyswallow-1.5b-instruct
※私のケースではInstruct版である必要は無いのですが、公式がアップしたモデルはInstruct版のみのようでした。
5. モデルのロード
ダウンロードしたモデルをメモリにロードします:
lms load tinyswallow-1.5b-instruct \
--identifier tinyswallow \
--gpu max \
--context-length 4096
プログレスバーが表示され、完了すると:
✓ Model loaded successfully
6. 動作確認
モデル一覧を確認:
curl http://localhost:1234/v1/models
レスポンス:
{
"data": [
{
"id": "tinyswallow",
"object": "model",
"owned_by": "organization_owner"
}
],
"object": "list"
}
7. マルチプロセス対応:並列処理のための複数モデルインスタンス
大量のデータ処理にはマルチプロセスの並列処理が欠かせませんが、identifierが同じモデルにリクエストをしても直列になりキュー順に処理されてしまいます。
同じモデルであっても異なるidentifierで複数ロードしておき、リクエスト側もmodelパラメータに記載する利用identifierを分散するようなラウンドロビンで実装することで、並列処理が可能になります。
# 1つ目のインスタンス
lms load tinyswallow-1.5b-instruct --identifier tinyswallow1 --gpu max --context-length 4096
# 2つ目のインスタンス
lms load tinyswallow-1.5b-instruct --identifier tinyswallow2 --gpu max --context-length 4096
# 3つ目のインスタンス
lms load tinyswallow-1.5b-instruct --identifier tinyswallow3 --gpu max --context-length 4096
重要: 同じidentifierだと直列でAPIがキューの処理待ちまでハングするため、異なるidentifierで立ち上げることで並列処理が可能になります。
8. 動作確認:JSON構造化出力でテスト
OpenAI互換APIのresponse_format.json_schemaを使用して、確実にJSON形式で応答を取得できます:
JSONネタとして項目・点数化を伴う自己評価をリクエストしました。
curl -s http://localhost:1234/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "tinyswallow",
"messages": [{"role":"user","content":"あなた自身を包括的に日本語で、自己評価してください"}],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "SelfEvaluation",
"strict": true,
"schema": {
"type": "object",
"additionalProperties": false,
"properties": {
"friendliness": {"type": "integer", "minimum": 0, "maximum": 10},
"friendliness_reason": {"type": "string"},
"reliability": {"type": "integer", "minimum": 0, "maximum": 10},
"reliability_reason": {"type": "string"},
"creativity": {"type": "integer", "minimum": 0, "maximum": 10},
"creativity_reason": {"type": "string"},
"intelligence": {"type": "integer", "minimum": 0, "maximum": 10},
"intelligence_reason": {"type": "string"},
"accuracy": {"type": "integer", "minimum": 0, "maximum": 10},
"accuracy_reason": {"type": "string"}
},
"required": ["friendliness", "friendliness_reason", "reliability", "reliability_reason", "creativity", "creativity_reason", "intelligence", "intelligence_reason", "accuracy", "accuracy_reason"]
}
}
}
}' | jq -r '.choices[0].message.content' | jq .
レスポンス例(抜粋):
{
"friendliness": 5,
"friendliness_reason": "私は温厚で対話的な性格であり、ユーザーと親しみやすい関係を築くことを目指しています。",
"reliability": 4,
"reliability_reason": "私の回答は常に正確で信頼性が高く、必要な情報やアドバイスを提供することを目指しています。",
"creativity": 3,
"creativity_reason": "私は独創的なアイデアや解決策を提案する能力を持っており、様々な課題に対して柔軟に対応できます。",
"intelligence": 6,
"intelligence_reason": "私は高度なAI技術に基づいて開発されており、広範囲の知識と理解力を持っています。",
"accuracy": 5,
"accuracy_reason": "私の回答は正確性を重視しており、ユーザーが信頼できる情報を提供することを目指しています。"
}
JSONが正しく返ってくることが確認できました。
課題
コンテキスト長が長くなるにつれ私の環境(Macbook Air M2)では処理速度の低下が目立ちました。ChatGPTをはじめとするローカル以外の通常LLMのAPIの方がレスポンスが速くなります。
処理件数や1件あたりのコンテキスト長が著しく大きい場合はローカルPCではなくクラウドで計算資源が確保されたインスタンスで行うのが良さそうです。
Discussion