You've learned how to combine a PromptTemplate and an LLM into a chain using the | operator, then run it with .invoke().
- Create a notebook (e.g. locally on VS Code, or on Google Colab).
- Use langchain-core<0.3
- You'll also need an OpenAI API key
Create a chain that generates a short joke about an animal.
- Build a
PromptTemplatewith one input variable,animal, and a template like"Tell me a short joke about a {animal}". - Create the chain using
prompt | llm. - Invoke it with
animal="penguin"and print the result.
Now create a chain that recommends a recipe based on two inputs: ingredient and cuisine.
- Build a
PromptTemplatewith two input variables,ingredientandcuisine. - Create the chain and invoke it with values of your choice.
- Print the result.
Bonus 1: Add a third input variable, diet (e.g. "vegetarian", "gluten-free"), to the recipe chain, and update the prompt to take it into account.
Bonus 2: Write a small Python function run_recipe_chain(ingredient, cuisine, diet) that builds the prompt, creates the chain, invokes it, and returns the result — so you can call it multiple times with different arguments without repeating code.
Solution — Iteration 1
prompt = PromptTemplate(
input_variables=["animal"],
template="Tell me a short joke about a {animal}"
)
chain = prompt | llm
result = chain.invoke({"animal": "penguin"})
print(result)Solution — Iteration 2
prompt = PromptTemplate(
input_variables=["ingredient", "cuisine"],
template="Suggest a {cuisine} recipe that uses {ingredient} as a main ingredient."
)
chain = prompt | llm
result = chain.invoke({"ingredient": "chicken", "cuisine": "Thai"})
print(result)Solution — Bonus 1
prompt = PromptTemplate(
input_variables=["ingredient", "cuisine", "diet"],
template="Suggest a {cuisine} recipe that uses {ingredient} as a main ingredient. It must be {diet}."
)
chain = prompt | llm
result = chain.invoke({"ingredient": "mushrooms", "cuisine": "Italian", "diet": "vegetarian"})
print(result)Solution — Bonus 2
def run_recipe_chain(ingredient, cuisine, diet):
prompt = PromptTemplate(
input_variables=["ingredient", "cuisine", "diet"],
template="Suggest a {cuisine} recipe that uses {ingredient} as a main ingredient. It must be {diet}."
)
chain = prompt | llm
return chain.invoke({"ingredient": ingredient, "cuisine": cuisine, "diet": diet})
print(run_recipe_chain("tofu", "Japanese", "vegan"))
print(run_recipe_chain("lentils", "Indian", "gluten-free"))