Content Hash Cache Pattern logo

Content Hash Cache Pattern

Community
mturac
content-hash-cache-pattern

SHA-256コンテンツハッシュを使用して、高コストなファイル処理結果をキャッシュします — パス非依存、自動無効化、サービスレイヤーの分離。

Overview

Publishermturac
Repositoryeverything-openai-codex
Skill namecontent-hash-cache-pattern
Stars
91
Forks
2
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by mturac on GitHub. Read the source before you install it.

Installation

Install the Content Hash Cache Pattern AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/mturac/everything-openai-codex.git /tmp/everything-openai-codex
mkdir -p .claude/skills
cp -r /tmp/everything-openai-codex/docs/ja-JP/skills/content-hash-cache-pattern .claude/skills/content-hash-cache-pattern
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Content Hash Cache Pattern in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Content Hash Cache Pattern on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Content Hash Cache Pattern is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

コンテンツハッシュファイルキャッシュパターン

SHA-256コンテンツハッシュをキャッシュキーとして使用して、高コストなファイル処理結果(PDF解析、テキスト抽出、画像分析)をキャッシュします。パスベースのキャッシュとは異なり、このアプローチはファイルの移動/名前変更に対して生き残り、コンテンツが変更されたときに自動的に無効化されます。

起動条件

  • ファイル処理パイプラインの構築(PDF、画像、テキスト抽出)
  • 処理コストが高く、同じファイルが繰り返し処理される場合
  • --cache/--no-cacheCLIオプションが必要な場合
  • 既存の純粋な関数を変更せずにキャッシュを追加したい場合

コアパターン

1. コンテンツハッシュベースのキャッシュキー

パスではなくファイルコンテンツをキャッシュキーとして使用します:

python
import hashlib
from pathlib import Path

_HASH_CHUNK_SIZE = 65536  # 大きなファイルには64KBチャンク

def compute_file_hash(path: Path) -> str:
    """ファイルコンテンツのSHA-256(大きなファイルにはチャンク処理)。"""
    if not path.is_file():
        raise FileNotFoundError(f"File not found: {path}")
    sha256 = hashlib.sha256()
    with open(path, "rb") as f:
        while True:
            chunk = f.read(_HASH_CHUNK_SIZE)
            if not chunk:
                break
            sha256.update(chunk)
    return sha256.hexdigest()

なぜコンテンツハッシュ? ファイルの名前変更/移動 = キャッシュヒット。コンテンツ変更 = 自動無効化。インデックスファイル不要。

2. キャッシュエントリの凍結データクラス

python
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class CacheEntry:
    file_hash: str
    source_path: str
    document: ExtractedDocument  # キャッシュされた結果

3. ファイルベースのキャッシュストレージ

各キャッシュエントリは{hash}.jsonとして保存されます — ハッシュによるO(1)検索、インデックスファイル不要。

python
import json
from typing import Any

def write_cache(cache_dir: Path, entry: CacheEntry) -> None:
    cache_dir.mkdir(parents=True, exist_ok=True)
    cache_file = cache_dir / f"{entry.file_hash}.json"
    data = serialize_entry(entry)
    cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")

def read_cache(cache_dir: Path, file_hash: str) -> CacheEntry | None:
    cache_file = cache_dir / f"{file_hash}.json"
    if not cache_file.is_file():
        return None
    try:
        raw = cache_file.read_text(encoding="utf-8")
        data = json.loads(raw)
        return deserialize_entry(data)
    except (json.JSONDecodeError, ValueError, KeyError):
        return None  # 破損をキャッシュミスとして扱う

4. サービスレイヤーラッパー(SRP)

処理関数を純粋に保ちます。キャッシュを別のサービスレイヤーとして追加します。

