

# 構造化された出力が必要
<a name="prompting-structured-output"></a>

一貫性のある構造化された出力形式を確保するために、XML、JSON、Markdown などの形式を含む*構造化された出力*を使用できます。このアプローチにより、ダウンストリームのユースケースは、モデルによって生成された出力をより効果的に取得して処理できます。モデルに明示的な指示を提供することで、事前定義されたスキーマに準拠する方法でレスポンスが生成されます。モデルが従うように `output schema` を指定することをお勧めします。

たとえば、ダウンストリームパーサーが JSON オブジェクトのキーに特定の命名規則を想定している場合は、クエリの**出力スキーマ**フィールドにこれを指定する必要があります。さらに、レスポンスを前書きなしで JSON 形式にしたい場合は、そのようにモデルに指示します。つまり、明示的に「**JSON 出力のみを生成してください。前書きを入れないでください。**」と記述します。

**モデルの開始に役立つ事前入力の使用**

効率的な代替策は、`assistant` コンテンツを事前入力してモデルのレスポンスを*調整*することです。この手法により、モデルのアクションを指示し、前書きを省き、JSON や XML などの特定の出力形式を適用できます。たとえば、アシスタントコンテンツを `"{"` または `"```json"` で事前入力した場合、その入力は、追加情報を指定せずに JSON オブジェクトを生成するようにモデルをガイドできます。

**ヒント**  
JSON の抽出を明示的に求めている場合、よく見られるパターンの 1 つは、JSON を ````json` で事前入力し、````` に停止シーケンスを追加することです。これにより、モデルはプログラムで解析できる JSON オブジェクトを出力します。

一般的な形式の例をいくつか次に示します。

------
#### [ JSON ]

```
JSON_schema = """Make sure your final response is a valid JSON schema follow the below Response Schema:

##Response Schema:
```json
{ 
"key1": "value1",
"key2": "value2",
key3: [{
"key3_1": "value_3_1,
"key3_2": "value_3_2,
...}```
"""
```

------
#### [ XML ]

```
XML_format = """Make sure your final response is a valid XML schema follow the below Response Schema:
##Response Schema:
<thinking>
( your thoughts go hee )
</thinking>
<output>
    <task>"task1"</task>
    <subtask>
    <task1_result> ( task 1 result )</task1_result>
    <task2_result> ( task 2 result )</task2_result>
    <task3_result> ( task 3 result )</task3_result>
    </subtask>
    <task>"task2"</task>
    <subtask>
    <task1_result> ( task 1 result )</task1_result>
    <task2_result> ( task 2 result )</task2_result>
    <task3_result> ( task 3 result )</task3_result>
    </subtask>
</output>

"""
```

------
#### [ Markdown ]

```
markdown_schema = """Make sure your final response is a valid Markdown schema follow the below Response Schema:

##Response Schema:
## Introduction
( 2-3 line intro)

## Design Guidance 
(Bulleted list of design guidance)

## Step by Step Instructions on Execution
( Bulleted list of instructions with each with bold title.

## Conclusion
( conclusion )


"""
```

------

次のコード例では、API を使用して事前入力する方法を示しています。

```
import boto3
import json

# Create a Bedrock Runtime client.
client = boto3.client(
    "bedrock-runtime",
    region_name="us-east-1"
)

request_body = {
    "system": [
        {"text": "You write JSON objects based on the given instructions"}
    ],
    "messages": [
        {
            "role": "user",
            "content": [{"text": "Provide details about the best selling full-frame cameras in past three years.
Answer in JSON format with keys like name, brand, price and a summary."}]
        },
        {
            "role": "assistant",
            "content": [{"text": " Here is the JSON response: ```json"}]
        },
    ],
    "inferenceConfig": {
        "maxTokens": 300,
        "temperature": 0,
    }
}

