Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(compiler): opt-in OpenRouter Response Caching for compiler LLM calls by pitimon · Pull Request #40 · VectifyAI/OpenKB · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(compiler): opt-in OpenRouter Response Caching for compiler LLM calls by pitimon · Pull Request #40 · VectifyAI/OpenKB · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(compiler): opt-in OpenRouter Response Caching for compiler LLM calls by pitimon · Pull Request #40 · VectifyAI/OpenKB · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(compiler): opt-in OpenRouter Response Caching for compiler LLM calls by pitimon · Pull Request #40 · VectifyAI/OpenKB · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(compiler): opt-in OpenRouter Response Caching for compiler LLM calls by pitimon · Pull Request #40 · VectifyAI/OpenKB · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(compiler): opt-in OpenRouter Response Caching for compiler LLM calls by pitimon · Pull Request #40 · VectifyAI/OpenKB · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(compiler): opt-in OpenRouter Response Caching for compiler LLM calls by pitimon · Pull Request #40 · VectifyAI/OpenKB · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,13 @@
Step 3: A + summary → concepts plan (create/update/related).
Step 4: Concurrent LLM calls (A cached) → generate new + rewrite updated concepts.
Step 5: Code adds cross-ref links to related concepts, updates index.

Anthropic prompt caching is enabled via ``cache_control`` markers at two
breakpoints: end of the document message (caches system + doc across all
N+M+2 calls) and end of the assistant summary message (caches the additional
summary prefix across N+M concept-generation calls). Providers that do not
support cache_control receive a normalized list-of-blocks content payload,
which LiteLLM passes through cleanly.
"""
from __future__ import annotations

Expand DownExpand Up@@ -131,6 +138,50 @@
# LLM helpers
# ---------------------------------------------------------------------------

def _cached_text(text: str) -> list[dict]:
"""Wrap a text payload into a content-block list with an Anthropic
ephemeral cache_control marker.

LiteLLM passes the marker through to Anthropic (and OpenRouter →
Anthropic). For providers that ignore cache_control, the list-of-blocks
payload remains a valid OpenAI-compatible content shape.
"""
return [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}]


def _response_cache_headers(config: dict, model: str) -> dict:
"""Build OpenRouter Response Caching headers from config.

Returns an empty dict when the feature is disabled or the active model
is not routed through OpenRouter (the headers would have no effect on
direct provider calls). When enabled, emits ``X-OpenRouter-Cache: true``
and, if a TTL is configured, ``X-OpenRouter-Cache-TTL: <seconds>``.
"""
if not config.get("response_cache", False):
return {}
if not model.startswith("openrouter/"):
return {}
headers = {"X-OpenRouter-Cache": "true"}
ttl = config.get("response_cache_ttl")
if ttl is not None:
headers["X-OpenRouter-Cache-TTL"] = str(int(ttl))
return headers


def _build_llm_kwargs(config: dict, model: str) -> dict:
"""Compose extra LiteLLM kwargs derived from config (e.g. response cache).

Currently only emits an ``extra_headers`` entry when OpenRouter Response
Caching is enabled. Returns an empty dict when no extras apply, so the
caller can splat with ``**`` and fall back to existing behaviour.
"""
extras: dict = {}
cache_headers = _response_cache_headers(config, model)
if cache_headers:
extras["extra_headers"] = cache_headers
return extras


class _Spinner:
"""Animated dots spinner that runs in a background thread."""

Expand DownExpand Up@@ -168,15 +219,23 @@ def _format_usage(elapsed: float, usage) -> str:


def _fmt_messages(messages: list[dict], max_content: int = 200) -> str:
"""Format messages for debug output, truncating long content."""
"""Format messages for debug output, truncating long content.

Accepts both plain-string content and the list-of-blocks shape used by
cache_control-tagged messages (joins all text blocks for preview).
"""
parts = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if len(content) > max_content:
preview = content[:max_content] + f"... ({len(content)} chars)"
raw = msg["content"]
if isinstance(raw, list):
text = "".join(b.get("text", "") for b in raw if isinstance(b, dict))
else:
text = raw
if len(text) > max_content:
preview = text[:max_content] + f"... ({len(text)} chars)"
else:
preview = content
preview = text
parts.append(f" [{role}] {preview}")
return "\n".join(parts)

Expand All@@ -199,13 +258,15 @@ def _llm_call(model: str, messages: list[dict], step_name: str, **kwargs) -> str
return content.strip()


async def _llm_call_async(model: str, messages: list[dict], step_name: str) -> str:
async def _llm_call_async(model: str, messages: list[dict], step_name: str, **kwargs) -> str:
"""Async LLM call with timing output and debug logging."""
logger.debug("LLM request [%s]:\n%s", step_name, _fmt_messages(messages))
if kwargs:
logger.debug("LLM kwargs [%s]: %s", step_name, kwargs)

t0 = time.time()

response = await litellm.acompletion(model=model, messages=messages)
response = await litellm.acompletion(model=model, messages=messages, **kwargs)
content = response.choices[0].message.content or ""

elapsed = time.time() - t0
Expand DownExpand Up@@ -576,25 +637,34 @@ async def _compile_concepts(
max_concurrency: int,
doc_brief: str = "",
doc_type: str = "short",
extra_kwargs: dict | None = None,
) -> None:
"""Shared Steps 2-4: concepts plan → generate/update → index.

