Metadata-Version: 2.1
Name: kinako-llama-cpp
Version: 0.3.24.post7
Summary: Python bindings for the llama.cpp library
Author-Email: Andrei Betlen <abetlen@gmail.com>
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Project-URL: Homepage, https://github.com/abetlen/llama-cpp-python
Project-URL: Issues, https://github.com/abetlen/llama-cpp-python/issues
Project-URL: Documentation, https://llama-cpp-python.readthedocs.io/en/latest/
Project-URL: Changelog, https://llama-cpp-python.readthedocs.io/en/latest/changelog/
Requires-Python: >=3.8
Requires-Dist: typing-extensions>=4.5.0
Requires-Dist: numpy>=1.20.0
Requires-Dist: diskcache>=5.6.1
Requires-Dist: jinja2>=2.11.3
Provides-Extra: server
Requires-Dist: uvicorn>=0.22.0; extra == "server"
Requires-Dist: fastapi>=0.100.0; extra == "server"
Requires-Dist: pydantic-settings>=2.0.1; extra == "server"
Requires-Dist: sse-starlette>=1.6.1; extra == "server"
Requires-Dist: starlette-context<0.4,>=0.3.6; extra == "server"
Requires-Dist: PyYAML>=5.1; extra == "server"
Provides-Extra: test
Requires-Dist: pytest>=7.4.0; extra == "test"
Requires-Dist: httpx>=0.24.1; extra == "test"
Requires-Dist: scipy>=1.10; extra == "test"
Requires-Dist: fastapi>=0.100.0; extra == "test"
Requires-Dist: sse-starlette>=1.6.1; extra == "test"
Requires-Dist: starlette-context<0.4,>=0.3.6; extra == "test"
Requires-Dist: pydantic-settings>=2.0.1; extra == "test"
Requires-Dist: huggingface-hub>=0.23.0; extra == "test"
Provides-Extra: dev
Requires-Dist: ruff>=0.15.7; extra == "dev"
Requires-Dist: twine>=4.0.2; extra == "dev"
Requires-Dist: mkdocs>=1.4.3; extra == "dev"
Requires-Dist: mkdocstrings[python]>=0.22.0; extra == "dev"
Requires-Dist: mkdocs-material>=9.1.18; extra == "dev"
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: httpx>=0.24.1; extra == "dev"
Provides-Extra: all
Description-Content-Type: text/markdown

# 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
# 既存の公式版, 念のため kinako_llamaを一度削除する
pip uninstall llama-cpp-python -y
pip uninstall kinako-llama-cpp -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

## License

This project is licensed under the terms of the MIT license.
