【Ollama】ローカル環境でLLM推論が可能!特徴や使い方を徹底解説

「ローカル環境で手軽にLLM推論したい」「機密性の高いデータを保護しつつ高度な言語処理したい」などの悩みを一度でも持ったことがある方、その悩みを解決するツール「Ollama」についてご説明します!
「Ollama」はllama.cppをバックエンドにしたオープンソースソフトウェア(OSS)です。
しかも、外部サーバーに依存することなく、ローカル環境で高度な言語処理ができるとのこと。つまり、「Ollama」はLLM推論を高速かつユーザーフレンドリーな形で利用できちゃうんです!
そんな「Ollama」について本記事で徹底解説しますので、ぜひ最後までご覧ください!
Ollamaとは?

「Ollama」は、2023年8月にリリースされ、ローカル環境でも高度なLLM推論ができる点が強みのオープンソースのAIツールです。
さまざまな便利機能がリリースされており、2024年12月6日にリリースされたStructured Outputs機能では、JSONスキーマで定義したフォーマットにLLMの出力を制御することが可能になりました。
公式ブログ上では、以下のようなStructed Outputsのユースケースが紹介されているので参考にしてみてください!
- ドキュメントからのデータ解析
- 画像からのデータ抽出
- すべての言語モデルの応答の構造化
- JSONモードよりも高い信頼性と一貫性
Ollamaの特徴
主な特徴は2つあり、
- ローカル環境での動作を重視しており、インターネット接続のない環境でもOK
- llama.cppをベースに設計されているため、ローカル環境でも高速な動作を実現
といったことが可能です!
ローカル環境で利用することで、データ漏えいを防止することはもちろんのこと、インターネット接続に依存せず利用できたり、クラウドサービスの利用コストを削減できたりと多くのメリットを得ることができます。
データのセキュリティを担保したい方、オフライン環境で利用したい方にピッタリなOSSですね!
Ollamaでサポートしている言語モデル
Ollamaは様々な言語モデルに対応しており、ユースケースに応じて最適なモデルを選択することが可能です。
モデル | ユースケース |
---|---|
Llama 3 | 文章生成、要約、校正 |
Llama 2 | チャットボット、対話型AI |
Gemma 2 | 医療や法務のテキスト解析 |
Mistral | 意味解析、感情分析 |
Moondream 2 | 創作、感情に基づく文章生成 |
Neural Chat | カスタマーサポート、音声アシスタント |
Starling | 質問応答、検索エンジン |
Code Llama | コード生成、デバッグ |
LLaVA | 画像キャプション生成、画像認識 |
Solar | 情報検索、FAQ自動回答 |
DeepSeek-R1 | 数学、コード、推論の各タスクにおいてOpenAI-o1に匹敵 |
DeepSeek-R1については、LlamaとQwenをベースとした6つの蒸留モデルと通常モデルに対応しています。
ローカル環境で、これだけ多くのユースケースに対応できるのはありがたいですね!ぜひ、ご自身のプロジェクトに適したモデル探しの参考にしてみてください!
ライセンス
ライセンス詳細は以下の通りです。
利用用途 | 可否 |
---|---|
商用利用 | ⭕ |
改変 | ⭕ |
配布 | ⭕ |
特許利用 | ⭕ |
私的利用 | ⭕ |
商用利用も可能ですが、利用するモデル自体のライセンスも確認するようにしましょう。
Ollamaの使い方
ここからは実際にOllamaを使っていきます。早速Ollamaのインストールを進めていきましょう!
Ollamaのシステム要件
- OS:macOS 12+, Linux, Windows 10+
- RAM:最低8GB(16GB以上推奨)
- ストレージ:モデルによって異なるが、最低10GB以上の空き容量
1.Ollamaのインストール
公式サイトからインストーラーをダウンロードします。

