Optimizing production agents with Amazon Bedrock AgentCore Observability
https://aws.amazon.com/blogs/machine-learning/optimizing-production-agents-with-amazon-bedrock-agentcore-observability/📌 【AWS 技術分享】解決 AI Agent 效能瓶頸:從「能動」到「好用」的監控策略
TL;DR:利用 Amazon Bedrock AgentCore Observability 與 CloudWatch,識別並解決 Agent 執行緩慢與記憶體無限制增長問題。
當 AI Agent 從原型轉向正式生產環境時,挑戰會從「如何讓它運作」轉變為「如何保持快速與高效」。在解決了無限迴圈或工具呼叫錯誤等功能性問題後,工程師往往會遇到更隱蔽的挑戰:Agent 運作完全正確,但效能極差。
🤔 隱形的效能殺手:回應緩慢與記憶體膨脹
回應延遲(Latency)與無限制的記憶體增長是生產環境中最常見的營運問題。這些問題通常不會觸發錯誤警示,但會隨著時間推移侵蝕使用者信任並增加成本。
- 回應過慢:當使用者期待亞秒級(sub-second)回應,卻得到數秒的延遲時,即便任務成功,互動體驗也會崩潰。
- 記憶體膨脹:在長對話會話中,隨著 Context(上下文)不斷累積,Agent 可能會觸發 Token 限制、丟失重要資訊,甚至導致會話意外終止。
🧩 找出效能瓶頸:從 CloudWatch 進行診斷
要優化 Agent,必須先識別哪些請求違反了你設定的「效能預算」(Performance Budgets)。
- 識別高延遲請求:透過 CloudWatch 查詢執行時間超過預定閾值(例如 3 秒)的 Agent 呼叫,並記錄其
RequestId。 - 分析執行時間線(Timeline):利用 OpenTelemetry trace 查看請求內部的操作序列。常見的耗時來源包括:
- 記憶體檢索(Memory Retrieval):理想狀況應在 200 毫秒內完成;若超過此時間,代表記憶體組織效率低下。
- 工具呼叫(Tool Invocation):檢查是否有特定工具導致整體流程變慢。
- Token 生成:模型生成 Token 是序列化的,生成 500 個 Token 的時間會比 100 個長得多。
- 序列化處理(Sequential Operations):檢查是否將可以並行(Parallel)執行的獨立操作,改成了一個接一個依序執行。
📊 優化策略:將「慢」轉為「快」
針對上述問題,可以採取以下實務手段進行最佳化:
- 針對工具執行:實施快取(Caching)、連接池(Connection pooling)或優化資料庫索引;若工具持續緩慢,應獨立進行效能分析。
- 針對記憶體檢索:
- 將大型命名空間(Namespace)拆分為特定主題(如:偏好、歷史、領域知識)。
- 將舊對話摘要(Summarize)成精簡條目,而非逐字儲存。
- 為每個命名空間設定容量限制(例如:50 條近期訊息)。
- 針對 Token 生成:優化 Prompt,鼓勵模型提供簡短直接的回答(如 2-3 句),並增加長度限制。
- 針對序列化處理:將獨立的工具呼叫改為並行執行。例如:原本需要 2s + 1.5s + 1s 的序列化呼叫,改為並行後可能只需 2s,大幅降低延遲。
⚠️ 預防記憶體失控:監控會話狀態
在長對話會話中,Token 使用量會隨對話時間線性增長。若缺乏定期的記憶體提取(Memory Extraction)與修剪(Pruning),Agent 會面臨 Context Window 耗盡的風險。
透過 CloudWatch Logs Insights 監控記憶體相關的日誌,可以發現 Agent 是否在不斷新增記憶體(如透過 add_conversation_note 等工具)卻沒有進行任何整合或刪減,這就是無限制增長的徵兆。
🎯 實務啟示
對於正在建置生產級 Agent 的工程師來說,建立「效能預算」與「監控儀錶板」至關重要。不要等到使用者抱怨才發現問題,應主動透過 CloudWatch 監控 P95 回應時間與記憶體增長趨勢,並透過並行化與摘要技術,確保 Agent 在長對話中依然保持高效。
🔗 來源
- 標題:Optimizing production agents with Amazon Bedrock AgentCore Observability
- 作者/機構:Joshua Lacy @ AWS ML
- 連結:https://aws.amazon.com/blogs/machine-learning/optimizing-production-agents-with-amazon-bedrock-agentcore-observability/
#AI #LLM #AWS #AmazonBedrock #MachineLearning #AgentCore #Observability #CloudWatch #SoftwareEngineering #PerformanceOptimization
原始資料 AWS ML · 收集於 2026-08-01
摘要原文
As your AI agents move from prototype to production, the challenges shift from getting them to work to keeping them fast and efficient. In Part 1 of this series, we walked through debugging two common agent failures: infinite loops and tool invocation errors. Those scenarios dealt with agents that were broken. In this post, we tackle a different challenge: agents that work correctly but perform poorly. Slow response times and unbounded memory growth are the most common operational issues that surface after you resolve the initial debugging problems. They don’t trigger error alerts, but they erode user trust and increase costs over time. Using AgentCore Observability , a capability of Amazon Bedrock AgentCore, and Amazon CloudWatch , you will learn how to identify performance bottlenecks across your agent’s execution path and diagnose memory issues in long-running sessions. You will also implement monitoring practices that catch degradation before users notice it. For additional information and best practices, review AgentCore Evaluations , a capability of Amazon Bedrock AgentCore, and AgentCore Insights . You need an AWS account with Amazon Bedrock AgentCore access, CloudWatch Transaction Search enabled, and a deployed agent. See Part 1 for full setup details. Agents experience performance bottlenecks when they work correctly but respond too slowly. You expect sub-second responses but experience multi-second delays. Agents complete tasks successfully, but the latency makes them impractical for interactive use cases. This scenario is particularly challenging because slow is subjective. What’s acceptable for a batch processing agent is unacceptable for a customer service chatbot. You must establish performance budgets for your specific use case, then systematically identify which components violate those budgets. Performance degradation often manifests gradually. Agents might start with acceptable 2-second response times, but as you add features, integrate more tools, or accumulate more memory, latency creeps to 5 seconds, then 10, then becomes unusable. P95 response times exceed your thresholds, users abandon sessions, but error rates stay low. The agent works correctly but responds too slowly. Figure 1 — Session details showing multiple traces with consistently high latency. The three invocations took 7.5-8.2 seconds (average span latency), demonstrating a systemic performance bottleneck rather than occasional slowness. This pattern indicates the agent’s architecture needs optimization. To find bottlenecks, start by identifying high-latency requests. Query CloudWatch for agent invocations that exceed your performance budget: This query returns agent invocations that took longer than 3 seconds (adjust the threshold based on your requirements), sorted by latency. Pick a representative high-latency request and note its RequestId . Next, analyze the request timeline to understand where time is spent: The query shows you the sequence of operations within the request and how long each took. Look for operations that consume disproportionate time. Common culprits include memory retrieval operations, tool invocations, token generation, and sequential operations that could run in parallel. Figure 2 — OpenTelemetry trace timeline showing 17 spans across three sequential execute_event_loop_cycle operations. The tools (customer_lookup, order_history) execute one after another rather than in parallel, with each cycle waiting for the previous one to complete. This sequential pattern compounds latency across each tool invocation. Check memory retrieval latency specifically: Memory retrieval should complete in under 200 milliseconds, representing the point where users begin perceiving noticeable delays in interactive applications. Higher latency suggests inefficient memory organization. Examine tool invocation latency to identify slow integrations: The query identifies which tools contribute most to overall latency. A single slow tool can bottleneck the entire agent workflow. Performance bottlenecks typically stem from three root causes. Slow tool execution occurs when external tools take seconds to respond because of poor optimization, overload, or network issues. Latencies compound with sequential calls, so a 2-second tool called three times becomes a 6-second bottleneck. Excessive token generation is a factor because foundation models (FMs) produce tokens sequentially, meaning a 500-token response takes 5x longer than a 100-token one, impacting both latency and cost. Finally, sequential processing , performing independent operations one at a time instead of in parallel, increases both cost and compute times. For slow tool execution, implement caching, connection pooling, and proper database indexing to reduce response times. Set timeout limits and consider faster tool alternatives. If a tool consistently lags, profile it independently. The issue might be network latency, cold starts, or resource contention rather than the tool’s logic itself. For memory retrieval, replace single large namespaces with topic-specific partitions, such as preferences, history, and domain knowledge, to reduce search space. Summarize old conversations into compact entries rather than storing them verbatim, and set size limits per namespace, such as 100 preferences, 50 recent messages, or 500 domain facts. For token generation, optimize prompts to encourage brief, direct answers of 2–3 sentences unless more detail is requested. Add explicit length constraints and monitor token usage with alerts for unexpectedly long responses. For sequential processing, run independent tool calls in parallel. Sequential calls totaling 4.5s (2s + 1.5s + 1s) drop to only 2s when parallelized, often cutting latency by 50 percent or more with minimal effort. To verify your optimizations, re-run the latency query from the identifying bottlenecks section. Confirm that P95 response times now fall within your performance budget and that the trace timeline shows parallel execution where expected. Agents experience memory issues in long-running sessions when they maintain sessions where memory usage grows unbounded. Agents accumulate context, and eventually, agents hit token limits, lose important context, or exhaust available memory. Sessions fail unexpectedly, and you lose conversation state. This scenario is particularly problematic for agents that support extended workflows, such as customer service sessions, research assistants, or monitoring agents. Without proper memory management, these use cases become impractical. When abnormally long agent sessions exist, token usage grows linearly with session duration. Memory retrieval latency increases over time as memory stores grow. Sessions terminate unexpectedly with out-of-memory errors or context window exceeded errors. Figure 3 — Session details for the memorygrowth_Agent showing 6 traces, 15.7K total tokens consumed, and an average trace latency of 3,757 ms within a single session. Token usage grows with each successive invocation, demonstrating unbounded context accumulation. In production sessions spanning hours, this pattern leads to context window exhaustion and unexpected session failures. To identify long-running sessions with high memory usage: The query returns sessions lasting longer than one hour (3600 seconds), sorted by memory size. Pick a session with unusually high memory usage and note its SessionId . Examine memory extraction patterns to verify consolidation is occurring: Figure 4 — CloudWatch Logs Insights showing 209 memory-related log entries concentrated around 18:20. The spike in memory operations indicates the agent storing information without consolidation. Each invocation adds new memory entries (through add_conversation_note and add_user_context tools) without pruning or summarizing old data, demonstrating the unbounded growth pattern. Memory extraction should occur regularly throughout the session.
由 tencent/hy3:free 自動生成