Generating text with language models

Introduction to Amazon Bedrock

Nikhil Rangarajan

Data Scientist

Sending prompts to language models

  • Prompt: the input text you send to the model
    • "Explain how AWS Lambda works"

An icon representing the prompt.

Introduction to Amazon Bedrock

Sending prompts to language models

  • Prompt: the input text you send to the model
    • "Explain how AWS Lambda works"
  • Completion: the text generated by the model
    • "AWS Lambda is a serverless compute service that..."

Icons representing the prompt and completion.

Introduction to Amazon Bedrock

Sending prompts to language models

  • Prompt: the input text you send to the model
    • "Explain how AWS Lambda works"
  • Completion: the text generated by the model
    • "AWS Lambda is a serverless compute service that..."
  • Response:
    • Generated text (completion)
    • Metadata (tokens, model info)
    • Status information

Three icons in sequence representing the prompt, completion, and response.

Introduction to Amazon Bedrock

Applying basic prompt engineering techniques

  • Techniques for better results:
    • Clarity and specificity: write detailed and precise instructions
    • Role assignment: give a persona to improve contextual understanding
    • Formatting instructions: add constraints to guide the response
"Explain the benefits of exercise 
in simple terms."
"You are a nutritionist. Explain the 
benefits of a balanced diet."
"List the top 3 benefits of cloud 
computing in bullet points."
Introduction to Amazon Bedrock

Advanced text parsing techniques

  • Handle missing or unexpected keys
data = json.loads(response['body'].read())
if 'completion' in data:
    output = data['completion']

else: output = "Key not found"
  • Multi-Level JSON Parsing to navigate deeply nested structures
try:
    nova_output = data.decode()["output"]

except (KeyError, IndexError) as e: nova_output = f"Error: {str(e)}"
Introduction to Amazon Bedrock

Response processing and text handling

  • Unicode or encoding issues: handle special characters in text responses
    # Ensure proper encoding
    output = data['completion'].encode('utf-8').decode('unicode_escape')
    print(output)
    
  • Processing large responses: split or truncate large outputs for usability
    # Truncate response for display
    output = data['completion'][:500]  # Limit to 500 characters
    print(output)
    
Introduction to Amazon Bedrock

Category extraction with Bedrock

  • Example: classifying text data
  • Use structured prompts with clear category options
  • Provide explicit instructions for single-category output
  • Process model responses efficiently
  • Result: Accurate text categorization

Icons representing text classification

Introduction to Amazon Bedrock

Category extraction with Bedrock

def categorize_ticket(ticket, categories):
  prompt = f"Categorize into one: {', '.join(categories)}. 
  Ticket: {ticket}"
  response = bedrock.invoke_model(
    modelId='amazon.nova-micro-v1:0',
    body=json.dumps({"messages": [{"role": "user", "content": 
                                   [{"text": prompt}]}]}))

return json.loads(nova_response.get("body").read().decode())["output"]
{"output": {"message": {"role": "assistant","content": [
        {
          "text": "Customer Service"
        }]}, "stop_reason": "stop_sequence"}}
Introduction to Amazon Bedrock

Let's practice!

Introduction to Amazon Bedrock

Preparing Video For Download...