Filling "LLM OS Memory" with Just the Right "Bytes": Context Engineering at JAPAN AI

⭐️This is Day 23 of the JAPAN AI Advent Calendar 2025⭐️
This is Kui Xiong, tech lead of the Agent Core team at JAPAN AI, where we build our agentic framework that enables other teams to build powerful agents for our customers.
LLMs power an agent's ability to complete tasks, but only when we provide them with accurate and comprehensive context. Without proper context management, even the most advanced models fail.
Introduction
With the progress of fundamental LLM and the prevalence of agents, the complexity of tasks that agents complete continues to increase. Correspondingly, the amount of contextual information that agents need to process is also growing rapidly. In this situation, we face:
- Growing context gradually becomes noise, unable to be effectively utilized by LLMs or even misleading LLMs into making incorrect judgments
- Massive context gradually exceeds LLM context window limits, causing tasks to fail in the middle
- The number of tools corresponding to task completion keeps growing, ineffectively occupying context
Although for over the past 3 years, we see model hallucination rates decreasing and model context handling capacity increasing over time, just as in the traditional computer industry where we still need an advanced operating system to maximize chip capabilities, to fully leverage LLM performance, we need an effective system to manage context and accurately send it to LLMs for analysis and processing when needed. This is what we call Context Engineering when it comes to managing the context for each user's request before involving LLM.
Nowadays, we have implemented a sophisticated system to compose the context for LLM both cost friendly and efficiently, from which I would like to highlight the following:
- Our memory extraction/retrieval system to provide LLMs with long-term important information, along with windowed user-assistant message history and dynamic context injection system to compose the final message list for LLM
- Multi-agent architecture to reduce context occupation from tool call results with isolated context for sub-agent to complete independent task
- Both user command driven and auto detection driven context compaction methods to prevent context overflow
- Intelligent tool selection and dynamic tool activation to reduce tool token consumption and still remain accessibility to necessary tools
How We Manage Context
LLM context generally consists of two parts, as we can see in below illustration:
- Messages: system instructions, user instructions, assistant responses and tool execution results
- Available tool list: tool descriptions and parameter descriptions

Usually for one round of chat with an agent, system prompt and user input should remain the same whereas assistant response and tool execution result will keep growing. Our system manages both messages and tools in terms of context engineering.
Figure 1: Example of LLM context
Memory system and dynamic context injection
Generally, system prompt doesn’t change, user input doesn’t change in one round chat either, but will grow with multiple rounds of chat, assistant response and tool execution results always grow continuously as tasks execute . In order to make system prompts more adaptive, and to provide more context-aware instructions, we use dynamic context injection to dynamically load specific prompts based on different models, different tool configurations, or more complex conditional expression logic. These prompts guide the LLM to more accurately complete subsequent actions.
Each user-agent interaction generates new information. As interactions increase, most outdated information in the past no longer guides new tasks required by users. However, to ensure important information isn't missed, we need a memory system to extract and retrieve this important information, avoiding users repeatedly providing duplicate information over longer time scales, which would degrade user experience. Currently, JAPAN AI fully retains the most recent K (e.g., 50) user-assistant messages and uses memory tools at runtime to preserve important information. When building context, we proactively retrieve relevant memory information using the current user input and inject memories to ensure the LLM receives both long-term and short-term user context.

System prompts and system instructions are loaded dynamically based on current existing context information, like user input, tools activated etc. They remain the same for current user request, while assistant response and tool results will grow while agent runs
Figure 2 Memory and Dynamic Context Injection
Multi-Agent
In a single-agent system, each tool call result generates new context. Sometimes we don't need all results from all tools. For example, when a user generates a certain slide and needs to introduce a company, we first call a search tool to get internet information, then call the slide generation tool to fill in relevant results. The core of this task is completing slide generation, and the intermediate search results are actually useless for the task—we only need the final summarized company introduction information.
If we introduce a slide generator sub-agent, we only need to provide this sub-agent with the corresponding task prompt. Ultimately, in our parent agent's context, only slide information exists, thus saving context space. As illustrated below, we implement sub-agent task generation and scheduling through tool calls.

When LLM decides to delegate work to a sub-agent, it will make a tool call, and the parent agent will prepare the sub-agent context with existing context information. When the sub-agent returns the result, the parent agent will append the result to its own context.
Figure 3 Parent agent v.s Sub-agent workflow
Context Compaction
LLM context windows are ultimately limited. As task execution steps increase and execution time extends, context length will inevitably reach the LLM's processing limit. To support LLMs executing more tool calls and more complex tasks, we need to compact context. Currently, JAPAN AI supports two modes of context compaction — command driven and proactive detection driven.
Command driven compression is initiated by users issuing a compaction command, and the system compacts current context information into a specific markdown format upon receiving the command. Proactive detection mode means the system automatically triggers the compaction when it detects that the accumulated context length exceeds a certain percentage (e.g 60%) of the current model's supported context length.
Whether command driven or proactive detection driven, subsequent task execution or conversations continue based on the compressed context, which is by design to be smaller than the context before compaction.

When we do context compaction, we only compact the lengthy history message, newly generated assistant message and tool results, leaving system prompt, system instructions untouched. We also keep the last user message to avoid user intention drifting after compaction.
Figure 4 Context compaction example
Tool selection
Tool calling is an indispensable step for LLMs to complete tasks. To enable LLMs to select and use the correct tools, agents need to provide a proper tool set candidate that can complete the current task. To avoid consuming tokens unnecessarily and to avoid LLM hallucinations about which tool to use, we cannot provide too many tools to the LLM.
A basic consensus is to use as few and as general tools as possible for the LLM, then let the LLM autonomously explore basic tool combinations to complete tasks. This base tool approach can satisfy common tasks, but sometimes scenario-specific tools are necessary—for example, operating Google Drive and operating Notion documents require different tools. In such cases, for specific tasks in specific scenarios, we need to dynamically adjust the tool set to meet user needs.
Currently, JAPAN AI's approach is to configure a basic available tool set for the agent at task start, while quickly retrieving available tools through task descriptions. However, when specific tools are needed during long-term task execution, we provide a tool search tool that retrieves based on task descriptions to find appropriate specific tools for handling the current task.

