

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

# OpenAI 模型
<a name="model-parameters-openai"></a>

OpenAI 提供以下开放权重模型：
+ [https://huggingface.co/openai/gpt-oss-20b](https://huggingface.co/openai/gpt-oss-20b) – 一种经过优化的小型模型，旨在降低延迟，且适用于本地或特定使用案例。
+ [https://huggingface.co/openai/gpt-oss-120b](https://huggingface.co/openai/gpt-oss-120b) – 一种经过优化的大型模型，适用于生产环境、通用使用案例或高推理需求使用案例。

下表对有关模型的信息进行了汇总：


| 信息 | gpt-oss-20b | gpt-oss-120b | 
| --- | --- | --- | 
| 发行日期 | 2025 年 8 月 5 日 | 2025 年 8 月 5 日 | 
| 模型 ID | openai.gpt-oss-20b-1:0 | openai.gpt-oss-120b-1:0 | 
| 产品 ID | 不适用 | 不适用 | 
| 支持的输入模态 | 文本 | 文本 | 
| 支持的输出模态 | 文本 | 文本 | 
| 上下文窗口 | 128,000 | 128,000 | 

OpenAI 模型支持以下功能：
+ 使用以下操作的[模型调用](inference.md)：
  + [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)
  + [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html)
  + [OpenAI 聊天补全 API](inference-chat-completions.md)
+ 使用 [Batch 推断](batch-inference.md)。[CreateModelInvocationJob](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateModelInvocationJob.html)
+ 通过使用模型调用操作中的标头应用安全[护栏](guardrails.md)。

**Topics**
+ [OpenAI 请求正文](#model-parameters-openai-request)
+ [OpenAI 响应正文](#model-parameters-openai-response)
+ [OpenAI 模型使用示例](#model-parameters-openai-use)

## OpenAI 请求正文
<a name="model-parameters-openai-request"></a>

有关请求正文中的参数及其描述的信息，请参阅 OpenAI 文档中的[创建聊天补全](https://platform.openai.com/docs/api-reference/chat/create)。

通过以下方式使用请求正文字段：
+ 在[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)或OpenAI聊天完成请求中，请在请求正文中添加字段。
+ 在 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 请求中，执行以下操作：
  + 按如下方式映射 `messages`：
    + 对于角色为的每条消息`developer`，在`system`数组[SystemContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_SystemContentBlock.html)中添加 `content` a。
    + 对于角色为`user`或的每条消息`assistant`，将添加到`content`字段[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)中的，并在`messages`数组`role`中[消息](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html)的`role`字段中指定。`content`
  + 将以下字段的值映射到 `inferenceConfig` 对象中的相应字段：  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-openai.html)
  + 在 `additionalModelRequestFields` 对象中添加任何其他字段。

**构造请求正文时的注意事项**
+ OpenAI 模型仅支持文本输入和文本输出。
+ `model` 字段中的值必须与标头中的值匹配。您可省略该字段，它将自动填充为与标头相同的值。
+ `stream` 字段中的值必须与您使用的 API 操作匹配。您可省略该字段，它将自动填充为正确的值。
  + 如果使用 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)，则该`stream`值必须为`false`。

## OpenAI 响应正文
<a name="model-parameters-openai-response"></a>

OpenAI 模型的响应正文与 OpenAI 返回的聊天补全对象的结构一致。有关响应字段的更多信息，请参阅 OpenAI 文档中的[聊天补全对象](https://platform.openai.com/docs/api-reference/chat/object)。

**注意**  
如果您使用 `InvokeModel`，则模型推理将包含在 `<reasoning>` 标签中，并置于响应文本内容之前。

## OpenAI 模型使用示例
<a name="model-parameters-openai-use"></a>

此部分提供了一些说明如何使用 OpenAI 模型的示例。

### 先决条件
<a name="model-parameters-openai-use-prereq"></a>

在尝试这些示例之前，请确认已满足以下前提条件：
+ **身份验证** — 您可以使用您的 AWS 证书或 Amazon Bedrock API 密钥进行身份验证。

  设置您的 AWS 凭证或生成 Amazon Bedrock API 密钥来验证您的请求。
  + 要了解如何设置 AWS 证书，请参阅使用[AWS 安全凭证进行编程访问](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)。
  + 要了解有关 Amazon Bedrock API 密钥以及如何生成密钥的信息，请参阅 “构建” 一章中的 API 密钥部分。
**注意**  
如果您使用 OpenAI 聊天补全 API，则只能使用 Amazon Bedrock API 密钥进行身份验证。
+ **终端节点** — 找到与要在 [Amazon Bedrock 运行时终端节点和配额中使用的 AWS 区域相对应的终端节点](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)。如果您使用 S AWS DK，则在设置客户端时可能只需要指定区域代码，而无需指定整个终端节点。您必须使用与示例中使用的模型所支持的区域关联的端点。
+ **模型访问权限** - 请求对 OpenAI 模型的访问权限。有关更多信息，请参阅 [使用 SDK 和 CLI 管理模型访问权限](model-access.md#model-access-modify)。
+ **（如果示例使用 SDK）安装 SDK**-安装后，设置默认凭据和默认 AWS 区域。如果您未设置默认凭证或区域，则必须在相关代码示例中明确指定它们。有关标准化凭证提供商的更多信息，请参阅[AWS SDKs 和工具标准化凭证](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html)提供商。
**注意**  
如果您使用 OpenAI SDK，则只能使用 Amazon Bedrock API 密钥进行身份验证，并且必须明确设置 Amazon Bedrock 端点。

展开要查看的示例所在的部分：

### OpenAI 创建聊天补全
<a name="model-parameters-openai-use-chat-completions"></a>

要查看有关使用 OpenAI 创建聊天补全 API 的示例，请选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

以下 Python 脚本使用 OpenAI Python SDK 调用创建聊天补全 API：

```
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 using curl ]

您可以在终端运行以下命令，通过 curl 调用创建聊天补全 API：

```
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!"
        }
    ]
}'
```

------

### InvokeModel
<a name="model-parameters-openai-use-invoke"></a>

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Python ]

```
import boto3
import json

# Initialize the Bedrock Runtime client
client = boto3.client('bedrock-runtime')

# Model ID
model_id = 'openai.gpt-oss-20b-1:0'

# Create the request body
native_request = {
  "model": model_id, # You can omit this field
  "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?"
    }
  ],
  "max_completion_tokens": 150,
  "temperature": 0.7,
  "top_p": 0.9,
  "stream": False # You can omit this field
}

# Make the InvokeModel request
response = client.invoke_model(
    modelId=model_id,
    body=json.dumps(native_request)
)

# Parse and print the message for each choice in the chat completion
response_body = json.loads(response['body'].read().decode('utf-8'))

for choice in response_body['choices']:
    print(choice['message']['content'])
```

------

### Converse
<a name="model-parameters-openai-use-converse"></a>

使用统一的 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) API 时，您需要将 OpenAI 创建聊天补全字段映射到 Converse 请求正文中与其对应的字段。

例如，将以下聊天补全请求正文与其相应的 Converse 请求正文进行比较：

------
#### [ Create chat completion request body ]

```
{
  "model": "openai.gpt-oss-20b-1:0",
  "messages": [
    {
      "role": "developer",
      "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?"
    }
  ],
  "max_completion_tokens": 150,
  "temperature": 0.7
}
```

------
#### [ Converse request body ]

```
{
    "messages": [
        {
            "role": "user", 
            "content": [
                {
                    "text": "Hello! How can I help you today?"
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "text": "What is the weather like today?"
                }
            ]
        }
    ],
    "system": [
        {
            "text": "You are a helpful assistant."
        }
    ],
    "inferenceConfig": {
        "maxTokens": 150,
        "temperature": 0.7
    }
}
```

------

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Python ]

```
# Use the Conversation API to send a text message to Anthropic Claude.

import boto3
from botocore.exceptions import ClientError

# Initialize the Bedrock Runtime client
client = boto3.client("bedrock-runtime")

# Set the model ID
model_id = "openai.gpt-oss-20b-1:0"

# Set up messages and system message
messages = [
    {
        "role": "assistant", 
        "content": [
            {
                "text": "Hello! How can I help you today?"
            }
        ]
    },
    {
        "role": "user",
        "content": [
            {
                "text": "What is the weather like today?"
            }
        ]
    }
]

system = [
    {
        "text": "You are a helpful assistant."
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=messages,
        system=system,
        inferenceConfig={
            "maxTokens": 150, 
            "temperature": 0.7, 
            "topP": 0.9
        },
    )

    # Extract and print the response text.
    for content_block in response["output"]["message"]["content"]:
        print(content_block)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```

------

### 带护栏的 InvokeModel
<a name="model-parameters-openai-use-guardrails-invoke"></a>

在运行模型调用时，可通过在模型调用请求头中指定护栏 ID、版本以及是否启用护栏跟踪来应用护栏。

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Python ]

```
import boto3
from botocore.exceptions import ClientError
import json

# Initiate the Amazon Bedrock Runtime client
bedrock_runtime = boto3.client("bedrock-runtime")

# Model ID
model_id = "openai.gpt-oss-20b-1:0"

# Replace with actual values from your guardrail
guardrail_id = "GR12345"
guardrail_version = "DRAFT"

# Create the request body
native_request = {
  "model": model_id, # You can omit this field
  "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?"
    }
  ],
  "max_completion_tokens": 150,
  "temperature": 0.7,
  "top_p": 0.9,
  "stream": False # You can omit this field
}

