AI DataBase wAPI Core

A core server-side mod for Minecraft 1.21.1 (NeoForge) that enables async external AI API calls and lightweight JSON-based data storage. It provides APIs for other mods and has no standalone features.

by
36 Downloads
neoforgelibrarymanagementutility
Rent Server with this Mod

About this Mod

  1. English / 2. 日本語

AI DataBase wAPI Core (aidbwapi_core)

A core server-side mod for Minecraft 1.21.1 (NeoForge) that provides asynchronous request functionality to external AI (OpenAI-compatible LLM APIs) and a lightweight JSON-based persistent storage (database functionality).
This mod does not provide standalone features (such as chatbots) on its own; it is designed as a system infrastructure (Core) that allows other mods (dependent mods) to easily utilize advanced AI functions and data storage via the Java API (AiCoreAPI / DatabaseManager).


🚀 Features & Architecture

1. AI Request Network (Advanced AI Integration & Autonomous Failover)

Equipped with an autonomous failover and rate-limiting system designed to ensure safe and reliable communication with external APIs while minimizing server load.

  • Full Async Processing & Serial Queues (Async Executor):
    All HTTP requests to AI are executed using CompletableFuture and Java's standard HttpClient mechanism (asynchronous I/O), ensuring that Minecraft ticks are never blocked. Furthermore, it is designed for safety by ensuring the "number of concurrent executions is always at most one (queue management)," preventing multiple simultaneous transmissions of the same prompt string.

  • Lazy Evaluation Reset (Lazy Reset):
    Initialization checks for "daily execution limits" and "per-minute execution limits" for models do not use periodic server tasks (constant monitoring). Instead, it adopts a Lazy Reset mechanism where calculations and resets are performed on-the-fly by comparing timestamps at the moment the next request occurs, resulting in zero standby server load.

  • Key Distribution & Distributed Round-Robin (Priority & Load Balancing):
    Multiple API keys can be registered for the same provider or model. You can set a priority (priority: lower values indicate higher priority) for each ModelEntry. The system automatically falls back (switches to another model/key) to the next highest priority in the event of errors or rate limit exhaustion.
    Additionally, if multiple models with the same priority exist, the system distributes the requests using a "Round-Robin" method, automatically preventing load concentration on a specific API key. This allows for safe operation by aggregating rate limit quotas from multiple free API keys.

  • Penalty Point (PP) System & Probabilistic Skipping (Penalty System):
    When communication errors occur, the model is not immediately disabled. Instead, it is assigned Penalty Points (PP) based on the severity of the error, while a temporary cooldown is applied (Default: 429 = 60s, 5xx = 120s, Timeout = 60s, Connection Failure = 300s).

    • HTTP 429 (Rate Limited): +1 PP
    • HTTP 5xx (Server Error): +5 PP
    • Timeout / Connection / DNS Failure: +7 PP
    • Successful Communication: Halves PP (PP /= 2)

    When selecting an execution candidate, models with PP are temporarily skipped with a probability calculated as:
    $$\frac{PP}{PP + 4.0}$$
    The system autonomously avoids or suppresses access to endpoints that are currently unstable by moving to the next candidate.

  • 100-Round Fail-Safe Loop:
    If all candidate models are currently in probabilistic skip or cooldown, the system loops back to the beginning of the candidate list for a re-draw. To prevent infinite loops, a robust fail-safe terminates the process after a maximum of 100 rounds, either selecting the highest priority available model (lowest priority value) as a compromise or returning a complete failure to the API layer.

  • Exception Handling (HTTP 400 Bad Request):
    If a configuration-related error occurs, such as HTTP 401 (Unauthorized) or HTTP 404 (Model Not Found), the specific model is automatically disabled (disabled) and the system immediately falls back (retries) to the next candidate. However, for HTTP 400 (Bad Request), since the issue is likely a bug specific to the prompt or data structure, switching models is unlikely to succeed. Therefore, the system returns an error immediately to the calling dependent mod without failing over (instant termination of useless loops).

2. JSON Storage System (Database Functionality)

A foundation that allows dependent mods to save and load their own data with extreme ease. The storage format is strictly fixed to JSON.

  • Category Registration & Hierarchical Management:
    By calling registerCategory("my_mod") during initialization, dependent mods (external mods) automatically generate a directory structure linked to that category name. Data is automatically sorted into "General Data (Global)" and "Individual Player (UUID) Data" folders. (Note: Data cannot be saved without prior registration).
  • Memory Caching & Dynamic Resolution:
    Frequently accessed data is cached as a Map in memory upon loading. Subsequent get/set operations are processed immediately without disk I/O. The root path for the storage directory is automatically determined by retrieving the correct path (e.g., root/world/aidbwapi_core/) during the ServerStartedEvent.
  • Synchronous & Immediate Save Mechanism:
    When a write operation (set()) is performed on the database, the memory cache is updated and an immediate synchronous file write (flush) is executed. (Note: While error logs use a background delay timer every 3 hours, the DB itself does not have an asynchronous auto-save delay feature). For safety, a manual force-save command (db save) is also implemented.

