Skip to content

Personal AI, On Personal Devices

Python

feat: add SystemPromptBuilder with frozen prefix and char limits

Tarun Suresh978749e9f89e
diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.py
index 97f631e6..f6e9f4b7 100644
--- a/src/openjarvis/core/config.py
+++ b/src/openjarvis/core/config.py
@@ -1065,6 +1065,17 @@ class MemoryFilesConfig:
nudge_interval: int = 10
+@dataclass(slots=True)
+class SystemPromptConfig:
+ """Limits and strategy for system-prompt assembly."""
+
+ soul_max_chars: int = 4000
+ memory_max_chars: int = 2500
+ user_max_chars: int = 1500
+ skill_desc_max_chars: int = 60
+ truncation_strategy: str = "head_tail"
+
+
@dataclass
class JarvisConfig:
"""Top-level configuration for OpenJarvis."""
@@ -1090,6 +1101,7 @@ class JarvisConfig:
optimize: OptimizeConfig = field(default_factory=OptimizeConfig)
agent_manager: AgentManagerConfig = field(default_factory=AgentManagerConfig)
memory_files: MemoryFilesConfig = field(default_factory=MemoryFilesConfig)
+ system_prompt: SystemPromptConfig = field(default_factory=SystemPromptConfig)
@property
def memory(self) -> StorageConfig:
diff --git a/src/openjarvis/prompt/__init__.py b/src/openjarvis/prompt/__init__.py
new file mode 100644
index 00000000..9d48db4f
--- /dev/null
+++ b/src/openjarvis/prompt/__init__.py
@@ -0,0 +1 @@
+from __future__ import annotations
diff --git a/src/openjarvis/prompt/builder.py b/src/openjarvis/prompt/builder.py
new file mode 100644
index 00000000..dd844668
--- /dev/null
+++ b/src/openjarvis/prompt/builder.py
@@ -0,0 +1,87 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import List, Optional, Tuple
+
+from openjarvis.core.config import MemoryFilesConfig, SystemPromptConfig
+
+
+class SystemPromptBuilder:
+ """Assembles system prompts with frozen prefix for cache stability."""
+
+ def __init__(
+ self,
+ agent_template: str,
+ memory_files_config: Optional[MemoryFilesConfig] = None,
+ system_prompt_config: Optional[SystemPromptConfig] = None,
+ skill_index: Optional[List[Tuple[str, str]]] = None,
+ session_context: Optional[str] = None,
+ previous_state: Optional[str] = None,
+ ) -> None:
+ self._agent_template = agent_template
+ self._mf_config = memory_files_config or MemoryFilesConfig()
+ self._sp_config = system_prompt_config or SystemPromptConfig()
+ self._skill_index = skill_index or []
+ self._session_context = session_context
+ self._previous_state = previous_state
+ self._frozen_prefix: Optional[str] = None
+
+ def build(self) -> str:
+ if self._frozen_prefix is None:
+ self._frozen_prefix = self._build_frozen_prefix()
+ parts = [self._frozen_prefix]
+ if self._session_context:
+ parts.append(f"\n\n## Session Context\n\n{self._session_context}")
+ if self._previous_state:
+ parts.append(f"\n\n## Previous State\n\n{self._previous_state}")
+ return "".join(parts)
+
+ def _build_frozen_prefix(self) -> str:
+ sections: list[str] = []
+ sections.append(self._agent_template)
+ soul = self._load_file(
+ self._mf_config.soul_path, self._sp_config.soul_max_chars,
+ )
+ if soul:
+ sections.append(f"## Agent Persona\n\n{soul}")
+ memory = self._load_file(
+ self._mf_config.memory_path,
+ self._sp_config.memory_max_chars,
+ )
+ if memory:
+ sections.append(f"## Agent Memory\n\n{memory}")
+ user = self._load_file(
+ self._mf_config.user_path, self._sp_config.user_max_chars,
+ )
+ if user:
+ sections.append(f"## User Profile\n\n{user}")
+ if self._skill_index:
+ skill_lines = []
+ for name, desc in self._skill_index:
+ truncated = desc[: self._sp_config.skill_desc_max_chars]
+ if len(desc) > self._sp_config.skill_desc_max_chars:
+ truncated = truncated[:-3] + "..."
+ skill_lines.append(f"- **{name}**: {truncated}")
+ sections.append("## Available Skills\n\n" + "\n".join(skill_lines))
+ return "\n\n".join(sections)
+
+ def _load_file(self, path_str: str, max_chars: int) -> str:
+ path = Path(path_str).expanduser()
+ if not path.exists():
+ return ""
+ content = path.read_text()
+ if len(content) <= max_chars:
+ return content
+ return self._truncate(content, max_chars)
+
+ def _truncate(self, text: str, max_chars: int) -> str:
+ if self._sp_config.truncation_strategy == "head_tail":
+ head_size = int(max_chars * 0.7)
+ tail_size = int(max_chars * 0.2)
+ omitted = len(text) - head_size - tail_size
+ return (
+ text[:head_size]
+ + f"\n\n[...truncated {omitted} chars...]\n\n"
+ + text[-tail_size:]
+ )
+ return text[:max_chars] + "\n[...truncated...]"
diff --git a/tests/prompt/__init__.py b/tests/prompt/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/prompt/test_builder.py b/tests/prompt/test_builder.py
new file mode 100644
index 00000000..13cc20ac
--- /dev/null
+++ b/tests/prompt/test_builder.py
@@ -0,0 +1,119 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from openjarvis.core.config import MemoryFilesConfig, SystemPromptConfig
+
+
+def memory_dir(tmp_path: Path) -> Path:
+ soul = tmp_path / "SOUL.md"
+ soul.write_text("You are a helpful research assistant.")
+ memory = tmp_path / "MEMORY.md"
+ memory.write_text("- User prefers concise answers\n- User is a data scientist")
+ user = tmp_path / "USER.md"
+ user.write_text("- Name: Alice\n- Role: ML Engineer")
+ return tmp_path
+
+
+def test_build_frozen_prefix(memory_dir: Path):
+ from openjarvis.prompt.builder import SystemPromptBuilder
+ builder = SystemPromptBuilder(
+ agent_template="You are Jarvis.",
+ memory_files_config=MemoryFilesConfig(
+ soul_path=str(memory_dir / "SOUL.md"),
+ memory_path=str(memory_dir / "MEMORY.md"),
+ user_path=str(memory_dir / "USER.md"),
+ ),
+ system_prompt_config=SystemPromptConfig(),
+ )
+ prompt = builder.build()
+ assert "Jarvis" in prompt
+ assert "helpful research assistant" in prompt
+ assert "concise answers" in prompt
+ assert "Alice" in prompt
+
+
+def test_frozen_prefix_stability(memory_dir: Path):
+ from openjarvis.prompt.builder import SystemPromptBuilder
+ builder = SystemPromptBuilder(
+ agent_template="You are Jarvis.",
+ memory_files_config=MemoryFilesConfig(
+ soul_path=str(memory_dir / "SOUL.md"),
+ memory_path=str(memory_dir / "MEMORY.md"),
+ user_path=str(memory_dir / "USER.md"),
+ ),
+ system_prompt_config=SystemPromptConfig(),
+ )
+ first = builder.build()
+ (memory_dir / "MEMORY.md").write_text("- CHANGED CONTENT")
+ second = builder.build()
+ assert first == second
+
+
+def test_char_limit_truncation(memory_dir: Path):
+ from openjarvis.prompt.builder import SystemPromptBuilder
+ (memory_dir / "SOUL.md").write_text("x" * 10000)
+ builder = SystemPromptBuilder(
+ agent_template="You are Jarvis.",
+ memory_files_config=MemoryFilesConfig(
+ soul_path=str(memory_dir / "SOUL.md"),
+ memory_path=str(memory_dir / "MEMORY.md"),
+ user_path=str(memory_dir / "USER.md"),
+ ),
+ system_prompt_config=SystemPromptConfig(soul_max_chars=100),
+ )
+ prompt = builder.build()
+ assert prompt.count("x") <= 100
+ assert "truncated" in prompt.lower()
+
+
+def test_skill_index_in_prompt(memory_dir: Path):
+ from openjarvis.prompt.builder import SystemPromptBuilder
+ skills = [("api_health_check", "Check API health across all endpoints")]
+ builder = SystemPromptBuilder(
+ agent_template="You are Jarvis.",
+ memory_files_config=MemoryFilesConfig(
+ soul_path=str(memory_dir / "SOUL.md"),
+ memory_path=str(memory_dir / "MEMORY.md"),
+ user_path=str(memory_dir / "USER.md"),
+ ),
+ system_prompt_config=SystemPromptConfig(),
+ skill_index=skills,
+ )
+ prompt = builder.build()
+ assert "api_health_check" in prompt
+ assert "Check API health" in prompt
+
+
+def test_dynamic_section_appended(memory_dir: Path):
+ from openjarvis.prompt.builder import SystemPromptBuilder
+ builder = SystemPromptBuilder(
+ agent_template="You are Jarvis.",
+ memory_files_config=MemoryFilesConfig(
+ soul_path=str(memory_dir / "SOUL.md"),
+ memory_path=str(memory_dir / "MEMORY.md"),
+ user_path=str(memory_dir / "USER.md"),
+ ),
+ system_prompt_config=SystemPromptConfig(),
+ session_context="Platform: CLI | Session: abc123",
+ )
+ prompt = builder.build()
+ assert "Platform: CLI" in prompt
+
+
+def test_missing_files_handled(tmp_path: Path):
+ from openjarvis.prompt.builder import SystemPromptBuilder
+ builder = SystemPromptBuilder(
+ agent_template="You are Jarvis.",
+ memory_files_config=MemoryFilesConfig(
+ soul_path=str(tmp_path / "missing_soul.md"),
+ memory_path=str(tmp_path / "missing_memory.md"),
+ user_path=str(tmp_path / "missing_user.md"),
+ ),
+ system_prompt_config=SystemPromptConfig(),
+ )
+ prompt = builder.build()
+ assert "Jarvis" in prompt