6
2

【ローカルLLM】Ollama Python Libraryのメソッド一覧と動作例

Last updated at Posted at 2024-06-23

準備

Ollama Python Libraryのインストール

Ollamaは下記より入手・インストールが可能です。
https://ollama.com/

Ollamaを実際に使用するにあたっては、Ollamaのアプリケーションを起動したのちに、下記のようなコマンドを実行すれば良いです。

$ ollama run phi3

上記を実行すると、ローカルにPhi-3-Miniのモデルファイルがない場合は自動的に入手してくれます。そのため、1度目の起動時に数GBの通信が必要になります。上記ではPhi-3-Miniを入手しますが、下記を実行することでLlama 3を入手することも可能です。

$ ollama run llama3

また、Ollama Pythonはpip install ollamaを実行することでPyPIより入手が可能です。

メソッドのまとめにあたって

https://github.com/ollama/ollama-python
上記に記載のあるメソッドについて取りまとめを行います。

import ollama
response = ollama.chat(model='llama3', messages=[
  {
    'role': 'user',
    'content': 'Why is the sky blue?',
  },
])
print(response['message']['content'])

上記がサンプルコードです。実行すると下記のような結果が得られます。

The sky appears blue to us due to a phenomenon called Rayleigh scattering. As sunlight travels through Earth's atmosphere, it interacts with gas molecules and tiny particles. Sunlight consists of different colors of light, each having varying wavelengths. Blue light has shorter wavelengths compared to other colors in the visible spectrum....

Ollama Python Libraryのメソッド一覧と動作例

メソッドまとめ

メソッド名 機能
chat ユーザーの入力に対し、返答を返す
generate ユーザーの入力に対し、返答を返す
list インストール済みのモデルの一覧を取得
show 指定したモデルの詳細を確認する
create modelfileに基づいて新たなモデルを構築する
copy モデルをコピーする
delete モデルを消去する
pull ollama libraryからモデルを取得する
push model libraryにモデルをアップロードする
embeddings 入力した文章に対応するembeddingを返す、デフォルトの次元はphi3は3072、llamaは4096
ps 直前に動かしたモデルについて返す

動作例

chat

import ollama

response1 = ollama.chat(model='llama3', messages=[
  {
    'role': 'user',
    'content': 'What is the capital of France? (Only capital name)',
  },
])
response2 = ollama.chat(model='llama3', messages=[
  {
    'role': 'user',
    'content': 'And what about Germany? (Only capital name)',
  },
])

print(response1['message']['content'])
print(response2['message']['content'])

・実行結果

Paris
Berlin

generate

import ollama

response1 = ollama.generate(model='phi3', prompt='What is the capital of France? (Only capital name)')
response2 = ollama.generate(model='phi3', prompt='And what about Germany? (Only capital name)')

print(response1['response'])
print(response2['response'])

・実行結果

Paris
Berlin

embedding

import ollama

response = ollama.embeddings(model='llama3', prompt='The sky is blue because of rayleigh scattering')

print(len(response['embedding']))

・実行結果

3072
import ollama

response = ollama.embeddings(model='llama3', prompt='The sky is blue because of rayleigh scattering')

print(len(response['embedding']))

・実行結果

4096

参考

・Ollama API
https://github.com/ollama/ollama/blob/main/docs/api.md

・Ollama Python Library
https://github.com/ollama/ollama-python

6
2
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
6
2