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

"[llama-cpp-pythonを使ってGemmaモデルを使ったOpenAI互換サーバーを起動しSpring AIからアクセスする](/entries/778)"と同じ要領でMetaの[Llama 3](https://huggingface.co/meta-llama/Meta-Llama-3-8B)を試します。


**目次**
<!-- 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="llama-3"`は以下のコミットでサポートされたので、v0.2.64以上を使用してください。

https://github.com/abetlen/llama-cpp-python/commit/8559e8ce88b7c7343004eeccb7333b806034b01c

### Llama 3のダウンロード


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

llama-cpp-pythonで利用するモデルはGGUF形式である必要があるので、今回はGGUF形式に変換された以下のモデルを使用します。

https://huggingface.co/QuantFactory/Meta-Llama-3-8B-Instruct-GGUF

`Meta-Llama-3-8B-Instruct.Q4_K_M.gguf`を`/opt/models/`にダウンロードしてください。

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

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

```
python3 -m llama_cpp.server --chat_format=llama-3 --model /opt/models/Meta-Llama-3-8B-Instruct.Q4_K_M.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-755f1cc0-39e1-408c-b119-11034492b500",
  "object": "chat.completion",
  "created": 1715328366,
  "model": "/opt/models/Meta-Llama-3-8B-Instruct.Q4_K_M.gguf",
  "choices": [
    {
      "index": 0,
      "message": {
        "content": "Here's one:\n\nWhy couldn't the bicycle stand up by itself?\n\n(Wait for it...)\n\nBecause it was two-tired!\n\nHope that made you laugh!",
        "role": "assistant"
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 17,
    "completion_tokens": 32,
    "total_tokens": 49
  }
}
```

#### 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
Here's one:

Why couldn't the bicycle stand up by itself?

(Wait for it...)

Because it was two-tired!

Hope that made you smile! Do you want to hear another one?
```

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

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