When LLM finds that the base tool set is not capable of handling current task, it will then call the tool search tool to find relevant tools from our tool vector DB (pinecone), after receiving the new tool candidates list, it will then determine which tool to activate and insert the selected tool into the base tool set.
Figure 5 Tool selection example
While these techniques form the foundation of our context engineering approach, implementing them in production revealed several non-trivial challenges. This section will discuss some specific examples and share the thinking process behind our implementations.
Challenges and Solutions
Challenge 1: Dynamic Context Injection and KV Cache
LLM KV cache is a technique that not only improves response speed but also reduces token consumption when sending requests to LLM. However, because KV cache is based on prefix matching, any modification to the prefix causes cache hit misses. To maximize cache hits, we need to ensure injection consistency while enabling dynamic context injection. As we can see in Figure 2 where we show the dynamic context injection. We divided the message list into 5 segments: system instructions -> message-start system instructions -> history messages -> message-end system instructions -> task execution messages.
Within a single task execution cycle, everything from system prompts to message-end system instructions remains unchanged, while task execution messages append in sequence, allowing perfect KV cache utilization. However, across tasks, e.g when the first user request finishes and the user initiates a new request, if we want to maximize KV cache reuse, we need to ensure the stability of the dynamically injected context. So that we can reuse the kv cache created by previous request handling. At present, we maintain the stability of system prompts, message-start system instruction by specifying the priority and order them before we inject them into context. History messages are kept in their generation order and retrieved back from DB before each user request.
Challenge 2: Multi-Agent Context Isolation and Sharing
To enable sub-agents to efficiently complete tasks, we need to pass parent agent context information to sub-agents. Simply sharing all parent agent context information with sub-agents may cause context pollution or prevent sub-agents from focusing. We combine LLM-generated task descriptions and context summaries, and support forking parent agent message lists to ensure we provide sub-agents with sufficiently focused and comprehensive new context information. Meanwhile, we establish message pipelines between sub-agents and parent agents to pass messages for real-time display of sub-agent feedback. Finally, before returning results, if necessary, we summarize sub-agent execution results before returning them to the parent agent to prevent sub-agents from returning excessively large results that ineffectively occupy context.

While we isolate the context between parent agent and sub-agent, we still need to provide enough information for sub-agent to finish their work. And when a sub-agent needs a long time to finish the work, we need to somehow bridge the intermediate result back to the UI in order to tell the user that there is still a task running.
Figure 6 Sub-agent context isolation and response sharing
Challenge 3: Tool Selection Response Speed
In our initial tool selection flow implementation, we chose to provide the available tool set all at once, keeping it unchanged throughout the task execution cycle. However, this brought a user experience problem: each user request performed vector retrieval for tools regardless of the complexity of the user request, which greatly slowed response speed for simple tasks. To alleviate this problem, we optimized the tool selection process. Before the task starts, we only perform lightweight tool retrieval and provide a final fallback tool set. During task execution, we provide a tool for searching tools. When the agent believes the current tool set cannot complete the next task, it calls this tool search tool to dynamically find appropriate tools and load them into the tool set provided to the LLM. This reduces meaningless tool retrieval, improves user request response speed (from previously ~3 seconds for all requests to less than 1s for simple tasks, and same latency for full tool search but with less frequency), and ensures necessary tools can be loaded and used.

We only do one tool search for each user input in our initial version, and the tool set is kept unchanged for the whole task execution lifetime. Whereas in our improved version, the initial tool retrieval is simple and fast, and LLM can decide to load new tools when needed.
Figure 7 Tool selection improvement example
Summary
Context engineering is one of the hottest topics in current agent development. JAPAN AI has done extensive work in this direction, including:
- Combining long-term important memory and short-term complete message lists to dynamically construct new message lists that efficiently utilize KV cache
- Using multi-agent systems to reasonably isolate independent subtask contexts to avoid ineffective parent agent context growth
- Providing both user-initiated and system-automatic context compression methods to reasonably avoid context overflow
- Providing dynamic tool loading mechanisms to prevent excessive tools from wasting context space
Although this work has made our agents more powerful, we still have many areas worth improving and optimizing, such as:
- More accurate memory retrieval mechanisms, and memory forgetting/updating mechanisms to prevent stale information from polluting context
- Context compression storage optimization for different scenarios—for example, targeted optimization for deep research compression needs versus slide generation compression needs
- Timely reflection of tool updates and additions in retrieval results
- Script function calling to further reduce context occupation from tool results
References
- Effective context engineering for AI agents. https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
- Context Engineering for AI Agents: Lessons from Building Manus. https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus
- Context Engineering for Agents. https://rlancemartin.github.io/2025/06/23/context_engineering/
- Context Engineering in Manus. https://rlancemartin.github.io/2025/10/15/manus/
For more information about JAPAN AI's agent platform, visit our website or reach out to our team.
Interested in building AI infrastructure at scale? We're hiring engineers who love solving hard problems at the intersection of AI and distributed systems. Learn more about careers at JAPAN AI.
株式会社ジーニー JAPAN AI / Developer の求人一覧hrmos.co