Ollama APIを使用してみる

Ollama APIを使用してみる
Photo by Yuvy Dhaliah / Unsplash

前回掲載した「Ollamaを使ってGemma3を動かしてみる」の続きで、今回はOllamaをAPI経由で使ってみたいと思います。

下記のサイトに従って、さっそくAPI経由でGemma3を使ってみましょう。

ollama/docs/api.md at main · ollama/ollama
Get up and running with Llama 3.3, DeepSeek-R1, Phi-4, Gemma 3, and other large language models. - ollama/ollama

「なぜ空は青いの?」というプロンプトを投げてみます。

$ curl http://localhost:11434/api/generate -d '{"model": "gemma3:4b", "prompt": "why is the sky blue?"}'

実行すると、下記のようなJSON形式のトークンが大量に返ってきます。

{"model":"gemma3:4b","created_at":"2025-03-22T07:13:10.853999081Z","response":"Okay","done":false}
{"model":"gemma3:4b","created_at":"2025-03-22T07:13:10.869625184Z","response":",","done":false}
{"model":"gemma3:4b","created_at":"2025-03-22T07:13:10.885367015Z","response":" let","done":false}
・・・
{"model":"gemma3:4b","created_at":"2025-03-22T07:13:18.669263566Z","response":"","done":true,"done_reason":"stop","context":[105,2364,107,36425,563,506,7217,3730,236881,106,107,105,4368,107,19058,236764,1531,236789,…,14958,236881],"total_duration":7932202761,"load_duration":83298185,"prompt_eval_count":15,"prompt_eval_duration":31841824,"eval_count":575,"eval_duration":7816488604}

"response"の後の文字列が返答です。最初のトークンのresponseは「Okay」、次のトークンのresponseは「,」その次は「let」という順です。つなげていくと、「Okay, let 's break down why th sky is blue…」と続いていました。

五月雨式ではなく、1つのJSONオブジェクトとして、レスポンスを受け取りたい場合は、「"stream": false」を設定します。

$ curl http://localhost:11434/api/generate -d '{"model": "gemma3:4b", "prompt": "Why is the sky blue? Please teach in Japanese. ", "stream": false}'

{"model":"gemma3:4b","created_at":"2025-03-22T09:45:51.325515578Z","response":"Okay, let's explain why the sky is blue in Japanese! Here's a breakdown, aiming for clarity and suitable for someone learning the language:\n\n**1. The Basic Explanation (Simple Version):**\n\n「空が青いのは、太陽の光が空気中を散乱するからです。」 **2. A Slightly More Detailed Explanation (More Japanese):**\n\n「太陽の光は、色々な色を含んでいます。例えば、赤やオレンジ、黄色などです。しかし、光は波の形をしていて、波の形は波長(はなが)というもので、波長が短いほど、その色を散らすのが得意です。青い光は波長が短くて、空気中の小さな分子(ぶんし)にぶつかって、四方八方(しほうはちほう)に散らばります。だから、空を見上げると、青い光が私たちの目にたくさん届いて、空が青く見えるのです。」…}

次回は、Pythonを使ってOllamaのAPIを呼び出してみたいと思います。