💻 Requirements & Setup

  • Minecraft: 1.21.1
  • Mod Loader: NeoForge 21.1.219 or later
  • Java: Java 21 or higher
  • Side: Required on both Server and Client

Installation:
Place this mod (aidbwapi_core-x.x.x.jar) into the mods folder of your server or client and launch.


⚙️ Configuration & Directory Structure

All settings, databases, and error logs are deployed in the server root directory or under saves/[world_name]/ for clients.

  • config/aidbwapi_core-common.toml: Basic operational settings for the entire mod.
    • commandPermissionLevel: Required OP level for all /dbwapi commands (Default: 2). Can be changed from 0 to 4.
    • requestTimeoutSeconds: Timeout for AI communication responses (Default: 60 seconds).
    • penaltyCurveFactor: Adjustment factor for the PP skip probability curve (Default: 4.0).
    • Other settings include cooldown seconds for various HTTP errors (rateLimitSeconds, etc.) and the periodic flush interval for error logs (flushIntervalMinutes). Some basic settings can be changed and persisted instantly via in-game commands.
  • config/aidbwapi_core-keynames.json: Stores AI endpoint URLs, API keys in plain text, model lists, and various rate limit settings (dailyLimit, minuteLimit) in a structured format.
    • ⚠️ [IMPORTANT] API Key Security & Registration Method
      As a specification of this mod, API keys are not encrypted and are saved as plain text within this JSON file. While keys can be registered via in-game commands (/dbwapi keyname setkey), due to Minecraft's specifications, the full command you type into the chat (the plain text API key string) will be recorded as-is in the server's logs/latest.log and console log files.
      To ensure security, avoid in-game command entry. Instead, we strongly recommend opening this file directly with a text editor, editing/saving the "apiKey": "sk-xxxx..." field, and then running the /dbwapi reload command in-game to reload the settings.
  • [World Save Root]/aidbwapi_core/[category_name]/: The root for settings and data storage for each category saved and cached via CategoryDatabaseHandle, etc.
    • global.json for general data and a players/ folder containing <UUID>.json files for individual players are placed directly under the category.
  • [World Save Root]/aidbwapi_core/log/: The destination where the error history (debug logs) of AI and DB processing accumulated in memory is exported in JSON format in the background.
    • A maximum of 20 files are kept for the latest error logs by default, with older files being automatically rotated (deleted).
    • Any unsaved error states remaining in memory are flushed during server shutdown/termination (ServerStoppingEvent) to ensure they are saved to disk.

🛠️ Command Reference

Initial AI setup and various model settings/management can be easily performed via in-game commands.
All commands start with /dbwapi.

  • Arguments & Suggestions: When entering identifiers (KeyName or Model name), suggestions (Tab completion) will be displayed for all registered settings in-game. Syntax errors or insufficient arguments will be rejected as per Brigadier standards.
  • Message Format Colors: All feedback from commands starts with [AiDb] (Green). The target of the operation (values or names) is highlighted in Yellow. Errors and warnings are output in Red text.
  • Strict Output Protection for API Keys: When API key information is output to the chat via display commands (info or list), it is masked for protection: "If the original key is 5 characters or longer, only the first 4 characters are displayed, and all remaining characters are masked with ****." "If the key is 4 characters or fewer, all characters are masked with **** as an exception." Raw keys are never output to the screen or logs.

📌 General & Config

  • /dbwapi status: Summary of system operation. Displays the number of loaded KeyNames and Models, as well as the count of AI and DB errors currently queued in memory for output.
  • /dbwapi reload: Force reloads the TOML and JSON (keynames.json) configuration files. Always run this after manual text editing.
  • /dbwapi version: Displays the version of this mod.
  • /dbwapi config show: Displays the currently applied debug log settings (debugLogging) and AI communication timeout (requestTimeoutSeconds).
  • /dbwapi config debug true|false: Instantly toggles the debug level (detailed log output) on/off and persists the setting.
  • /dbwapi config timeout <seconds>: Changes and persists the AI communication timeout (basic setting).

📌 KeyName Management

Centralized management of the set consisting of the URL (provider endpoint) and API key as a system-wide "Registered Name (keyName)."

  • /dbwapi keyname list / info <keyName>: Displays a list of all registered KeyNames or details for a specific KeyName. (API keys are masked).
  • /dbwapi keyname add <keyName> <apiUrl> <apiKey>: Registers a connection info set for a new AI provider (OpenAI-compatible). ※ While duplicate registered names (keyName) are errors, registering the same apiUrl and apiKey under different names is permitted (for load balancing).
  • /dbwapi keyname seturl <keyName> <apiUrl>: Updates only the API endpoint URL of an existing KeyName.
  • /dbwapi keyname setkey <keyName> <apiKey>: Updates the API key of an existing KeyName. (※ Warning: Risk of log exposure. Direct JSON editing is recommended for safety.)
  • /dbwapi keyname remove <keyName> [confirm]: Safety-locked deletion. Requires true at the end to execute.

📌 Model & Failover Management

