0
0
LangChainframework~30 mins

Context formatting and injection in LangChain - Mini Project: Build & Apply

Choose your learning style9 modes available
Context Formatting and Injection with LangChain
📖 Scenario: You are building a simple chatbot that answers questions about a product catalog. You want to prepare the context by formatting product details and then inject this context into your LangChain prompt template.
🎯 Goal: Create a dictionary with product details, format this data into a context string, and inject it into a LangChain prompt template to prepare for generating answers.
📋 What You'll Learn
Create a dictionary called product_info with exact keys and values
Create a string variable called context that formats the product details
Create a LangChain PromptTemplate called template that uses the context variable
Create a prompt by formatting the template with the context
💡 Why This Matters
🌍 Real World
Formatting and injecting context is essential when building chatbots or AI assistants that need to provide answers based on specific data.
💼 Career
Many AI and software development jobs require preparing and managing prompt templates with dynamic context for language models.
Progress0 / 4 steps
1
Create the product information dictionary
Create a dictionary called product_info with these exact entries: 'name': 'Smartphone X', 'price': '$799', 'features': '5G, OLED display, 128GB storage'.
LangChain
Need a hint?

Use curly braces {} to create a dictionary with the exact keys and values.

2
Format the product information into a context string
Create a string variable called context that formats the product details from product_info into this exact format: "Product: Smartphone X\nPrice: $799\nFeatures: 5G, OLED display, 128GB storage" using an f-string.
LangChain
Need a hint?

Use an f-string with newline characters \n to format the string exactly.

3
Create a LangChain PromptTemplate using the context
Import PromptTemplate from langchain.prompts. Then create a PromptTemplate called template with input_variables=['context'] and template="Here is the product info:\n{context}\nPlease answer the question.".
LangChain
Need a hint?

Use from langchain.prompts import PromptTemplate and create the template with the exact input_variables and template string.

4
Format the prompt with the context string
Create a variable called prompt by calling template.format(context=context) to inject the formatted context into the prompt template.
LangChain
Need a hint?

Call template.format() with the context variable to create the final prompt string.