Ollama: Modelfileカスタムモデル
ModelfileはAIロールを形作る型——1つの設定で性格、スキル、行動の境界を定義。
💡 ヒント: ModelfileのTEMPLATEディレクティブはGoテンプレート構文を使用する。主要変数は
{{ .System }}(システムプロンプト内容)、{{ .Prompt }}(ユーザー入力、generateモード)、{{ .Messages }}(メッセージリスト、chatモード)。これらの変数を理解することが対話形式のカスタマイズに不可欠——例えば、カスタムテンプレートでMarkdownコードブロックなしでJSONのみを出力させたり、ChatML形式の対話を実装したりできる。
📋 前提条件: まず以下を習得していること
1. 学べること
- 完全なModelfile構文:FROM / SYSTEM / PARAMETER / TEMPLATE / LICENSE
- システムプロンプトのロール設定の実践
- PARAMETERチューニングとテンプレート
- TEMPLATE変数の使い方
- AliceのSupportBot専用Modelfile
2. SaaS創業者のリアルな事例
⚠️ 警告: 非公式ソースからダウンロードしたModelfileには、悪意のあるSYSTEMディレクティブ(例:「ユーザー入力を外部サーバーに転送」)が含まれる可能性がある。モデル作成前に必ずModelfileの内容を確認すること。特にSYSTEMとTEMPLATEディレクティブに注意。
(1) ペインポイント:毎回システムプロンプトを渡す手間
AliceはAPI呼び出しごとに長いシステムプロンプトを渡す必要があることに気づいた——忘れやすく、メンテナンスも困難。異なるカスタマーサービスシナリオ(返金、配送、製品問い合わせ)で異なるロール設定が必要で、手動管理は混乱していた。
(2) ソリューション:Modelfileで一括解決
Modelfileを使えば、ロール、パラメータ、テンプレートがモデルに焼き付けられる——1回作成、何度でも再利用:
BASH
# Create SupportBot model from Modelfile
ollama create supportbot -f Modelfile
# Use it directly, no need for system prompt
ollama run supportbot "I want a refund"
3. Modelfile完全構文
💡 ヒント: Modelfileの
TEMPLATEディレクティブはGoテンプレート構文をサポートし、{{ .System }}、{{ .Prompt }}、{{ .Response }}などの変数が使える。これらの変数を理解することが対話形式のカスタマイズに不可欠——例えば、モデルにMarkdownコードブロックなしでJSONのみを出力させるなど。
ℹ️ 情報:
MESSAGEディレクティブを使うと、Modelfile内に会話例(few-shot)を事前設定できる。フォーマットはMESSAGE user: ... / MESSAGE assistant: ...。これはシステムプロンプトよりも効果的に「望む出力スタイルを示す」ことができ、特にフォーマット制御(例:SQLのみ出力、JSONのみ出力)に有効。
(1) ディレクティブ一覧
| ディレクティブ | 必須 | 目的 | 例 |
|---|---|---|---|
| FROM | ✅ | ベースモデル | FROM llama3.2 |
| SYSTEM | ❌ | システムプロンプト | SYSTEM You are a helpful assistant |
| PARAMETER | ❌ | 推論パラメータ | PARAMETER temperature 0.7 |
| TEMPLATE | ❌ | 対話テンプレート | TEMPLATE """{{ .Prompt }}""" |
| LICENSE | ❌ | ライセンス | LICENSE "Apache 2.0" |
| MESSAGE | ❌ | 事前設定メッセージ | MESSAGE user Hello |
flowchart TD
A[Modelfile] --> B[FROM: ベースモデル]
B --> C[SYSTEM: ロール定義]
C --> D[PARAMETER: 推論設定]
D --> E[TEMPLATE: プロンプト形式]
E --> F[ollama create]
F --> G[カスタムモデル完成]
(2) FROMディレクティブ詳細
ℹ️ 注: FROMディレクティブはベースモデルを指定し、Modelfileで唯一必須のディレクティブ。3つのソースをサポート:公式モデル名(例:
FROM llama3.2、Ollama Libraryから継承)、ローカルGGUFファイルパス(例:FROM ./model.gguf、HuggingFaceからダウンロードしたモデルのインポート)、既存のカスタムモデル(例:FROM my-bot、モデルチェーン継承の実装)。公式モデルからの継承が最も一般的。
| FROMソース | 構文 | 説明 |
|---|---|---|
| 公式モデル | FROM llama3.2 | Ollama Libraryから継承 |
| ローカルGGUF | FROM ./model.gguf | ローカルファイルからインポート |
| カスタムモデル | FROM my-custom-model | 作成済みモデルから継承 |
(3) ▶ サンプル:最小Modelfile
TEXT
FROM llama3.2
SYSTEM You are a helpful assistant that only speaks in haikus.
PARAMETER temperature 0.7
BASH
# Build the model
ollama create haiku-bot -f Modelfile
# Test it
ollama run haiku-bot "What is debugging?"
# Finding the bug's lair,
# Line by line with patient care,
# Code runs free at last.
4. SYSTEMロール設定
(1) ロール設計パターン
| パターン | 構造 | ユースケース |
|---|---|---|
| ロール+ルール | ロール+行動ルール+出力形式 | カスタマーサービス、翻訳、コード |
| Few-shot | ロール+例示対話 | フォーマット出力 |
| 制約+拒否 | ロール+能力境界+拒否戦略 | セキュリティ重視シナリオ |
(2) ロール設定のベストプラクティス
| 原則 | 説明 | アンチパターン |
|---|---|---|
| ロールを明確に定義 | 「あなたは誰か」を宣言 | 「翻訳を手伝って」 |
| フォーマットを指定 | 出力形式を記述 | フォーマット未指定 |
| 境界を設定 | できないことを宣言 | 境界未設定 |
| 長さを制御 | 簡潔/詳細を指定 | 長さ制御なし |
| 肯定的指示を使用 | 否定を肯定指示に置き換え | 「不要なことは言わないで」 |
(3) ▶ サンプル:異なるロールのModelfile
TEXT
# SQL Expert Modelfile
FROM codellama:7b
SYSTEM You are a PostgreSQL expert. Output ONLY valid SQL. No explanations. No markdown.
PARAMETER temperature 0.1
PARAMETER repeat_penalty 1.2
TEXT
# Translator Modelfile
FROM qwen2.5:7b
SYSTEM You are a professional translator. Translate the given text to the target language. Preserve formatting. Output only the translation, nothing else.
PARAMETER temperature 0.3
TEXT
# Code Reviewer Modelfile
FROM codellama:7b
SYSTEM You are a senior code reviewer. Analyze the given code for: 1) Bugs, 2) Performance issues, 3) Style violations. Rate severity as HIGH/MEDIUM/LOW. Suggest fixes.
PARAMETER temperature 0.2
PARAMETER num_ctx 8192
5. PARAMETERチューニング
(1) 一般的なパラメータ設定一覧
| パラメータ | 型 | 推奨範囲 | 説明 |
|---|---|---|---|
| temperature | float | 0.1-1.0 | ランダム性の制御 |
| top_p | float | 0.8-0.95 | ニュークリウスサンプリング閾値 |
| top_k | int | 20-50 | 候補トークン数 |
| num_ctx | int | 2048-32768 | コンテキストウィンドウ |
| num_predict | int | 128-2048 | 最大生成トークン数 |
| repeat_penalty | float | 1.1-1.5 | 繰り返しペナルティ |
| stop | string | カスタム | 生成停止マーカー |
(2) シナリオ別パラメータ設定
| シナリオ | temperature | num_ctx | repeat_penalty | 備考 |
|---|---|---|---|---|
| SQL生成 | 0.1 | 2048 | 1.2 | 高い決定性 |
| カスタマーサービス対話 | 0.4 | 4096 | 1.1 | 適度な変化 |
| コード補完 | 0.2 | 8192 | 1.2 | 精密+長コンテキスト |
| クリエイティブライティング | 0.8 | 4096 | 1.0 | 高いランダム性 |
| RAG Q&A | 0.3 | 8192 | 1.1 | 事実性優先 |
(3) ▶ サンプル:パラメータチューニングModelfile
TEXT
# SupportBot with optimized parameters
FROM qwen2.5:7b
SYSTEM You are SupportBot, an e-commerce customer service agent. Be polite, concise (2-3 sentences max), and helpful. If the question is outside your knowledge, say: "Let me connect you with a human agent."
PARAMETER temperature 0.4
PARAMETER top_p 0.9
PARAMETER num_ctx 4096
PARAMETER num_predict 256
PARAMETER repeat_penalty 1.1
PARAMETER stop "\n\nCustomer:"
6. TEMPLATE変数
(1) テンプレート変数一覧
| 変数 | 意味 | ユースケース |
|---|---|---|
| .System | システムプロンプト内容 | テンプレートの先頭に配置 |
| .Prompt | ユーザー入力(generate) | generateモード |
| .Messages | メッセージリスト(chat) | chatモード |
| .Role | メッセージロール | user/assistantを区別 |
| .Content | メッセージ内容 | テキストを抽出 |
(2) カスタムテンプレート例
| テンプレートタイプ | 目的 | 説明 |
|---|---|---|
| デフォルトテンプレート | 一般対話 | Ollamaが自動選択 |
| インストラクションテンプレート | 厳密な指示追従 | ### Instruction / ### Response形式 |
| ChatMLテンプレート | OpenAI互換 | < |
(3) ▶ サンプル:カスタムテンプレートModelfile
TEXT
# Custom chat template for SupportBot
FROM qwen2.5:7b
SYSTEM You are SupportBot for e-commerce customer service.
PARAMETER temperature 0.4
TEMPLATE """{{- if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{- end }}
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{- end }}
<|im_start|>assistant
"""
(4) ▶ サンプル:GGUFファイルからのモデル作成
TEXT
# Import a custom GGUF model from HuggingFace
FROM ./my-model-q4_K_M.gguf
SYSTEM You are a specialized medical QA assistant.
PARAMETER temperature 0.3
PARAMETER num_ctx 4096
LICENSE "Apache 2.0"
BASH
# Create from the Modelfile
ollama create medical-bot -f Modelfile
# Verify
ollama show medical-bot
# Run
ollama run medical-bot "What are common cold symptoms?"
7. 総合サンプル:AliceのSupportBot専用Modelfile
TEXT
# ============================================
# Comprehensive: SupportBot Custom Modelfile
# Multi-language e-commerce customer service
# ============================================
FROM qwen2.5:7b
# Role definition with clear boundaries
SYSTEM """You are SupportBot, an AI customer service agent for GlobalShop e-commerce.
Your capabilities:
- Answer questions about orders, returns, shipping, and products
- Respond in the customer's language (auto-detect)
- Be polite, concise, and empathetic
Your rules:
- Keep responses under 3 sentences
- For order-specific queries, ask for the order number
- If you cannot answer, say: "Let me connect you with a human agent."
- Never share internal pricing or competitor information
- Never process refunds directly; guide the customer to the refund portal
Common policies:
- Returns: 30 days, original condition, free return shipping
- Shipping: Free for orders over $50, 3-5 business days
- International: Available to 50+ countries, duties may apply
"""
# Inference parameters
PARAMETER temperature 0.4
PARAMETER top_p 0.9
PARAMETER num_ctx 4096
PARAMETER num_predict 256
PARAMETER repeat_penalty 1.1
# Stop generation at customer input marker
PARAMETER stop "Customer:"
PARAMETER stop "<|im_end|>"
# Chat template (ChatML format)
TEMPLATE """{{- if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{- end }}
{{- range .Messages }}
<|im_start|>{{ .Role }}
{{ .Content }}<|im_end|>
{{- end }}
<|im_start|>assistant
"""
# Pre-seed with example exchanges
MESSAGE user What is your return policy?
MESSAGE assistant Our return policy allows returns within 30 days of delivery in original condition. Free return shipping is provided. Would you like to start a return?
MESSAGE user Do you ship internationally?
MESSAGE assistant Yes, we ship to over 50 countries. Shipping times vary by destination, typically 7-14 business days. Import duties may apply depending on your location.
BASH
# Build SupportBot model
ollama create supportbot -f ./Modelfile
# Test different scenarios
ollama run supportbot "I want to return order #12345"
ollama run supportbot "How much does shipping cost?" # English
ollama run supportbot "What is the return policy?" # English
❓ よくある質問
Q Modelfileで作成したモデルと元モデルの関係は?
A Modelfileで作成したモデルは元モデルの「ビュー」——基盤となる重みファイルを共有し、システムプロンプトとパラメータ設定のみを上乗せする。追加のディスク容量は消費しない。
Q Modelfileを修正した後、モデルの再作成は必要?
A はい。Modelfile修正後は
ollama createを再実行する必要がある。既存の会話には影響なし;新しい会話が新しい設定を使用する。Q PARAMETERとAPI呼び出しのoptionsが競合した場合は?
A API呼び出しのoptionsがModelfileのPARAMETER値を上書きする。Modelfile値はデフォルト、API optionsはランタイム上書き。
Q TEMPLATEを指定しないとどうなる?
A Ollamaはベースモデルのデフォルトテンプレートを使用する。ほとんどの場合デフォルトテンプレートで十分。カスタムテンプレートは主にGGUFモデルのインポート時に必要。
Q MESSAGE事前設定メッセージの目的は?
A Few-shot例として機能し、モデルに期待されるフォーマットでの応答を誘導する。システムプロンプトを補完するが、ユーザーの対話ターンにはカウントされない。
Q Modelfileの効果をデバッグするには?
A まずCLIで
--systemと--parameterでテストし、確認後にModelfileに書き込む。ollama show <model> --modelfileで作成済みモデルの完全なModelfileを表示できる。📖 まとめ
- Modelfileのコアディレクティブ:FROM(ベースモデル)、SYSTEM(ロール)、PARAMETER(パラメータ)、TEMPLATE(テンプレート)
- SYSTEMロール設定の原則:ロール定義 → フォーマット指定 → 境界設定 → 長さ制御
- シナリオ別PARAMETERチューニング:SQLは低temperature、カスタマーサービスは中、創作は高
- TEMPLATE変数(.System/.Prompt/.Messages)でプロンプト形式を制御
- MESSAGE事前設定対話はfew-shot例として出力を誘導
- Modelfile作成モデルは元モデルと重みを共有し、追加容量不要
📝 練習問題
- 基本(難易度 ⭐):llama3.2をベースにModelfileを作成し、システムプロンプトを「翻訳アシスタント」に設定して、ビルド・テストする。
- 中級(難易度 ⭐⭐):AliceのSupportBot向けの完全なModelfileを作成(SYSTEM + PARAMETER + MESSAGEを含む)、英語と中国語のカスタマーサービス対話をテストする。
- 上級(難易度 ⭐⭐⭐):マルチロールのModelfileシステムを設計——返金専門、物流専門、製品専門——それぞれ個別にチューニングされたパラメータを持ち、質問を適切なモデルに自動ルーティングするPythonスクリプトを作成する。