Model identifiers are always specified as <keyName>.<model_name> (e.g., taro_groq.llama-3-70b).

  • /dbwapi model list / info <keyName>.<model_name>: Displays the operational status of all models (priority, penalty/PP status, current status, etc.) and detailed limit metrics for individual models.
  • /dbwapi model add <keyName>.<model_name> [dailyLimit] [minuteLimit]: Adds a new available model to the parent KeyName. Use -1 for unlimited.
  • /dbwapi model move <keyName>.<model_name> up|down: Moves/swaps the priority of a specified model one level up (up) or one level down (down).
  • /dbwapi model limit <keyName>.<model_name> daily|minute <value>: Changes the maximum limits for a model (-1 for unlimited). Changes are applied immediately.
  • /dbwapi model enable <keyName>.<model_name> / disable <keyName>.<model_name>: Enables or temporarily disables the lottery setting for a specific model.
    • [Recovery from Auto-Disable]: If an endpoint configuration issue occurs (e.g., HTTP 401/403 Invalid API Key or HTTP 404 Not Found), the system will automatically force the model to be disabled (disabled). After resolving the mismatch (e.g., via seturl), manually restore it using this enable command.
  • /dbwapi model reset <keyName>.<model_name>: Instantly resets the accumulated PP (penalty) and cooldown status of the target model to zero.
  • /dbwapi model resetall: Resets "all models" currently registered at once.
  • /dbwapi model remove <keyName>.<model_name> [confirm]: Deletes the specified model. (※ Safety lock required; true at the end is mandatory).

📌 AI Test, Error Logs, & DB Management (Tests & Logger)

  • /dbwapi ai status: Displays the number of AI requests currently being processed (Active) and those in the asynchronous processing wait queue (Queue).
  • /dbwapi ai test: Uses the "currently valid model" to send a short test prompt and check if a text response actually returns.
  • /dbwapi ai errors [count]: Outputs a history of recent AI communication errors (up to 50 entries, default 10).
  • /dbwapi ai errors clear: Clears the error history memory for display.
  • /dbwapi db list: Displays a list of all category names currently registered in the DatabaseManager.
  • /dbwapi db info <category>: Displays metrics such as the storage root path, global DB key count, and current player UUID cache count.
  • /dbwapi db errors [count] / db errors clear: Same as ai errors but for DB-specific logs (e.g., FILE_WRITE_ERROR).
  • /dbwapi db save: Explicitly forces a file write (flush) of all changes in all databases in memory.

📦 For Developers: Java API Implementation (API Layer for Developers)

The Core infrastructure is utilized by calling it via the singleton (getInstance()) or various static methods from the Java code of your dependent mod. Please include aidbwapi_core as a dependency (e.g., compileOnly) in your build.gradle before implementing.

1. Asynchronous Request to AI (AiCoreAPI)

All internal rate-limit checks, key distribution, failovers, and exception handling pipelines are hidden.

import com.morwapi.aidbwapi_core.api.AiCoreAPI;

// Execution results are returned asynchronously as CompletableFuture<String>.
AiCoreAPI.getInstance().requestAI("Tell me the appeal of Minecraft in 100 characters")
    .thenAccept(response -> {
        // [On Success] Process the AI response string (response).
        System.out.println("AI Response: " + response);
        
        // ⚠️ [CAUTION] This is executed in a "Separate Thread (inside AsyncExecutor)".
        // To safely access the Minecraft world (sending chat, placing blocks, entity operations, etc.),
        // you must ensure the processing is returned to the main thread (Server Thread)
        // using a task queue like server.execute(() -> { ... }).
    })
    .exceptionally(ex -> {
        // [On Failure/Exception] Reached if all models are unavailable,
        // retry limit (100) exceeded, or request parameters are invalid (HTTP 400).
        System.out.println("AI Communication Error: " + ex.getMessage());
        return null; // CompletableFuture requirement
    });

### 2. JSON Database and Categories (`CategoryDatabaseHandle`)
Register and obtain categories via `AiCoreAPI`, and receive handles for `PlayerDatabase` or `GlobalDatabase` to save and read data.

**[IMPORTANT] JsonStorageEngine Specifications and Types:**
This database is not a high-performance ORM tool for directly saving and fully restoring complex custom class structures (POJOs). Due to GSON specifications, all data restored from JSON files via `get()` is loaded as collections of **`Map<String, Object>`** (or primitive types).
Therefore, while you can pass custom class instances when saving, the design is extremely simple and assumes you will cast or reconstruct them from Maps or standard types (or deserialize separately with GSON) when reading. Use with simple Maps, numbers, or strings is recommended.

import com.morwapi.aidbwapi_core.api.AiCoreAPI;
import com.morwapi.aidbwapi_core.api.CategoryDatabaseHandle;
import java.util.UUID;

// ------ During Mod Initialization (e.g., FMLCommonSetupEvent) ------

// [1]. Automatic generation and registration of categories
AiCoreAPI.getInstance().registerCategory("guild_mod");

