> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/jp/moderu/tutorials/functiongemma.md).

# FunctionGemma: 実行とファインチューニングの方法

FunctionGemmaをデバイスやスマートフォンでローカルに実行・ファインチューニングする方法を学びましょう。

FunctionGemmaは、Googleによる新しい2.7億パラメータのモデルで、関数呼び出しとファインチューニング向けに設計されています。ベースは [Gemma 3](/docs/jp/moderu/tutorials/gemma-3-how-to-run-and-fine-tune.md) 270Mで、テキストのみのツール呼び出し用に特化して学習されており、その小ささのおかげで自分のスマートフォンにデプロイするのに最適です。

フル精度モデルを次で実行できます: **550MB RAM** （CPU）で、今なら **ファインチューニング** Unslothでローカル実行できます。初日からのサポートのためにUnslothと提携してくださったGoogle DeepMindに感謝します！

<a href="/docs/jp/moderu/tutorials/functiongemma.md#run-functiongemma" class="button secondary">実行チュートリアル</a><a href="/docs/jp/moderu/tutorials/functiongemma.md#fine-tuning-functiongemma" class="button primary">FunctionGemmaのファインチューニング</a>

* 実行するためのFunctionGemma GGUF: [unsloth/functiongemma-270m-it-GGUF](https://huggingface.co/unsloth/functiongemma-270m-it-GGUF)

**無料ノートブック:**

* ファインチューニングして **ツール呼び出しの前に推論/思考する** を使って [FunctionGemmaノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\).ipynb)
* 実行 **マルチターンのツール呼び出し** 無料の [マルチターンツール呼び出しノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-Multi-Turn-Tool-Calling.ipynb)
* ファインチューニングして **モバイル操作を有効化する** （カレンダー、タイマー設定）を、私たちの [モバイルアクションノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-Mobile-Actions.ipynb)

### ⚙️ 使用ガイド

Googleは推論に次の設定を推奨しています:

* `top_k = 64`
* `top_p = 0.95`
* `temperature = 1.0`
* 最大コンテキスト長 = `32,768`&#x20;

チャットテンプレート形式は、以下を使用すると確認できます:

{% code overflow="wrap" %}

```python
def get_today_date():
    """ 今日の日付を取得します """
    return {"today_date": "2025年12月18日"}
    
tokenizer.apply_chat_template(
    [
        {"role" : "user", "content" : "今日は何日ですか？"},
    ],
    tools = [get_today_date], add_generation_prompt = True, tokenize = False,
)
```

{% endcode %}

#### FunctionGemmaのチャットテンプレート形式:

