fix(agent): force final LLM response when max iterations exhausted

When the agent hits max_tool_iterations with tool calls still pending,
make one additional LLM call without tools to force a text response
instead of returning the empty default message.

Also remove the user-facing "Memory threshold reached" notification
from chat channels — this is an internal optimization that should only
appear in logs, not in Telegram/Discord/etc.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
dj-oyu 2026-02-20 15:12:08 +09:00
parent c67c4a9eb3
commit 2fc9b05833

View file

@ -761,6 +761,23 @@ func (al *AgentLoop) runLLMIteration(ctx context.Context, agent *AgentInstance,
} }
} }
// If max iterations exhausted with tool calls still pending,
// make one final LLM call without tools to force a text response.
if finalContent == "" && iteration >= agent.MaxIterations {
logger.WarnCF("agent", "Max iterations reached, forcing final response without tools",
map[string]interface{}{
"agent_id": agent.ID,
"iteration": iteration,
})
forceResp, forceErr := agent.Provider.Chat(ctx, messages, nil, agent.Model, map[string]interface{}{
"max_tokens": 8192,
"temperature": 0.7,
})
if forceErr == nil && forceResp.Content != "" {
finalContent = forceResp.Content
}
}
return finalContent, iteration, nil return finalContent, iteration, nil
} }
@ -795,13 +812,12 @@ func (al *AgentLoop) maybeSummarize(agent *AgentInstance, sessionKey, channel, c
if _, loading := al.summarizing.LoadOrStore(summarizeKey, true); !loading { if _, loading := al.summarizing.LoadOrStore(summarizeKey, true); !loading {
go func() { go func() {
defer al.summarizing.Delete(summarizeKey) defer al.summarizing.Delete(summarizeKey)
if !constants.IsInternalChannel(channel) { logger.InfoCF("agent", "Memory threshold reached, optimizing conversation history",
al.bus.PublishOutbound(bus.OutboundMessage{ map[string]interface{}{
Channel: channel, "session_key": sessionKey,
ChatID: chatID, "history_len": len(newHistory),
Content: "Memory threshold reached. Optimizing conversation history...", "token_estimate": tokenEstimate,
}) })
}
al.summarizeSession(agent, sessionKey) al.summarizeSession(agent, sessionKey)
}() }()
} }