# Invoke the model and extract the response body.
response = client.invoke_model(
    modelId="amazon.nova-micro-v1:0",
    body=json.dumps(request_body)
)
model_response = json.loads(response["body"].read())
```

**注記**  
構造化された出力の場合、ツールの使用法を活用しているかどうかにかかわらず、greedy デコードパラメータを使用することをお勧めします。つまり、`temperature=0` です。

## 例 1: 出力スキーマを追加する
<a name="structure-collapsible1"></a>

適切なスキーマで出力スキーマセクションを追加すると、モデルはそのスキーマに合わせようとします。ただし、モデル出力は決定的ではなく、出力スキーマとは異なる場合があります。


| ロール |  | Prompt | 
| --- |--- |--- |
| ユーザー | 過去 3 年間に最も売れたフルフレームカメラの詳細を教えてください。名前、ブランド、価格、概要などのキーを含む JSON 形式で回答してください。 | 過去 3 年間に最も売れたフルフレームカメラの詳細を教えてください。JSON 形式でのみ回答する必要があります。以下の出力スキーマに従ってください。<br />**出力スキーマ:**<pre>[{<br />    "name": "name goes here",<br />    "brand": "brand goes here",<br />    "price": "price goes here",<br />    "summary": "summary goes here"<br />}]</pre> | 
| Assistant |  <pre>[<br /> {<br /> "name": "Sony Alpha A7R IV",<br /> "brand": "Sony",<br /> "price": "Approximately $3,500",<br /> "summary": "The Sony Alpha A7R IV is renowned for its<br /> exceptional image quality, thanks to a 61-megapixel<br /> full-frame sensor. It also features 4K video recording<br /> and a robust build, making it a favorite among professional<br /> photographers and videographers."<br /> },<br /> {<br /> "name": "Canon EOS R5",<br /> "brand": "Canon",<br /> "price": "Approximately $3,900",<br /> "summary": "The Canon EOS R5 combines high-resolution<br /> imaging with advanced video capabilities. It houses a<br /> 45-megapixel sensor, 8K video recording, and impressive<br /> autofocus performance, appealing to both photography<br /> and filmmaking professionals."<br /> },<br /> {<br /> "name": "Nikon Z7 II",<br /> "brand": "Nikon",<br /> "price": "Approximately $2,800",<br /> "summary": "The Nikon Z7 II offers a 45.7-megapixel<br /> full-frame sensor and is praised for its high resolution<br /> and excellent dynamic range. It also supports 4K video<br /> recording and features a versatile Z-mount lens system,<br /> making it a strong contender in the full-frame market."<br /> },<br /> {<br /> "name": "Fujifilm GFX 100S",<br /> "brand": "Fujifilm",<br /> "price": "Approximately $7,000",<br /> "summary": "While not a traditional full-frame camera,<br /> the Fujifilm GFX 100S stands out with its 102-megapixel<br /> medium format sensor. It is lauded for its stunning detail<br /> and color reproduction, though it comes at a higher price<br /> point and is aimed at specialized users."<br /> }<br /> ]</pre>  |  <pre>[<br /> {<br /> "name": "Nikon D850",<br /> "brand": "Nikon",<br /> "price": "$3,296.95",<br /> "summary": "The Nikon D850 is a professional full-frame<br /> DSLR camera known for its exceptional image quality,<br /> 45.7-megapixel resolution, 7 fps continuous shooting,<br /> and 4K video capabilities."<br /> },<br /> {<br /> "name": "Canon EOS 5D Mark IV",<br /> "brand": "Canon",<br /> "price": "$3,499.00",<br /> "summary": "The Canon EOS 5D Mark IV is a popular<br /> full-frame DSLR appreciated for its 30.4-megapixel sensor,<br /> 4K video recording, robust build quality, and reliable<br /> autofocus system."<br /> },<br /> {<br /> "name": "Sony A7R III",<br /> "brand": "Sony",<br /> "price": "$3,198.00",<br /> "summary": "The Sony A7R III is a high-resolution<br /> full-frame mirrorless camera renowned for its 42.4-megapixel<br /> sensor, excellent low-light performance, and versatile<br /> lens compatibility."<br /> },<br /> {<br /> "name": "Fujifilm GFX 100S",<br /> "brand": "Fujifilm",<br /> "price": "$5,999.99",<br /> "summary": "The Fujifilm GFX 100S is a medium format<br /> mirrorless camera that stands out for its 102-megapixel<br /> sensor, high dynamic range, and exceptional color reproduction."<br /> },<br /> {<br /> "name": "Sony A7 III",<br /> "brand": "Sony",<br /> "price": "$1,998.00",<br /> "summary": "The Sony A7 III is a full-frame mirrorless<br /> camera popular among enthusiasts and professionals for<br /> its 24.2-megapixel sensor, fast autofocus, and 4K video<br /> capabilities."<br /> }<br /> ]</pre>  | 

## 例 2: モデルレスポンスを事前入力する
<a name="structure-collapsible2"></a>

もう 1 つの方法は、アシスタントのメッセージに望ましい最初のテキストを含めることで、モデルのレスポンスを事前入力することです。この場合、Amazon Nova モデルの応答は、アシスタントのメッセージが終わる場所から続行されます。


| ロール | Prompt | 
| --- |--- |
| ユーザー | 過去 3 年間に最も売れたフルフレームカメラの詳細を教えてください。レスポンスは JSON 形式。レスポンスに含めるキー: 名前、ブランド、年、価格、概要。 | 
| アシスタント *(事前入力)* | ```json | 
| Assistant |  <pre>{<br /> "cameras": [<br /> {<br /> "name": "Sony Alpha A7 III",<br /> "brand": "Sony",<br /> "year": 2018,<br /> "price": "$1999",<br /> "summary": "The Sony Alpha A7 III is a highly acclaimed<br /> full-frame mirrorless camera known for its excellent<br /> image quality, advanced autofocus system, and 4K video<br /> capabilities."<br /> },<br /> {<br /> "name": "Canon EOS R5",<br /> "brand": "Canon",<br /> "year": 2020,<br /> "price": "$3899",<br /> "summary": "The Canon EOS R5 is a top-tier full-frame<br /> mirrorless camera that offers stunning 45MP images, 8K<br /> video recording, and exceptional performance in various<br /> lighting conditions."<br /> },<br /> {<br /> "name": "Nikon Z7 II",<br /> "brand": "Nikon",<br /> "year": 2020,<br /> "price": "$2999",<br /> "summary": "The Nikon Z7 II is a flagship full-frame<br /> mirrorless camera with a 45.7MP sensor, superb image<br /> quality, and advanced video recording features."<br /> },<br /> {<br /> "name": "Fujifilm GFX 100S",<br /> "brand": "Fujifilm",<br /> "year": 2020,<br /> "price": "$7999",<br /> "summary": "The Fujifilm GFX 100S is a medium format<br /> mirrorless camera known for its impressive 102MP sensor,<br /> beautiful film simulations, and versatile lens options."<br /> },<br /> {<br /> "name": "Sony Alpha A7R IV",<br /> "brand": "Sony",<br /> "year": 2019,<br /> "price": "$3499",<br /> "summary": "The Sony Alpha A7R IV features a 61MP<br /> sensor, excellent low-light performance, and advanced<br /> video capabilities, making it a favorite among<br /> professional photographers."<br /> }<br /> ]<br /> }<br /> ```</pre>  | 

## 例 3: 使用するツールを指定する
<a name="structure-collapsible3"></a>

3 つ目の方法は、ツール使用スキーマセクションに *Pydantic JSON スキーマ*を含めることで、ツール使用を用いてモデルのレスポンスに特定のスキーマを強制することです。提供されたスキーマに*ツールの選択*を指定できます。Amazon Nova のレスポンスは、選択したツールに基づいて構造化されます。ツール使用の活用方法の詳細については、「[Amazon Nova でのツールの使用 (関数呼び出し)](tool-use.md)」を参照してください。


|  |  | 
| --- |--- |
| ユーザー | 以下に示すクエリから、関連するエンティティを抽出します。<pre>Query: John works in BUILDING-0987<br />and has been in charge of product id 23564#.<br />His performance has been excellent in past<br />year and he is up for a raise.<br /><br />Use the print_entities tool.</pre> | 
| ToolConfig |  <pre>tool_config = {<br />    "tools": [<br />        {<br />            "toolSpec": {<br />                    "name": "print_entities",<br />                    "description": "Extract the named entity based on provided input",<br />                    "inputSchema": {<br />                        "type": "object",<br />                        "properties": {<br />                            "name": {<br />                               "type": "string",<br />                               "description": "The extracted entity name. This should be a name of a person, place, animal or thing"<br />                            },<br />                            "location": {<br />                               "type": "string",<br />                                "description": "The extracted location name. This is a site name or a building name like SITE-001 or BUILDING-003"<br />                            },<br />                            "product": {<br />                              "type": "string",<br />                              "description": "The extracted product code, this is generally a 6 digit alphanumeric code such as 45623#, 234567"<br />                            }<br />                        },<br />                        "required": ["name", "location", "product"]<br />                 }<br />            }<br />        }<br />    ],<br />    "toolChoice": {<br />        "tool": {<br />            "name": "print_entities"<br />        }<br />    }<br />}</pre>  | 