try:
    response = bedrock_runtime.invoke_model(
        modelId=model_id,
        body=json.dumps(native_request),
        guardrailIdentifier=guardrail_id,
        guardrailVersion=guardrail_version,
        trace='ENABLED',
    )
    response_body = json.loads(response.get('body').read())
    print("Received response from InvokeModel API (Request Id: {})".format(response['ResponseMetadata']['RequestId']))
    print(json.dumps(response_body, indent=2))

except ClientError as err:
    print("RequestId = " + err.response['ResponseMetadata']['RequestId'])
    raise err
```

------

### 带 OpenAI 聊天补全功能的护栏
<a name="model-parameters-openai-use-guardrails-chat-completions"></a>

要查看在 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);
```

------

### 批量推理
<a name="model-parameters-openai-use-batch"></a>

利用[批量推理](batch-inference.md)功能，您可以根据多个提示异步运行模型推理。要使用 OpenAI 模型运行批量推理，请执行以下操作：

1. 创建一个 JSONL 文件，并在其中填入至少最小数量的 JSON 对象，且每个对象之间用换行符分隔。每个 `modelInput` 对象必须符合 [OpenAI 创建聊天补全](https://platform.openai.com/docs/api-reference/chat/create)请求正文的格式要求。以下是包含 OpenAI 请求正文的 JSONL 文件中前两行的示例。

   ```
   {
       "recordId": "RECORD1", 
       "modelInput": {
           "messages": [
               {
                   "role": "system", 
                   "content": "You are a helpful assistant."
               }, 
               {
                   "role": "user", 
                   "content": "Can you generate a question with a factual answer?"
               }
           ], 
           "max_completion_tokens": 1000
       }
   }
   {
       "recordId": "RECORD2", 
       "modelInput": {
           "messages": [
               {
                   "role": "system", 
                   "content": "You are a helpful assistant."
               }, 
               {
                   "role": "user", 
                   "content": "What is the weather like today?"
               }
           ], 
           "max_completion_tokens": 1000
       }
   }
   ...
   ```
**注意**  
`model` 字段是可选字段，如果您省略该字段，批量推理服务将根据标头自动为您插入该字段。  
检查您的 JSONL 文件是否符合[设置格式并上传批量推理数据](batch-inference-data.md)中概述的批量推理配额。

1. 将该文件上传到 Amazon S3 存储桶。

1. 使用 [Amazon Bedrock 控制平面终端节点](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-cp)发送[CreateModelInvocationJob](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateModelInvocationJob.html)请求，字段中指定了上一步中的 S3 存储桶，并在`inputDataConfig`字段中指定了OpenAI`modelId`模型。

有关 end-to-end代码示例，请参阅[批量推理的代码示例](batch-inference-example.md)。替换为适用于 OpenAI 模型的正确配置。