本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用OpenAI聊天完成 API 調用模型
您可以使用OpenAI建立聊天完成 API 搭配 Amazon Bedrock 模型來執行模型推論。
您可以透過下列方式呼叫建立聊天完成 API:
選取主題以進一步了解:
OpenAI 聊天完成 API 支援的模型和區域
您可以使用建立聊天完成 API 搭配 Amazon Bedrock 和支援這些OpenAI模型的 AWS 區域中支援的所有模型。如需支援的模型和區域的詳細資訊,請參閱 Amazon Bedrock 中支援的基礎模型。
使用聊天完成 API 的先決條件
若要查看使用聊天完成 API 的先決條件,請選擇您偏好方法的索引標籤,然後遵循下列步驟:
- OpenAI SDK
-
- HTTP request
-
建立聊天完成
如需建立聊天完成 API 的詳細資訊,請參閱 OpenAI 文件中的下列資源:
Amazon Bedrock 目前不支援其他OpenAI聊天完成 API 操作。
若要了解如何使用OpenAI建立聊天完成 API,請選擇您偏好方法的索引標籤,然後遵循下列步驟:
- OpenAI SDK (Python)
-
若要使用 OpenAI SDK 建立聊天完成,請執行下列動作:
-
匯入 OpenAI SDK 並使用下列欄位設定用戶端:
-
base_url
– 將 Amazon Bedrock 執行期端點字首為 /openai/v1
,格式如下:
https://${bedrock-runtime-endpoint}
/openai/v1
-
api_key
– 指定 Amazon Bedrock API 金鑰。
-
default_headers
– 如果您需要包含任何標頭,您可以將它們作為索引鍵/值對包含在此物件中。您也可以在進行特定 API 呼叫extra_headers
時,在 中指定標頭。
-
搭配 用戶端使用 chat.completions.create()
方法,並在請求內文messages
中最少指定 model
和 。
下列範例會呼叫 中的建立聊天完成 APIus-west-2
。使用實際 API 金鑰取代 $AWS_BEARER_TOKEN_BEDROCK
。
from openai import OpenAI
client = OpenAI(
base_url="https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1",
api_key="$AWS_BEARER_TOKEN_BEDROCK" # Replace with actual API key
)
completion = client.chat.completions.create(
model="openai.gpt-oss-20b-1:0",
messages=[
{
"role": "developer",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
]
)
print(completion.choices[0].message)
- HTTP request
-
若要使用直接 HTTTP 請求建立聊天完成,請執行下列動作:
-
將 Amazon Bedrock 執行期端點字首為 來指定 URL/openai/v1/chat/completions
,格式如下:
https://${bedrock-runtime-endpoint}
/openai/v1/chat/completions
-
在 Authorization
標頭中指定您的 AWS 登入資料或 Amazon Bedrock API 金鑰。
-
在請求內文中,在請求內文messages
中至少指定 model
和 。
下列範例使用 curl 呼叫 中的建立聊天完成 APIus-west-2
。使用實際 API 金鑰取代 $AWS_BEARER_TOKEN_BEDROCK
:
curl -X POST https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AWS_BEARER_TOKEN_BEDROCK" \
-d '{
"model": "openai.gpt-oss-20b-1:0",
"messages": [
{
"role": "developer",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
]
}'
在聊天完成時包含護欄
若要在模型輸入和回應中包含保護措施,請在執行模型調用時套用護欄,方法是在請求內文中包含下列額外參數做為欄位:
如需 Amazon Bedrock Guardrails 中這些參數的詳細資訊,請參閱 測試您的護欄。
若要查看在OpenAI聊天完成時使用護欄的範例,請選擇您偏好方法的索引標籤,然後遵循以下步驟:
- OpenAI SDK (Python)
-
import openai
from openai import OpenAIError
# Endpoint for Amazon Bedrock Runtime
bedrock_endpoint = "https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1"
# Model ID
model_id = "openai.gpt-oss-20b-1:0"
# Replace with actual values
bedrock_api_key = "$AWS_BEARER_TOKEN_BEDROCK"
guardrail_id = "GR12345"
guardrail_version = "DRAFT"
client = openai.OpenAI(
api_key=bedrock_api_key,
base_url=bedrock_endpoint,
)
try:
response = client.chat.completions.create(
model=model_id,
# Specify guardrail information in the header
extra_headers={
"X-Amzn-Bedrock-GuardrailIdentifier": guardrail_id,
"X-Amzn-Bedrock-GuardrailVersion": guardrail_version,
"X-Amzn-Bedrock-Trace": "ENABLED",
},
# Additional guardrail information can be specified in the body
extra_body={
"amazon-bedrock-guardrailConfig": {
"tagSuffix": "xyz" # Used for input tagging
}
},
messages=[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "assistant",
"content": "Hello! How can I help you today?"
},
{
"role": "user",
"content": "What is the weather like today?"
}
]
)
request_id = response._request_id
print(f"Request ID: {request_id}")
print(response)
except OpenAIError as e:
print(f"An error occurred: {e}")
if hasattr(e, 'response') and e.response is not None:
request_id = e.response.headers.get("x-request-id")
print(f"Request ID: {request_id}")
- OpenAI SDK (Java)
-
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponseFor;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
// Endpoint for Amazon Bedrock Runtime
String bedrockEndpoint = "http://bedrock-runtime.us-west-2.amazonaws.com/openai/v1"
// Model ID
String modelId = "openai.gpt-oss-20b-1:0"
// Replace with actual values
String bedrockApiKey = "$AWS_BEARER_TOKEN_BEDROCK"
String guardrailId = "GR12345"
String guardrailVersion = "DRAFT"
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(bedrockApiKey)
.baseUrl(bedrockEndpoint)
.build()
ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
.addUserMessage("What is the temperature in Seattle?")
.model(modelId)
// Specify additional headers for the guardrail
.putAdditionalHeader("X-Amzn-Bedrock-GuardrailIdentifier", guardrailId)
.putAdditionalHeader("X-Amzn-Bedrock-GuardrailVersion", guardrailVersion)
// Specify additional body parameters for the guardrail
.putAdditionalBodyProperty(
"amazon-bedrock-guardrailConfig",
JsonValue.from(Map.of("tagSuffix", JsonValue.of("xyz"))) // Allows input tagging
)
.build();
HttpResponseFor<ChatCompletion> rawChatCompletionResponse =
client.chat().completions().withRawResponse().create(request);
final ChatCompletion chatCompletion = rawChatCompletionResponse.parse();
System.out.println(chatCompletion);