Qwen の言語モデルと日本語で対話できる chatBOT プログラム(llama-cpp-python, Python を使用)(Windows 上)

概要

Qwen(Alibaba による大規模言語モデル)を GGUF 形式に量子化したモデルを,llama-cpp-python を用いて動かし,日本語で対話できる chatBOT を作る.Python のプログラムを紹介する.Qwen は日本語を含む多言語に強く,日本語での入出力をそのまま扱えるため,翻訳を挟む処理は不要である.なお,本ページはかつて Meta の OPT モデルを FlexLLMGen(開発終了)で動かす内容であったが,FlexLLMGen の後継として GPU メモリが少ない環境でも動く同種の技術を調査した結果,量子化モデルを軽量に動かせる llama-cpp-python と,2026年8月時点で最新の Qwen の言語モデルの組み合わせに置き換えた.

目次

関連する外部ページ

サイト内の関連情報

第1章:前準備

Build Tools for Visual Studio 2026(ビルドツール)のインストール

Build Tools for Visual Studio 2026(ビルドツール)のインストールを行い、C/C++ コードのビルド環境を整える。

[Build Tools for Visual Studio 2026(ビルドツール)のインストール手順を見るには、ここをクリック]

Windows での Build Tools for Visual Studio 2026 のインストール

Build Tools for Visual Studio は,Visual Studio の IDE を含まない C/C++ コンパイラ,ライブラリ,ビルドツール等のコマンドライン向け開発ツールセットである。インストール済みの場合,この手順は不要である。

以下のコマンドは、Build Tools が未インストールの場合は winget で新規インストールし、インストール済みの場合は setup.exe modify でコンポーネントを追加する(バージョンは変更しない)。

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windows キーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