// [2]. Obtaining a DB handle for operation
CategoryDatabaseHandle dbHandle = AiCoreAPI.getInstance().getCategoryDatabase("guild_mod");

// ------ Implementation Example (e.g., PlayerJoinEvent) ------
UUID playerId = player.getUUID();

// [1]. Loading data (Read)
// Restored from JSON as Map format, etc. Returns null if not created.
Object rawData = dbHandle.getPlayerDB().get(playerId, "killCount");
int killCount = 0;

if (rawData != null) {
    // Since numbers may become Double due to GSON, receive as Number type and cast.
    killCount = ((Number) rawData).intValue();
}

// [2]. Updating and saving data (Save)
killCount += 1;

// Arguments: Player UUID, storage identification key name, value to save (Object)
dbHandle.getPlayerDB().set(playerId, "killCount", killCount);

// ※ The moment this `set()` method is called, the file is written [synchronously and immediately]
// to `guild_mod/players/<UUID>.json` at the same time it is applied to the memory (cache-side Map).

## ⚖️ License (License)

The source code and provided binaries of this mod are provided and published under the **Apache License, Version 2.0**.
Creation and redistribution of commercial or non-commercial mods that use or depend on this infrastructure (API) are permitted freely within the scope of the license terms.
    

# AI DataBase wAPI Core (aidbwapi_core)

Minecraft 1.21.1 (NeoForge) 向けに、外部AI(OpenAI互換LLM API)への非同期リクエスト機能、およびJSONベースの軽量な永続化ストレージ(データベース機能)を提供するコア・サーバーサイドModです。
本Mod単体で完結する機能(チャットボット等)は持たず、他のMod(依存Mod)が高度なAI機能やデータ保存機能を Java API(`AiCoreAPI` / `DatabaseManager`) として簡単に利用できるように設計された**システム基盤(Core)**です。

---

## 🚀 コア機能とアーキテクチャ (Features & Architecture)

### 1. AI Request Network (高度なAI連携と自律型フェイルオーバー)
外部APIへの通信を、サーバー負荷を極限まで抑えつつ安全・確実に運用するための自律型フェイルオーバー・レートリミットシステム(AI動作を止めない仕組み)を備えています。

*   **完全非同期処理と直列キュー (Async Executor):**
    AIへのHTTPリクエストはすべて `CompletableFuture` とJava標準の `HttpClient` 機構(非同期I/O処理)を用いて実行され、MinecraftのTickを一切ブロックしません。また「同時実行数は常に最大1つまで(キュー管理)」とし、同一のプロンプト文字列を複数同時に多重送信しない安全設計が施されています。
*   **遅延評価リセット (Lazy Reset):**
    モデルの「1日あたりの実行上限」「1分あたりの実行上限」の初期化判定は、サーバーの定期処理(常時監視)を行わず、次回リクエストが発生した瞬間のタイムスタンプ比較で都度計算・リセットする「遅延評価(Lazy Reset)」メカニズムを採用しており、待機中のサーバー負荷はゼロです。
*   **キーの分散運用と分散ラウンドロビン (Priority & Load Balancing):**
    同一のプロバイダやモデルに対して、複数のAPIキーを登録できます。モデル(ModelEntry)ごとに優先度(`priority`: 数値が小さいほど高優先)を設定でき、レート上限到達時やエラー時には優先度の高い順へ自動でフォールバック(別モデル・別キーへの自動切替)を行います。
    さらに、**同率優先度のモデルが複数存在する場合、システムは「ラウンドロビン方式」で行き先を分散させ、特定のAPIキーへの負荷集中を自動で防ぎます**。無料APIのレート制限枠を複数キーで合算して安全に運用することが可能です。
*   **ペナルティポイント(PP)制と確率スキップ (Penalty System):**
    通信エラー等が発生した際、即座に対象モデルを無効化するのではなく、一時的なクールダウン秒数(デフォルト: 429=60秒, 5xx=120秒, Timeout=60秒, 接続失敗=300秒)を課すと同時に、**エラーの重大度に応じたペナルティポイント(PP)**を加算します。
    *   `HTTP 429` (レート制限): **+1 PP**
    *   `HTTP 5xx` (サーバーエラー): **+5 PP**
    *   `Timeout` / 接続・DNS解決失敗: **+7 PP**
    *   通信成功時: **PPを半減** (`PP /= 2`)
    
    実行候補の選出時、PPを持つモデルは `PP / (PP + 4.0)` の確率で一時的に見送られ(次点のモデルへ移行)、調子の悪いエンドポイントへのアクセスを自律的に回避・抑制します。
*   **最大100周のフェイルセーフループ (Fail-Safe Loop):**
    すべてのモデル候補が確率スキップやクールダウン中だった場合、候補リストの先頭に戻って再抽選ループが発生しますが、無限ループを防止するため「**最大100周で強制的に打ち切り、利用可能な中で最も優先度が高い(priorityが小さい)モデルを妥協選出するか、API層へ完全失敗を返す**」という強固なフェイルセーフが働きます。
