Lab 1: LangChain Modules#

This notebook demonstrates how to use pre-trained Large Language Models (LLM) for text generation. LLMs are trained on massive amounts of data, making them capable of solving several NLP tasks. LangChain offers several modules that simplify the use of LLMs for inference. In this notebook, we will use LangChain’s prompt templates to effectively solve different tasks with minimal lift.

Table of contents#

About this Lab#

Throughout this lab, you will encounter two types of interactive elements:

            ![Activity](../mlu_utils/images/activity.png)

            ![Challenge](../mlu_utils/images/challenge.png)

            No coding is needed for an activity. You try to understand a concept, answer questions, or run a code cell.

            Challenges are where you test your understanding by implementing something new or taking a short quiz.

Please work through this notebook from top to bottom to avoid errors due to missing code or context.

1. Setup and configuration#

1.1 Install and import dependencies#

First, let’s install and import the necessary libraries, including the LangChain library.

%%capture
!pip install -r ../requirements.txt --quiet
import warnings
warnings.filterwarnings("ignore")

import sys
import boto3
import pandas as pd
from IPython.display import Markdown

sys.path.append('..')

1.2 Validate LLM model access#

As a first step, we need to verify that the LLM models required in this lab are accessible. Let’s do that now by using the helper function validate_models_access and provide the list of LLM models that we require for this lab. If the call to validate_models_access returns any model ids in the output list, then you will need to go to the Amazon Bedrock console and enable access to the required models.

from mlu_utils.helpers import validate_models_access
if not validate_models_access(["amazon.nova-lite-v1:0", "mistral.mixtral-8x7b-instruct-v0:1"]):
    print("The models are accessible. You can go ahead running this notebook.")
The models are accessible. You can go ahead running this notebook.

1.3 Using Amazon Bedrock for inference#

Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs) from leading AI companies like AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon with a single API, along with a broad set of capabilities to build generative AI applications, simplifying development while maintaining privacy and security. Amazon Bedrock is serverless, which means that you don’t have to manage any infrastructure and simply use and integrate the LLMs hosted on the platform within applications.

In this workshop, we will primarily use LLMs through Bedrock APIs.

Each model hosted on Amazon Bedrock has a different set of inference parameters. Please refer this page to identify the inference parameters for the selected LLM. The Converse API in Amazon Bedrock provides a consistent interface for sending messages to various AI models and running inference on them.

Please opt for frugal practices when using Amazon Bedrock, such as using smaller LLMs for simpler tasks and only reserving the use of the larger LLMs for more complex use cases.

Activity

Activity: Prompting LLMs#

    Try different prompts and observe the responses generated by the model.

Important: Results may not be factually accurate and may be based on false assumptions.

from langchain_aws import ChatBedrockConverse
from langchain_core.output_parsers import StrOutputParser

bedrock_llm = ChatBedrockConverse(
    model="amazon.nova-lite-v1:0",
    temperature=0,
    max_tokens=None,
)
Markdown(bedrock_llm.invoke("What is the capital of Spain?").content)

The capital of Spain is Madrid. Madrid is not only the political center of Spain but also its largest city. It is located in the center of the Iberian Peninsula and is known for its rich history, cultural heritage, and vibrant lifestyle. The city is home to numerous museums, palaces, and landmarks, including the Royal Palace, the Prado Museum, and the Plaza Mayor. Madrid is also famous for its lively nightlife, culinary scene, and as a major transportation hub in Europe.

2. Prompt templates#

The input to the LLM (or any foundational model) is called a prompt. Prompts are typically in the form of text. They provide the LLM with all the necessary information to produce the respective response.

Prompt templates are parameterized model inputs serving as pre-defined recipes for LLMs. These templates can be reusable and enable LLMs to adapt to more number of tasks with minimal effort.

from langchain.prompts import PromptTemplate

template = """
You are a travel agent specialized in planning activities for tourists.
Plan a three day itenerary for a trip to {city}.
"""

# Define the prompt template from the string. The input variables are automatically inferred
prompt_template = PromptTemplate.from_template(template)

# Create the prompt for the LLM by setting the input variable
prompt_message = prompt_template.format(city="Paris")
print("Prompt: {}".format(prompt_message))
Prompt: 
You are a travel agent specialized in planning activities for tourists.
Plan a three day itenerary for a trip to Paris.
# Use the text generation pipeline to generate the response
prompt_template_response = bedrock_llm.invoke(prompt_message)

