

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

# DeepSeek 模型
<a name="model-parameters-deepseek"></a>

DeepSeek[的 R1 和 V3.1 text-to-text 模型是可用于通过 Invoke API ([InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)、) 和 Converse API（Converse 和 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)）进行推理的模型。[ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html)

使用 DeepSeek 模型进行推理调用时，您必须为模型创建提示。有关为 Amazon Bedrock 支持的 DeepSeek 模型创建提示的一般信息，请参阅 [DeepSeek 提示指南](https://api-docs.deepseek.com/guides/reasoning_model.html)。

**注意**  
你无法移除亚马逊 Titan、Amazon Nova、 DeepSeek-R1、Mistral AI、Meta Llama 3 Instruct 和 Meta Llama 4 机型的请求访问权限。您可以通过使用 IAM 策略并指定模型 ID 来防止用户对这些模型进行推理调用。有关更多信息，请参阅[拒绝对基础模型推理的访问权限](https://docs.aws.amazon.com/bedrock/latest/userguide/security_iam_id-based-policy-examples.html#security_iam_id-based-policy-examples-deny-inference                         .html)。
要使用获得最佳响应质量DeepSeek-R1，请将`max_tokens`参数限制为 8,192 个标记或更少。虽然 API 最多接受 32,768 个令牌，但超过 8,192 个令牌的响应质量会显著降低。这与推理推理指南中描述的模型的[推理](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html)能力一致。

本部分介绍 DeepSeek 模型的请求参数和响应字段。使用此信息通过[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)操作对DeepSeek模型进行推理调用。此部分还包括 Python 代码示例，这些示例展示了如何调用 DeepSeek 模型。

要在推理操作中使用模型，您需要相关模型的模型 ID。由于此模型是通过跨区域推理调用的，因此您需要使用[推理配置文件 ID](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) 作为模型 ID。例如，对于美国，您将使用 `us.deepseek.r1-v1:0`。
+ 模型名称：DeepSeek-R1
+ 文本模型

有关如何将DeepSeek模型与一起使用的更多信息 APIs，请参阅[DeepSeek模型](https://deepseek.com/)。

**DeepSeek 请求和响应**

**请求正文**

DeepSeek具有以下用于文本完成推理调用的推理参数。

```
{
    "prompt": string,
    "temperature": float, 
    "top_p": float,
    "max_tokens": int,
    "stop": string array
}
```

**字段：**
+ **prompt** –（字符串）必填的提示文本输入。
+ **temperature** –（浮点）小于或等于 1 的数值。
+ **top\$1p** –（浮点）小于或等于 1 的数值。
+ **max\$1to** kens —（int）使用的代币，最少 1 到最多 8,192 个代币以获得最佳质量。虽然 API 最多接受 32,768 个令牌，但超过 8,192 个令牌的响应质量会显著降低。
+ **stop** –（字符串数组）最多 10 个项目。

**响应正文**

DeepSeek 具有以下响应参数，用于进行文本补全推理调用。此示例是来自 DeepSeek 的文本补全，且不返回内容推理块。

```
{
    "choices": [
        {
            "text": string,
            "stop_reason": string
        }
    ]
}
```

**字段：**
+ **stop\$1reason** –（字符串）响应停止生成文本的原因。值为 `stop` 或 `length`。
+ **stop** –（字符串）模型已完成对输入提示的文本生成。
+ **length** –（字符串）生成的文本的词元长度超过了对 `InvokeModel`（如果您要对输出进行流式传输，则为 `InvokeModelWithResponseStream`）的调用中的 `max_tokens` 值。响应被截断为 `max_tokens` 个词元。增加 `max_tokens` 的值，并重试请求。

**示例代码**

此示例展示了如何调用 DeepSeek-R1 模型。

```
# Use the API to send a text message to DeepSeek-R1.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS 区域 of your choice.
client = boto3.client("bedrock-runtime", region_name="us-west-2")

# Set the cross Region inference profile ID for DeepSeek-R1
model_id = "us.deepseek.r1-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Embed the prompt in DeepSeek-R1's instruction format.
formatted_prompt = f"""
<｜begin▁of▁sentence｜><｜User｜>{prompt}<｜Assistant｜><think>\n
"""

body = json.dumps({
    "prompt": formatted_prompt,
    "max_tokens": 512,
    "temperature": 0.5,
    "top_p": 0.9,
})

try:
    # Invoke the model with the request.
    response = client.invoke_model(modelId=model_id, body=body)

    # Read the response body.
    model_response = json.loads(response["body"].read())
    
    # Extract choices.
    choices = model_response["choices"]
    
    # Print choices.
    for index, choice in enumerate(choices):
        print(f"Choice {index + 1}\n----------")
        print(f"Text:\n{choice['text']}\n")
        print(f"Stop reason: {choice['stop_reason']}\n")
except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```

**Converse**

请求正文 - 使用此请求正文示例调用 ConverseAPI。

```
{
    "modelId": string, # us.deepseek.r1-v1:0
    "system": [
        {
            "text": string
        }
    ],
    "messages": [
        {
            "role": string,
            "content": [
                {
                    "text": string
                }
            ]
        }
    ],
    "inferenceConfig": {
        "temperature": float,
        "topP": float,
        "maxTokens": int,
        "stopSequences": string array
    },
    "guardrailConfig": { 
        "guardrailIdentifier":"string",
        "guardrailVersion": "string",
        "trace": "string"
    }
}
```

**字段：**
+ **system** –（可选）请求的系统提示。
+ **messages** –（必要）输入消息。
  + **role** – 对话回合的角色。有效值为 `user` 和 `assistant`。
  + **content** –（必填）对话回合的内容（采用对象数组形式）。每个对象均包含一个 type 字段，可以在其中指定下列值之一：
    + **text** –（必填）如果指定此类型，则必须包括一个 text 字段并将文本提示指定为其值。
+ **inferenceConfig** 
  + **temperature** -（可选）值：最小值 = 0。最大值 = 1。
  + **topP** -（可选）值：最小值 = 0。最大值 = 1。
  + **maxTokens** –（可选）停止前要生成的词元的最大数量。值：最小值 = 0。最大值 = 32768。
  + **stopSequences** –（可选）将导致模型停止生成输出的自定义文本序列。最大值 = 10 个项目。

响应正文 - 使用此请求正文示例调用 ConverseAPI。

```
{
    "message": {
        "role" : "assistant",
        "content": [
            {
                "text": string
            },
            {
                "reasoningContent": {
                    "reasoningText": string
                }
            }
        ],
    },
    "stopReason": string,
    "usage": {
        "inputTokens": int,
        "outputTokens": int,
        "totalTokens": int
    }
    "metrics": {
        "latencyMs": int
    }
}
```

**字段：**
+ **message** – 从模型返回的响应。
+ **role** – 生成的消息的对话角色。此值始终为 `assistant`。
+ **content** – 由模型生成的内容（以数组形式返回）。有两种类型的内容：
  + **text** – 响应的文本内容。
  + **reasoningContent** –（可选）模型响应中的推理内容。
    + **reasoningText** – 模型响应中的推理文本。
+ **stopReason** – 模型停止生成响应的原因。
  + **end\$1turn** – 模型达到了停止点的回合。
  + **max\$1tokens** – 生成的文本超过了 `maxTokens` 输入字段的值或超过了模型支持的最大词元数量。

示例代码——以下是 DeepSeek 制作一个调用 ConverseAPI 的示例。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use the Converse API with DeepSeek-R1 (on demand).
"""

import logging
import boto3

from botocore.client import Config
from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_conversation(bedrock_client,
                          model_id,
                          system_prompts,
                          messages):
    """
    Sends messages to a model.
    Args:
        bedrock_client: The Boto3 Bedrock runtime client.
        model_id (str): The model ID to use.
        system_prompts (JSON) : The system prompts for the model to use.
        messages (JSON) : The messages to send to the model.

    Returns:
        response (JSON): The conversation that the model generated.

    """

    logger.info("Generating message with model %s", model_id)

    # Inference parameters to use.
    temperature = 0.5
    max_tokens = 4096

    # Base inference parameters to use.
    inference_config = {
        "temperature": temperature,
        "maxTokens": max_tokens,
    }

    # Send the message.
    response = bedrock_client.converse(
        modelId=model_id,
        messages=messages,
        system=system_prompts,
        inferenceConfig=inference_config,
    )

    # Log token usage.
    token_usage = response['usage']
    logger.info("Input tokens: %s", token_usage['inputTokens'])
    logger.info("Output tokens: %s", token_usage['outputTokens'])
    logger.info("Total tokens: %s", token_usage['totalTokens'])
    logger.info("Stop reason: %s", response['stopReason'])

    return response

def main():
    """
    Entrypoint for DeepSeek-R1 example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "us.deepseek.r1-v1:0"

    # Setup the system prompts and messages to send to the model.
    system_prompts = [{"text": "You are an app that creates playlists for a radio station that plays rock and pop music. Only return song names and the artist."}]
    message_1 = {
        "role": "user",
        "content": [{"text": "Create a list of 3 pop songs."}]
    }
    message_2 = {
        "role": "user",
        "content": [{"text": "Make sure the songs are by artists from the United Kingdom."}]
    }
    messages = []

    try:
        # Configure timeout for long responses if needed
        custom_config = Config(connect_timeout=840, read_timeout=840)
        bedrock_client = boto3.client(service_name='bedrock-runtime', config=custom_config)

        # Start the conversation with the 1st message.
        messages.append(message_1)
        response = generate_conversation(
            bedrock_client, model_id, system_prompts, messages)

        # Add the response message to the conversation.
        output_message = response['output']['message']
        
        # Remove reasoning content from the response
        output_contents = []
        for content in output_message["content"]:
            if content.get("reasoningContent"):
                continue
            else:
                output_contents.append(content)
        output_message["content"] = output_contents
        
        messages.append(output_message)

        # Continue the conversation with the 2nd message.
        messages.append(message_2)
        response = generate_conversation(
            bedrock_client, model_id, system_prompts, messages)

        output_message = response['output']['message']
        messages.append(output_message)

        # Show the complete conversation.
        for message in messages:
            print(f"Role: {message['role']}")
            for content in message['content']:
                if content.get("text"):
                    print(f"Text: {content['text']}")
                if content.get("reasoningContent"):
                    reasoning_content = content['reasoningContent']
                    reasoning_text = reasoning_content.get('reasoningText', {})
                    print()
                    print(f"Reasoning Text: {reasoning_text.get('text')}")
            print()

    except ClientError as err:
        message = err.response['Error']['Message']
        logger.error("A client error occurred: %s", message)
        print(f"A client error occured: {message}")

    else:
        print(
            f"Finished generating text with model {model_id}.")


if __name__ == "__main__":
    main()
```