*   **例外処理 (HTTP 400 Bad Request):**
    `HTTP 401`(認証エラー)や `HTTP 404`(モデル不存在)のような構成不良エラーが発生した場合、対象モデル自体を自動無効化(`disabled`)した上で直ちに次のモデル候補へフォールバック(再試行)します。しかし、`HTTP 400`(リクエスト不正)に関しては「プロンプトや送信データの構造そのものにバグがある」ため、どのモデルに切り替えても失敗する可能性が高く、フェイルオーバーさせずに即座に呼び出し元の依存Mod側へエラーを返却します(無駄なループの即時打ち切り)。

### 2. JSON Storage System (データベース機能)
依存Modが独自のデータを極めて簡単に保存・読み出しできる基盤です。保存フォーマットは**JSON完全固定**です。

*   **カテゴリの登録と階層管理:**
    依存Mod(外部Mod)が初期化時などに `registerCategory("my_mod")` を呼ぶことで、そのカテゴリ名に紐づくディレクトリ構成が自動生成されます。「汎用データ(Global)」と「プレイヤー個別(UUID)データ」は自動でフォルダが振り分けられ保存されます。(※事前登録を行わずにデータを保存することはできません)。
*   **メモリキャッシュと動的解決:**
    頻繁にアクセスされるデータは、読み込み時にメモリ上にMapとしてキャッシュされ、以後の `get` / `set` はディスクアクセス(I/O)を行わず即座に処理されます。保存先ディレクトリのルートパスは、サーバー起動時イベント(`ServerStartedEvent`)を利用して `root/world/aidbwapi_core/` 等の正しいパスを自動取得して決定します。
*   **同期的・即時セーブ機構:**
    データベースに対する書き込み(`set()` の呼び出し)が行われると、メモリ上のキャッシュが更新されるのと同時に**即座に同期的ファイル書き出し(フラッシュ)**が実行されます。(※エラーログ出力のみはバックグラウンドの3時間ごとの遅延タイマーを使用しますが、DB自体に非同期オートセーブの遅延機能は存在しません)。安全のため、手動での強制保存(`db save`)コマンドも実装されています。

---

## 💻 動作要件とインストール (Requirements & Setup)

*   **Minecraft:** 1.21.1
*   **Mod Loader:** NeoForge 21.1.219 以降
*   **Java:** Java 21 以上
*   **サイド:** サーバー・クライアント両方必須

**インストール:**
当Mod (`aidbwapi_core-x.x.x.jar`) をサーバーまたはクライアントの `mods` フォルダに配置して起動します。

---

## ⚙️ 設定ファイルとディレクトリ構造 (Configuration)

すべての設定やデータベース・エラーログは、サーバーのルートディレクトリ、またはクライアントの `saves/[ワールド名]/` 配下に展開されます。

*   **`config/aidbwapi_core-common.toml`** : Mod全体の基礎動作設定ファイル。
    *   `commandPermissionLevel`: 全ての `/dbwapi` コマンドの要求OP権限レベル(デフォルト `2`)。0〜4に変更可能です。
    *   `requestTimeoutSeconds`: AI通信の応答タイムアウト秒数(デフォルト `60`秒)。
    *   `penaltyCurveFactor`: PPスキップ確率計算曲線の調整係数(デフォルト `4.0`)。
    *   他、各種HTTPエラー時のクールダウン秒数(`rateLimitSeconds` 等)や、エラーログの定期フラッシュ間隔(`flushIntervalMinutes`)等を設定可能。一部の基礎設定はインゲームコマンド(`/dbwapi config ...` 等)からでも即座に変更・永続化されます。
*   **`config/aidbwapi_core-keynames.json`** : AIエンドポイントURL、APIキーの平文、およびモデル一覧と各種レート制限(`dailyLimit`, `minuteLimit`)の設定が構造化保存されます。
    *   **⚠️【重要】APIキーのセキュリティ・登録方法について**
        Modの仕様としてAPIキー自体は暗号化されず、このJSONファイル内に平文で保存されます(`.gitignore` 等での防衛やOSサーバー権限による保護運用を前提としています)。インゲームのコマンド(`/dbwapi keyname setkey`)からでも登録可能ですが、**Minecraftの仕様上、あなたがチャット欄に打ち込んだコマンド全文(APIキーの平文文字列)は、サーバーの `logs/latest.log` やコンソール画面のログファイルにそのまま丸見えで記録されてしまいます。**
        セキュリティを担保するため、外部に提供される可能性のあるサーバーを運用する場合、ゲーム内でのコマンド入力は避け、**本ファイルを直接テキストエディタで開き `"apiKey": "sk-xxxx..."` を書き換え・保存したうえで、ゲーム内で `/dbwapi reload` コマンドを実行して再読み込みさせる運用を強く推奨します。**
*   **`[ワールド保存ルート]/aidbwapi_core/[カテゴリ名]/`** : `CategoryDatabaseHandle` 等を経由して保存・キャッシュされた各カテゴリの設定・データ保存ルート。
    *   カテゴリ直下に汎用データ(`global.json`)と、プレイヤー個別フォルダ(`players/<UUID>.json`)が配置されます。