# Printing the response in a favorable format
Markdown(prompt_template_response.content)

Day 1: Exploring Iconic Landmarks

Morning:

  • Eiffel Tower: Start your day with a visit to the iconic Eiffel Tower. Arrive early to avoid the crowds and take the elevator to the top for a breathtaking view of Paris.

  • Champ de Mars: After descending, take a leisurely stroll through the beautiful Champ de Mars park.

Afternoon:

  • Seine River Cruise: Head to the Seine River for a one-hour cruise. This will give you a unique perspective of the city and its landmarks.

  • Lunch: Enjoy a traditional French lunch at a nearby café.

Evening:

  • Montmartre: Visit the charming Montmartre district. Explore the narrow streets, visit the Sacré-Cœur Basilica, and enjoy the artistic atmosphere.

  • Dinner: Dine at a local bistro in Montmartre, savoring classic French cuisine.

Day 2: Art and Culture

Morning:

  • Louvre Museum: Spend the morning at the Louvre, one of the world’s largest and most visited museums. Don’t miss the Mona Lisa and the Venus de Milo.

Afternoon:

  • Lunch: Have lunch at a café near the Louvre.

  • Musée d’Orsay: Visit this museum, housed in a former railway station, to see an extensive collection of Impressionist and Post-Impressionist masterpieces.

Evening:

  • Seine River Walk: Take a relaxing evening walk along the Seine, enjoying the lights and the atmosphere.

  • Dinner: Enjoy dinner at a riverside restaurant.

Day 3: Hidden Gems and Local Experiences

Morning:

  • Le Marais: Explore the historic Le Marais district. Visit its narrow streets, boutique shops, and historic buildings.

  • Place des Vosges: Visit this beautiful square, the oldest planned square in Paris.

Afternoon:

  • Lunch: Enjoy a meal at a traditional French brasserie in Le Marais.

  • Musée de l’Orangerie: Visit this small but exquisite museum, known for its collection of Impressionist and Post-Impressionist paintings, including Monet’s Water Lilies.

Evening:

  • Canal Saint-Martin: Stroll along the Canal Saint-Martin, a trendy area with many cafes and bars.

  • Dinner: Have dinner at a local restaurant in the Canal Saint-Martin area.

  • Nightcap: End your trip with a nightcap at a cozy Parisian bar.

2.1 Prompt templates with variable number of inputs#

We can use multiple inputs while defining a prompt template. Note that when using multiple inputs, the input keys should match the keys in the prompt template.

Activity

Activity: Interactive prompt template tool#

        Try to create prompt templates in the tool using the following techniques and examine how LLMs can be dynamically prompted:

            Define the variables in the prompt using { }
            Set the variable names in the field below.
            Click 'Generate Response' to prompt the LLM with the formated prompt

Example to try:#

        Copy this template into the widget:
        Write a {length} {genre} story about {character} who discovers {discovery} in {setting}.
        Then fill in the variables with values like:

            length: short
            genre: science fiction
            character: a curious teenager
            discovery: an ancient alien artifact
            setting: an abandoned subway station

        Try changing the variables to see how the model's response changes. Then create your own template to experiment with!

Important: Amazon Bedrock employs guardrails which may prevent the model from generating reponses from sensitive, toxic or harmful prompts.

from mlu_utils.widgets.prompt_template import create_prompt_interface
prompt_interface = create_prompt_interface(bedrock_llm)
display(prompt_interface)

3. Output parsers#

Output parsers help transform the raw text responses from LLMs into structured formats that are easier to work with programmatically. Instead of having to manually parse text responses, output parsers provide a standardized way to convert LLM outputs into specific data structures like dictionaries, lists, or custom objects.

There are many output parsers available in LangChain. Here is a table with a few of them:

Name

Description

Output Type

JSONOutputParser

Returns a JSON object as specified. You specify a Pydantic model and it will return JSON for that model. Probably the most reliable output parser for getting structured data that does NOT use function calling.

JSON object

XMLOutputParser

Returns a dictionary of tags. Use when XML output is needed. Use with models that are good at writing XML (like Anthropic’s).

dict

CSVOutputParser

Returns a list of comma separated values.

List[str]

RetryWithErrorOutputParser

Wraps another output parser. If that output parser errors, then this will pass the original inputs, the bad output, and the error message to an LLM and ask it to fix it. Compared to OutputFixingParser, this one also sends the original instructions.

