> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demonstration of Prompt Engineering Part 2

> Guide to prompt engineering showing role, strict JSON schema, few-shot examples, and a Python Amazon Bedrock example to produce consistent machine-readable outputs

This lesson demonstrates how adding structure, constraints, and examples to your prompts yields more consistent, reliable outputs. We'll show a compact JSON schema you can require the model to return, provide few-shot examples, and present a runnable Python example for Amazon Bedrock. Use these patterns to reduce ambiguity and speed iterations.

<Callout icon="lightbulb" color="#1CB2FE">
  Use a clear role, a strict output format, and representative examples. These three elements combined make prompts much more predictable and easier to integrate into applications.
</Callout>

## Required output format

Require the model to return only valid JSON in this exact structure:

```json theme={null}
{
  "category": "",
  "priority": "",
  "sentiment": "",
  "recommended_action": ""
}
```

Enforcing a strict schema like this reduces parsing errors and simplifies downstream automation.

<Callout icon="warning" color="#FF6B6B">
  Always validate the model output as JSON before consuming it in production. If the model returns invalid JSON, fail safely and retry with clearer constraints.
</Callout>

## Few-shot examples

Providing a couple of representative examples (few-shot) helps the model map free-text tickets to the structured fields you expect.

Example 1 — Billing ticket:

```json theme={null}
Ticket: "My invoice has the wrong company name."

{
  "category": "Billing",
  "priority": "Medium",
  "sentiment": "Neutral",
  "recommended_action": "Route to billing support to correct invoice details."
}
```

Example 2 — Security ticket:

```json theme={null}
Ticket: "I think someone has accessed my account without permission."

{
  "category": "Security",
  "priority": "Critical",
  "sentiment": "Concerned",
  "recommended_action": "Escalate immediately to the security team and advise the user to change their password."
}
```

New ticket to classify:

```json theme={null}
Ticket: "I cannot log in and I need access before a client meeting in 30 minutes."
```

Expected machine-readable output (example):

```json theme={null}
{
  "category": "Login",
  "priority": "Critical",
  "sentiment": "Urgent",
  "recommended_action": "Immediately assist with login issue to ensure access before client meeting."
}
```

## Why this works

* Role + constraints + examples reduces ambiguity and narrows the model's output distribution.
* A fixed schema simplifies parsing and downstream routing.
* Few-shot examples teach the mapping from natural language to structured fields.

### Prompt components (quick reference)

| Component | Purpose | Example / Notes |
| - | - | - |
| Role | Sets the model's persona | `You are a support operations assistant.` |
| Output format | Constrains structure | Use the JSON schema shown above. |
| Examples | Demonstrates expected mapping | Include diverse tickets and expected outputs. |
| Validation | Ensures correctness | Parse and validate JSON before use. |

## Practical Python example (Amazon Bedrock)

Below is a compact Python snippet illustrating how to send the prompt to Bedrock (adjust the API call to your SDK version). The core idea is to send the role + prompt and then parse the returned text as JSON.

```python theme={null}
import boto3
import json

client = boto3.client("bedrock-runtime", region_name="us-east-1")

prompt = """
You are a support operations assistant.

Classify this ticket and return only valid JSON in the following format:
{
  "category": "",
  "priority": "",
  "sentiment": "",
  "recommended_action": ""
}

Ticket:
I cannot log in and I need access before a client meeting in 30 minutes.
"""

# Example using a 'converse' style call. Adjust parameter names to match your SDK version.
response = client.converse(
    modelId="amazon.nova-micro-v1:0",
    messages=[
        {"role": "system", "content": {"type": "text", "text": "You are a support operations assistant."}},
        {"role": "user", "content": {"type": "text", "text": prompt}}
    ]
)

# Parse and print the model output (structure depends on SDK/model; adapt accordingly)
# Below assumes the model's text output is available at response["messages"][0]["content"]["text"]
model_text = ""
if "messages" in response and response["messages"]:
    first = response["messages"][0].get("content", {})
    model_text = first.get("text") or first.get("body") or ""

try:
    parsed = json.loads(model_text)
    print(json.dumps(parsed, indent=2))
except Exception:
    # Fallback: print raw model text if it wasn't valid JSON
    print(model_text)
```

Example console run (cleaned):

```bash theme={null}
$ python prompt_eng.py
{
  "category": "Login",
  "priority": "Critical",
  "sentiment": "Urgent",
  "recommended_action": "Immediate assistance required to resolve login issue before client meeting in 30 minutes."
}
```

## What to expect from iterative prompt engineering

* More consistent outputs as you refine role and examples
* Faster integration because the model produces predictable, structured responses
* Reusable prompt templates that work across use cases once tuned

Key takeaway: prompt engineering is an iterative discipline. Start with a role, define a strict output format, add diverse examples, validate outputs, and iterate.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/BVCvDn4rl3j0TCQq/images/Introduction-to-Amazon-Bedrock/Extract-Insights-Using-Prompt-Engineering/Demonstration-of-Prompt-Engineering-Part-2/key-takeaway-prompt-engineering.jpg?fit=max&auto=format&n=BVCvDn4rl3j0TCQq&q=85&s=624e0e52e483b8920d4a6d684fc8e570" alt="A presentation slide titled &#x22;Key Takeaway.&#x22; It states that prompt engineering is the process of structuring and refining prompts so models produce more reliable and useful results." width="1920" height="1080" data-path="images/Introduction-to-Amazon-Bedrock/Extract-Insights-Using-Prompt-Engineering/Demonstration-of-Prompt-Engineering-Part-2/key-takeaway-prompt-engineering.jpg" />
</Frame>

You have your prompt, inspect the result, address weaknesses, and iterate. Each refinement should yield stronger, more consistent outputs.

This wraps up this short lesson on prompt engineering. Try these techniques in a hands-on lab to practice and reinforce the concepts.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/BVCvDn4rl3j0TCQq/images/Introduction-to-Amazon-Bedrock/Extract-Insights-Using-Prompt-Engineering/Demonstration-of-Prompt-Engineering-Part-2/whats-next-prompt-engineering-lab-brain.jpg?fit=max&auto=format&n=BVCvDn4rl3j0TCQq&q=85&s=7a3f9c02afbad37071952ec99b6d88a3" alt="A presentation slide titled &#x22;What's Next?&#x22; with the subtitle &#x22;Practicing various prompt engineering techniques LAB.&#x22; On the right is a teal circular icon showing a stylized brain merged with circuit lines." width="1920" height="1080" data-path="images/Introduction-to-Amazon-Bedrock/Extract-Insights-Using-Prompt-Engineering/Demonstration-of-Prompt-Engineering-Part-2/whats-next-prompt-engineering-lab-brain.jpg" />
</Frame>

## Links and references

* [Amazon Bedrock documentation](https://aws.amazon.com/bedrock/)
* Bedrock SDK reference: check your SDK's method names for "converse", "invoke\_model", or equivalent.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-amazon-bedrock/module/0ab16cbf-afef-4ca5-b8f5-a280c6cdb92d/lesson/6dcc49d3-f530-4e6f-8fdb-b1d4c6e38441" />

  <Card title="Practice Lab" icon="flask-conical" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-amazon-bedrock/module/0ab16cbf-afef-4ca5-b8f5-a280c6cdb92d/lesson/60b44f76-c848-4781-8b48-09fd2948a352" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.