

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

# Anthropic Claude 文字完成 API
<a name="model-parameters-anthropic-claude-text-completion"></a>

本節提供推論參數和使用 Anthropic Claude 模型搭配文字完成 API 的程式碼範例。

**Topics**
+ [Anthropic Claude 文字完成 API 概觀](#model-parameters-anthropic-claude-text-completion-overview)
+ [支援的模型](#claude-messages-supported-models)
+ [請求與回應](#model-parameters-anthropic-claude-text-completion-request-response)
+ [程式碼範例](#api-inference-examples-claude-text-completion)

## Anthropic Claude 文字完成 API 概觀
<a name="model-parameters-anthropic-claude-text-completion-overview"></a>

使用文字完成 API，從使用者提供的提示產生單回合文字。例如，您可以使用文字完成 API 來產生部落格文章的文字，或摘要來自使用者的文字輸入。

如需建立 Anthropic Claude 模型提示的相關資訊，請參閱[提示設計簡介](https://docs.anthropic.com/claude/docs/introduction-to-prompt-design)。如果您想要搭配 [Anthropic Claude 訊息 API](model-parameters-anthropic-claude-messages.md) 使用現有的文字完成提示，請參閱[從文字完成遷移](https://docs.anthropic.com/claude/reference/migrating-from-text-completions-to-messages)。

## 支援的模型
<a name="claude-messages-supported-models"></a>

您可以搭配下列 Anthropic Claude 模型使用文字完成 API。
+ Anthropic Claude Instant v1.2
+ Anthropic Claude v2
+ Anthropic Claude v2.1 

## 請求與回應
<a name="model-parameters-anthropic-claude-text-completion-request-response"></a>

請求本文在請求 `body` 欄位中傳遞到 [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)。

如需詳細資訊，請參閱 Anthropic Claude 文件中的 [https://docs.anthropic.com/claude/reference/complete\$1post](https://docs.anthropic.com/claude/reference/complete_post)。

------
#### [ Request ]

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

```
{
    "prompt": "\n\nHuman:<prompt>\n\nAssistant:",
    "temperature": float,
    "top_p": float,
    "top_k": int,
    "max_tokens_to_sample": int,
    "stop_sequences": [string]
}
```

以下是必要的參數。
+  **prompt** – (必要) 您想要讓 Claude 完成的提示。為了產生適當的回應，您需要使用交替 `\n\nHuman:` 和 `\n\nAssistant:` 對話回合來格式化提示。例如：

  ```
  "\n\nHuman: {userQuestion}\n\nAssistant:"
  ```

  如需詳細資訊，請參閱 Anthropic Claude 文件中的[提示驗證](https://docs.anthropic.com/claude/reference/prompt-validation)。
+  **max\$1tokens\$1to\$1sample** – (必要) 停止之前要產生的字符數目上限。我們建議 4,000 個記號上限以獲得最佳效能。

  請注意，Anthropic Claude 模型可能會在達到 `max_tokens_to_sample` 的值之前停止產生字符。不同的 Anthropic Claude 模型對此參數具有不同的最大值。如需詳細資訊，請參閱 Anthropic Claude 文件中的[模型比較](https://docs.anthropic.com/claude/docs/models-overview#model-comparison)。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)

以下是選用參數。
+  **stop\$1sequences** – (選用) 導致模型停止產生的序列。

  Anthropic Claude 模型會在 `"\n\nHuman:"` 上停止，且未來可能包含額外的內建停止序列。使用 `stop_sequences` 推論參數來包含其他字串，向模型發送訊號以停止產生文字。
+  **temperature** – (選用) 注入回應的隨機性量。對於分析/複選，請使用接近 0 的值，對於創意和生成任務，請使用接近 1 的值。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)
+  **top\$1p** – (選用) 使用核心取樣。

  在核心取樣中，Anthropic Claude 會以遞減的機率順序計算每個後續字符所有選項的累積分佈，並在達到 `top_p` 指定的特定機率時將其切斷。您應該更改 `temperature` 或 `top_p`，但不能同時更改。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)
+  **top\$1k** – (選用) 僅針對每個後續字符杖從前 K 個選項中取樣。

  使用 `top_k` 移除長尾低機率回應。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html)

------
#### [ Response ]

此 Anthropic Claude 模型會傳回文字完成推論呼叫的下列欄位。

```
{
    "completion": string,
    "stop_reason": string,
    "stop": string
}
```
+ **completion** – 產生的完成直到並排除停止序列。
+ **stop\$1reason** – 模型停止產生回應的原因。
  + **"stop\$1sequence"** – 模型已達到停止序列 — 您使用 `stop_sequences` 推論參數提供，或模型內建的停止序列。
  + **"max\$1tokens"** – 超過模型 `max_tokens_to_sample`，或模型的字符數目上限。
+ **stop** – 如果您指定 `stop_sequences` 推論參數，則 `stop` 包含向模型發送訊號以停止產生文字的停止序列。例如，下列回應中的 `holes`。

  ```
  {
      "completion": " Here is a simple explanation of black ",
      "stop_reason": "stop_sequence",
      "stop": "holes"
  }
  ```

  如未指定 `stop_sequences`，`stop` 的值將會是空白。

------

## 程式碼範例
<a name="api-inference-examples-claude-text-completion"></a>

這些範例展示如何利用隨需輸送量呼叫 *Anthropic Claude V2* 模型。若要使用 Anthropic Claude version 2.1，請將 `modelId` 的值變更為 `anthropic.claude-v2:1`。

```
import boto3
import json
brt = boto3.client(service_name='bedrock-runtime')

body = json.dumps({
    "prompt": "\n\nHuman: explain black holes to 8th graders\n\nAssistant:",
    "max_tokens_to_sample": 300,
    "temperature": 0.1,
    "top_p": 0.9,
})

modelId = 'anthropic.claude-v2'
accept = 'application/json'
contentType = 'application/json'

response = brt.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)

response_body = json.loads(response.get('body').read())

# text
print(response_body.get('completion'))
```

以下範例展示如何使用 Python 產生串流文字，並使用提示*寫一篇關於在火星生活的 1000 字文章*以及 Anthropic Claude V2 模型：

```
import boto3
import json

brt = boto3.client(service_name='bedrock-runtime')

body = json.dumps({
    'prompt': '\n\nHuman: write an essay for living on mars in 1000 words\n\nAssistant:',
    'max_tokens_to_sample': 4000
})
                   
response = brt.invoke_model_with_response_stream(
    modelId='anthropic.claude-v2', 
    body=body
)
    
stream = response.get('body')
if stream:
    for event in stream:
        chunk = event.get('chunk')
        if chunk:
            print(json.loads(chunk.get('bytes').decode()))
```