

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 批量推理的代码示例
<a name="batch-inference-example"></a>

本章中的代码示例展示了如何创建批量推理作业、如何查看关于该作业的信息以及如何停止该作业。此示例使用 `InvokeModel` API 格式。有关使用 `Converse` API 格式的信息，请参阅[设置格式并上传批量推理数据](batch-inference-data.md)。

选择一种语言，以查看相应的代码示例：

------
#### [ Python ]

创建一个名*abc.jsonl*为的 JSONL 文件，并为包含至少最少记录数的每条记录添加一个 JSON 对象（请参阅每个**批处理推理作业的最小记录数**）。*\$1Model\$1* [Amazon Bedrock 的配额](quotas.md)在本示例中，您将使用 Anthropic Claude 3 Haiku 模型。以下示例显示了文件中的第一个输入 JSON：

```
{
    "recordId": "CALL0000001", 
    "modelInput": {
        "anthropic_version": "bedrock-2023-05-31", 
        "max_tokens": 1024,
        "messages": [ 
            { 
                "role": "user", 
                "content": [
                    {
                        "type": "text", 
                        "text": "Summarize the following call transcript: ..." 
                    } 
                ]
            }
        ]
    }
}
... 
# Add records until you hit the minimum
```

创建名为的 S3 存储桶*amzn-s3-demo-bucket-input*，并将文件上传到该存储桶。然后创建一个名为的 S3 存储桶*amzn-s3-demo-bucket-output*，用于将输出文件写入其中。运行以下代码片段提交任务并*jobArn*从响应中获取：

```
import boto3

bedrock = boto3.client(service_name="bedrock")

inputDataConfig=({
    "s3InputDataConfig": {
        "s3Uri": "s3://amzn-s3-demo-bucket-input/abc.jsonl"
    }
})

outputDataConfig=({
    "s3OutputDataConfig": {
        "s3Uri": "s3://amzn-s3-demo-bucket-output/"
    }
})

response=bedrock.create_model_invocation_job(
    roleArn="arn:aws:iam::123456789012:role/MyBatchInferenceRole",
    modelId="anthropic.claude-3-haiku-20240307-v1:0",
    jobName="my-batch-job",
    inputDataConfig=inputDataConfig,
    outputDataConfig=outputDataConfig
)

jobArn = response.get('jobArn')
```

返回作业的 `status`。

```
bedrock.get_model_invocation_job(jobIdentifier=jobArn)['status']
```

列出批量推理作业. *Failed* 

```
bedrock.list_model_invocation_jobs(
    maxResults=10,
    statusEquals="Failed",
    sortOrder="Descending"
)
```

停止已开始的作业。

```
bedrock.stop_model_invocation_job(jobIdentifier=jobArn)
```

------