{% hint style="info" %}
FunctionGemmaにはsystemまたは **developerメッセージが必要です** として `以下の関数で関数呼び出しができるモデルです` Unsloth版には、渡し忘れた場合のためにこれが組み込み済みなので、ぜひ次を使ってください [unsloth/functiongemma-270m-it](https://huggingface.co/unsloth/functiongemma-270m-it)
{% endhint %}

{% code overflow="wrap" lineNumbers="true" %}

```
<bos><start_of_turn>developer\n以下の関数で関数呼び出しができるモデルです<start_function_declaration>declaration:get_today_date{description:<escape>今日の日付を取得します<escape>,parameters:{type:<escape>OBJECT<escape>}}<end_function_declaration><end_of_turn>\n<start_of_turn>user\n今日は何日ですか？<end_of_turn>\n<start_of_turn>model\n
```

{% endcode %}

## 🖥️ FunctionGemmaを実行

ローカルデスクトップ向けガイドは下記をご覧ください。スマホ向けデプロイガイドも参照できます。

#### Llama.cppチュートリアル（GGUF）:

llama.cpp で実行する手順（ほとんどのデバイスに収めるため、4bit を使用します）：

{% stepper %}
{% step %}
最新の `llama.cpp` を [GitHubこちら](https://github.com/ggml-org/llama.cpp)。以下のビルド手順に従うこともできます。変更してください `-DGGML_CUDA=ON` を `-DGGML_CUDA=OFF` GPUがない場合、またはCPU推論のみを使いたい場合は。 **Apple Mac / Metalデバイスの場合**、次を設定します `-DGGML_CUDA=OFF` その後は通常どおり続けてください。Metalサポートはデフォルトで有効です。

{% code overflow="wrap" %}

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
git clone https://github.com/ggml-org/llama.cpp
cmake llama.cpp -B llama.cpp/build \
    -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-cli llama-mtmd-cli llama-server llama-gguf-split
cp llama.cpp/build/bin/llama-* llama.cpp
```

{% endcode %}
{% endstep %}

{% step %}
Hugging Faceから直接取得できます。モデルが非常に小さいため、量子化されていないフル精度のBF16版を使用します。

```bash
./llama.cpp/llama-cli \
    -hf unsloth/functiongemma-270m-it-GGUF:BF16 \
    --jinja -ngl 99 --ctx-size 32768 \
    --top-k 64 --top-p 0.95 --temp 1.0
```

{% endstep %}

{% step %}
以下をインストールした後、( `pip install huggingface_hub hf_transfer` をインストール後）。 `BF16` または他の量子化版でも構いません（ただし、モデルが小さいため4ビット未満にすることは推奨されません）。

```python
# !pip install huggingface_hub hf_transfer
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/functiongemma-270m-it-GGUF",
    local_dir = "unsloth/functiongemma-270m-it-GGUF",
    allow_patterns = ["*BF16*"],
)
```

{% endstep %}

{% step %}
その後、会話モードでモデルを実行します:

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \
    --model unsloth/functiongemma-270m-it-GGUF/functiongemma-270m-it-BF16.gguf \
    --ctx-size 32768 \
    --n-gpu-layers 99 \\
    --seed 3407 \\
    --prio 2 \\
    --top-k 64 \
    --top-p 0.95 \\
    --temp 1.0 \\
    --jinja
```

{% endcode %}
{% endstep %}
{% endstepper %}

## 📱 モバイルへのデプロイ

小さいサイズのおかげで、FunctionGemmaをスマートフォン上で実行・デプロイすることもできます。私たちはPyTorchと協力し、量子化対応学習（[QAT](/docs/jp/burogu/quantization-aware-training-qat.md))を用いて70%の精度を回復し、その後それらをエッジデバイスへ直接デプロイする、簡潔なワークフローを作成しました。

* FunctionGemmaをローカルで次にデプロイ: **Pixel 8** そして **iPhone 15 Pro** を実現するには **約50トークン/秒の推論速度**
* プライバシー優先、即時応答、オフライン機能を手に入れましょう
* 次の [無料のColabノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(0_6B\)-Phone_Deployment.ipynb) Qwen3 0.6Bをファインチューニングしてスマホ向けにエクスポートするには—Gemma3に変更して、次に従うだけです: [Gemma 3 ExecuTorchドキュメント](https://github.com/pytorch/executorch/tree/main/examples/models/gemma3).

{% content-ref url="/pages/6b439ad8eedcbf85fcbca5c3aa910e0d71794507" %}
[Run LLMs on your Phone](/docs/jp/ji-chu/inference-and-deployment/deploy-llms-phone.md)
{% endcontent-ref %}

スマホにデプロイするためのiOSおよびAndroidチュートリアルをご覧ください:

<a href="/docs/jp/ji-chu/inference-and-deployment/deploy-llms-phone.md#ios-deployment" class="button secondary" data-icon="apple">iOSチュートリアル</a><a href="/docs/jp/ji-chu/inference-and-deployment/deploy-llms-phone.md#android-deployment" class="button secondary" data-icon="android">Androidチュートリアル</a>

## 🦥 FunctionGemmaのファインチューニング

Googleは次のように述べています: **FunctionGemmaはファインチューニングすることを意図しています** あなたの特定の関数呼び出しタスク、マルチターンのユースケースを含め、に合わせてファインチューニングするためのものです。Unslothは現在FunctionGemmaのファインチューニングをサポートしています。私たちは2つのファインチューニングノートブックを作成し、モデルを次の方法で学習させる方法を示しています: **Colabノートブックを通じて、フルファインチューニングまたはLoRAを無料で実行できます:**

{% columns %}
{% column %}
[**ツール呼び出し前に推論するファインチューニングノートブック**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\).ipynb)

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_(270M).ipynb>" %}
{% endcolumn %}

