

# 使用 Converse API
<a name="using-converse-api"></a>

Converse API 为与 Amazon Nova 模型交互提供统一接口。该接口抽象封装了模型专属细节，并以统一方式处理所有 Amazon Nova 模型的多轮对话、系统提示与流式响应。

**Topics**
+ [请求结构](#converse-api-request-structure)
+ [使用系统提示词](#converse-api-system-prompt)
+ [推理参数](#converse-api-inference-params)
+ [使用推理](#converse-api-reasoning)

## 请求结构
<a name="converse-api-request-structure"></a>
+ **多轮对话：**在多次交互中保留上下文信息
+ **系统提示：**设定角色、回复规范等系统指令
+ **文档聊天：**与单个或批量文档进行交互、查询
+ **视觉能力：**处理并分析图像与视频内容
+ **工具使用：**支持模型使用外部工具和 API
+ **安全护栏：**应用内容过滤与安全控制策略
+ **推理能力：**通过扩展思考实现复杂问题求解

Converse API 基本请求包含模型 ID 和消息列表：

```
import boto3

bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')

response = bedrock.converse(
    modelId='us.amazon.nova-2-lite-v1:0',
    messages=[
        {
            'role': 'user',
            'content': [{'text': 'What is machine learning?'}]
        }
    ]
)

content_list = response["output"]["message"]["content"]
# Extract the first text block
text = next((item["text"] for item in content_list if "text" in item), None)
if text is not None:
    print(text)
```

## 使用系统提示词
<a name="converse-api-system-prompt"></a>

系统提示词为模型提供上下文信息和操作指令：

```
import boto3

bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')

response = bedrock.converse(
    modelId='us.amazon.nova-2-lite-v1:0',
    system=[
        {'text': 'You are a helpful AI assistant specializing in cloud computing.'}
    ],
    messages=[
        {
            'role': 'user',
            'content': [{'text': 'Explain serverless computing.'}]
        }
    ]
)

# Print the response text
content_list = response["output"]["message"]["content"]
text = next((item["text"] for item in content_list if "text" in item), None)
if text is not None:
    print(text)
```

## 推理参数
<a name="converse-api-inference-params"></a>

使用推理参数控制模型的输出。以下推理参数可用。
+  maxTokens（整数）：要生成的最大词元数（最多 65,000 个）。未指定时，模型将根据请求上下文使用动态默认值。
+  temperature（浮点数）：控制随机性（0.0 – 1.0，默认值 0.7）。数值越低，输出结果越具确定性 
+  topP（浮点数）：核采样阈值（0 – 1，默认值 0.9）。数值越低，输出结果越聚焦 
+  stopSequences（数组）：遇到指定字符序列时停止生成 

 示例：

```
import boto3
bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')

response = bedrock.converse(
    modelId='us.amazon.nova-2-lite-v1:0',
    messages=[
        {
            'role': 'user',
            'content': [{'text': 'Write a short story.'}]
        }
    ],
    inferenceConfig={
        'maxTokens': 512,
        'temperature': 0.7,
        'topP': 0.9,
        'stopSequences': ['END']
    }
)

content_list = response["output"]["message"]["content"]
text = next((item["text"] for item in content_list if "text" in item), None)
if text is not None:
    print(text)
```

## 使用推理
<a name="converse-api-reasoning"></a>

Nova 2 Lite 支持扩展思考能力，可用于复杂问题求解。使用 `reasoningConfig` 启用推理功能。

默认情况下，推理功能处于禁用状态，以便优化简单查询的速度和成本。如需处理更复杂的任务，可以启用推理功能。Nova 2 通过三个强度级别提供对推理深度的灵活控制：

低强度 (`maxReasoningEffort: "low"`)  
适用场景：复杂度更高、需结构化思考的任务。例如代码审查与优化建议（模型需细致评估现有代码质量）、需综合考量多重要素的分析任务，或适合采用系统化方法解决的问题场景。低强度适用于复合型任务，仅需基础推理即可提升精度，无需开展深度多步骤规划。

中强度 (`maxReasoningEffort: "medium"`)  
适用场景：多步骤任务和编码工作流。例如软件开发与调试（模型需在修改前理解现有代码结构）、跨多个文件或组件协同的代码生成、存在相互依赖关系的多步骤计算，以及带有多重约束条件的规划任务。中强度适用于需协调多个工具且模型需在一系列连续操作中保持上下文的智能代理工作流，效果最佳。

高强度 (`maxReasoningEffort: "high"`)  
适用场景：STEM 推理和高级问题求解。例如需要严谨分步验证的高等数学问题与证明、需深度探究的科学分析研究任务、涉及多维度架构考量的复杂系统设计，以及影响重大的关键决策场景。高强度可在需要高阶推理、审慎评估备选方案并全面验证结论的任务中，实现最高精度。

以下示例展示了不同级别的推理强度：

------
#### [ Low effort ]

```
import boto3

bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')

response = bedrock.converse(
    modelId='us.amazon.nova-2-lite-v1:0',
    system=[{"text": "You are a highly capable personal assistant"}],
    messages=[{
        "role": "user",
        "content": [{"text": "Provide a meal plan for a gluten free family of 4."}]
    }],
    inferenceConfig={
        "temperature": 0.7,
        "topP": 0.9,
        "maxTokens": 10000
    },
    additionalModelRequestFields={
        "reasoningConfig": {
            "type": "enabled",
            "maxReasoningEffort": "low"
        }
    }
)
```

------

 **推理参数：**

 以下为推理相关参数 
+ `type`：`enabled` 或 `disabled`（默认值：`disabled`）
+ `maxReasoningEffort`：`low`、`medium` 或 `high`。启用推理功能时，此参数为必填项。

**注意**  
将 `maxReasoningEffort` 设置为 `high` 时，不可同时使用 temperature、topP 和 topK 参数。因为组合使用会导致错误。

响应包含推理内容：

```
{
    "output": {
        "message": {
            "role": "assistant",
            "content": [
                {
                    "reasoningContent": {
                        "reasoningText": {
                            "text": "[REDACTED]"
                        }
                    }
                },
                {
                    "text": "Based on the premises, we can conclude..."
                }
            ]
        }
    },
    "stopReason": "end_turn"
}
```

**注意**  
在 Amazon Nova 2 中，推理内容会显示为 `[REDACTED]`。相关推理词元仍会计费，因其有助于提升输出质量。当前在响应结构中保留该字段，是为了便于未来开放显示推理内容。我们正积极与客户协作，确定展示模型推理过程的最优方案。