云成本失控,账单触目惊心?AgentCore帮你智能管控、及时止损!

张开发
2026/4/17 8:35:01 15 分钟阅读

分享文章

云成本失控,账单触目惊心?AgentCore帮你智能管控、及时止损!
在云原生时代企业数字化转型的步伐不断加快云基础设施已成为业务发展的核心支撑。然而伴随着云服务使用规模的快速增长云成本管理正成为企业面临的重大挑战。云成本的有效监控与管理已不再是可选项而是企业数字化战略成功的关键要素。云计算的弹性特性虽然带来了便利但也埋下了成本失控的隐患。在实际生产环境中经常遇到代码缺陷导致的资源泄露问题如程序bug引起的无限循环创建实例或者异常退出后未正确释放资源临时创建的大规格实例在项目结束后被遗忘持续产生费用自动扩缩容策略配置不当也是常见问题。这些问题往往在月度账单生成时才被发现此时损失已经造成错过了最佳的止损时机。另一方面传统的成本监控方法有一定局限性。例如通过Cost Explore Report查询历史成本分析和可视化图表或通过Cost and Usage ReportCUR进行复杂的成本分析需要编写复杂的SQL语句处理海量账单数据。原始账单数据结构复杂包含数百个字段和服务类型手工分析效率较低且对业务部门、财务部门等非技术人员并不友好。本文设计并实现了一套智能云成本监控与告警系统使用者通过自然语言与Agent交互获取与云成本相关的分析建议和优化方案同时实现异常告警。方案概述技术栈选型Agent框架Strands AgentsStrands Agents是一套由亚马逊云科技开源的AI Agent SDK。它的核心目标是让开发者用极少量的代码快速构建出具备推理、规划和执行能力的生产级AI助手。它具备全环境运行能力支持任何具备推理与工具使用能力的模型包括Amazon Bedrock仅海外业务使用等模型并通过LiteLLM实现对其他厂商模型的兼容。不同于LangGraph等需要开发者手动定义复杂状态机或图结构的框架Strands强调由LLM原生地进行规划、工具调用和自我反思。开发者只需定义Prompt、工具和模型剩下的编排逻辑由模型自主完成另外Strands Agents与亚马逊云科技云原生深度整合提供与Amazon Bedrock、Amazon Lambda、Amazon ECS等服务的无缝集成在某些场景下可减少开发步骤。Agent运行时Agentcore RuntimeAmazon Bedrock AgentCore Runtime是亚马逊云科技推出的一个专为AI Agents打造的托管运行环境。它作为Amazon Bedrock AgentCore仅海外业务使用的核心组件旨在解决开发者在将AI Agent从“概念原型”推向“生产级应用”时面临的架构、安全和扩展性挑战。核心功能Serverless托管提供全托管的执行环境开发者只需上传Agent代码支持容器镜像或Python压缩包无需管理底层服务器、负载均衡或扩展策略。框架与模型无关Agnostic支持LangGraph、CrewAI、LlamaIndex等多种开源框架和各种主流模型给予开发者极高的灵活性。长时运行支持专门针对复杂、多步骤的任务进行了优化单次执行时长最高可支持8小时。统一入口与交互基于Agent Card实现Agent的发现与交互通过简单的SDK调用即可实现复杂的会话管理。主要优势会话级隔离利用microVM技术为每个用户会话提供完全隔离的计算环境有效防止数据泄露和跨会话干扰。内置身份验证通过Amazon Bedrock AgentCore Identity实现与Amazon IAM及第三方服务的安全集成。自动扩展能够根据请求量从零自动扩展到数千个并发会话只需按实际处理时间付费。全链路追踪内置Amazon CloudWatch生成式AI可观测性可以深入查看Agent的推理步骤、工具调用记录和决策逻辑极大方便了调试与合规审计。系统架构设计单Agent双模式架构智能成本优化系统使用一个智能Agent同时承担交互式咨询和自动化监控两种职责避免Agent间协调的复杂性和延迟问题。架构图如下所示该Agent基于Amazon Bedrock AgentCore Runtime使用Amazon Bedrock LLM API作为决策引擎通过Tools与Amazon Cost Explorer、Budgets等API集成。在监控模式下同一个Agent通过EventBridge定时触发主动执行成本异常检测发现问题时自动通过SNS发送结构化告警。在交互模式下Agent作为成本专家顾问理解用户的自然语言查询并智能选择合适的分析工具将复杂的成本数据转化为易懂的业务洞察支持以下功能实时咨询多维度分析服务、区域、时间维度。基于历史数据的ML成本预测。成本趋势分析与优化建议识别成本增长趋势和周期性模式。多账户预算统一管理Payer账户统一查看所有关联账户成本发现某个账户的异常支出。核心功能实现完整代码和目录结构请参阅Github本章节针对关键部分展开介绍。Githubhttps://github.com/CrazyCha/Agent-cost-optimizationStrands Agents初始化Strands支持多种模型接入方式本文使用Amazon Bedrock中的sonnect-4.5模型。import osfrom strands import Agent, toolfrom strands.models import BedrockModel # Configuration - can be overridden via environment variablesMODEL_ID os.getenv(MODEL_ID, xxxxxxxx) model BedrockModel(model_idMODEL_ID) agent Agent( modelmodel, tools[ list_linked_accounts, analyze_cost_anomalies, get_budget_information, forecast_future_costs, get_service_cost_breakdown, get_multi_account_cost_breakdown, compare_accounts_costs, get_current_month_costs, ], system_prompt prompt左右滑动查看完整示意其中不同的Tools实现了不同的业务逻辑封装相关内容将在下文展开。system prompt定义了Agent的核心身份和行为准则详细规定Agent何时应调用外部工具如搜索、API、数据库以及如何处理返回结果。以下是成本分析Agent的系统提示词参考system_promptYou are an AWS Cost Optimization Expert Assistant deployed in a payer account. Your role is to help users understand, monitor, and optimize AWS spending across all linked accounts in the organization.You have access to powerful tools to:- List all linked accounts in the organization- Detect cost anomalies and unusual spending patterns- Retrieve budget status and forecasts- Analyze service-level cost breakdowns- Predict future costs using ML- Provide current month spending details- Analyze costs across all linked accounts in the organization- Compare spending between different linked accountsGuidelines:1. When users ask about costs, FIRST use list_linked_accounts to show available accounts2. Always use the appropriate tools to get real data - never make up numbers2. Provide clear, actionable insights based on the data3. When users ask about costs, be specific about time periods and services4. For multi-account scenarios, clearly identify which linked account has the highest costs5. If you detect high costs or anomalies, proactively suggest optimization strategies6. Be conversational and helpful, explaining technical concepts in simple terms7. When multiple tools are needed, use them in logical order8. Remember youre running from the payer account and can see all linked accountsCost Optimization Best Practices to recommend:- Review and terminate idle resources (EC2, EBS, RDS) across all accounts- Right-size over-provisioned instances based on utilization- Use Savings Plans or Reserved Instances for predictable workloads- Implement auto-scaling to match demand- Move infrequently accessed data to cheaper storage tiers- Set up budget alerts to catch cost spikes early- Use AWS Cost Explorer regularly for trend analysis- Implement cost allocation tags across all linked accounts- Consider account-level budgets for better cost controlAlways be proactive in identifying cost-saving opportunities across the entire organization!,)左右滑动查看完整示意Agentcore Runtime初始化与调用在cost optimization agent定义时完成注册Agentcore Runtime。from bedrock_agentcore.runtime import BedrockAgentCoreApp # 初始化AgentCore Runtime Appapp BedrockAgentCoreApp() # 注册Agent到Runtimeapp.agent()def invoke_agent(prompt: str) - str: return cost_agent.chat(prompt)左右滑动查看完整示意在deploy.py中完成镜像打包和agent推送# AgentCore Runtime创建def create_agent_runtime(): agentcore_client boto3.client(bedrock-agentcore) response agentcore_client.create_agent_runtime( agentRuntimeNameruntime_name, containerImagecontainer_image_uri, executionRoleArnexecution_role_arn, # 其他配置参数 ) return response[agentRuntimeArn]左右滑动查看完整示意关键Tools定义成本异常检测工具使用Amazon Cost Anomaly Detection API进行机器学习驱动的异常检测分析指定天数内的成本模式识别异常波动。关键代码如下def detect_cost_anomalies(days: int 7) - str: 检测AWS成本异常使用机器学习算法识别异常模式 try: ce_client boto3.client(ce) # 计算时间范围 end_date datetime.now().date() start_date end_date - timedelta(daysdays) # 获取异常检测结果 response ce_client.get_anomalies( DateInterval{ StartDate: start_date.strftime(%Y-%m-%d), EndDate: end_date.strftime(%Y-%m-%d) }, MaxResults50 ) anomalies response.get(Anomalies, []) ifnot anomalies: return f过去{days}天未检测到成本异常 # 分析异常详情 analysis [] total_impact 0 for anomaly in anomalies: impact float(anomaly.get(Impact, {}).get(MaxImpact, 0)) total_impact impact # 获取异常根因分析 root_causes [] for cause in anomaly.get(RootCauses, []): service cause.get(Service, Unknown) region cause.get(Region, Unknown) usage_type cause.get(UsageType, Unknown) root_causes.append(f{service} ({region}) - {usage_type}) analysis.append({ date: anomaly.get(AnomalyStartDate), impact: impact, score: anomaly.get(AnomalyScore, {}).get(MaxScore, 0), root_causes: root_causes }) # 生成分析报告 report f检测到 {len(anomalies)} 个成本异常\n report f总影响金额: ${total_impact:.2f}\n\n for i, item in enumerate(analysis[:3], 1): report f异常 {i}:\n report f 日期: {item[date]}\n report f 影响: ${item[impact]:.2f}\n report f 异常分数: {item[score]:.1f}\n report f 根因: {, .join(item[root_causes][:2])}\n\n return report except Exception as e: return f异常检测失败: {str(e)}左右滑动查看完整示意多账户成本聚合工具为Payer账户设计的多账户成本管理Organizations API集成、权限处理、数据聚合与排序提供账户级别的成本排名和趋势分析。特别说明该功能需要为执行角色添加ce:GetDimensionValues权限才能查看各个关联账号的详细成本分解。def get_multi_account_costs(days: int 30) - str:# 获取所有关联账户 try: accounts_response org_client.list_accounts() all_accounts { acc[Id]: acc[Name] for acc in accounts_response[Accounts] } except Exception: # 如果不是组织主账户使用当前账户 sts_client boto3.client(sts) current_account sts_client.get_caller_identity()[Account] all_accounts {current_account: Current Account} # 按账户分组获取成本数据 response ce_client.get_cost_and_usage( TimePeriod{ Start: start_date.strftime(%Y-%m-%d), End: end_date.strftime(%Y-%m-%d) }, GranularityMONTHLY, Metrics[UnblendedCost], GroupBy[ {Type: DIMENSION, Key: LINKED_ACCOUNT} ] ) # 按成本排序 sorted_accounts sorted( account_costs.items(), keylambda x: x[1], reverseTrue ) report f多账户成本分析 (过去{days}天)\n report f总成本: ${total_cost:.2f}\n report f账户数量: {len(account_costs)}\n\n return report左右滑动查看完整示意其他工具功能说明如下预算监控工具get_all_budgets获取所有亚马逊云科技服务预算的状态和利用率控预算超支风险和剩余额度。成本预测工具get_cost_forecast基于历史数据预测未来成本趋势使用Amazon Cost Explorer的机器学习预测能力。服务成本分析工具get_service_costs按亚马逊云科技服务维度分析成本分布提供服务级别的优化建议。账户成本比较工具compare_account_costs比较不同账户间的成本差异提供账户级别的成本优化建议。详细代码和实现方式请参考Github。定时监控实现定时监控系统使用Amazon EventBridge触发定时任务驱动Amazon Lambda调用cost optimization agent查询input固定为“检查过去7天的成本异常如果发现异常请详细说明”并在Lambda中针对返回结果进行关键字匹配并将告警通知推送至指定位置。其中Lambda函数的关键代码如下所示def lambda_handler(event, context): Lambda处理函数 - 每日成本异常检查 agent_runtime_arn os.environ[AGENT_RUNTIME_ARN] sns_topic_arn os.environ[SNS_TOPIC_ARN] try: query 检查过去7天的成本异常如果发现异常请详细说明 response agentcore_client.invoke_agent_runtime( agentRuntimeArnagent_runtime_arn, qualifierDEFAULT, payloadjson.dumps({prompt: query}) ) # 异常检测 if detect_anomaly_keywords(agent_response): send_anomaly_alert(sns_client, sns_topic_arn, agent_response) return create_response(200, 发现成本异常已发送告警, True, agent_response) else: return create_response(200, 成本检查正常无异常, False, agent_response) def detect_anomaly_keywords(agent_response): 基于关键词和上下文的异常检测 anomaly_keywords [ 异常, 异常检测, 成本激增, 超出预期, 显著增长, 预算超支, 成本飙升, 异常波动 ] # 关键词匹配 has_keywords any(keyword in agent_response for keyword in anomaly_keywords) # 上下文分析简化版 negative_indicators [正常, 未检测到, 无异常, 稳定] has_negative any(indicator in agent_response for indicator in negative_indicators) return has_keywords andnot has_negative左右滑动查看完整示意功能测试本节对成本分析的常见场景进行效果测试。根据下图结果Agent能够根据问题进行针对性回答并且给出有效建议满足系统设计需求。附录核心文件架构cost_optimization_agent.py # 主代理文件├── tools/│ ├── cost_explorer_tools.py # Cost Explorer API工具│ ├── budget_tools.py # Budgets API工具│ └── multi_account_tools.py # 多账户成本分析工具├── test_local.py # 本地基础功能测试├── test_agentcore_runtime.py # runtime功能测试└── deploy.py # AgentCore部署脚本左右滑动查看完整示意参考资料部署Strands Agentshttps://strandsagents.com/1.x/documentation/docs/user-guide/deploy/deploy_to_bedrock_agentcore/Githubhttps://github.com/aws-samples/sample_agentic_ai_strands本篇作者王昀哲亚马逊云科技行业解决方案架构师负责基于亚马逊云科技的云计算方案架构咨询和设计。目前专注于ISV行业。新用户注册海外区域账户可获得最高200美元服务抵扣金覆盖Amazon Bedrock生成式AI相关服务。“免费计划”账户类型确保零花费安心试用。星标不迷路开发更极速关注后记得星标「亚马逊云开发者」听说点完下面4个按钮就不会碰到bug了点击阅读原文查看博客获得更详细内容

更多文章