{% column %}
[**モバイル操作ファインチューニングノートブック**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-Mobile-Actions.ipynb)

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_(270M)-Mobile-Actions.ipynb>" %}
{% endcolumn %}
{% endcolumns %}

〜では [**ツール呼び出し前に推論するファインチューニングノートブック**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\).ipynb)、次のことを行います **関数呼び出しの前に「think/reason」するようにファインチューニングします**。Chain-of-thought推論は、ツール使用能力を向上させるうえでますます重要になっています。

FunctionGemmaは、関数呼び出しに特化した小さなモデルです。独自のチャットテンプレートを使用します。ツール定義とユーザープロンプトが与えられると、構造化された出力を生成します。その出力を解析してツールを実行し、結果を取得し、それを使って最終的な回答を生成できます。

| ターンの種類           | 内容                                                                                                                                                                                                                                                                                    |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **開発者プロンプト**     | <p><code>\<start\_of\_turn>developer</code></p><p><code>次の関数で関数呼び出しができます:</code></p>                                                                                                                                                                                                  |
| **関数宣言**         | <p><code>\<start\_function\_declaration>declaration:get\_weather{</code></p><p><code>description: "都市の天気を取得します",</code></p><p><code>parameters: { city: STRING }</code></p><p><code>}</code></p><p><code>\<end\_function\_declaration></code></p><p><code>\<end\_of\_turn></code></p> |
| **ユーザーターン**      | <p><code>\<start\_of\_turn>user</code></p><p><code>パリの天気はどうですか？</code></p><p><code>\<end\_of\_turn></code></p>                                                                                                                                                                        |
| **関数呼び出し**       | <p><code>\<start\_of\_turn>model</code></p><p><code>\<start\_function\_call>call:get\_weather{</code></p><p><code>city: "paris"</code></p><p><code>}</code></p><p><code>\<end\_function\_call></code></p>                                                                             |
| **関数応答**         | <p><code>\<start\_function\_response>response:get\_weather{temperature:26}</code></p><p><code>\<end\_function\_response></code></p>                                                                                                                                                   |
| **アシスタントの締めくくり** | <p><code>パリの気温は26度です。</code></p><p><code>\<end\_of\_turn></code></p>                                                                                                                                                                                                                  |

ここでは、交互に挟む推論ではなく単一の思考ブロックを使った簡略版を、〜を通じて実装します: `<think></think>`。その結果、モデルとのやり取りは次のようになります:

| **思考** + **関数呼び出し** | <p><code>\<start\_of\_turn>model</code></p><p><mark style="color:青色;"><strong><code>\<think></code></strong></mark></p><p><mark style="color:青色;"><strong><code>ユーザーはパリの天気を求めています。get\_weatherツールがあります。city引数を指定して呼び出すべきです。</code></strong></mark></p><p><mark style="color:青色;"><strong><code>\</think></code></strong></mark></p><p><code>\<start\_function\_call>call:get\_weather{</code></p><p><code>city: "paris"</code></p><p><code>}</code></p><p><code>\<end\_function\_call></code></p> |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

## :accordion:モバイル操作向けのFunctionGemmaのファインチューニング

FunctionGemmaにモバイル操作を行わせる方法を示すノートブックも作成しました。〜では [**モバイル操作ファインチューニングノートブック**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-Mobile-Actions.ipynb)、評価も有効にし、デバイス上の操作向けにファインチューニングするとうまく機能することを、評価損失が下がっていく様子で示しています:

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FkRax7Sl7fN7fN3GoFgiG%2Fimage.png?alt=media&amp;token=e9b648f9-27ae-408b-aa0d-0baf77e5403d" alt="" width="375"><figcaption></figcaption></figure>

