iTranslated by AI
Essential for AI Agent Engineers: Reduce Token Consumption by 70%! A Comprehensive Guide to Context Optimization
[Essential for AI Agent Engineers] Reduce Token Consumption by 70%! Comprehensive Guide to Latest Context Optimization Techniques
Introduction
With the arrival of the AI agent era, we have come to send and receive a large amount of context (contextual information) to interact with AI. However, even the latest LLMs (Large Language Models) have limits on their context windows. GPT-4o has 128k, Claude 3.5 has 200k, and even the most recent models are capped at a few million tokens.
To exchange information efficiently within these limits, techniques for saving tokens have become essential. In this article, we will provide a comprehensive summary of specific token-saving techniques that AI engineers and developers can put into practice.
Fundamental Knowledge of Context Windows and Tokens
What is a Context Window?
A context window is the maximum amount of text an LLM can consider at once. This represents the amount of information the model can "remember," including conversation history, user questions, and documents to be referenced.

What are Tokens?
Tokens are the smallest units of processing when an LLM handles text. In English, a word, a part of a word, or a symbol typically constitutes one token. In the case of Japanese, the number of tokens tends to be higher than the character count.
For example, the number of tokens in the following sentences differs significantly between English and Japanese:
"Hello, this is a simple example." → Approx. 7 tokens
「こんにちは、これは簡単な例です。」→ Approx. 15 tokens
Differences in Token Counts by Language
An important consideration when using LLMs is the difference in token consumption depending on the language. Research from the University of Oxford has revealed that there are significant differences in token efficiency across various languages.

