

# 구조화된 출력 필요
<a name="prompting-structured-output"></a>

일관되고 구조화된 출력 형식을 보장하기 위해 XML, JSON 또는 마크다운과 같은 형식을 포함한 *구조화된 출력*을 사용할 수 있습니다. 이 접근 방식을 사용하면 다운스트림 사용 사례가 모델에서 생성된 출력을 보다 효과적으로 사용하고 처리할 수 있습니다. 모델에 명시적 지침을 제공하면 미리 정의된 스키마를 준수하는 방식으로 응답이 생성됩니다. 모델이 따라야 할 `output schema`를 제공하는 것이 좋습니다.

예를 들어 다운스트림 구문 분석기가 JSON 객체의 키에 대한 특정 명명 규칙을 예상하는 경우 쿼리의 **출력 스키마** 필드에 이를 지정해야 합니다. 또한, 머리말 텍스트 없이 JSON 형식으로 응답을 받는 것을 선호하는 경우 모델에 그에 맞는 지시를 내리세요. 즉, ‘**JSON 출력만 생성하고, 머리말을 제공해서는 안 됩니다.**’라고 지시합니다.

**사전 채우기를 사용하여 모델 시작 지원**

효율적인 대안은 `assistant` 콘텐츠를 미리 채워서 모델의 응답을 *넛지*하는 것입니다. 이 기술을 사용하면 모델의 작업을 지시하고, 머리말을 우회하고, JSON 및 XML과 같은 특정 출력 형식을 적용할 수 있습니다. 예를 들어 어시스턴트 콘텐츠에 `"{"` 또는 `"```json"`을 미리 입력하면 추가 정보를 제공하지 않고도 모델이 JSON 개체를 생성하도록 안내할 수 있습니다.

**작은 정보**  
명시적으로 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())
```

**참고**  
구조화된 출력의 경우 도구 사용을 활용하는지 여부와 관계없이 복잡한 디코딩 파라미터를 사용하는 것이 좋습니다. 즉, `temperature=0`으로 설정합니다.

## 예제 1: 출력 스키마 추가
<a name="structure-collapsible1"></a>

적절한 스키마로 출력 스키마 섹션을 추가하면 모델이 해당 스키마에 맞게 설정됩니다. 그러나 모델 출력은 결정적이지 않으며 출력 스키마와 다를 수 있습니다.


| 역할 |  | 프롬프트 | 
| --- |--- |--- |
| User | 지난 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>

또 다른 접근 방식은 어시스턴트의 메시지에 원하는 초기 텍스트를 포함하여 모델의 응답을 미리 채우는 것입니다. 이 경우 Amazon Nova 모델의 응답은 어시스턴트의 메시지가 중단된 지점부터 계속됩니다.


| 역할 | 프롬프트 | 
| --- |--- |
| User | 지난 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>

세 번째 접근 방식은 도구 사용 스키마 섹션에 *Pydantic JSON 스키마*를 포함하여 모델 응답에 특정 스키마를 강제로 적용하는 것입니다. 제공된 스키마에 *도구 선택*을 지정할 수 있으며 선택한 도구에 따라 Amazon Nova의 응답이 구성됩니다. 도구 활용 방법에 대해 자세히 알아보려면 [Amazon Nova에서 도구 사용(함수 직접 호출)](tool-use.md) 섹션을 참조하세요.


|  |  | 
| --- |--- |
| User | 아래 제공된 쿼리에서 관련 개체를 추출합니다.<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>  | 