Metadata-Version: 2.4
Name: kinako-llama-cpp
Version: 0.3.24.post2
Summary: [Beta] A custom llama-cpp-python wheel tailored for Intel 10th Gen CPUs on Windows 11.
Home-page: https://github.com/sak301537/gemma4-portable-for-Windows11
Author: sora_sakurai/toshiaki_sakurai
Author-email: t301537@mbr.nifty.com
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: Microsoft :: Windows :: Windows 11
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-python
Dynamic: summary

# kinako-llama-cpp
**⚠️ This package is an early experimental/testing release.
This is a custom-built, wheel-embedded distribution of llama-cpp-python optimized to run LLMs like Gemma 4 smoothly on everyday, mid-to-low spec PCs running Windows 11 (specifically tested on Intel 7th, 8th, 9th, 10th, and 13th Gen CPUs).

**⚠️ 本パッケージは検証用の早期（取り急ぎの）リリースです。**
知人・友人環境での動作検証を通じ、今後記述や構成を随時修正・アップデートしていく前提のプロジェクトです。
本パッケージは、Windowsの身近な低スペックPC環境において、軽量LLMを動作させることを目的とした `llama-cpp-python` のカスタムビルド（Wheel同梱版）です。

> **開発者より：**
> 現時点ではWindows＋CPU AVX2環境での動作を想定していますが、構成の厳密な検証はこれからです。（Intel 7,8,9,10,13世代/Win11で確認済）
> 実際に `pip install` してみて動いた・動かなかったなどのフィードバック（動作報告）をもとに、セットアップ設定やドキュメントを順次修正していきます。

### インストール方法
```bash
pip install kinako-llama-cpp

Important (English):
If you already have the official llama-cpp-python installed in your environment, installing this package directly may cause module conflicts inside the llama_cpp folder.
Please make sure to uninstall the official version before installing this package to prevent any broken dependencies.

Bash
### ⚠️ すでに公式の llama-cpp-python をインストールしている方へ / For Existing Users

**重要 (Japanese):**
もし、すでに本家（公式）の `llama-cpp-python` をインストール済みの環境に本パッケージを導入する場合、中身のモジュール（`llama_cpp`）が衝突して正常に動作しなくなる恐れがあります。
本パッケージを試す前に、必ず一度既存のパッケージをアンインストールしてください。

```bash
# 既存の公式版を一度削除する
pip uninstall llama-cpp-python -y

# その後、本パッケージをインストールする
pip install kinako-llama-cpp

> Python program sample
>
import os
import sys
from llama_cpp import Llama

# ── 設定項目 / Configuration ──
MODEL_PATH = r"C:\pythonfiles\llm\gemma-4-E2B-it-RotorQuant-Q8_0.gguf"

print("--- LLMモデルを読み込んでいます（数秒〜十数秒かかります）... ---")
print("--- Loading LLM model (This may take a few seconds)... ---")

try:
    llm = Llama(
        model_path=MODEL_PATH, 
        n_ctx=2048,
        n_batch=128,      # 過去の履歴を読み直す速度をCPU向けに最適化 / Optimized for CPU
        n_gpu_layers=0    # 完全CPUモード / CPU Only Mode
    )
except Exception as e:
    print(f"[ERROR] Model file not found or could not be loaded.")    
    print(f"\n【エラー】モデルファイルが見つからないか、読み込めませんでした。")
    print(f"Please check the path: {MODEL_PATH}")
    input("\nPress Enter to exit...")
    sys.exit(1)

print("\n=========================================")
print("  Windows CPU-driven PC Chat")
print("  Type 'exit' to quit the chat. / 終了するには「exit」と入力してください。")
print("=========================================\n")

# 過去の会話履歴を保存するリスト / Chat history list
chat_history = []

while True:
    try:
        user_input = input("You / あなた: ")
        
        if not user_input.strip():
            continue
            
        if user_input.strip().lower() == "exit":
            print("Closing chat. Thank you! / チャットを終了します。お疲れ様でした！")
            break
        
        # -------------------------------------------------
        # プロンプトの組み立て / Prompt Construction
        # -------------------------------------------------
        # 多言語に対応できるよう、指示を英語に統一し「ユーザーの言語に合わせる」ルールを追加
        system_prompt = "System: Act as a helpful AI assistant. Reply kindly and politely within 400 characters. (Please respond in the same language the user speaks.)\n"
        #日本語のみの場合
        #system_prompt = "System: 親切なAIとして、400文字以内で、優しく丁寧に回答してください。\n"
        
        # 履歴を直近の2回分（発言数に直すと最大4つ）に絞る
        recent_history = chat_history[-4:]
        history_text = "".join(recent_history)
        
        # 今回の質問をドッキング
        current_prompt = f"User: {user_input}\nAI: "
        full_prompt = system_prompt + history_text + current_prompt
        
        print("\nAI: ", end="", flush=True)
        
        # ストリーミング実行 / Streaming Execution
        response_stream = llm(
            full_prompt,
            max_tokens=500,  # 余裕を持たせた上限設定
            stop=["User:", "\nUser:", "System:", "\nSystem:"],
            echo=False,
            stream=True
        )
        
        # 1文字ずつ出力しながら、今回の回答テキストを記録
        ai_response = ""
        for chunk in response_stream:
            text = chunk["choices"][0]["text"]
            sys.stdout.write(text)
            sys.stdout.flush()
            ai_response += text
            
        print("\n-----------------------------------------")
        
        # ── 今回の会話を履歴リストに追加 ──
        chat_history.append(f"User: {user_input}\n")
        chat_history.append(f"AI: {ai_response.strip()}\n")
        
    except KeyboardInterrupt:
        print("\n Exit requested. Closing chat./ チャットを終了します。")
        print("\n")
        break
    except Exception as e:
        print(f"\n An error occurred / エラーが発生しました  {e}")
        break