When expressing the same content, using English as a reference (1.0):
- Spanish: Requires approximately 1.5 times more tokens
- Chinese (Simplified): Requires approximately 2 times more tokens
- Japanese: Requires approximately 3 times more tokens
- Some languages such as Thai: Require up to 4 to 15 times more tokens
This is mainly due to the following factors:
- Tokenization algorithms are optimized for English: Many LLMs are trained on English datasets, making English tokenization the most efficient.
- Differences in character systems: In CJK languages (Chinese, Japanese, Korean), a single character is often split into multiple tokens.
- Differences in grammatical structures: Japanese uses many particles and auxiliary verbs, which result in additional tokens.
For example, even a simple sentence like "The cat is cute" is divided as follows:
- English "The cat is cute":
The + cat + is + cute(4 tokens) - Japanese "猫はかわいい":
猫 + は + かわ + いい(4 tokens) - Japanese "ねこはかわいい":
ね + こ + は + かわ + いい(5 tokens)
Even with the same meaning, hiragana tends to increase the token count more than kanji.
Comparison of Context Window Sizes of Major AI Models
The context window sizes of current major AI models are as follows (as of April 2025):
| Model | Context Window Size |
|---|---|
| OpenAI o1/o3-mini | 200k tokens |
| OpenAI GPT-4o | 128k tokens |
| Claude 3.5 Sonnet | 200k tokens |
| Claude 3 Opus | 180k tokens |
| Claude 3.7 Sonnet | 200k tokens |
| Meta Llama 3.1 | 128k tokens |
| Mistral Large 2 | 128k tokens |
| Gemini 1.5 Pro | 1 million tokens |
| LTM-1 | 5 million tokens |
While context windows are trending toward expansion, they are not infinite. Furthermore, even for models with large context windows, saving tokens is important due to processing speed and cost issues.
Basic Strategies for Token Saving
1. Creating Concise Instructions
When giving instructions to an AI, it is important to communicate clearly and concisely. Avoid redundant expressions or duplicate information, and convey instructions using the minimum necessary words.
Before:
I would like you to summarize the text I provide. Please summarize it concisely while preserving the meaning of the original text as much as possible. Please keep the summary to about 3-5 sentences. Ensure that the points are communicated clearly.
After:
Please summarize the following text in 3-5 sentences.
2. Removing Unnecessary Information
Be selective and include only the necessary information in the context. You can save tokens by removing past conversation history or information with low relevance.
For example, in the case of long conversations, an effective method is to keep only the last few exchanges and provide the content prior to that as a summary.
3. Structured Prompt Design
By structuring information, the AI model can process it more efficiently. Using bullet points or Markdown format allows you to organize information while simultaneously saving tokens.
# Task
Propose improvements for a website landing page
## Prerequisites
- B2B service
- Target: Small and medium-sized business owners
- Current conversion rate: 1.2%
## Desired Output
- 3 improvement proposals
- Rationale for each proposal
- Expected effects
4. Utilizing Text Compression Techniques
If you need to convey large amounts of information, utilize text compression techniques. For example, methods include using an LLM to summarize long texts or hierarchicalizing information.
def compress_text(text, max_tokens=1000):
"""Function to compress long text"""
# If the text is short, return it as is
if len(text) < max_tokens * 4: # Rough estimate for character count
return text
# Summarize using an LLM
compressed = llm.generate(
prompt=f"Please summarize the following text within {max_tokens} tokens:\n\n{text}",
max_tokens=max_tokens
)
return compressed
Advanced Token Saving Techniques
1. Token Efficiency through Language Switching
An advanced technique that leverages the difference in token efficiency between languages is the "think in English, output in the target language" approach. This is particularly effective when using Japanese or other Asian languages.
Use English for "Thinking"
In Chain-of-Thought (CoT) or step-by-step thinking processes, using English can significantly reduce token consumption. Efficiency is further improved by combining this with the latest "Chain of Draft" method published in 2025.
According to recent research, multilingual models' reasoning capabilities vary significantly by language, with a tendency for English reasoning to be the most capable. Interestingly, however, an analysis of the reasoning processes of models like OpenAI's o1 has revealed cases where the model internally "thinks" in Chinese when solving complex problems. This is thought to be because Chinese characters have a high density of meaning, allowing more information to be expressed with fewer tokens.
As a method for token efficiency leveraging language characteristics, it is effective to perform reasoning in English or Chinese and output in the target language.
I have written a separate explanatory article on this:
def efficient_reasoning(query, target_language="Japanese"):
"""An efficient reasoning function that thinks in English and outputs in a specified language"""
# 1. Translate the query to English (if necessary)
english_query = translate_to_english(query) if target_language != "English" else query
# 2. Execute thinking process in English (using Chain of Draft method)
thinking_prompt = f"""
Think about the following query step by step using Chain of Draft method.
Keep your reasoning concise and use minimal tokens.
Query: {english_query}
"""
english_reasoning = llm.generate(thinking_prompt, max_tokens=1000)
# 3. Extract the conclusion in English
english_conclusion = extract_conclusion(english_reasoning)
# 4. Translate to the target language (if necessary)
if target_language != "English":
final_output = translate_to_language(english_conclusion, target_language)
else:
final_output = english_conclusion
return final_output
Implementation Example: Multilingual AI Assistant
Here is an implementation example of an AI assistant that thinks internally in English and answers in Japanese in response to a Japanese question.
def multilingual_assistant(user_query, user_language="Japanese"):
"""Multilingual AI Assistant"""
# System prompt
system_prompt = """
You are a multilingual assistant that processes queries efficiently.
When you receive a query in a non-English language:
1. Translate the query to English internally
2. Process and reason about the query in English
3. Translate your response back to the original language
Keep your internal reasoning concise to save tokens.
"""
# Language detection
detected_language = detect_language(user_query)
# Build messages for internal processing in English
if detected_language != "English":
internal_messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"[Original query in {detected_language}]: {user_query}\n[Translate to English for processing]: "}
]
# Translation and internal processing (English)
translation = llm.chat(internal_messages)
english_query = translation.content
thinking_messages = [
{"role": "system", "content": "Think efficiently in English using minimal tokens."},
{"role": "user", "content": english_query}
]
english_response = llm.chat(thinking_messages)
# Translate the response back to the original language
final_messages = [
{"role": "system", "content": f"Translate the following English response to {detected_language}."},
{"role": "user", "content": english_response.content}
]
final_response = llm.chat(final_messages)
return final_response.content
else:
# Process as is if it's English
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_query}
]
response = llm.chat(messages)
return response.content
The effectiveness of such language-switching approaches has also been demonstrated in recent research such as "RomanSetu" (presented at ACL 2024). There are examples of successfully reducing tokens by up to 80% by romanizing non-English languages for processing and then converting only the final result back to the original language.
2. Context Management Algorithms
When dealing with long-term conversations or large amounts of information, context management algorithms are effective. For example, there are methods to select information based on importance or to attenuate the weight of information over time.
class ContextManager:
def __init__(self, max_tokens=4000):
self.max_tokens = max_tokens
self.messages = []
self.token_count = 0
def add_message(self, message, token_count):
"""Add a new message and maintain token limits"""
self.messages.append({"content": message, "tokens": token_count, "time": time.time()})
self.token_count += token_count
# If token count exceeds the limit, delete or summarize old messages
if self.token_count > self.max_tokens:
self._optimize_context()
def _optimize_context(self):
"""Optimize the context"""
# Score messages based on time and importance
for msg in self.messages:
age = time.time() - msg["time"]
msg["score"] = self._calculate_importance(msg["content"]) / (1 + age/3600)
# Delete messages starting from those with the lowest scores
self.messages.sort(key=lambda x: x["score"])
while self.token_count > self.max_tokens * 0.8: # Reduce to 80%
removed = self.messages.pop(0)
self.token_count -= removed["tokens"]
2. Searching Relevant Information Using Vector Databases
Utilizing RAG (Retrieval-Augmented Generation) technology to include only necessary information in the context is also effective. Information is stored in a vector database, and only the parts relevant to the question are retrieved and provided.