*   **`[ワールド保存ルート]/aidbwapi_core/log/`** : メモリ上に蓄積されたAI・DB処理時のエラー履歴(デバッグログ)がバックグラウンドでJSON形式出力される出力先。
    *   最新のエラーログ出力はデフォルトで最大 `20` ファイル保持され、古いものから自動ローテーション(削除)されます。
    *   また、メモリに残存する未保存のエラー状態は、サーバー終了・シャットダウン時(`ServerStoppingEvent`)に割り込みでフラッシュされ、確実にディスクへ救済・保存されます。

---

## 🛠️ コマンドリファレンス (Command Reference)

AIの初期セットアップやモデルの各種設定・管理は、インゲームコマンドから手軽に行えます。
すべてのコマンドは `/dbwapi` で始まります。(デフォルト要求権限: `common.toml` 記載のレベル。初期値は2)

*   **引数・サジェストの仕様:** 識別子(KeyNameやModel名)を入力する際、登録済みの設定すべてがインゲームでサジェスト(Tab補完)表示されます。構文エラーや引数不足はBrigadier標準として弾かれます。
*   **メッセージフォーマット表示色:** コマンドからのフィードバックはすべてシステムメッセージとして `[AiDb]` (緑色) から始まり、操作対象(数値や名前)は黄色でハイライトされます。エラーや警告は全体が赤色テキストで出力されます。
*   **APIキー等の出力保護の徹底:** 画面表示用コマンド(`info` や `list`)等でAPIキー情報がチャットに出力される際は、保護のため「元のキーが5文字以上の場合は**先頭4文字のみ表示し、残りの全文字を `****` にマスキング**」「元のキーが4文字以下の場合は**例外として全文字を `****` にマスキング**」した状態でのみ表示され、生キーが画面に出力されることは絶対にありません。また、システムログの出力時などにもキーは一切含まれません。

### 📌 全般 (General & Config)
*   `/dbwapi status` : システム全体の稼働サマリー。ロード済みのKeyName数とモデル数に加え、メモリ上で出力待機状態(Queue)になっているAIエラー・DBエラーの件数を表示します。
*   `/dbwapi reload` : TOMLおよびJSON(`keynames.json`)設定ファイルを強制的に再読み込みします。テキスト手動編集時は必ず実行してください。
*   `/dbwapi version` : 当Modのバージョンを表示します。
*   `/dbwapi config show` : 現在適用されているデバッグログ設定(`debugLogging`)とAI通信タイムアウト秒数(`requestTimeoutSeconds`)を表示します。
*   `/dbwapi config debug true|false` : デバッグレベル(詳細ログ出力)のオン/オフを即座に切り替え・永続化します。
*   `/dbwapi config timeout <秒>` : AI通信のタイムアウト秒数(基礎設定)を変更・永続化します。

### 📌 キー(KeyName)管理 (KeyName Management)
URL(プロバイダエンドポイント)とAPIキーのセットを、システム共通の**「登録名(keyName)」**として一元管理します。
*   `/dbwapi keyname list` / `info <keyName>` : 登録済みの全KeyNameの一覧、または指定したKeyNameの詳細を表示します。(APIキーはマスクされます)
*   `/dbwapi keyname add <keyName> <apiUrl> <apiKey>` : 新しいAIプロバイダ(OpenAI互換)に対する接続情報セットを登録します。※登録名(`keyName`)の重複はエラーですが、`apiUrl` と `apiKey` に同一の内容を別名で複数登録することは許可されています(負荷分散のため)。
*   `/dbwapi keyname seturl <keyName> <apiUrl>` : 既存のKeyNameのAPIエンドポイントURLのみを更新します。
*   `/dbwapi keyname setkey <keyName> <apiKey>` : 既存のKeyNameのAPIキーを更新します。**(※前述のログ残存リスクがあります。安全のためJSONの直接編集を推奨します。)**
*   `/dbwapi keyname remove <keyName> [confirm]` : 誤操作防止の安全装置付き削除。末尾引数(`[confirm]`)を省略または `false` で実行した場合は、削除確認の警告ログのみ出力して終了します。末尾に明示的に `true` を指定した場合のみ、KeyName(およびそのKeyNameに紐づくすべてのモデル設定群)が完全に削除されます。