N/A

PydanticOutputParser

Takes a user defined Pydantic model and returns data in that format.

pydantic.BaseModel

YAMLOutputParser

Takes a user defined Pydantic model and returns data in that format. Uses YAML to encode it.

pydantic.BaseModel

PandasDataFrameOutputParser

Useful for doing operations with pandas DataFrames.

dict

EnumOutputParser

Parses response into one of the provided enum values.

Enum

DatetimeOutputParser

Parses response into a datetime string.

datetime.datetime

StructuredOutputParser

An output parser that returns structured information. It is less powerful than other output parsers since it only allows for fields to be strings. This useful when you are working with smaller LLMs.

Dict[str, str]

from langchain_core.output_parsers import JsonOutputParser
import json

# Set up the parser
parser = JsonOutputParser()

template = """
Generate a JSON text describing a fictional character with the following attributes:
- name
- age
- profession
- hobbies (as an array)
- address (as a nested object with street, city, and country)

{format_instructions}
"""

prompt = PromptTemplate(
    template=template,
    input_variables=[],
    partial_variables={"format_instructions": parser.get_format_instructions()}
)

# Generate and parse the output
output = bedrock_llm.invoke(prompt.format()).content
result = parser.parse(output)

# Print the entire JSON structure
print("Full JSON output:")
print(json.dumps(result, indent=2))
Full JSON output:
{
  "name": "Alice Johnson",
  "age": 32,
  "profession": "Software Engineer",
  "hobbies": [
    "Reading",
    "Hiking",
    "Playing the Guitar"
  ],
  "address": {
    "street": "123 Maple Street",
    "city": "Springfield",
    "country": "USA"
  }
}
Markdown(output)
{
  "name": "Alice Johnson",
  "age": 32,
  "profession": "Software Engineer",
  "hobbies": [
    "Reading",
    "Hiking",
    "Playing the Guitar"
  ],
  "address": {
    "street": "123 Maple Street",
    "city": "Springfield",
    "country": "USA"
  }
}

Activity

Activity: Experimenting with JSON output parsers#

    Use this interactive widget to explore how output parsers transform LLM responses into structured data.

        Examine the template that includes {format_instructions} — this is where the parser inserts guidance for the LLM
        Click "Generate JSON" to see how the LLM produces structured JSON following the parser's instructions
        Try modifying the template to request different JSON structures (e.g., add new fields, change data types, create deeper nested objects)
        Notice how the parser handles the conversion from raw text to a proper Python dictionary
from mlu_utils.widgets.json_output_parser_widget import JsonParserUI
json_ui = JsonParserUI(llm=bedrock_llm)
json_ui.display()

4. Chains#

Chains are the most basic building block chain. The simplest chain takes in a prompt template, formats it with the user input, and returns the response from an LLM.

Let’s use a prompt template from the lab and embed it into a simple chain.

4.1 Chains with LCEL#

LandChain Expression Language (LCEL) is a powerful way to compose LangChain components together into processing pipelines or “chains.” It uses the pipe operator (|) to connect components, creating a clean, readable flow of data transformation.

With LCEL, you can:

  • Build complex chains with minimal code

  • Easily combine prompts, models, and parsers

  • Create reusable components that can be mixed and matched

  • Process inputs through multiple stages of transformation

The pipe operator (|) passes the output from one component as input to the next component in the chain. This functional approach makes it easy to understand the flow of data and to modify chains by adding, removing, or swapping components.

In the example below, we create a simple chain that:

  1. Takes a topic and audience as input

  2. Formats them into a prompt using a PromptTemplate

  3. Sends the formatted prompt to our Amazon Bedrock LLM

  4. Parses the output as a string using StrOutputParser

from langchain_core.output_parsers import StrOutputParser

explanation_prompt = PromptTemplate.from_template("Explain {topic} to {audience}")

explanation_chain = explanation_prompt | bedrock_llm | StrOutputParser()

explanation_response = explanation_chain.invoke(
    {
        "topic" : "Astrophysics",
        "audience" : "kids"
    }
)

Markdown(explanation_response)