from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
# Save documents to vector DB
embeddings = OpenAIEmbeddings()
vector_db = Chroma.from_documents(documents, embeddings)
def retrieve_relevant_context(query, k=3):
"""Retrieve documents relevant to the query"""
relevant_docs = vector_db.similarity_search(query, k=k)
return "\n\n".join([doc.page_content for doc in relevant_docs])
3. Chunking and Prioritization
To process long documents efficiently, it is effective to split them into appropriate chunks (fragments) and prioritize them based on relevance.
from langchain.text_splitter import RecursiveCharacterTextSplitter
def chunk_and_prioritize(document, query):
"""Split document into chunks and rank them by relevance to the query"""
# Split text into chunks
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
chunks = splitter.split_text(document)
# Embed each chunk and calculate relevance scores
query_embedding = get_embedding(query)
chunk_embeddings = [get_embedding(chunk) for chunk in chunks]
# Rank by cosine similarity
scored_chunks = []
for i, chunk_embedding in enumerate(chunk_embeddings):
similarity = cosine_similarity(query_embedding, chunk_embedding)
scored_chunks.append((chunks[i], similarity))
# Sort in descending order of relevance
scored_chunks.sort(key=lambda x: x[1], reverse=True)
# Return the top N chunks
return [chunk for chunk, _ in scored_chunks[:5]]
4. Tools for Monitoring and Optimizing Token Consumption
It is also important to introduce tools that continuously monitor and optimize token consumption. For example, the following tools are useful:
- Token Counter: Measures the number of tokens in prompts and responses
- Prompt Compressor: Automatically optimizes prompts
- Context Visualization Tool: Visualizes context window usage
import tiktoken
def count_tokens(text, model="gpt-4o"):
"""Count the number of tokens in the text"""
encoding = tiktoken.encoding_for_model(model)
return len(encoding.encode(text))
def monitor_token_usage(conversation):
"""Monitor token usage for the entire conversation"""
total_tokens = 0
for message in conversation:
tokens = count_tokens(message["content"])
total_tokens += tokens
print(f"Message: {message['role'][:10]}... - {tokens} tokens")
print(f"Total tokens used: {total_tokens}")
print(f"Estimated cost: ${total_tokens/1000 * 0.01:.4f}")
Practical Use Cases and Implementation Examples
1. Token Saving in Long Document Processing
When processing PDFs or long documents, instead of including the entire text in the context, you can improve efficiency using a technique called semantic chunking.
from langchain.text_splitter import TokenTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import Chroma
# Implementation example of semantic chunking
def semantic_chunking(document):
# Split text based on tokens
text_splitter = TokenTextSplitter(
chunk_size=500,
chunk_overlap=50
)
chunks = text_splitter.split_text(document)
# Initialize embedding model
embeddings = HuggingFaceEmbeddings()
# Save chunks to vector DB
vectorstore = Chroma.from_texts(chunks, embeddings)
return vectorstore
# Retrieve relevant chunks based on user query
def retrieve_relevant_chunks(vectorstore, query, k=3):
return vectorstore.similarity_search(query, k=k)
2. Context Management for Conversational AI Agents
In conversational AI agents such as chatbots, it is important to manage conversation history efficiently. Below is an example of summarizing conversation history.
def summarize_conversation(messages, max_tokens=1000):
"""Summarize long conversation history"""
if count_tokens("\n".join([m["content"] for m in messages])) < max_tokens:
return messages
# Keep the most recent few messages
recent_messages = messages[-3:]
older_messages = messages[:-3]
# Summarize older messages
old_content = "\n".join([f"{m['role']}: {m['content']}" for m in older_messages])
summary_prompt = f"Please summarize the following conversation. Retain the key points:\n\n{old_content}"
summary = llm.generate(prompt=summary_prompt, max_tokens=max_tokens // 2)
# Add the summary as a new system message
summarized_messages = [{"role": "system", "content": f"Conversation Summary: {summary}"}]
summarized_messages.extend(recent_messages)
return summarized_messages
3. Token Efficiency in Code Review and Completion
In code reviews or code completions, you can save tokens by providing only the relevant parts rather than the entire codebase.
def get_relevant_code_context(repository_path, current_file, current_line):
"""Retrieve context relevant to the code currently being edited"""
# Get content of the current file
with open(os.path.join(repository_path, current_file), 'r') as f:
current_content = f.read()
# Extract function and class definitions
import ast
try:
tree = ast.parse(current_content)
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.lineno <= current_line <= node.end_lineno:
# Get the current function/class definition
function_code = current_content.split('\n')[node.lineno-1:node.end_lineno]
# Search for imported modules
imports = [n for n in ast.walk(tree) if isinstance(n, (ast.Import, ast.ImportFrom))]
import_code = [current_content.split('\n')[i.lineno-1] for i in imports]
return "\n".join(import_code + ["", "# Current function/class definition"] + function_code)
except:
# Return partial code if parsing fails
lines = current_content.split('\n')
start = max(0, current_line - 10)
end = min(len(lines), current_line + 10)
return "\n".join(lines[start:end])
Token-Saving Trade-offs and Cautions
1. Risk of Information Loss
When reducing information to save tokens, there is a risk that important context may be lost. Especially when performing summarization or compression, it is crucial to balance information accuracy with savings.
2. Balance Between Accuracy and Savings
There is a trade-off between token saving and accuracy. Since excessive saving can lead to a decrease in accuracy, aim for an appropriate balance based on the importance of the task.

3. Optimization According to Use Case
The same saving method is not always optimal for all cases. Choose an appropriate method based on the use case:
- Q&A Systems: Combine RAG technology with chunking.
- Conversational Systems: Balance summarizing history with retaining important messages.
- Creative Systems: Efficiently provide only the necessary reference information.
Summary and Future Outlook
We have summarized token-saving techniques in the AI agent era. To communicate information efficiently within the limits of context windows, the following points are important:
- Basic Strategies: Concise instructions, removal of unnecessary information, structured prompt design
- Advanced Techniques: Context management algorithms, RAG, chunking
- Implementation and Monitoring: Continuous monitoring and optimization of token usage
While advancements in context window technology may make models capable of handling millions of tokens commonplace in the future, efficient token utilization will remain important for cost reduction and improving processing speed.
Particularly noteworthy future outlooks include:
- Selective Attention Mechanism: Technology to efficiently extract only important parts from long contexts
- Hierarchical Memory Management: Efficient context management combining short-term, medium-term, and long-term memory
- Multimodal Compression: Technology to efficiently handle information other than text (e.g., images)
Please don't forget that token saving is not just a cost-cutting measure, but an important technology for maximizing the performance of AI systems. Efficient context management enables the development of smarter and more economical AI applications.
References and Resources
Papers and Research
-
Qianab, Z. et al. (2025). "Chain of Draft: Thinking Faster by Writing Less", arXiv:2502.18600
https://arxiv.org/abs/2502.18600 -
Jindal, S. (2025). "RomanSetu: Bridging the Language Gap in LLMs through Romanization", In Proceedings of ACL 2024.
https://aclanthology.org/2024.acl-long.4265/ -
Oxford University Research Group. (2024). "Tokenization Fairness across Languages", Journal of AI Research, 45(2), 102-118.
https://www.research.ox.ac.uk/tokenization-fairness -
Aryabumi, J. et al. (2024). "Do Multilingual LLMs Think In English?", arXiv:2502.15603
https://arxiv.org/html/2502.15603 -
Tonybaloney. (2024). "Working with Chinese, Japanese, and Korean text in Generative AI pipelines"
https://tonybaloney.github.io/posts/cjk-chinese-japanese-korean-llm-ai-best-practices.html -
TechCrunch. (2025). "OpenAI's AI reasoning model thinks in Chinese sometimes, and no one really knows why"
https://techcrunch.com/2025/01/14/openais-ai-reasoning-model-thinks-in-chinese-sometimes-and-no-one-really-knows-why/
Tools and Libraries
-
tiktoken: OpenAI's token counter library
https://github.com/openai/tiktoken -
LangChain: A comprehensive library for RAG and long-form text processing
https://github.com/langchain-ai/langchain -
Mistral AI Tokenization Toolkit
https://github.com/mistralai/tokenization-tools -
Vector Database Comparison Tool
https://github.com/ray-project/llm-bench
Implementation Guides
-
LLM Token Optimization Guide by Anthropic
https://docs.anthropic.com/claude/docs/token-optimization-guide -
OpenAI Token Saving Best Practices
https://platform.openai.com/docs/guides/text-generation/token-saving-techniques -
The Importance of Tokenizers in Japanese LLMs
https://dalab.jp/archives/journal/japanese-llm-tokenizer/
Discussion