---
title: llama-cpp-pythonを使ってGemmaモデルを使ったOpenAI互換サーバーを起動しSpring AIからアクセスする
tags: ["Python", "llama.cpp", "OpenAI", "Machine Learning", "MPS", "Gemma", "Spring AI"]
categories: ["AI", "LLM", "llama.cpp"]
date: 2024-02-25T07:34:19Z
updated: 2024-05-10T09:18:21Z
---

"[llama-cpp-pythonを使ってローカルLLMでテキスト生成とOpenAI互換サーバーを立てる](/entries/770)"と同じ要領でGoogleの[Gemma](https://huggingface.co/google/gemma-2b)を試します。


**目次**
<!-- toc -->

### llama-cpp-pythonのインストール

まずはvenvを作成します。

```
mkdir -p $HOME/work/llm
cd $HOME/work/llm
python3 -m venv .venv
source .venv/bin/activate
```

llama-cpp-pythonのインストールします。serverも一緒にインストールします。

```
CMAKE_ARGS="-DLLAMA_METAL=on" pip install --force-reinstall --no-cache-dir 'llama-cpp-python[server]'
```

> ℹ️ Apple SiliconのMac上でエラーが出る場合は、 https://github.com/abetlen/llama-cpp-python/blob/main/docs/install/macos.md のセットアップを試してください。

`chat_format="gemma"`は以下のコミットでサポートされたので、v0.2.48以上を使用してください。

https://github.com/abetlen/llama-cpp-python/commit/251a8a2cadb4c0df4671062144d168a7874086a2


### Gemmaのダウンロード


```
sudo mkdir -p /opt/models
sudo chown -R $USER /opt/models
```

7Bのモデルはファイルサイズが大きいので、2Bのモデルをダウンロードします。

https://huggingface.co/google/gemma-2b/tree/main

`gemma-2b.gguf`を`/opt/models/`にダウンロードしてください。

### OpenAI互換サーバーの起動

以下のコマンドでサーバーを立ち上げます。`--chat_format=gemma`を指定する必要があります。

```
python3 -m llama_cpp.server --chat_format=gemma --model /opt/models/gemma-2b-it.gguf --n_gpu_layers 1
```

以下からAPIドキュメントを確認できます。

http://localhost:8000/docs


> OpenAIの["Create chat completion" API](https://platform.openai.com/docs/api-reference/chat/create)は`model`パラメータが必須ですが、<br>
> llama-cpp-pythonの方は`model`パラメータはなくても良いみたいです。

#### curlでアクセス

```
curl -s http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
   "messages": [
      {"role": "user", "content": "Give me a joke."}
   ]
 }' | jq .
```

何かジョークが返ってきました。

```json
{
  "id": "chatcmpl-79f5ae4c-cf47-494c-a82c-a7e3747ab463",
  "object": "chat.completion",
  "created": 1708846379,
  "model": "/opt/models/gemma-2b-it.gguf",
  "choices": [
    {
      "index": 0,
      "message": {
        "content": "Why did the scarecrow win an award?\n\nBecause he was outstanding in his field!",
        "role": "assistant"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 14,
    "completion_tokens": 18,
    "total_tokens": 32
  }
}
```


```
curl -s http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
   "messages": [
      {"role": "user", "content": "日本の首都はどこですか？"}
   ]
 }' | jq .
```

日本語もいけるようです。

```
{
  "id": "chatcmpl-3f111b5e-4244-4cfc-9818-d23b8d04ccb2",
  "object": "chat.completion",
  "created": 1708846400,
  "model": "/opt/models/gemma-2b-it.gguf",
  "choices": [
    {
      "index": 0,
      "message": {
        "content": "日本の首都は東京です。東京は日本の東部に位置し、日本を代表する都市です。",
        "role": "assistant"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 14,
    "completion_tokens": 22,
    "total_tokens": 36
  }
}
```

#### Spring AIでアクセス

[Spring AI](https://docs.spring.io/spring-ai/reference/index.html)を使ったアプリからアクセスしてみます。
OpenAI互換なので、Spring AIの[OpenAI用のChat Client](https://docs.spring.io/spring-ai/reference/api/clients/openai-chat.html)が利用できます。

サンプルアプリはこちらです。<br>
https://github.com/making/hello-spring-ai

```
git clone https://github.com/making/hello-spring-ai
cd hello-spring-ai
./mvnw clean package -DskipTests=true
java -jar target/hello-spring-ai-0.0.1-SNAPSHOT.jar --spring.ai.openai.base-url=http://localhost:8000 --spring.ai.openai.api-key=dummy
```


```
$ curl localhost:8080
What do you call a boomerang that won't come back?

A stick.
```

このアプリ自体はOpenAI向けのアプリですが、プロパティを変えるだけででGemmaも使えるのがllama-cpp-pythonを使う利点ですね。

OpenAI APIとの互換性は気にせず、Gemmaを使いたいだけであれば、[spring-ai-ollama](https://docs.spring.io/spring-ai/reference/api/clients/ollama-chat.html)経由で[Ollama](https://ollama.com/)を使うこともできます。