python
def extract_with_cache(
    file_path: Path,
    *,
    cache_enabled: bool = True,
    cache_dir: Path = Path(".cache"),
) -> ExtractedDocument:
    """サービスレイヤー: キャッシュチェック -> 抽出 -> キャッシュ書き込み。"""
    if not cache_enabled:
        return extract_text(file_path)  # 純粋な関数、キャッシュの知識なし

    file_hash = compute_file_hash(file_path)

    # キャッシュを確認
    cached = read_cache(cache_dir, file_hash)
    if cached is not None:
        logger.info("Cache hit: %s (hash=%s)", file_path.name, file_hash[:12])
        return cached.document

    # キャッシュミス -> 抽出 -> 保存
    logger.info("Cache miss: %s (hash=%s)", file_path.name, file_hash[:12])
    doc = extract_text(file_path)
    entry = CacheEntry(file_hash=file_hash, source_path=str(file_path), document=doc)
    write_cache(cache_dir, entry)
    return doc

主要な設計上の決定

決定根拠
SHA-256コンテンツハッシュパス非依存、コンテンツ変更で自動無効化
{hash}.jsonファイル命名O(1)検索、インデックスファイル不要
サービスレイヤーラッパーSRP: 抽出は純粋に保ち、キャッシュは別の関心事
手動JSONシリアル化凍結データクラスのシリアル化を完全制御
破損はNoneを返すグレースフルデグラデーション、次回の実行で再処理
cache_dir.mkdir(parents=True)最初の書き込み時に遅延ディレクトリ作成

ベストプラクティス

  • パスではなくコンテンツをハッシュ — パスは変わるが、コンテンツのアイデンティティは変わらない
  • 大きなファイルはチャンク処理でハッシュ — ファイル全体をメモリに読み込まないようにする
  • 処理関数を純粋に保つ — キャッシュについて何も知らないようにする
  • 切り捨てたハッシュでキャッシュヒット/ミスをログ記録 — デバッグのため
  • 破損をグレースフルに処理 — 無効なキャッシュエントリはミスとして扱い、クラッシュしない

避けるべきアンチパターン

python
# 悪い例: パスベースのキャッシュ(ファイルの移動/名前変更で壊れる)
cache = {"/path/to/file.pdf": result}

# 悪い例: 処理関数内にキャッシュロジックを追加(SRP違反)
def extract_text(path, *, cache_enabled=False, cache_dir=None):
    if cache_enabled:  # この関数は今や2つの責任を持っている
        ...

# 悪い例: ネストされた凍結データクラスでdataclasses.asdict()を使用
# (複雑なネストされた型で問題を引き起こす可能性がある)
data = dataclasses.asdict(entry)  # 代わりに手動シリアル化を使用

使用すべき場合

  • ファイル処理パイプライン(PDF解析、OCR、テキスト抽出、画像分析)
  • --cache/--no-cacheオプションが有益なCLIツール
  • 同じファイルが複数回にわたって現れるバッチ処理
  • 既存の純粋な関数を変更せずにキャッシュを追加する場合

使用すべきでない場合

  • 常に最新でなければならないデータ(リアルタイムフィード)
  • 非常に大きなキャッシュエントリ(代わりにストリーミングを検討)
  • ファイルコンテンツ以外のパラメータに依存する結果(例:異なる抽出設定)

Frequently asked questions

What does the Content Hash Cache Pattern AI skill do?

SHA-256コンテンツハッシュを使用して、高コストなファイル処理結果をキャッシュします — パス非依存、自動無効化、サービスレイヤーの分離。

Why use Content Hash Cache Pattern on TypingMind?

Because you install it once and use it with any model. Content Hash Cache Pattern is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Content Hash Cache Pattern in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/mturac/everything-openai-codex/tree/main/docs/ja-JP/skills/content-hash-cache-pattern. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Content Hash Cache Pattern?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Content Hash Cache Pattern?

As many as you like. As long as a model supports skills, you can use Content Hash Cache Pattern with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Content Hash Cache Pattern AI skill free?

Yes. It is published on GitHub by mturac under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