2.インストーラーを実行
インストーラーをダウンロードし、指示に従ってollamaコマンドがターミナル上で動かせるようになれば導入は完了です!
ollama --version
# ollama version is 0.5.7
本記事では、最新バージョン0.5.7を使っていきます。(※2025年1月27日時点)
Ollamaはアクティブに開発が進められていますので、気になる方はリリースノートを参考にしてみてください!
筆者は導入に5分もかからなかったので、お手軽に環境構築できる点も非常にありがたいですね・・!
Ollamaを使う際の注意点
ここまでOllamaの良い点をあげてきましたが、注意点も確認しておきましょう。
- 長期間使用していない場合、初回応答に時間がかかる
- しばらくOllamaを放置していると、再度利用する際にレスポンスタイムが10秒ほどかかる場合があります。
- GPUのメモリが乗りっぱなしになる
- デフォルトでは「モデルをロードしたままにするタイムアウト設定」がされていて、しばらく(たとえば5分間)操作が無い場合にGPUメモリを解放する仕組みがなされています。GPUメモリの占有が続くので、他の処理でGPUを使いたい場合はリソースを圧迫してしまうことになります。
メモリについての対策として、「アイドル状態(何もしない状態)が 600 秒(10 分)になったら GPU のメモリを解放する」などと追記することがあげられます。
短くしたい場合は、600の部分を60(1分)や180(3分)等に変更することもできるので、GPU乗りっぱなし問題はこれで解決できると思います!
ollama serve --idle-timeout 600
しかし、フラグの書式や単位(秒 or 分)は、使用しているOllamaのバージョンやビルドによって異なる場合があるので、ollama serve –helpコマンドや最新ドキュメントを確認するようにしましょう。
OllamaでLlama-3-ELYZA-JP-8Bを動かしてみた
ここからは実際に、日本語に特化した大規模言語モデル「Llama-3-ELYZA-JP-8B」を動かしてみます!
Llama-3-ELYZA-JP-8Bは、ELYZA社が提供する「ELYZA LLM for JP」シリーズの最新モデルとして、Meta社の「Llama 3」をベースとした80億パラメータの大規模言語モデルです。
80億パラメータの軽量なモデルでありながら、「GPT-3.5 Turbo」や「Claude 3 Haiku」、「Gemini 1.0 Pro」に匹敵すると言われています。
今回使用したいモデルは、Ollamaで標準サポートされていないため、自分で「Modelfile」を作成して、追加していきます。
1.モデルダウンロード
Hugging Faceから「Llama-3-ELYZA-JP-8B-q4_k_m.gguf」をダウンロードします。
参照:https://huggingface.co/elyza/Llama-3-ELYZA-JP-8B-GGUF/blob/main/Llama-3-ELYZA-JP-8B-q4_k_m.gguf
2.ファイル作成
Modelfileを作成し、Llama3モデルと同じ内容になるように、以下の設定を記述します。
FROM ./Llama-3-ELYZA-JP-8B-q4_k_m.gguf
TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|>
{{ .System }}<|eot_id|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|>
{{ .Prompt }}<|eot_id|>{{ end }}<|start_header_id|>assistant<|end_header_id|>
{{ .Response }}<|eot_id|>"""
PARAMETER stop "<|start_header_id|>"
PARAMETER stop "<|end_header_id|>"
PARAMETER stop "<|eot_id|>"
PARAMETER stop "<|reserved_special_token"
3.モデル作成
以下コマンドを実行して、2で作成したファイルからモデルを作成します。
ollama create elyza:jp8b -f Modelfile
10秒ほどで作成が完了しました!
4.モデル実行
以下のコマンドでモデルを実行します。
ollama run elyza:jp8b
5.プロンプト(>>>)入力
モデルを実行すると以下のような入力欄が表示されるので、色々試していきましょう!

> ollama run elyza:jp8b<br>>>> Send a message (/? for help)
一問一答(Q.歴代で最も興行収入が高い映画は?)

回答
世界の興行収入ランキングトップ10(Box Office Mojo調べ)に基づく情報です。
2023年現在、歴代で最も興行収入が高い映画は「アバター」(2009年)です。
興行収入:27億5600万ドル(約3034億円)
ジェームズ・キャメロン監督作品で、SF大作の金字塔と評されています。3D映像技術を駆使し、壮大な世界観と独特のストーリーが話題になりました。
2021年には、ディズニー映画「スター・ウォーズ/スカイウォーターの夜明け」が興行収入24億ドル超えしてランクインしましたが、「アバター」を超えるには至りませんでした。
一問一答(Q.最初に宇宙へ行った人は誰で、いつ?)

回答
最初に宇宙へ行った人は、ユーリ・ガガリーンというソビエト連邦の飛行士です。彼は1961年4月12日、ソ連の宇宙船「ヴォストーク1号」に搭乗し、高度約200kmの地球の大気圏まで到達しました。
この時、ガガーリンは27歳でした。彼は世界は初の有人宇宙飛行を成功させましたが、その直後、機体の問題で大急ぎで帰還する必要があり、地球の重力に適応する時間もなく、僅か9分間という短い時間で地上に戻りました。
この歴史的事件は「ガガーリン宇宙飛行」と呼ばれ、世界中で大きな話題を呼びました。
アルゴリズム実装(Q.クイックソートをPythonで書いてください)

回答
以下は、Pythonでクイックソートを実装した例です。
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
この関数は、クイックソートの基本的なアルゴリズムに従っています。まず、配列の長さが1以下の場合にはそのまま返します。次に、配列の真ん中の要素をピボットとして選びます。左側の要素はピボットより小さいもの、右側の要素はピボットより大きいものに分けます。最後に、左側と右側の部分を再度クイックソートして、結果を連結します。
この関数を使用するには、以下のように呼び出します。
arr = [5, 2, 8, 3, 1, 6, 4]
arr = quicksort(arr)
print(arr)
自然な文章が返ってきました!!!
速度も充分で、オフラインでここまで出来ちゃうOllama、圧巻です・・・!
他にも、翻訳や要約、プロンプトエンジニアリングなど活用できそうなので、興味のある方はぜひ試してみてください!
OllamaでDeepSeek-R1:1.5Bを動かしてみた
続いて、DeepSeek-R1の蒸留モデルであり、最軽量モデル「DeepSeek-R1-Distill-Qwen-1.5B」を試してみます!
1.モデルダウンロード
Ollama DeepSeek-R1サポートページからモデルをダウンロードします。まずは、ドロップダウンから「1.5b」を選択します。

すると以下の画像の通り、モデルダウンロード用コマンドが表示されるので、クリップボードにコピーしましょう。

2.モデル実行
先ほどコピーしたコマンドをターミナルで実行します。
ollama run deepseek-r1:1.5b
ダウンロードが完了すると以下のようにプロンプトが打ち込める状態になるので、これでモデルの実行は完了です。

3.プロンプト入力(>>>)
せっかくなので、「Llama-3-ELYZA-JP-8B」と同じプロンプトで出力結果の比較検証をしてみましょう。
アルゴリズム実装(Q.クイックソートをPythonで書いてください)
回答
<think>
Alright, the user is asking for a Quicksort implementation in Python. I
need to provide a clear and concise solution.
I'll structure the code step by step, explaining each part so it's easy to
follow.
First, I'll write the function definition with parameters arr and return.
Next, the base case: if the array has one or zero elements, just return it
as is.
Then, I'll choose a pivot. For simplicity, I'm choosing the last element.
After that, partition the array into elements less than pivot, equal to,
and greater than.
I'll handle the equal part recursively by sorting the smaller subarray.
Finally, concatenate the sorted parts: less + equal (sorted) + greater.
I should test it with a simple example to ensure it works.
Make sure to add comments explaining each step so the user understands how
the code functions.
</think>
はい! Quicksort は要素をative分のwayで、最eadyが選択し、要素が左右に分
classified します。 下の例を参考に writing your own implementation of
QuickSort in Python。
以下は Quicksort 的算法を Python で示した code です:
```python
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
less = [x for x in arr[:-1] if x < pivot]
greater = [x for x in arr[:-1] if x > pivot]
equal = [x for x in arr[:-1] if x == pivot]
equal_sorted = quicksort(equal)
return quicksort(less) + equal_sorted + quicksort(greater)
# 試行
print(quicksort([3, 6, 8, 10, 1, 2, 1]))
```
### 実際の codedecription:
- **Pivot**: 最eadyの要素を用いています。この例では `arr[-1]` 即然是 `1`。
- **Partition**: 順数が `pivot` 下に分 classified します。
- 最初から `pivot` 下の要素を `\ : arr[:-1]`
- 左の要素は `x < pivot`
- 右の要素は `x > pivot`
### 実際の operation:
- `less` : 探索が `pivot` 下に `$less = [x for x in arr[:-1] if x <
pivot]`
- `greater`: 探索が `pivot` 下に `$greater = [x for x in arr[:-1]
if x > pivot]`
### 等同の要素:
- `[x for x in arr[:-1] if x == pivot]`
### 記号解释:
- 等同の要素を recursively sort し、sorted 形式で再 \% 多数に分 classified
します。
- 最eady `quicksort(less)` と `quicksort(greater)`を回 \ `{return
quicksort(less) + equal_sorted + quicksort(greater)`
### 実際の result:
```
[1, 2, 3, 1, 6, 8, 10]
```
Quicksort は平均 `{O(n log n)}` 时间で実現します。最eadyの要素の候補が `\
: arr[:-1]` 形式で `[x for x in arr[:-1] if x < pivot]`を用いています。
中国語混じりの不自然な日本語で返ってきてしまいました。
解消法
日本語で出力するよう指示(※)してもいいですが、毎回やるのも面倒なので、システムを修正しちゃいましょう!
※参考:https://x.com/itnavi2022/status/1881579155042824218
ひとまず、「/bye」でOllamaから抜けます。
その後、適当に空のディレクトリへ移動し、以下のコマンドを叩きます。
ollama show --modelfile deepseek-r1:1.5b > Modelfile
ls -la
以下の画像のような出力が出るので、赤枠のModelfileをテキストエディタで開いて修正していきます。

修正する箇所は2つです。
- 6行目に「FROM deepseek-r1:1.5b」を追記
- 7行目に「SYSTEM “””You are a highly proficient Japanese-speaking AI assistant. You must conduct all conversations with users in Japanese. **Crucially, you must think and formulate your responses in Japanese.**”””」を追記
修正後のModelfile完成イメージは以下の通りです。

修正したModelfileをもとにモデルを作成するため、以下のコマンドを叩きます。
ollama create deepseek-r1-1.5b-jp -f ./Modelfile
生成後、モデルが問題なく作られているか、Ollamaのリストを確認してください。

これで日本語対応できているはずなので、再度モデルを実行してプロンプト入力していきます。
ollama run deepseek-r1:1.5b-jp:latest
Prompt:<strong>クイックソートをPythonで書いてください</strong>
修正後の回答
<think>
Alright, so I need to write a Python program that can perform a quick
sort. Hmm, quick sort is one of the most efficient sorting algorithms out
there, right? It works by selecting a pivot element and rearranging the
elements such that all elements less than the pivot come before it, and
those greater come after.
First, I should plan how to structure this program. The input will be an
array, so I'll start by reading that from standard input. That's easy
enough with the input() function in Python. But wait, what if the user
doesn't enter anything? Oh right, I should handle that case too, maybe
with a try-except block.
Once the input is read, the core of quick sort is partitioning the array.
So I need to select a pivot and split the array into elements less than or
equal to the pivot and those greater. I'll choose a random element as the
pivot because it makes the algorithm more efficient on average by reducing
the number of comparisons.
Next, I have to recursively apply the same process to the subarrays on
either side of the pivot until the entire array is sorted.
I should think about data types. The array elements can be integers or
maybe strings? Looking back at the user's message, it seems like they want
a numerical sort, so probably integers are intended.
Now, how to handle edge cases? For example, if all elements are the same,
the algorithm should still work fine without issues. Also, for even and
odd numbers of elements, quick sort handles them well as long as the
recursion isn't too deep. But Python's default recursion depth limit might
be a problem for large arrays; I'll need to consider that or switch to an
iterative approach if necessary.
Testing is important. I should write test cases where I can manually check
what the sorted array should look like and ensure my code produces it
correctly.
I also want to make sure that the function returns a new list each time,
so the original input isn't modified. That's already handled by returning
a new array at each step.
Another thing is how the pivot is chosen. For randomization, using the
random module's choice function would be better than just taking the first
element or an index from a range. Maybe something like selecting between 0
and len(arr)-1 with random.randint(0, len(arr)-1).
Wait, but if I'm modifying the list during partitioning, will that affect
subsequent calls? No, because each recursive call operates on its own
subarray, so it's safe.
I should also be cautious about using recursion in a way that might hit
Python's stack limit. If the input array is too long, say over 10^4
elements, this could cause a maximum recursion depth error or slow
performance. But perhaps for most cases, especially with small inputs, it
works fine.
Putting it all together, I'll structure my program like this:
1. Read the input using input() and handle any possible exceptions.
2. Define a recursive function to perform quick sort.
3. In the function:
a. Select a random pivot index.
b. Partition the array into elements less than or equal to the pivot
and those greater.
c. Recursively apply quick sort on the subarrays.
4. Call the function with the input array and print the sorted result.
I think that's a solid plan. Now, I'll translate this into Python code,
making sure everything is in Japanese as per the user's request.
</think>
```
def 快速 SORT:
# 誰ががとる?
pivot = random.randrange(len(arr))
arr[pivot], arr[0] = arr[0], arr[pivot]
# 接 rounding 选gt;
# 掛けgt;
less, greater = [], []
for num in arr:
if num <= arr[0]:
less.append(num)
elif num > arr[0]:
greater.append(num)
return 快速 SORT(less) + [arr[0]] + 快速 SORT(greater)
# 引数を入力
arr = input().strip()
# 定 number が整 数?
try:
if arr == '':
print('')
exit()
except ValueError as e:
print(e)
# 快速 SORT Done?
print 快速 SORT(arr)
```
検証結果
- Modelfile修正前ほどではないが、不完全な日本語で出力が返ってくる。
- 現状、日本語だと精度が下がるため、英語や中国語で実行させる方が良さそう。
- 「Llama-3-ELYZA-JP-8B」と比較すると、一部デバッグは必要ですが、コード自体の生成クオリティや生成スピードは問題なし。
まとめ
今回はOllamaで「Llama-3-ELYZA-JP-8B」と「DeepSeek-R1:1.5B」を動かしてみました!実装自体は簡単だったので、ローカルLLMを活用したいという方はまずここから試してみるもの良いのでは?と感じました。
そんなOllamaの特長は以下の内容でした!
メリット
- 外部サーバーに依存せず、ローカル環境で高度な言語処理が可能
- データのセキュリティを確保しながらLLMを活用可能
- 商用利用可能なライセンス体系
- 豊富な言語モデルに対応し、用途に応じて選択可能
外部サーバーに依存することなく、ローカル環境で高度な言語処理ができるので、活用法次第で自分専用のLLMを作れちゃう気がしました!今後のアップデートも楽しみです!
最後に
いかがだったでしょうか?
ローカル環境でのLLM推論やデータ保護が必要な場合、選択肢として「Ollama」を検討してみてください。
株式会社WEELは、自社・業務特化の効果が出るAIプロダクト開発が強みです!
開発実績として、
・新規事業室での「リサーチ」「分析」「事業計画検討」を70%自動化するAIエージェント
・社内お問い合わせの1次回答を自動化するRAG型のチャットボット
・過去事例や最新情報を加味して、10秒で記事のたたき台を作成できるAIプロダクト
・お客様からのメール対応の工数を80%削減したAIメール
・サーバーやAI PCを活用したオンプレでの生成AI活用
・生徒の感情や学習状況を踏まえ、勉強をアシストするAIアシスタント
などの開発実績がございます。
まずは、「無料相談」にてご相談を承っておりますので、ご興味がある方はぜひご連絡ください。

「生成AIを社内で活用したい」「生成AIの事業をやっていきたい」という方に向けて、生成AI社内セミナー・勉強会をさせていただいております。
セミナー内容や料金については、ご相談ください。
また、サービス紹介資料もご用意しておりますので、併せてご確認ください。