Sure! Let’s imagine the universe is like a giant playground, and astrophysics is the study of how everything in this playground works.

  1. What is Astrophysics?

    • Astrophysics is like being a detective for the universe. It’s the science of figuring out how stars, planets, and galaxies (big groups of stars) work and what they’re made of.

  2. Stars and Planets:

    • Stars: Think of stars as giant, glowing balls of gas. They shine because they’re really, really hot. Our Sun is a star, and it gives us light and warmth.

    • Planets: These are like big rocks that travel around stars. Our home, Earth, is a planet that travels around the Sun.

  3. Galaxies:

    • Imagine a galaxy as a giant, swirling city of stars. Our home galaxy is called the Milky Way, and it looks like a big, fuzzy band of light in the night sky.

  4. Black Holes:

    • These are like super-strong vacuum cleaners in space. They suck in everything around them, even light! That’s why they’re called “black” holes—they don’t let any light out.

  5. Space Exploration:

    • Scientists use telescopes (like super-powerful binoculars) to look at stars and planets far, far away. They also send robots and spacecraft to explore space and bring back pictures and information.

  6. Why It’s Cool:

    • By studying astrophysics, we can learn about the beginning of the universe, how stars are born and die, and even if there might be other places where life could exist, like on other planets.

So, astrophysics is all about exploring the universe, figuring out how it works, and discovering the amazing things that are out there!

4.2 Connecting multiple elements together#

LCEL allows you to build sophisticated processing pipelines by connecting multiple components and chains together. This enables you to create workflows where the output of one chain becomes the input to another, or where multiple chains feed into a single downstream component.

Key features demonstrated in this example:

  • Chain reuse: We’re reusing our previously defined explanation_chain as a component in a new chain

  • Input mapping: The {"explanation": explanation_chain} syntax creates a mapping where the output of explanation_chain is assigned to the explanation variable

  • Nested processing: The first chain generates an explanation, which is then analyzed by the second chain

  • Single invocation: Despite having multiple processing steps, we can invoke the entire workflow with a single call

This pattern is extremely powerful for creating multi-step reasoning processes, where an LLM first generates content and then evaluates or transforms its own output in subsequent steps.

analysis_prompt = PromptTemplate.from_template("Does the explaination talk about our solar system? {explanation}")

analysis_chain = {"explanation": explanation_chain} | analysis_prompt | bedrock_llm | StrOutputParser()

analysis_response = analysis_chain.invoke(
    {
        "topic" : "Astrophysics",
        "audience" : "kids"
    }
)

Markdown(analysis_response)

Yes, the explanation does talk about our solar system, specifically within the context of broader astrophysical concepts. Here’s how it ties in:

  1. What is Astrophysics?

    • Astrophysics is the science of understanding the universe, including our solar system.

  2. Stars and Planets:

    • Stars: The Sun, which is a star, is central to our solar system, providing light and warmth.

    • Planets: Earth, which is a planet, is part of our solar system and orbits the Sun.

  3. Galaxies:

    • While the explanation focuses on the Milky Way as our home galaxy, it indirectly includes our solar system as part of this galaxy.

  4. Black Holes:

    • Although black holes are not directly part of our solar system, understanding them is part of the broader study of astrophysics that includes our solar system.

  5. Space Exploration:

    • The mention of telescopes and spacecraft highlights how we explore not just distant galaxies but also our own solar system.

  6. Why is it Important?

    • Understanding our place in the universe includes understanding our solar system and its place within the Milky Way.

So, the explanation does indeed talk about our solar system, particularly in the context of stars (the Sun), planets (Earth), and our place within the Milky Way galaxy.

4.3 Sequential chains with multiple inputs#

We can also connect multiple chains together. This makes the workflow more complex by allowing a chain to take multiple inputs and pass along multiple outputs. For the next example, we will connect multple chains to allow the information the flow in a structured way. When dealing with multiple inputs and outputs, it is important to name the input and output keys.

from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough, RunnableParallel

# The prompts remain the same
screenwriter_prompt = PromptTemplate.from_template(
    """
You are a screenwriter. Given the title of the movie, it is your job to write a synopsis for that movie. 
Title: {title}"""
)

movie_critic_prompt = PromptTemplate.from_template(
    """
You are a movie critic from IMDB. Given the synopsis of the movie, it is your job to write a review of that movie. Be precise.
Synopsis: {synopsis}"""
)

target_demographic_prompt = PromptTemplate.from_template(
    """
Based on the critic review, suggest the target demographic for the movie. Be precise.
Critic Review: {review}"""
)

