

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 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)、[InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)) 和 Converse API ([Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 和 [ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)) 進行推論。

當您使用 DeepSeek 的模型進行推論呼叫時，您必須包含模型的提示。如需為 Amazon Bedrock 支援的 DeepSeek 模型建立提示的一般資訊，請參閱《[DeepSeek 提示指南](https://api-docs.deepseek.com/guides/reasoning_model)》。

**注意**  
您無法從 Amazon 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
+ 文字模型

如需如何搭配 API 使用 DeepSeek 模型的詳細資訊，請參閱 [DeepSeek 模型](https://deepseek.com/)。

**DeepSeek 請求與回應**

**請求內文**

DeepSeek 具有下列文字完成推論呼叫的推論參數。

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

**欄位：**
+ **prompt** – (字串) 提示的必要文字輸入。
+ **temperature** – (浮點數) 小於或等於 1 的數值。
+ **top\_p** – (浮點數) 小於或等於 1 的數值。
+ **max\_tokens** – (int) 使用的字符，最少 1 到最多 8，192 個字符以獲得最佳品質。雖然 API 接受最多 32，768 個字符，但回應品質會大幅降低超過 8，192 個字符。
+ **stop** – (字串陣列) 最多 10 個項目。

**回應內文**

DeepSeek 具有下列文字完成推論呼叫的回應參數。此範例是來自 DeepSeek 的文字完成，不會傳回內容推理區塊。

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

**欄位：**
+ **stop\_reason** – (字串) 回應停止產生文字的原因。值為 `stop` 或 `length`。
+ **stop** – (字串) 模型已完成產生輸入提示的文字。
+ **length** – (字串) 產生文字的字符長度超出對 `InvokeModel` 呼叫之 `max_tokens` 的值 (如果您正在串流輸出則為 `InvokeModelWithResponseStream`)。回應會截斷為 `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** – (選用) 請求的系統提示。
+ **訊息** – (必要) 輸入訊息。
  + **role** – 對話回合的角色。有效值為 `user` 和 `assistant`。
  + **content** – (必要) 對話回合的內容，作為物件陣列。每個物件都包含一個 typefield，您可以在其中指定下列其中一個值：
    + **text** – (必要) 如果您指定此類型，則必須包含文字欄位，並指定文字提示作為其值。
+ **inferenceConfig** 
  + **temperature** – (選用) 值：最小值 = 0。最大值 = 1。
  + **topP** – (選用) 值：最小值 = 0。最大值 = 1。
  + **maxTokens** – (選用) 停止之前要產生的字符數目上限。值：最小值 = 0。最大值 = 32,768。
  + **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\_turn** – 模型到達停止點的回合。
  + **max\_tokens** – 產生的文字超過 `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()
```