何が起きたのか
LangChainエージェントを実行したところ、タスクの途中で停止し、次のようなメッセージが返されました:
Agent stopped due to iteration limit or time limit.
最終的な回答はなし。部分的な結果か、まったく何も返ってきません。LangChainはデフォルトでエージェントを15回のイテレーションに制限しています。これはバグではなく、安全のための制限です。この制限がなければ、スタックしたエージェントが無限に実行され、何百回ものAPIコールを積み上げてしまう可能性があります。
この制限がかかる原因はいくつかあります:
- タスクが本質的にデフォルトの制限以上のツール呼び出しを必要としている。
- エージェントがループにはまり、進展なく同じツールを繰り返し呼び出している。
- LLMが最終的な回答を出さずに中間ステップを生成し続けている。
- ツールがエージェントの処理できない結果を返し続けている。
簡易診断
設定を変更する前に、verboseモードを有効にして、各イテレーションでエージェントが実際に何をしているかを確認しましょう:
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True, # str:
return f"Parsing failed: {str(error)[:100]}. Try a different approach."
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
max_iterations=25,
handle_parsing_errors=handle_error
)
修正4:ループの根本原因を修正する — プロンプトを改善する
特定のツールでエージェントがループしている場合、上限を引き上げるだけでは問題の先送りにしかなりません。十中八九、根本原因はエージェントにいつ停止するかを伝えていないシステムプロンプトにあります。明示的な停止ルールを追加しましょう:
from langchain.agents import create_react_agent
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template("""
You are a helpful assistant. Answer the question using the tools available.
IMPORTANT:
- If you've used a tool and have enough information to answer, stop and give the Final Answer immediately.
- Do NOT call the same tool twice with the same input.
- If a tool returns an error twice, stop and explain what you found so far.
{tools}
Question: {input}
{agent_scratchpad}
""")
agent = create_react_agent(llm=llm, tools=tools, prompt=prompt)
修正5:LangGraphエージェント(0.3.x以降)
LangGraphに移行済みの場合、イテレーション制限の仕組みが異なります。max_iterationsの代わりに、invokeの設定でrecursion_limitを指定します:
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(model=llm, tools=tools)
# 呼び出し時にconfigでrecursion_limitを渡す
result = agent.invoke(
{"messages": [("user", "your question here")]},
config={"recursion_limit": 50}
)
LangGraphはグラフの状態をストリームして、ループをステップごとにデバッグすることもできます:
for step in agent.stream(
{"messages": [("user", "your question here")]},
config={"recursion_limit": 50}
):
print(step)
print("---")
修正が機能したことを確認する
修正を適用した状態でエージェントを実行し、実際に最終回答に到達することを確認しましょう:
result = agent_executor.invoke({"input": "your test question"})
# 空またはエラーの結果ではなく、実際の出力が得られたか確認
print(result["output"])
assert "Agent stopped due to iteration limit" not in str(result)
assert len(result["output"]) > 0
verbose=Trueの状態では、イテレーション上限に達する前にFinal Answer:が表示されるはずです。それでもループしている場合は、ツールの出力を再確認し、プロンプトの指示を厳密にしてみてください。
修正方法のまとめ
- タスクが正当に長い場合:
max_iterationsを引き上げ、max_execution_timeを追加する。 - 上限到達時の出力が不正な場合:
early_stopping_method="generate"を設定する。 - パースエラーによるリトライが発生している場合:
handle_parsing_errors=Trueを有効にする。 - 同一ツールでのループが発生している場合:明示的な停止ルールでシステムプロンプトを修正する。
- LangGraphエージェントの場合:invokeの設定で
recursion_limitを使用する。