social_media_manager_prompt = PromptTemplate.from_template(
    """
You are a social media manager for a production company. You need to write a short social media post that appeals to the given target demographic given the movie critic review.
The social media post should mention the rating if it is more than three.
Target demographic: {target_demographic}
Critic review: {review}"""
)

# Create individual chains with runnables
screenwriter_chain = screenwriter_prompt | bedrock_llm | StrOutputParser()
movie_critic_chain = movie_critic_prompt | bedrock_llm | StrOutputParser()
target_demographic_chain = target_demographic_prompt | bedrock_llm | StrOutputParser()
social_media_manager_chain = social_media_manager_prompt | bedrock_llm | StrOutputParser()

# Implement the sequential chain using runnables
runnable_sequential_chain = (
    # Start with the input
    RunnableParallel({"title": RunnablePassthrough()})
    # Generate synopsis and keep the title
    .assign(synopsis=lambda x: screenwriter_chain.invoke({"title": x["title"]}))
    # Generate review and keep previous outputs
    .assign(review=lambda x: movie_critic_chain.invoke({"synopsis": x["synopsis"]}))
    # Generate target demographic and keep previous outputs
    .assign(target_demographic=lambda x: target_demographic_chain.invoke({"review": x["review"]}))
    # Generate social media post and keep all previous outputs
    .assign(social_media_post=lambda x: social_media_manager_chain.invoke({
        "target_demographic": x["target_demographic"],
        "review": x["review"]
    }))
)

# To use the chain:
result = runnable_sequential_chain.invoke("Interstellar 2: Beyond the Horizon")

# Format the responses in a dataframe and print
with pd.option_context("display.max_colwidth", None):
    display(pd.DataFrame.from_dict(result, orient="index"))

