

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

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

DeepSeek[R1 dan V3.1 model adalah model teks-ke-teks yang tersedia untuk digunakan untuk inferensi melalui 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)) dan Converse API (Converse dan). [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) 

Saat Anda membuat panggilan inferensi dengan DeepSeek model, Anda harus menyertakan prompt untuk model tersebut. Untuk informasi umum tentang membuat prompt untuk DeepSeek model yang didukung Amazon Bedrock, lihat panduan [DeepSeekprompt](https://api-docs.deepseek.com/guides/reasoning_model). 

**catatan**  
Anda tidak dapat menghapus akses permintaan dari Amazon Titan, Amazon Nova,, Mistral AI DeepSeek-R1, Meta Llama 3 Instruct, dan model Meta Llama 4. Anda dapat mencegah pengguna membuat panggilan inferensi ke model ini dengan menggunakan kebijakan IAM dan menentukan ID model. Untuk informasi lebih lanjut, lihat [Tolak akses untuk inferensi model pondasi](https://docs.aws.amazon.com/bedrock/latest/userguide/security_iam_id-based-policy-examples.html#security_iam_id-based-policy-examples-deny-inference                         .html).
Untuk kualitas respons yang optimal denganDeepSeek-R1, batasi `max_tokens` parameter menjadi 8.192 token atau kurang. Sementara API menerima hingga 32.768 token, kualitas respons secara signifikan menurun di atas 8.192 token. Ini sejalan dengan kemampuan penalaran model seperti yang dijelaskan dalam panduan penalaran [inferensi](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html).

Bagian ini menjelaskan parameter permintaan dan bidang respons untuk DeepSeek model. Gunakan informasi ini untuk membuat panggilan inferensi ke DeepSeek model dengan [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)operasi. Bagian ini juga mencakup contoh kode Python yang menunjukkan cara memanggil DeepSeek model.

Untuk menggunakan model dalam operasi inferensi, Anda memerlukan ID model untuk model tersebut. Karena model ini dipanggil melalui inferensi lintas wilayah, Anda perlu menggunakan [ID profil Inferensi sebagai ID](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) model. Misalnya, untuk AS, Anda akan menggunakannya`us.deepseek.r1-v1:0`.
+ Nama model: DeepSeek-R1
+ Model Teks

Untuk informasi selengkapnya tentang cara menggunakan DeepSeek model dengan API, lihat [DeepSeekModel](https://deepseek.com/).

**DeepSeekPermintaan dan Tanggapan**

**Badan permintaan**

DeepSeekmemiliki parameter inferensi berikut untuk panggilan inferensi Penyelesaian Teks.

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

**Bidang:**
+ **prompt** - (string) Input teks yang diperlukan dari prompt.
+ **suhu** — (float) Nilai numerik kurang dari atau sama dengan 1.
+ **top\_p** — (float) Nilai numerik kurang dari atau sama dengan 1.
+ **max\_tokens** — (int) Token yang digunakan, minimal 1 hingga maksimal 8.192 token untuk kualitas optimal. Sementara API menerima hingga 32.768 token, kualitas respons secara signifikan menurun di atas 8.192 token.
+ **stop** - (string array) Maksimal 10 item.

**Respon tubuh**

DeepSeekmemiliki parameter respons berikut untuk panggilan inferensi Penyelesaian Teks. Contoh ini adalah penyelesaian teks dariDeepSeek, dan tidak mengembalikan blok penalaran konten.

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

**Bidang:**
+ **stop\_reason** — (string) Alasan mengapa respon berhenti menghasilkan teks. Nilai `stop` atau`length`.
+ **stop** — (string) Model telah selesai menghasilkan teks untuk prompt input.
+ **length** — (string) Panjang token untuk teks yang dihasilkan melebihi nilai `max_tokens` dalam panggilan ke `InvokeModel` (atau`InvokeModelWithResponseStream`, jika Anda streaming output). Respons terpotong. `max_tokens` Tingkatkan nilai `max_tokens` dan coba permintaan Anda lagi.

**Contoh Kode**

Contoh ini menunjukkan cara memanggil DeepSeek-R1 model.

```
# 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 Region 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)
```

**Bercakap**

Request Body - Gunakan contoh badan permintaan ini untuk memanggil 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"
    }
}
```

**Bidang:**
+ **sistem** — (Opsional) Prompt sistem untuk permintaan.
+ **pesan** — (Wajib) Pesan masukan.
  + **peran** — Peran percakapan berubah. Nilai yang valid adalah `user` dan `assistant`.
  + **konten** — (Wajib) Isi percakapan berubah, sebagai array objek. Setiap objek berisi typefield, di mana Anda dapat menentukan salah satu nilai berikut:
    + **teks** - (Wajib) Jika Anda menentukan jenis ini, Anda harus menyertakan bidang teks dan menentukan prompt teks sebagai nilainya.
+ **InferensiConfig** 
  + **suhu** — (Opsional) Nilai: minimum = 0. maksimum = 1.
  + **TopP** - (Opsional) Nilai: minimum = 0. maksimum = 1.
  + **MaxTokens** — (Opsional) Jumlah maksimum token yang akan dihasilkan sebelum berhenti. Nilai: minimum = 0. maksimum = 32.768.
  + **StopSequences** - (Opsional) Urutan teks khusus yang menyebabkan model berhenti menghasilkan output. Maksimum = 10 item.

Response Body - Gunakan contoh badan permintaan ini untuk memanggil converseAPI.

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

**Bidang:**
+ **pesan** — Respons kembali dari model.
+ **peran** — Peran percakapan dari pesan yang dihasilkan. Nilainya selalu `assistant`.
+ **konten** — Konten yang dihasilkan oleh model, yang dikembalikan sebagai array. Ada dua jenis konten:
  + **text** — Isi teks dari respon.
  + **ReasoningContent** — (Opsional) Konten penalaran dari respons model.
    + **ReasoningText — Teks** penalaran dari respons model.
+ **StopReason** — Alasan mengapa model berhenti menghasilkan respons. 
  + **end\_turn** — Putaran model mencapai titik berhenti.
  + **max\_tokens** — Teks yang dihasilkan melebihi nilai bidang `maxTokens` input atau melebihi jumlah maksimum token yang didukung model.

Contoh Kode - Berikut adalah contoh DeepSeek membuat untuk memanggil 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()
```