Логотип Deferring Heavy Dependencies

Deferring Heavy Dependencies

Сообщество
wdm0006
deferring-heavy-dependencies

Keep expensive resources — ML models, spellcheck dictionaries, embedded databases, large third-party imports — off code paths that never use them. Covers constructor work paid by every caller, one-size factories that load the heaviest member for the cheapest request, load-and-unload-per-call masquerading as a cache, measuring per-call cost in a fresh process, telling a one-time import from a repeated model load, and the test fallout (patches that only now take effect, autouse fixtures that hide the dependency). Use when a trivially cheap operation takes hundreds of milliseconds, when adding a heavy dependency to a shared constructor or factory, or when reviewing a class whose `__init__` builds something most callers never touch.

Обзор

Издательwdm0006
Репозиторийpython-skills
Название навыкаdeferring-heavy-dependencies
Звёзды
111
Форки
17
Файлы в комплекте
Только инструкции
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — wdm0006. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Deferring Heavy Dependencies в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/wdm0006/python-skills/tree/main/skills/python/lazy-dependencies
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wdm0006/python-skills.git /tmp/python-skills
mkdir -p .claude/skills
cp -r /tmp/python-skills/skills/python/lazy-dependencies .claude/skills/deferring-heavy-dependencies
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Deferring Heavy Dependencies в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Deferring Heavy Dependencies, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Deferring Heavy Dependencies не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Deferring Heavy Dependencies

A word count should not load a language model. When it does, the cause is almost never the algorithm — it is that the cheap function shares a constructor, a factory, or an import with an expensive one. Profiling the function body finds nothing, because the time is spent before the body runs.

The cost is in construction, not in the call

python
# Bad — every instance builds a dictionary, whatever the caller asked for.
class TextAnalyzer:
    def __init__(self) -> None:
        self.spell_checker = SpellChecker()      # ~12 MB retained, ~80 ms

    def character_count(self, text: str) -> int:
        return len(text)                         # never touches spell_checker

character_count profiles as free and still takes 80 ms. Defer the field:

python
# Good — built on first real use, then cached on the instance.
class TextAnalyzer:
    def __init__(self) -> None:
        self._spell_checker: SpellChecker | None = None

    @property
    def spell_checker(self) -> SpellChecker:
        if self._spell_checker is None:
            self._spell_checker = SpellChecker()
        return self._spell_checker

functools.cached_property covers the common case with less code, but it is not equivalent: since 3.12 it has no lock around the first call (so concurrent first access can compute twice), and its reset/pre-populate idiom (del obj.x, obj.x = val) is easy to get wrong — deleting a never-computed attribute raises AttributeError. Use the explicit form when you need controlled locking or a guaranteed-safe reset path.

Deferring is only safe when construction has no side effect the caller depends on ordering-wise — opening a file, binding a port, registering a signal handler. If it does, it isn't initialization, it's an operation: give it a method name.

One factory for everything makes cheap paths pay for the expensive one

The pattern that produces the worst numbers is a single accessor that builds the whole family:

python
# Bad — loads the NLP model, then constructs all four analyzers.
def get_analyzers() -> dict[str, Any]:
    nlp = load_language_model()          # seconds
    return {
        "basic": BasicStatsAnalyzer(),   # pure len()/split()
        "readability": ReadabilityAnalyzer(),
        "keywords": KeywordAnalyzer(nlp),
        "detection": DetectionAnalyzer(nlp),
    }

Every entry point calls get_analyzers(), so character counts, word counts, and reading-time estimates each pay a full model load and unload. Measured in a fresh process, that is on the order of half a second per call for work that is otherwise microseconds.

Split by what the path actually needs. Either give each analyzer its own accessor, or make the model itself a lazy handle the analyzers that need it pull from. Then state the boundary explicitly — which helpers are pure (regex, string, third-party parsers) and which genuinely require the initialized model — because that boundary is what the next change will violate.

Load-and-unload per call is not a cache

A factory that loads a model, uses it, and unloads it at the end of the request has the worst of both: the cost of loading, and none of the benefit of keeping it. Cache the handle for the process lifetime.

That choice has a consequence worth stating in the code: a cache that is never cleared makes every constructor cost permanent, so anything expensive inside the cached objects must be lazy too. The two techniques are a pair — process-long caching is what makes eager __init__ work unrecoverable, and laziness is what makes process-long caching affordable.

