マルチエージェントAIによるトークン使用量削減のガイド
本文の状態
日本語全文を表示中
詳細モードで約8分の本文を読めます。
同じ出来事の情報源
この情報源を基点に整理
KDnuggets
本記事は、複数の AI エージェントを連携させる際のトークン消費量抑制に向けた 4 つの主要戦略を紹介し、コスト削減と実行速度向上の実現方法を解説する。
AI深層分析を開く2026年8月3日 23:32
AI深層分析
キーポイント
静的指示キャッシュ(プレフィックスマッチ)
LLM が逐次的な処理で同じシステムプロンプトを再読する非効率を防ぐため、事前準備された静的な長文指示をキー・バリューペアとして保存し、参照することで遅延とトークンコストを削減する手法である。
セマンティックキャッシュ(意図ベースの検索)
AI エージェントが既に解決した特定のタスクや質問に対して、その意味的な意図に基づいて過去の回答を再利用することで、重複した処理とトークン消費を防ぐ戦略である。
マルチエージェントアーキテクチャの最適化
複数の AI エージェントを連携させて複雑なワークフローに対処する際、アーキテクチャ自体をスケーリングしてもコストが同等に増大しないよう、トークン使用効率を高める実装戦略が必要となる。
メモリログとツール仕様の管理
実行速度の低下や計算予算の枯渇を招く要因であるメモリログや詳細なツール仕様などのデータ量を適切に管理することが、トークン使用量の抑制において不可欠であると指摘されている。
意味ベースのキャッシングによる意図の再利用
埋め込みベクトルを用いて過去の類似した意図を即座に特定し、必要に応じて LLM をバイパスして回答を提供する。これにより、同じ問題への再計算を防ぎトークン使用量を削減できる。
重要な引用
When multiple AI agents are strung together to cooperate and address complex workflows, the sheer volume of tokens may easily escalate.
Prefix caching... helps address this issue by storing such static, long instructions as a reference guide prepared ahead of time.
Managing token usage is vital for today's AI developers and practitioners as a whole.
In certain cases, this opens up the opportunity of entirely bypassing the LLM while still providing the right answer.
編集コメントを表示
編集コメント
本記事は、実務レベルで頻発するトークンコストの問題に対し、即座に適用可能な具体的な解決策を提示している。特に静的指示キャッシュやセマンティックキャッシュといった技術は、大規模なマルチエージェントシステム構築において不可欠な要素として注目されるべきである。
Source Article
元記事を日本語で読む
本文に関係しない購読案内、埋め込み通知、サイト内プロモーションは除いています。

導入
複数の AI エージェントを連携させて複雑なワークフローを処理する場合、トークン(テキスト要素や単位)の総量が急増する可能性があります。メモログから詳細なツールの仕様、システム指示まで、あらゆる情報が積み重なっていきます。その結果、実行速度が低下し、計算リソースが枯渇してしまう恐れがあります。
そのため、現在の AI 開発者にとってトークン使用量の管理は極めて重要です。ただし朗報もあります。適切な節約戦略を実装すれば、マルチエージェントアーキテクチャを拡張・合理化しても、コストが同比例して増大するわけではありません。本記事では、トークン使用量を削減するための具体的な 4 つの戦略を紹介し、その実働例を示します。
トークン使用量削減のための 4 つの主要戦略
マルチエージェント AI ソリューションを効率化しつつ、トークンの利用を最適化するために一般的に採用されているベストプラクティス 4 つをご紹介します。