Uses ``_CONCEPTS_PLAN_USER`` to get a plan with create/update/related
actions, then executes each action type accordingly.

``extra_kwargs`` is forwarded to every LiteLLM call (e.g. response-cache
headers). Defaults to no extras.
"""
source_file = f"summaries/{doc_name}.md"
extra_kwargs = extra_kwargs or {}

# --- Step 2: Get concepts plan (A cached) ---
concept_briefs = _read_concept_briefs(wiki_dir)

# Second cache breakpoint: end of the assistant summary message. Covers
# (system + doc + summary) for the plan call and every concept call.
summary_msg = {"role": "assistant", "content": _cached_text(summary)}

plan_raw = _llm_call(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPTS_PLAN_USER.format(
concept_briefs=concept_briefs,
)},
], "concepts-plan", max_tokens=1024)
], "concepts-plan", max_tokens=1024, **extra_kwargs)

try:
parsed = _parse_json(plan_raw)
Expand DownExpand Up@@ -632,12 +702,12 @@ async def _gen_create(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_PAGE_USER.format(
title=title, doc_name=doc_name,
update_instruction="",
)},
], f"concept: {name}")
], f"concept: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand All@@ -663,12 +733,12 @@ async def _gen_update(concept: dict) -> tuple[str, str, bool, str]:
raw = await _llm_call_async(model, [
system_msg,
doc_msg,
{"role": "assistant", "content": summary},
summary_msg,
{"role": "user", "content": _CONCEPT_UPDATE_USER.format(
title=title, doc_name=doc_name,
existing_content=existing_content,
)},
], f"update: {name}")
], f"update: {name}", **extra_kwargs)
try:
parsed = _parse_json(raw)
brief = parsed.get("brief", "")
Expand DownExpand Up@@ -741,16 +811,20 @@ async def compile_short_doc(
schema_md = get_agents_md(wiki_dir)
content = source_path.read_text(encoding="utf-8")

# Base context A: system + document
# Base context A: system + document. cache_control marker on the doc
# message creates a cache breakpoint that covers (system + doc) for
# every downstream call (summary, concepts-plan, every concept page).
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_SUMMARY_USER.format(
doc_name=doc_name, content=content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate summary ---
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary")
summary_raw = _llm_call(model, [system_msg, doc_msg], "summary", **extra_kwargs)
try:
summary_parsed = _parse_json(summary_raw)
doc_brief = summary_parsed.get("brief", "")
Expand All@@ -764,7 +838,7 @@ async def compile_short_doc(
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
summary, doc_name, max_concurrency, doc_brief=doc_brief,
doc_type="short",
doc_type="short", extra_kwargs=extra_kwargs,
)


Expand DownExpand Up@@ -792,20 +866,23 @@ async def compile_long_doc(
schema_md = get_agents_md(wiki_dir)
summary_content = summary_path.read_text(encoding="utf-8")

# Base context A
# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
system_msg = {"role": "system", "content": _SYSTEM_TEMPLATE.format(
schema_md=schema_md, language=language,
)}
doc_msg = {"role": "user", "content": _LONG_DOC_SUMMARY_USER.format(
doc_msg = {"role": "user", "content": _cached_text(_LONG_DOC_SUMMARY_USER.format(
doc_name=doc_name, doc_id=doc_id, content=summary_content,
)}
))}

extra_kwargs = _build_llm_kwargs(config, model)

# --- Step 1: Generate overview ---
overview = _llm_call(model, [system_msg, doc_msg], "overview")
overview = _llm_call(model, [system_msg, doc_msg], "overview", **extra_kwargs)

# --- Steps 2-4: Concept plan → generate/update → index ---
await _compile_concepts(
wiki_dir, kb_dir, model, system_msg, doc_msg,
overview, doc_name, max_concurrency, doc_brief=doc_description,
doc_type="pageindex",
doc_type="pageindex", extra_kwargs=extra_kwargs,
)
9 changes: 9 additions & 0 deletions openkb/config.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,15 @@
"model": "gpt-5.4-mini",
"language": "en",
"pageindex_threshold": 20,
# Opt-in OpenRouter Response Caching for compiler LLM calls.
# When enabled and the active model is routed via openrouter/, identical
# requests (same model, messages, params) return a cached response with
# zero token billing. Default off because responses are stored on
# OpenRouter — conflicts with strict zero-data-retention postures.
"response_cache": False,
# Optional TTL override in seconds (1..86400). When None, OpenRouter's
# default of 300s applies.
"response_cache_ttl": None,
}

GLOBAL_CONFIG_DIR = Path.home() / ".config" / "openkb"
Expand Down
Loading