Measure per call, in a fresh process

In-process timing after the first call measures nothing; the model is already resident. Time the first call of a cold process, one entry point at a time:

bash
python -c "
import time
from mypkg.api import character_count, readability_score
for fn, name in ((character_count, 'character_count'), (readability_score, 'readability_score')):
    t = time.perf_counter(); fn('hello world'); print(name, round(time.perf_counter() - t, 4))
"

Distinguish a one-time import from a repeated load. After the fix, one entry point often still shows a few hundred milliseconds on its first call — that is the third-party package importing, paid once per process, not a model load returning. Confirm which you are looking at before reading it as the fix failing:

bash
python -X importtime -c "import mypkg.api" 2>&1 | sort -k2 -n -r | head

Then re-time the same call a second time in the same process: a one-time import drops to near zero, a per-call load does not.

For the memory half, tracemalloc around a single construction gives the retained size that argues for laziness far better than a wall-clock number does.

An ambient fixture hides the dependency you are trying to remove

The test that should catch a re-introduced model load usually cannot, because a session-scoped autouse fixture already loaded the real model for the whole run. Everything passes whether or not the cheap path touched it.

Assert on the loader, not on the outcome:

python
def test_character_count_does_not_load_the_model(monkeypatch):
    loader = Mock(side_effect=AssertionError("model loaded on a model-free path"))
    monkeypatch.setattr("mypkg.api.load_language_model", loader)

    assert character_count("hello world")["characters"] == 11
    loader.assert_not_called()

Failing loudly from the mock is deliberate: a bare assert_not_called() at the end still passes if the production code catches the exception it provoked.

Making a field lazy changes when patches bind

This is the surprise that follows the refactor. A test like:

python
@patch("mypkg.analyzers.SpellChecker")
def test_spelling(self, mock_checker): ...

did nothing while the field was eager and the instance was built in setup_method — the real object was already bound before the patch applied, so the test exercised the real dictionary. Once the field is lazy, the patch is consulted at first use and finally takes effect. The tests keep passing, but they now assert against a mock. Re-read every test that patches the deferred constructor and decide, per test, whether the mock is what you wanted.

The same shift is useful on purpose: to exercise code behind a lazy handle without loading anything, populate the private slot directly.

python
manager = build_manager(config)
manager._model = Mock()          # fills the lazy cache …
manager._tokenizer = Mock()      # … so the loader is never called

That runs in milliseconds and needs no fixtures — but it reaches past the public API, so keep it to tests whose subject is the surrounding logic, not the loading.

Checklist

- [ ] No `__init__` builds a resource most callers never read
- [ ] Deferred construction is side-effect-free (else it's a method, not a field)
- [ ] Cheap entry points don't route through a factory that builds heavy ones
- [ ] Heavy handles are cached for the process, not loaded and unloaded per call
- [ ] Timings taken in a fresh process, first call, one entry point at a time
- [ ] One-time import cost told apart from a per-call load (`-X importtime`, second call)
- [ ] Retained size measured (`tracemalloc`) where memory is the argument
- [ ] A test asserts the loader is NOT called on model-free paths
- [ ] Tests that patch the now-lazy constructor re-read — some only now take effect

Часто задаваемые вопросы

Что делает навык ИИ Deferring Heavy Dependencies?

Keep expensive resources — ML models, spellcheck dictionaries, embedded databases, large third-party imports — off code paths that never use them. Covers constructor work paid by every caller, one-size factories that load the heaviest member for the cheapest request, load-and-unload-per-call masquerading as a cache, measuring per-call cost in a fresh process, telling a one-time import from a repeated model load, and the test fallout (patches that only now take effect, autouse fixtures that hide the dependency). Use when a trivially cheap operation takes hundreds of milliseconds, when adding...

Зачем использовать Deferring Heavy Dependencies в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Deferring Heavy Dependencies — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Deferring Heavy Dependencies в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/wdm0006/python-skills/tree/main/skills/python/lazy-dependencies. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Deferring Heavy Dependencies?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Deferring Heavy Dependencies?

С любым количеством. В TypingMind вы можете использовать Deferring Heavy Dependencies с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Deferring Heavy Dependencies?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — wdm0006. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