マルチエージェント AI システムにおけるトークン使用量削減の戦略
// 1. 静的指示キャッシュ(プレフィックス一致キャッシュ)の利用
これは「同じことを繰り返すな」という原則の一例です。現代の AI エージェントに不可欠な大規模言語モデル(LLM)は、連続するターンで同じシステムプロンプトを読み直すことに多くの処理エネルギーを費やしています。キー・バリューペアを保存する「プレフィックスキャッシング」は、事前に用意した参照ガイドとしてこうした静的で長い指示を保存することで、この課題に対処します。毎回「このエージェントとして行動する方法」の完全なマニュアルをモデルが読み直すのではなく、クエリを受け取った時点で要約された状態にブックマークを残すのです。その後のターンでは、モデルは単にそのブックマークを開き、新しいプロンプトの処理へ直接進むだけで済みます。その結果、準備に伴うレイテンシと、それに付随するトークンコストが大幅に削減されます。
// 2. セマンティックキャッシングの利用:意図ベースの検索
AI エージェントが特定の課題をすでに解決したことがあるなら、なぜゼロから新しい回答を生成させる必要があるのでしょうか?この戦略は、テキストの意味的性質を保持する数値ベクトル表現である「埋め込み(embeddings)」を活用し、過去の類似した意図を素早く特定します。例えば、「ルーターの再起動方法を知りたい」というプロンプトと「Wi-Fi ルータの再起動手順を教えて」という異なるユーザーからの質問も、セマンティックキャッシングによって同じ意図として認識されます。場合によっては、LLM を完全にスキップしながらも適切な回答を提供できる可能性があります。
// 3. ジャストインタイム・ツールリングの利用
この手法は「遅延読み込み」とも呼ばれ、AI エージェント構築における頻出する落とし穴に対処するために設計されています。具体的には、利用可能なすべての API ツールやデータベーススキーマといった膨大な「参照マニュアル」をコンテキストウィンドウの初期段階で詰め込むという問題です。当然ながら、そのようなアプローチはプロンプトが肥大化しノイズが増え、トークン消費量が過剰になる最悪のシナリオを招きます。
それよりも、エージェントに対してその機能の概要をまとめた高レベルで軽量なディレクトリを提供するのはどうでしょうか? エージェントが特定のタスクが必要だと判断した瞬間にのみ、そのツールに必要な詳細かつ微細な指示やパラメータを取得するトリガーが作動します。
// 4. タスクエスカレーションの活用:コスト効率の高いモデルルーティング
すべてのユーザーからのプロンプトを適切に処理するために、大規模で重厚なモデルが必要とは限りません。効果的なマルチエージェント AI アーキテクチャはトリアージセンターとして機能し、入力されるタスクの内容や複雑さに基づいて分析するルーティング層を備えています。その結果、データの整形やテキストの要約、意図の分類といった単純なタスクは、軽量で場合によっては無料のモデルに振り分けられ、ローカル環境で正常に実行されます。
一方、トークン消費が重要な重負荷かつ計算集約型のモデルは、「深層推論」や「複数のステップにわたる調整」など複雑なタスクに対してのみ専用に確保されます。
# 概要:実装例
多エージェント AI アプリケーションでトークン使用量を最適化するための 4 つの実践的な戦略について解説しました。それらの一部が実際にどのように機能するかを、高レベルな例を通じて確認してみましょう。
このコードスニペットは、セマンティックキャッシュとモデルルーティングの 2 つの戦略を組み合わせて使用する様子を示しています。文中では、テキストをセマンティックキャッシュに必要な埋め込みベクトルに変換するために、実際のモデルである Sentence Transformer が使用されています。LLM への呼び出し部分はモック処理となっていますが、軽量なモデル部分などは、Groq で提供されているような無料の軽量モデルに簡単に置き換えることができます。具体的な実装例については、こちらの記事 を参照してください。
import numpy as np
from sentence_transformers import SentenceTransformer
# Loading a free, local model to convert text into embeddings
embedder = SentenceTransformer('all-MiniLM-L6-v2')
# In-memory semantic cache and similarity threshold (0.90 = 90% similar)
semantic_cache = {}
SIMILARITY_THRESHOLD = 0.90
def cosine_similarity(vec1, vec2):
"""Calculates how closely related two queries are."""
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
def route_and_respond(user_query):
# 1. Converting the current query into an embedding vector
query_vector = embedder.encode(user_query)
# 2. Semantic Caching: Check if a similar problem was solved recently
for cached_vector, past_response in semantic_cache.values():
if cosine_similarity(query_vector, cached_vector) >= SIMILARITY_THRESHOLD:
return f"[Served from Cache] {past_response}"
# 3. Model Routing: Triage the task based on complexity
# Simple tasks get routed to a free, locally hosted model (e.g. Llama 3 via Ollama)
# This routing logic is illustrative-only; not be used in production
if "summarize" in user_query.lower() or len(user_query) < 100:
response = call_free_local_agent(user_query)
else:
# Complex multi-step reasoning escalates to a larger orchestration agent
response = call_heavy_reasoning_agent(user_query)
# 4. Save the new vector and response to our cache for future users
semantic_cache[user_query] = (query_vector, response)
return response
# --- Mocking Agent Functions for Illustration: no actual LLMs invoked here ---
def call_free_local_agent(prompt):
return "Action completed by local, zero-cost model."
def call_heavy_reasoning_agent(prompt):
return "Action completed by complex orchestration agent."
# Example Usage: mocking the alternate use of different agents/models
# Comment/uncomment to try both examples and try your own
print(route_and_respond("Summarize today's server logs"))
# print(route_and_respond("Draft an optimal one-month itinerary for my upcoming Japan trip. Take into consideration the set of documents, public transport timetables and other documents provided, along with real-time API information"))route_and_respond() 関数に渡されたプロンプトで要求されるタスクの複雑さによって、使用されるモデルの種類が決定されます。
このコードを実行した結果は、以下の 2 つの return メッセージのいずれかが出力されます。
def call_free_local_agent(prompt):
return "Action completed by local, zero-cost model."
def call_heavy_reasoning_agent(prompt):
return "Action completed by complex orchestration agent."# まとめ
本記事では、多エージェント AI アプリケーションやアーキテクチャを実装する際に特に注意すべき 4 つの主要戦略を解説しました。トークン使用量の最適化に加え、コストとレイテンシの削減にも重点を置いています。実践的なモックベースの例を通じて、セマンティックキャッシュとモデルルーティングという 2 つの戦略を組み合わせて適用する方法について理解を深めました。
AI、機械学習、深層学習、大規模言語モデル(LLM)の分野でリーダーシップを発揮し、執筆・講演・アドバイザリー活動を行うイヴァン・パロマーレス・カラスコーサ氏。彼は、実社会において AI を活用する方法を他者に指導・支援しています。
原文を表示

