View a markdown version of this page

构建人工智能代理 - Amazon Nova

构建人工智能代理

Amazon Nova 模型针对使用 Amazon Nova Act 构建人工智能代理进行了优化。这些模型优化了工具使用能力,提升了多步骤任务推理效果,增强了在复杂代理工作流中维持上下文的能力,并支持远程 MCP 工具。

创建代理

使用 Nova 构建的人工智能代理可协调多次工具调用,在持续交互过程中保持上下文,并在需要时进行纠错调整。扩展思考能力通过对复杂目标开展系统性推理,可优化代理工作流。建议采用 Strands Agents 等规划框架 SDK,使代理系统的规划与执行流程更加稳定可靠。

代理设计模式

使用 Nova 设计代理时:

  • 对于需要规划与验证的复杂多步骤工作流,建议将推理等级设为中级或高级,以便获得最佳效果

  • 启用 auto 工具选择,支持在代理交互过程中灵活选用工具

  • 设计错误处理机制,使代理能够恢复执行并采用调整后的方案重试

  • 保留对话历史,在代理交互全过程中维持上下文信息

  • 针对代理系统处理的非受控内容,部署完善的内容过滤与审核机制。例如,Amazon 提供 Amazon Bedrock 护栏功能,可在多个基础模型、知识库和代理中应用安全防护策略。此类护栏可过滤有害内容、屏蔽违规话题,并对个人身份信息等敏感数据进行脱敏处理。

多工具代理示例

tool_config = {     "tools": [         {             "toolSpec": {                 "name": "calculator",                 "description": "Perform mathematical calculations",                 "inputSchema": {                     "json": {                         "type": "object",                         "properties": {                             "expression": {                                 "type": "string",                                 "description": "Mathematical expression to evaluate"                             }                         },                         "required": ["expression"]                     }                 }             }         },         {             "toolSpec": {                 "name": "database_query",                 "description": "Query financial database for historical data",                 "inputSchema": {                     "json": {                         "type": "object",                         "properties": {                             "query": {                                 "type": "string",                                 "description": "SQL query to execute"                             }                         },                         "required": ["query"]                     }                 }             }         }     ] } response = client.converse(     modelId=" us.amazon.nova-2-lite-v1:0",     messages=[{         "role": "user",         "content": [{             "text": "Analyze our Q3 financial performance across all business units, calculate year-over-year growth rates with statistical significance testing, and recommend budget allocation strategies for Q4."         }]     }],     toolConfig=tool_config,     inferenceConfig={"maxTokens": 10000, "temperature": 1, “topP”: 0.9},     additionalModelRequestFields={         "reasoningConfig": {             "type": "enabled",             "maxReasoningEffort": "low"         }     } )

调用代理

代理调用涉及管理对话流程、处理工具调用以及在多次交互之间维护状态。

流式代理响应

通过流式响应实时呈现代理的推理过程与执行操作:

import boto3 response = client.converse_stream(     modelId=" us.amazon.nova-2-lite-v1:0",     messages=[{         "role": "user",         "content": [{             "text": "Design a scalable microservices architecture for an e-commerce platform handling 1M+ daily transactions. Consider data consistency, fault tolerance, performance, security, and cost optimization."         }]     }],     inferenceConfig={"maxTokens": 10000, "temperature": 10},     additionalModelRequestFields={         "reasoningConfig": {             "type": "enabled",             "maxReasoningEffort": "low"         }     } ) # Process the streaming response reasoning_complete = False for event in response["stream"]:     if "contentBlockDelta" in event:         delta = event["contentBlockDelta"]["delta"]                  if "reasoningContent" in delta:             reasoning_text = delta["reasoningContent"]["reasoningText"]["text"]             print(f"{reasoning_text}", end="", flush=True)         elif "text" in delta:             if not reasoning_complete:                 print(f" Final Architecture Design: ")                 reasoning_complete = True             print(f"{delta['text']}", end="", flush=True)

代理状态管理

维护对话历史与工具执行结果以保留上下文;以下示例仅演示单轮对话场景,但开发人员可根据工作流需求自行编排整个代理系统。此外,Strands 等 Amazon Web Services 工具可代表开发人员管理代理上下文和工具状态。

messages = [] messages = [] # Initial user query messages.append({     "role": "user",     "content": [{"text": user_query}] }) # Get agent response response = client.converse(     modelId=" us.amazon.nova-2-lite-v1:0",     messages=messages,     toolConfig=tool_config,     inferenceConfig=inf_params ) # Add assistant response to history messages.append(response["output"]["message"]) # Process tool calls and add results if response["stopReason"] == "tool_use":     tool = next(         block["toolUse"]         for block in response["output"]["message"]["content"]         if "toolUse" in block     )          # Execute tool     result = execute_tool(tool["name"], tool["input"])          # Add tool result to conversation     messages.append({         "role": "user",         "content": [{             "toolResult": {                 "toolUseId": tool["toolUseId"],                 "content": [{"json": result}],                 "status": "success"             }         }]     })          # Continue conversation     response = client.converse(         modelId=" us.amazon.nova-2-lite-v1:0",         messages=messages,         toolConfig=tool_config,         inferenceConfig=inf_params     )

代理最佳实践

有关代理最佳实践的更多信息,请参阅一般最佳实践

有关开发对话式人工智能代理的指南,请参阅语音转语音(Amazon Nova 2 Sonic)