display(Markdown("### Social Media Post:"))
Markdown(result['social_media_post'])
0
title Interstellar 2: Beyond the Horizon
synopsis **Title: Interstellar 2: Beyond the Horizon**\n\n**Genre:** Science Fiction, Adventure, Drama\n\n**Synopsis:**\n\nIn the aftermath of the events that unfolded on Proxima b, humanity stands on the precipice of a new era. The once-abandoned space stations and colonies have been revitalized, thanks to the pioneering efforts of the original crew. However, the universe remains a vast, unpredictable frontier.\n\n**Act 1:**\n\nThe film opens with a breathtaking view of the revitalized space stations orbiting Earth, bustling with activity and hope. Dr. Amelia Hart, the daughter of the late Dr. Amelia Brooks from the original crew, is now a leading scientist at the Interstellar Research Institute (IRI). She is working on a project to establish a stable wormhole network, which could drastically reduce travel time across the galaxy.\n\nAmelia's team discovers an anomaly in the data from the original wormhole, hinting at a previously unknown region of space. This region, dubbed "The Horizon," is believed to hold secrets that could change the fate of humanity. However, the anomaly also suggests that the wormhole's stability is at risk, threatening all existing space colonies.\n\n**Act 2:**\n\nA new crew is assembled, including Amelia, her brother Leo, a seasoned pilot named Captain Marcus Kane, and a brilliant but enigmatic engineer, Dr. Kaito Nakamura. They embark on a mission to investigate The Horizon, hoping to stabilize the wormhole and uncover its mysteries.\n\nAs they journey through the wormhole, they encounter unforeseen challenges, including gravitational anomalies and hostile alien lifeforms. The crew's bonds are tested as they face personal demons and the ever-present danger of space.\n\nUpon reaching The Horizon, they discover an ancient, advanced alien structure orbiting a black hole. The structure appears to be a gateway to another dimension, one that holds the key to stabilizing the wormhole. However, activating the gateway could have catastrophic consequences for the universe.\n\n**Act 3:**\n\nAmelia and her team must make a harrowing choice: proceed with activating the gateway, risking everything to save humanity, or find an alternative solution that could be more perilous but less destructive. Tensions rise as differing opinions clash, and the crew's trust in each other is put to the ultimate test.\n\nIn a climactic sequence, Amelia and Leo work together to devise a plan to stabilize the wormhole without activating the gateway. They manage to reroute the energy from the alien structure, successfully stabilizing the wormhole and saving the colonies.\n\nAs the crew returns to Earth, they are hailed as heroes. The film ends with Amelia looking out into the vastness of space, contemplating the endless possibilities that lie beyond the horizon, and the responsibility that comes with exploring them.\n\n**Epilogue:**\n\nA final scene shows the IRI planning its next mission, with Amelia at the helm, ready to lead humanity into a new age of exploration and discovery. The horizon, once a boundary, is now just another step in the journey beyond.
review **Title: Interstellar 2: Beyond the Horizon - A Bold Leap into the Cosmos**\n\n**Rating: ★★★★☆ (4/5)**\n\n**Review:**\n\n"Interstellar 2: Beyond the Horizon" is a thrilling continuation of the interstellar saga that began with its predecessor. The film successfully builds upon the legacy of the original, delivering a gripping narrative that balances emotional depth with high-stakes science fiction.\n\n**Act 1:**\n\nThe film opens with a stunning visual feast, showcasing the revitalized space stations orbiting Earth. This sets the stage for a story that is as much about human resilience and innovation as it is about the mysteries of the universe. Dr. Amelia Hart, portrayed with admirable depth by [Actress's Name], emerges as a compelling protagonist. Her connection to the original crew's legacy adds a personal layer to the narrative, making her quest for stabilizing the wormhole both a scientific and emotional journey.\n\n**Act 2:**\n\nThe ensemble cast, including [Actor's Name] as Captain Marcus Kane and [Actor's Name] as Dr. Kaito Nakamura, brings a dynamic energy to the screen. Their interactions are well-crafted, highlighting the diverse perspectives and expertise required for such a perilous mission. The challenges they face, from gravitational anomalies to hostile alien lifeforms, are depicted with a sense of realism that keeps the audience engaged. The visual effects are top-notch, particularly in scenes depicting the wormhole and the alien structure, which are both awe-inspiring and terrifying.\n\n**Act 3:**\n\nThe film's climax is where it truly shines. The ethical dilemma of activating the gateway versus finding an alternative solution is handled with nuance, allowing the audience to grapple with the weight of the crew's decision. The tension is palpable, and the final sequence, where Amelia and Leo work together to stabilize the wormhole, is both heart-pounding and emotionally resonant. The resolution is satisfying, offering a sense of hope and responsibility that aligns with the film's themes.\n\n**Epilogue:**\n\nThe epilogue sets the stage for future adventures, with the Interstellar Research Institute poised to embark on new missions. This open-ended conclusion leaves the audience eager for what comes next, ensuring that the legacy of "Interstellar" continues to evolve.\n\n**Final Thoughts:**\n\n"Interstellar 2: Beyond the Horizon" is a bold and ambitious film that respects its predecessor while carving out its own identity. It is a testament to the power of human ingenuity and the enduring spirit of exploration. With its stellar performances, breathtaking visuals, and thought-provoking narrative, this film is a must-watch for fans of science fiction and adventure.
target_demographic Based on the critic review, the target demographic for "Interstellar 2: Beyond the Horizon" appears to be:\n\n1. **Science Fiction Enthusiasts**: The review highlights the film's gripping narrative, high-stakes science fiction elements, and its continuation of the interstellar saga, which would appeal to fans of the genre.\n\n2. **Fans of the Original "Interstellar"**: The review mentions that the film builds upon the legacy of the original, making it particularly appealing to those who enjoyed the first movie.\n\n3. **Young Adults (Ages 18-35)**: The film's themes of human resilience, innovation, and exploration, combined with its dynamic ensemble cast and stunning visual effects, are likely to resonate with this age group.\n\n4. **Tech-Savvy Audiences**: The film's realistic depiction of space technology and its focus on scientific challenges would appeal to viewers interested in space exploration and futuristic concepts.\n\n5. **Emotionally Invested Viewers**: The review notes the film's emotional depth and the personal layer added by the protagonist's journey, suggesting it will appeal to audiences who appreciate character-driven stories.\n\nIn summary, the target demographic includes science fiction fans, followers of the original "Interstellar," young adults, tech-savvy viewers, and those who enjoy emotionally engaging narratives.
social_media_post 🚀 **Embark on a New Interstellar Adventure!** 🌌\n\nAre you ready to dive back into the cosmos? "Interstellar 2: Beyond the Horizon" is here, and it's a thrilling continuation that's not to be missed! 🌠\n\n🔭 **For Science Fiction Enthusiasts:** Experience the gripping narrative and high-stakes science fiction that will keep you on the edge of your seat.\n\n🌟 **For Fans of the Original "Interstellar":** The film builds upon the legacy of the first, bringing back beloved characters and introducing new ones in an epic saga.\n\n👩‍🚀 **For Young Adults (Ages 18-35):** Join the journey of human resilience, innovation, and exploration with a dynamic cast and stunning visual effects.\n\n💡 **For Tech-Savvy Audiences:** Marvel at the realistic depiction of space technology and futuristic concepts that push the boundaries of science fiction.\n\n❤️ **For Emotionally Invested Viewers:** Feel the emotional depth and personal layer added by the protagonist's journey, making this film a character-driven masterpiece.\n\n🌟 **Rating:** ★★★★☆ (4/5)\n\nDon't miss out on this must-watch film that balances emotional depth with high-stakes science fiction. Join Dr. Amelia Hart and her crew as they navigate the mysteries of the universe in "Interstellar 2: Beyond the Horizon." 🌠\n\n#Interstellar2 #BeyondTheHorizon #ScienceFiction #MovieReview #MustWatch #VisualEffects #EmotionalJourney #SpaceAdventure #TechSavvy #YoungAdults #FanFavorite

Social Media Post:

🚀 Embark on a New Interstellar Adventure! 🌌

Are you ready to dive back into the cosmos? “Interstellar 2: Beyond the Horizon” is here, and it’s a thrilling continuation that’s not to be missed! 🌠

🔭 For Science Fiction Enthusiasts: Experience the gripping narrative and high-stakes science fiction that will keep you on the edge of your seat.

🌟 For Fans of the Original “Interstellar”: The film builds upon the legacy of the first, bringing back beloved characters and introducing new ones in an epic saga.

👩‍🚀 For Young Adults (Ages 18-35): Join the journey of human resilience, innovation, and exploration with a dynamic cast and stunning visual effects.

💡 For Tech-Savvy Audiences: Marvel at the realistic depiction of space technology and futuristic concepts that push the boundaries of science fiction.

❤️ For Emotionally Invested Viewers: Feel the emotional depth and personal layer added by the protagonist’s journey, making this film a character-driven masterpiece.

🌟 Rating: ★★★★☆ (4/5)

Don’t miss out on this must-watch film that balances emotional depth with high-stakes science fiction. Join Dr. Amelia Hart and her crew as they navigate the mysteries of the universe in “Interstellar 2: Beyond the Horizon.” 🌠

#Interstellar2 #BeyondTheHorizon #ScienceFiction #MovieReview #MustWatch #VisualEffects #EmotionalJourney #SpaceAdventure #TechSavvy #YoungAdults #FanFavorite

Activity

Activity: Sequential chain builder#

    This tool helps you build a sequence of AI tasks without coding. Each chain uses the output from previous chains to create a workflow.
How to use it:#
            Define Input Variables

                Type a variable name (e.g., "title") and click "Add Variable"
                Add all variables you'll need
                Click "Finalize Input Variables" when done

            Build Your Chain

                Chain Name: Give your step a name (e.g., "screenwriter")
                Prompt Template: Write instructions using {variable_name} to reference available variables
                Output Key: Name for this step's output (e.g., "synopsis")
                Click "Add Chain"
                Repeat to add more steps to your sequence

            Run Your Chain

                Enter values for your input variables
                Click "Run Sequential Chain"
                View the results from each step
Example:#
            Add input variable: "title"
            Create first chain:

                    Name: "screenwriter"
                    Prompt: "Write a movie synopsis for: {title}"
                    Output: "synopsis"

            Create second chain:

                    Name: "critic"
                    Prompt: "Write a review of: {synopsis}"
                    Output: "review"

            Run with "Star Wars" as the title

        That's it! The tool will show you the synopsis and review it generated.
from mlu_utils.widgets.chain_builder import create_sequential_chain_builder
display(create_sequential_chain_builder(bedrock_llm))

5. Quizzes#

    ![Challenge](../mlu_utils/images/challenge.png)

Challenge: Quizzes#

    Answer the following questions to test your understanding about prompt templates and chains.
from mlu_utils.quiz_questions import lab1_question1, lab1_question2

lab1_question1.display()
lab1_question2.display()

Conclusion#

In this lab, you have:

    Explored various LangChain modules that enable building applications powered by LLMs
    Utilized prompt templates to dynamically prompt LLMs
    Built chains to connect the LLM with a prompt template
    Connected multiple chains together to accomplish complex workflows