例えば、次のプロンプトが与えられたとします `2025年6月6日金曜日の午後2時に「Team Sync Meeting」のリマインダーを設定してください。`

{% code overflow="wrap" %}

```python
[{'role': 'developer',
  'content': '現在日時（YYYY-MM-DDTHH:MM:SS形式）: 2025-06-04T15:29:23\n曜日は水曜日です\n以下の関数で関数呼び出しができるモデルです\n',
  'tool_calls': None},
 {'role': 'user',
  'content': '2025年6月6日金曜日の午後2時に「Team Sync Meeting」のリマインダーを設定してください。',
  'tool_calls': None}]
```

{% endcode %}

私たちは、モデルが次を出力できるようにファインチューニングしました:

{% code overflow="wrap" %}

```
<start_of_turn>user
2025年6月6日金曜日の午後2時に「Team Sync Meeting」のリマインダーを設定してください。<end_of_turn>
<start_of_turn>model
<start_function_call>call:create_calendar_event{body:None,datetime:2025-06-06 14:00:00,email:None,first_name:None,last_name:None,phone_number:None,query:None,subject:None,title:<escape>Team Sync Meeting<escape>,to:None}<end_function_call><start_function_response>
```

{% endcode %}

## :man\_running:FunctionGemmaを使ったマルチターンのツール呼び出し

FunctionGemmaがマルチターンのツール呼び出しを行える方法を示すノートブックも作成しました。〜では [**マルチターンツール呼び出しノートブック**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-Multi-Turn-Tool-Calling.ipynb)、FunctionGemmaが長いメッセージのやり取りの中でツールを呼び出せることを示しています。例えば下記をご覧ください:

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F5bewasaWZp4r48LSL0fd%2Fimage.png?alt=media&amp;token=6aab6fd4-1560-4a46-ac41-305764019440" alt=""><figcaption></figcaption></figure>

まず、ツールを次のように指定する必要があります:

{% code expandable="true" %}

```python
def get_today_date():
    """
    今日の日付を取得します

    戻り値:
        today_date: 2025年12月18日形式の今日の日付
    """
    from datetime import datetime
    today_date = datetime.today().strftime("%d %B %Y")
    return {"today_date": today_date}

def get_current_weather(location: str, unit: str = "celsius"):
    """
    指定した場所の現在の天気を取得します。

    引数:
        location: 市と州。例: "San Francisco, CA, USA" または "Sydney, Australia"
        unit: 気温を返す単位。（選択肢: ["celsius", "fahrenheit"]）

    戻り値:
        temperature: 指定した場所の現在の気温
        weather: 指定した場所の現在の天気
    """
    if "San Francisco" in location.title():
        return {"temperature": 15, "weather": "sunny"}
    elif "Sydney" in location.title():
        return {"temperature": 25, "weather": "cloudy"}
    else:
        return {"temperature": 30, "weather": "rainy"}

def add_numbers(x: float | str, y: float | str):
    """
    2つの数を足します

    引数:
        x: 1つ目の数
        y: 2つ目の数

    戻り値:
        result: x + y
    """
    return {"result" : float(x) + float(y)}

def multiply_numbers(x: float | str, y: float | str):
    """
    2つの数を掛け算します

    引数:
        x: 1つ目の数
        y: 2つ目の数

    戻り値:
        result: x * y
    """
    return {"result" : float(x) * float(y)}
```

{% endcode %}

次に、すべてのツールのマッピングを作成します:

```python
FUNCTION_MAPPING = {
    "get_today_date" : get_today_date,
    "get_current_weather" : get_current_weather,
    "add_numbers": add_numbers,
    "multiply_numbers": multiply_numbers,
}
TOOLS = list(FUNCTION_MAPPING.values())
```