REM ============================================================
REM Visual C++ 再頒布可能パッケージ (VCRedist 2015-)
REM ============================================================
winget install --scope machine --id Microsoft.VCRedist.2015+.x64 -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/quiet /norestart"
if not "%ERRORLEVEL%"=="0" ( color 0c & echo VCRedist のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM ============================================================
REM Visual Studio Build Tools + Desktop development with C++
REM (VCTools、MSBuildTools、CMake連携、Clang、Windows 11 SDK)
REM ============================================================
REM 進行中のインストーラーを停止(ロック競合回避。対象プロセスが存在しない場合は
REM taskkillがエラーを返すが、これは想定内であるため出力のみ抑制する)
taskkill /F /IM vs_setup.exe /T >nul 2>&1
taskkill /F /IM vs_installer.exe /T >nul 2>&1
taskkill /F /IM vs_installerservice.exe /T >nul 2>&1
taskkill /F /IM msiexec.exe /T >nul 2>&1

REM Build Tools + Desktop development with C++(VCTools)+ 追加コンポーネント(一括)
REM 未インストール時: winget で新規インストール
REM インストール済み時: setup.exe modify でコンポーネント追加(バージョンは変更しない)
winget list --id Microsoft.VisualStudio.BuildTools 2>nul | findstr /i "BuildTools" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    for /f "usebackq delims=" %P in (`"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do start /wait "" "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" modify --installPath "%P" --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64 --includeRecommended --quiet --norestart --nocache
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のコンポーネント追加に失敗しました & ping 127.0.0.1 -n 6 >nul & color )
) else (
    winget install --scope machine --id Microsoft.VisualStudio.BuildTools -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64"
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )
)

REM
REM BuildTools のインストールパスを vswhere.exe で取得(メジャーバージョンに依存しない)
set "VSWHERE=C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
set "BT_PATH="
for /f "usebackq delims=" %P in (`"%VSWHERE%" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do set "BT_PATH=%P"
if not defined BT_PATH ( color 0c & echo Build Tools のインストールパスを取得できませんでした & ping 127.0.0.1 -n 6 >nul & color )

REM 破損時の修復(任意、動作がおかしくなった場合)
REM if defined BT_PATH "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" repair --installPath "%BT_PATH%" --quiet --norestart
REM 導入確認(インストールパスが表示されれば正常)
"%VSWHERE%" -products * -requires Microsoft.VisualStudio.Workload.VCTools -property installationPath

上記のコマンドでは、Build Tools 本体と Visual C++ 再頒布可能パッケージをインストールし、続いて以下のコンポーネントを追加している。

追加のコンポーネントが必要になった場合は Visual Studio Installer で個別にインストールできる。

インストール完了の確認

winget list Microsoft.VisualStudio.BuildTools

Visual Studio を必要とするとき

Visual Studio の機能を必要とする場合は,追加インストールできる。

Python 3.12 のインストール

Pythonのインストールを行い、Pythonのプログラムを実行する環境を整える。扱う環境は、Windows搭載パソコンである。金子研究室では、Python 3.12.10を推奨する。

[Windows での Python 3.12 のインストール手順を見るには、ここをクリック]

Windows での Python 3.12 のインストール

以下のいずれかの方法でPython 3.12をインストールする。Pythonがインストール済みの場合、この手順は不要である。

方法 1:winget によるインストール

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動するとPATHが反映される。

REM Python 3.12 をシステム領域にインストール
winget install --id Python.Python.3.12 -e --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0 Include_pip=1 Include_launcher=1 InstallLauncherAllUsers=1 TargetDir=\"C:\Program Files\Python312\""
if not "%ERRORLEVEL%"=="0" ( color 0c & echo Python 3.12 のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM Python と Scripts を PATH 先頭に追加
powershell -NoProfile -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; if(Test-Path $p){$k=[Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment',$true); $c=$k.GetValue('Path','',[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames); $t=$k.GetValueKind('Path'); $new=$c; if((';'+$new+';') -notlike \"*;$p;*\"){$new=$p+';'+$new}; if((';'+$new+';') -notlike \"*;$s;*\"){$new=$s+';'+$new}; if($new -ne $c){$k.SetValue('Path',$new,$t)}; $k.Close()}"

REM 現在のセッションにも反映(システムPATHを再取得して連結)
for /f "usebackq tokens=2,*" %A in (`reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) do set "PATH=%B"

REM pip / wheel の更新
python -m pip install --no-user -U pip wheel
if not "%ERRORLEVEL%"=="0" ( color 0c & echo pip / wheel の更新に失敗しました & ping 127.0.0.1 -n 6 >nul & color )

方法 2:インストーラーによるインストール

  1. Python公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンからWindows用インストーラーをダウンロードする。
  2. ダウンロードしたインストーラーを実行する。
  3. 初期画面の下部に表示される「Add python.exe to PATH」にチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから python コマンドを実行できない。
  4. 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。

インストールの確認

コマンドプロンプトで以下を実行する。

python --version

バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。

NVIDIA ドライバ,NVIDIA CUDA ツールキット 12.8 のインストール(Windows 上)

サイト内の関連ページNVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバNVIDIA CUDA ツールキット のインストールを行う.GPU が無い場合や,CPU だけで動かす場合は,この手順は不要である.

関連する外部ページ

llama-cpp-python のインストール(Windows 上)

llama-cpp-python は,llama.cpp(GGUF 形式の量子化モデルを動かす C/C++ 製のエンジン)の Python バインディングである.CUDA 12.8 でビルド済みの配布物は無いため,NVIDIA CUDA ツールキット 12.8 と Build Tools for Visual Studio 2026 を用いて,ソースからビルドしながらインストールする.GPU が無い場合や,CPU だけで動かす場合は,最後のコマンドから「$env:CMAKE_ARGS = "-DGGML_CUDA=on"」の行を省いて実行する.

管理者権限コマンドプロンプトを起動する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。

次のコマンドを,PowerShell で実行する.1行目を実行してから2行目を実行する.

$env:CMAKE_ARGS = "-DGGML_CUDA=on"
python -m pip install --no-user -U huggingface-hub llama-cpp-python
ビルドには数分から数十分かかる.GPU 用のカーネルをビルドするため,NVIDIA CUDA ツールキットと Build Tools for Visual Studio 2026 のインストールが,あらかじめ済んでいる必要がある.

関連する外部ページ

第2章:chatBOT プログラムの作成と実行

次の Python プログラムは,llama-cpp-pythonLlama.from_pretrained により,Hugging Face 上の Qwen3.8-27B の GGUF ファイルを取得し,マイクを使わずキーボードから日本語で入力した文章に対して,日本語で応答する chatBOT を作るものである.音声合成には,win32api(pywin32)を使用する.Qwen3.8-27B は,2026年8月時点で Alibaba が公開している最新の言語モデルの一つであり,Apache 2.0 ライセンスで公開されている.GPU のメモリ(VRAM)が 24GB に満たない場合は,「Q4_K_M」の部分を,より小さい量子化(例えば「IQ4_XS」や「Q3_K_M」)に置き換えるか,パラメータ数の少ない Qwen の言語モデルを使用する.

プログラム実行は,次のプログラムを c.py のようなファイル名で保存したあと,「python c.py」のように実行する.初回実行時に,GGUF ファイルが自動的にダウンロードされる.Qwen3.8-27B は,既定で「考える」処理(thinking)を行い,回答の前に <think></think> で囲まれた思考過程を出力する.この思考過程は,正規表現を用いて取り除いてから,画面表示と音声合成に使う.

"""Run a chatBOT with llama-cpp-python and the Qwen language model."""
# usage: python c.py
import re
from llama_cpp import Llama
import win32com.client

speech = win32com.client.Dispatch("Sapi.SpVoice")

llm = Llama.from_pretrained(
    repo_id="ggml-org/Qwen3.8-27B-GGUF",
    filename="*Q4_K_M.gguf",
    n_gpu_layers=-1,
    n_ctx=8192,
    verbose=False,
)

messages = [
    {"role": "system", "content": "あなたは親切な日本語のアシスタントです。"}
]

while True:
    inp = input("Human: ")
    if not inp:
        print("exit...")
        break

    messages.append({"role": "user", "content": inp})
    result = llm.create_chat_completion(
        messages=messages,
        temperature=0.7,
        max_tokens=1024)
    raw_outputs = result["choices"][0]["message"]["content"]
    outputs = re.sub(r".*?", "", raw_outputs, flags=re.DOTALL).strip()
    print(outputs)
    speech.Speak(outputs)
    messages.append({"role": "assistant", "content": raw_outputs})
「n_gpu_layers=-1」は,モデルの全レイヤーを GPU にオフロードする指定である.GPU のメモリが足りない場合は,「n_gpu_layers」を減らすか,「n_gpu_layers=0」として CPU だけで動かす.

実行すると,キーボードから入力した日本語の文章に対して,日本語で応答が返る.DeepL などの翻訳を経由しないため,応答までの時間も短くなる.