LangChain
Chains, prompt templates, output parsers — build a structured Q&A bot in 30 lines.
A raw LLM API call gives you text. But real AI products need: structured JSON output, conversation memory, tool calls, retries on failure, streaming responses.
LangChain is the plumbing that connects an LLM to the rest of your application. Like Django for web — you could build everything from scratch, but why?
📈 LangChain Building Blocks (5–25 min)
PromptTemplate — parameterized prompt with {variables}.
LLM / ChatModel — the model call (ChatGroq, ChatOpenAI, etc.).
OutputParser — coerce raw text into Python objects (str, JSON, Pydantic).
Chain (|) — pipe them together: prompt | llm | parser.
💻 Live Demo — Course Q&A Bot (25–45 min)
>from langchain_groq import ChatGroq from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.messages import HumanMessage, SystemMessage import os llm = ChatGroq( model="llama3-8b-8192", api_key=os.getenv("GROQ_API_KEY"), temperature=0.3 ) # 1. Simple chain: prompt | llm | parser prompt = ChatPromptTemplate.from_messages([ ("system", "You are an AI tutor for Core2CloudX internship students. Answer clearly in 3 sentences max. Always give a code example."), ("human", "{question}") ]) parser = StrOutputParser() chain = prompt | llm | parser answer = chain.invoke({"question": "What is gradient descent?"}) print(answer) # 2. Structured output with Pydantic from pydantic import BaseModel from langchain_core.output_parsers import JsonOutputParser class ConceptCard(BaseModel): concept: str one_line: str analogy: str code_example: str parser2 = JsonOutputParser(pydantic_object=ConceptCard) prompt2 = ChatPromptTemplate.from_template( "Explain the ML concept: {concept}\n{format_instructions}" ) chain2 = prompt2 | llm | parser2 card = chain2.invoke({ "concept": "Overfitting", "format_instructions": parser2.get_format_instructions() }) print(card)
📋 You Code It (45–55 min)
Build a ConversationChain that remembers context. Ask it: "My name is Priya", then in the next turn ask "What is my name?" — it should recall. Use ChatMessageHistory from LangChain.
⚡ Day 10 Cheat Sheet
ChatPromptTemplate.from_messages()prompt | llm | parserchain.invoke({"var": val})chain.stream({...})StrOutputParser()JsonOutputParser(pydantic_object=M)format_instructionsChatMessageHistory()