ツール呼び出しと解析のコードも必要です:

{% code expandable="true" %}

```python
#@title FunctionGemmaの解析コード（拡張可能）
import re
def extract_tool_calls(text):
    def cast(v):
        try: return int(v)
        except:
            try: return float(v)
            except: return {'true': True, 'false': False}.get(v.lower(), v.strip("'\""))

    return [{
        "name": name,
        "arguments": {
            k: cast((v1 or v2).strip())
            for k, v1, v2 in re.findall(r"(\w+):(?:<escape>(.*?)<escape>|([^,}]*))", args)
        }
    } for name, args in re.findall(r"<start_function_call>call:(\w+)\{(.*?)\}<end_function_call>", text, re.DOTALL)]

def process_tool_calls(output, messages):
    calls = extract_tool_calls(output)
    if not calls: return messages
    messages.append({
        "role": "assistant",
        "tool_calls": [{"type": "function", "function": call} for call in calls]
    })
    results = [
        {"name": c['name'], "response": FUNCTION_MAPPING[c['name']](**c['arguments'])}
        for c in calls
    ]
    messages.append({ "role": "tool", "content": results })
    return messages

def _do_inference(model, messages, max_new_tokens = 128):
    inputs = tokenizer.apply_chat_template(
        messages, tools = TOOLS, add_generation_prompt = True, return_dict = True, return_tensors = "pt",
    )
    output = tokenizer.decode(inputs["input_ids"][0], skip_special_tokens = False)

    out = model.generate(**inputs.to(model.device), max_new_tokens = max_new_tokens,
                         top_p = 0.95, top_k = 64, temperature = 1.0,)
    generated_tokens = out[0][len(inputs["input_ids"][0]):]
    return tokenizer.decode(generated_tokens, skip_special_tokens = True)
    
def do_inference(model, messages, print_assistant = True, max_new_tokens = 128):
    output = _do_inference(model, messages, max_new_tokens = max_new_tokens)
    messages = process_tool_calls(output, messages)
    if messages[-1]["role"] == "tool":
        output = _do_inference(model, messages, max_new_tokens = max_new_tokens)
    messages.append({"role": "assistant", "content": output})
    if print_assistant: print(output)
    return messages
```

{% endcode %}

これでモデルを呼び出せます！

```python
from unsloth import FastLanguageModel
import torch
max_seq_length = 4096 # 任意のシーケンス長を選べます！
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/functiongemma-270m-it",
    max_seq_length = max_seq_length, # 長いコンテキスト用に任意の値を選べます!
    load_in_4bit = False,  # 4ビット量子化でメモリを削減
    load_in_8bit = False, # [NEW!] 少し高精度で、メモリを2倍使用します
    load_in_16bit = True, # [NEW!] 16ビットLoRAを有効にします
    full_finetuning = False, # [NEW!] いまはフルファインチューニングも可能です！
    # token = "hf_...", # ゲート付きモデルを使う場合は1つ使用してください
)

messages = []
messages.append({"role": "user", "content": "今日は何日ですか？"})
messages = do_inference(model, messages, max_new_tokens = 128)
```

FunctionGemma向けに作成した3つのノートブックを試してみてください:

{% columns %}
{% column %}
[ツール呼び出し前に推論するファインチューニングノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\).ipynb)

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_(270M).ipynb>" %}
{% endcolumn %}

{% column %}
[モバイル操作ファインチューニングノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-Mobile-Actions.ipynb)

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_(270M)-Mobile-Actions.ipynb>" %}
{% endcolumn %}

{% column %}
[マルチターンツール呼び出しノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_\(270M\)-Multi-Turn-Tool-Calling.ipynb)

{% embed url="<https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/FunctionGemma_(270M)-Multi-Turn-Tool-Calling.ipynb>" %}
{% endcolumn %}
{% endcolumns %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/jp/moderu/tutorials/functiongemma.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