### 📌 モデル管理 (Model & Failover Management)
モデルの識別子は、どのプロバイダのモデルかが分かるように、常に **`<keyName>.<モデル名>`**(例: `taro_groq.llama-3-70b` のようにドットで区切り)で指定します。
*   `/dbwapi model list` / `info <keyName>.<モデル名>` : 全モデルの稼働状況(優先度、ペナルティ・PP状況、現在有効か等)や、個別モデルの詳細な制限メトリクスを表示します。
*   `/dbwapi model add <keyName>.<モデル名> [dailyLimit:日次上限] [minuteLimit:分間上限]` : 親となるKeyNameに対して新しい利用可能モデルを追加します。上限値引数を省略した場合、または `-1` を入力した場合は「日次/分次ともに無制限」として登録されます。
*   `/dbwapi model move <keyName>.<モデル名> up|down` : 指定モデルの優先度(Priority順位)を、1つ上(`up`)または 1つ下(`down`)に移動・入れ替えます。
*   `/dbwapi model limit <keyName>.<モデル名> daily|minute <値>` : モデルの上限回数を変更します(`-1` で無制限)。設定の変更は即時適用されます。
*   `/dbwapi model enable <keyName>.<モデル名>` / `disable <keyName>.<モデル名>` : 指定モデルの抽選設定を有効化/一時無効化します。
    *   **【自動無効化からの復旧】**: 例外(`HTTP 401/403 Invalid API Key` や `HTTP 404 Not Found`) など、恒久的に失敗する設定問題が発覚した場合、システムが対象モデルを自動的に強制無効化(`disabled`)します。エンドポイントの不整合等を解消(`seturl` 等)した後、この `enable` コマンドで手動復帰させてください。
*   `/dbwapi model reset <keyName>.<モデル名>` : 対象モデルの蓄積されたPP(ペナルティ)や、クールダウン状態を即座にゼロにリセットします。
*   `/dbwapi model resetall` : 現在登録されている「全モデル」を一斉にリセットします。
*   `/dbwapi model remove <keyName>.<モデル名> [confirm]` : 指定モデルを削除します。(※安全装置あり。末尾に `true` が必須です)

### 📌 AI動作テスト・エラーログ・DB管理 (Tests & Logger)
*   `/dbwapi ai status` : 現在実行・処理中の(`Active`)リクエストと、非同期処理の待機キュー(`Queue`)に入っているAIリクエストの件数を表示します。
*   `/dbwapi ai test` : 「現在有効なモデル(最も優先度が高く、通信可能なもの)」を利用して、システムから数十文字の短いテストプロンプトをAIに送信し、実際にテキストの返答が来るかどうかの疎通(結合)テストを行います。
*   `/dbwapi ai errors [表示件数]` : キューに蓄積されている「直近で発生したAI通信エラー(HTTPステータスコードや原因例外等)」の履歴を時間・対象モデル名とともに最大50件(省略時はデフォルト10件)チャット欄に素早く出力します。エラーの特定に便利です。
*   `/dbwapi ai errors clear` : 画面表示用のエラー履歴メモリを空にします。(※ディスク上のログファイル自体は削除されません)
*   `/dbwapi db list` : 依存Mod等から `DatabaseManager` に現在登録されている全カテゴリ名の一覧を表示します。
*   `/dbwapi db info <カテゴリ名>` : 対象カテゴリの保存先ルートパス、グローバルDBのキー数(ロード済の規模感)、および現在キャッシュに乗っているプレイヤー毎のUUIDデータの総数などのメトリクスを表示します。
*   `/dbwapi db errors [件数]` / `db errors clear` : `ai errors` と同じ仕組みで、DB特有のログ(`FILE_WRITE_ERROR` 等)をチャットに出力(省略時はデフォルト10件)・クリアします。
*   `/dbwapi db save` : メモリ上の全データベースの変更内容を明示的に強制ファイル書き出し(フラッシュ)させます。(※通常は `set` 時に自動で即時同期保存されるため、直接メモリを改ざんした場合の救済用です)。

---

## 📦 開発者向け: Java APIの実装利用方法 (API Layer for Developers)

当Core基盤は、依存Mod(自作Mod等)の Java コードから、シングルトン(`getInstance()`)または各種 Static メソッド経由で呼び出して利用します。`build.gradle` で `aidbwapi_core` を依存解決(`compileOnly` 等)に含めた上で実装してください。

### 1. AIへの非同期リクエスト (`AiCoreAPI`)
内部でのレート制限チェック、キーの振り分け、フォールバック、例外ハンドリングパイプラインをすべて隠蔽しています。
呼び出し側の開発者は「プロンプト文字列を投げて、CompletableFuture で結果の文字列を受け取る」だけで完結する非常にシンプルな設計として機能します。