**
# Introduction
When multiple AI agents are strung together to cooperate and address complex workflows, the sheer volume of tokens** — text elements or units, so to speak — may easily escalate. Everything adds up: from memory logs to detailed tool specifications, system instructions, and so on. Eventually, this leads to dragged down speed of executions and computing budget exhaustion.
Consequently, managing token usage is vital for today's AI developers and practitioners as a whole. There's good news, though: scaling up and streamlining a multi-agent architecture doesn't necessarily entail equal scaling of costs if you know how to properly implement some strategies for saving token usage. This article introduces and shows four of them in action.
# Four Key Strategies for Saving Token Usage
**
Below are four commonly adopted best practices to streamline multi-agent AI solutions while optimizing the use of tokens.

Strategies for saving token usage in multi-agent AI systems
// 1. Using Static Instruction Caching (Prefix-Match Caching)
Consider this one as a "don't repeat yourself" rule. Large language models (LLMs), an indispensable part of modern AI agents, invest much processing energy re-reading the same system prompts in successive turns. Prefix caching, which consists of storing key-value pairs, helps address this issue by storing such static, long instructions as a reference guide prepared ahead of time. Rather than having the model re-read the whole "how-to-act-as-this-agent" instruction manual every time, the model bookmarks a summarized state upon receiving a query. In subsequent turns, the model only needs to open that bookmark and go straight to processing the new prompt. As a result, latency due to preparation is significantly cut down, and so are the associated token costs.
// 2. Using Semantic Caching: Intent-Based Recall
If an AI agent has already solved a specific problem before, why ask it to generate a brand new response from scratch? This strategy leverages embeddings — numerical, vector-based representations of text that "retain" semantic properties — and uses them to quickly identify similar past intents. For instance, two distinct users' prompts like "*How can I reset my router?*" and "*What are the steps to restart my wifi box?*" would be recognized as the same intent based on semantic caching. In certain cases, this opens up the opportunity of entirely bypassing the LLM while still providing the right answer.
// 3. Using Just-in-Time Tooling
Also known as lazy loading, this technique is designed to tackle a frequent pitfall in AI agent building: front-loading context windows with huge "reference manuals" of every single API, tool, and database schema within their reach. Of course, that would be the perfect recipe for bloated, noisy prompts and excessive token consumption. Instead, why not give the agent a high-level, lean directory of its capabilities? Only when the agent identifies a specific task required at a given moment does it trigger the fetching of the detailed, fine-grained instructions and parameters needed for that specific tool.
// 4. Using Task Escalation: Cost-Efficient Model Routing
Not all user prompts require a massive, heavy-hitting model to be properly addressed. Effective multi-agent AI architectures are designed to act as triage centers, endowed with a routing layer that analyzes every incoming task based on its nature and complexity. Accordingly, simpler tasks like formatting data, summarizing text, or classifying intent are routed to lightweight, often free models capable of successfully running these tasks locally. Meanwhile, heavy, compute-intensive models where token consumption matters are "reserved" exclusively for complex tasks like those requiring deep reasoning or orchestration across multiple steps.
# Implementation Example in a Nutshell
Now that we've covered four practical strategies that can help optimize token usage in multi-agent AI applications, how about illustrating how some of them work through a high-level example?
This code snippet illustrates how to combine two of them: semantic caching and model routing. The code uses an actual model — a sentence transformer — to convert text into the embeddings needed for semantic caching. The calls to LLMs are mocked, but you can easily replace the code (especially for the lightweight model part) with an actual, free-weights model like those available at Groq**, as shown in this article, for instance.
import numpy as np
from sentence_transformers import SentenceTransformer
# Loading a free, local model to convert text into embeddings
embedder = SentenceTransformer('all-MiniLM-L6-v2')
# In-memory semantic cache and similarity threshold (0.90 = 90% similar)
semantic_cache = {}
SIMILARITY_THRESHOLD = 0.90
def cosine_similarity(vec1, vec2):
"""Calculates how closely related two queries are."""
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
def route_and_respond(user_query):
# 1. Converting the current query into an embedding vector
query_vector = embedder.encode(user_query)
# 2. Semantic Caching: Check if a similar problem was solved recently
for cached_vector, past_response in semantic_cache.values():
if cosine_similarity(query_vector, cached_vector) >= SIMILARITY_THRESHOLD:
return f"[Served from Cache] {past_response}"
# 3. Model Routing: Triage the task based on complexity
# Simple tasks get routed to a free, locally hosted model (e.g. Llama 3 via Ollama)
# This routing logic is illustrative-only; not be used in production
if "summarize" in user_query.lower() or len(user_query) < 100:
response = call_free_local_agent(user_query)
else:
# Complex multi-step reasoning escalates to a larger orchestration agent
response = call_heavy_reasoning_agent(user_query)
# 4. Save the new vector and response to our cache for future users
semantic_cache[user_query] = (query_vector, response)
return response
# --- Mocking Agent Functions for Illustration: no actual LLMs invoked here ---
def call_free_local_agent(prompt):
return "Action completed by local, zero-cost model."
def call_heavy_reasoning_agent(prompt):
return "Action completed by complex orchestration agent."
# Example Usage: mocking the alternate use of different agents/models
# Comment/uncomment to try both examples and try your own
print(route_and_respond("Summarize today's server logs"))
# print(route_and_respond("Draft an optimal one-month itinerary for my upcoming Japan trip. Take into consideration the set of documents, public transport timetables and other documents provided, along with real-time API information"))The complexity of the task requested in the prompt passed to route_and_respond() will determine which model type is used.
The output of executing this code will be either one of the two return messages in these functions:
def call_free_local_agent(prompt):
return "Action completed by local, zero-cost model."
def call_heavy_reasoning_agent(prompt):
return "Action completed by complex orchestration agent."# Wrapping Up
This article described four key strategies to be aware of when implementing multi-agent AI applications and architectures, with emphasis on optimizing token usage and reducing costs and latency. Through a practical, mock-based example, we reinforced our understanding of applying two of them in combination: semantic caching and model routing.
Iván Palomares Carrascosa is a leader, writer, speaker, and adviser in AI, machine learning, deep learning & LLMs. He trains and guides others in harnessing AI in the real world.
今日のまとめ
AIデイリーブリーフで今日の重要ニュースをまとめ読み