```java
import com.morwapi.aidbwapi_core.api.AiCoreAPI;

// CompletableFuture<String> として実行結果が非同期に返却されます。
AiCoreAPI.getInstance().requestAI("Minecraftの魅力を100文字で教えて")
    .thenAccept(response -> {
        // [成功時想定] AIのレスポンス文字列(response)を取得して処理。
        System.out.println("AIの回答: " + response);
        
        // ⚠️【注意】ここは「別スレッド(AsyncExecutor内部)」で実行されています。
        // マイクラの世界(チャット送信、ブロック設置、エンティティ操作等)へ安全にアクセスするためには、
        // 必ず server.execute(() -> { ... }) 等のタスクキューを用いて
        // 処理をメインスレッド(Server Thread)へ確実に戻してください。
    })
    .exceptionally(ex -> {
        // [失敗時・例外時] 登録されている全モデルが使用不可(全滅)か、リトライ100件超過、
        // あるいはリクエストパラメータ不正(HTTP 400)等で完全失敗した場合に到達します。
        // エラーの種別(RATE_LIMITED, ALL_FAILED等)や詳細がメッセージ(ex.getMessage())に含まれます。
        System.out.println("AI通信エラー: " + ex.getMessage());
        return null; // CompletableFuture要件
    });

2. JSONデータベースとカテゴリ (CategoryDatabaseHandle)

AiCoreAPI を経由してカテゴリを登録・取得し、PlayerDatabase または GlobalDatabase のハンドルを受け取ってデータの保存・読出を行います。

【重要】JsonStorageEngineの仕様と型:
当DBは、独自の複雑なクラス構造(POJO)を直接保存・完全復元する高機能ORMツールではありません。Gsonの仕様等により、JSONファイルから get() で展開(復元)されたデータはすべて Map<String, Object>(あるいはプリミティブ型)のコレクションとしてロードされます。
そのため、保存時は自分で独自クラスインスタンスを渡すことも可能ですが、読込時はMapや標準型から自分でキャスト・再構築(あるいは別途Gsonでのデシリアライズ)を行う前提の、極めてシンプルな機能設計となっています。単純なMapや数値、文字列ベースでの利用を推奨します。

import com.morwapi.aidbwapi_core.api.AiCoreAPI;
import com.morwapi.aidbwapi_core.api.CategoryDatabaseHandle;
import java.util.UUID;

// ------ Modの初期化時 (FMLCommonSetupEvent等) ------

// [1]. カテゴリの自動生成・登録
AiCoreAPI.getInstance().registerCategory("guild_mod");

// [2]. 操作用DBハンドルの取得
CategoryDatabaseHandle dbHandle = AiCoreAPI.getInstance().getCategoryDatabase("guild_mod");

// ------ 実装例 (PlayerJoinEvent等) ------
UUID playerId = player.getUUID();

// [1]. データのロード (読み込み)
// JSONからMap形式等で復元されます。未作成の場合は null が返ります。
Object rawData = dbHandle.getPlayerDB().get(playerId, "killCount");
int killCount = 0;

if (rawData != null) {
    // Gsonにより数値はDouble等になる場合があるため、Number型で受け取りキャストします
    killCount = ((Number) rawData).intValue();
}

// [2]. データの更新とセーブ (保存)
killCount += 1;

// 引数: プレイヤーUUID, 保存識別キー名, 保存する値(Object)
dbHandle.getPlayerDB().set(playerId, "killCount", killCount);

// ※この `set()` メソッドを呼んだ瞬間に、メモリ(キャッシュ側のMap)への適用と同時に、
// `guild_mod/players/<UUID>.json` へ【同期的かつ即座に】ファイルが書き出されます。

⚖️ ライセンス (License)

このModのソースコードおよび提供されるバイナリは Apache License, Version 2.0 で提供・公開されています。
本基盤(API)を利用・依存した商用・非商用Modの作成および再配布は、ライセンス条項の範囲内で自由に行っていただけます。

Available Versions

AI DataBase wAPI Core 1.21.1-0.1.2release
MC 1.21.1neoforge
March 4, 2026
AI DataBase wAPI Core 1.21.1-0.1.0release
MC 1.21.1neoforge
March 3, 2026

How to Install AI DataBase wAPI Core on Your Server

1

Order Server

Order a Minecraft Java server with at least 3 GB RAM (4 GB recommended).

2

Set neoforge Loader

In the panel under "Egg", select the neoforge loader and matching Minecraft version (1.21.1).

3

Install Mod

Open the mod browser in the dashboard and search for "AI DataBase wAPI Core". Click "Install" – done! Alternatively, upload the .jar via SFTP to the /mods folder.

Compatibility

Mod Loaders

neoforge

Minecraft Versions

1.21.1

Server-side

Required

Recommended RAM

4 GB(min. 3 GB)

Frequently Asked Questions

AI DataBase wAPI Core server crashes on startup – what to do?

Most common cause: wrong neoforge version or insufficient RAM. Check the server log (latest.log) for "OutOfMemoryError" or "Mixin" errors. With Mado Hosting: ensure at least 3 GB RAM is allocated and the loader matches the mod version (1.21.1). You can switch loaders with one click in the panel.

Is AI DataBase wAPI Core compatible with neoforge?

AI DataBase wAPI Core officially supports neoforge for Minecraft 1.21.1. The Mado dashboard automatically detects incompatible loader combinations.

Server lagging with AI DataBase wAPI Core – how to optimize performance?

Recommended RAM: 4 GB (per 8 players). Use /spark profiler to check if AI DataBase wAPI Core consumes the most tick time. Common fixes: reduce server view-distance to 8-10, install "performant" or "starlight" as supplementary mods on Forge. With Mado Hosting, your server runs on NVMe SSDs with dedicated CPU cores for minimal latency.

Rent Modded Server

Install AI DataBase wAPI Core with just one click on your server.

Recommended RAM
4 GBab €8/mo
Min. 3 GB | +1 GB pro 8 Spieler
Create Server Now
1-Click Mod Install
NVMe SSD Storage
DDoS Protection included

Details

License
Apache License 2.0
Server-side
Required

Supported Versions

1.21.1