iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Examples

A small gallery of working LangChain patterns: a structured-output extraction chain, a tool-calling agent, and a RAG pipeline. Each is short enough to copy and adapt, and uses modern LangChain APIs (LCEL + langgraph-style runnables).

Three pasteable LangChain examples

EXAMPLE
# ---------------------------------------------
# 1) Structured extraction with Pydantic
# ---------------------------------------------
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field

class Invoice(BaseModel):
    supplier: str
    invoice_no: str
    total_amount: float = Field(description='Total in dollars, not cents')
    currency: str
    due_date: str = Field(description='ISO 8601')

llm = ChatOpenAI(model='gpt-4o-mini', temperature=0)
extractor = (
    ChatPromptTemplate.from_messages([
        ('system', 'You extract structured fields from invoice text. Output ONLY JSON matching the schema.'),
        ('human',  '{text}'),
    ])
    | llm.with_structured_output(Invoice)
)

invoice_text = '''ACME Pty Ltd  Invoice #2026-0612  Total: AUD 1,294.50  Due: 11 July 2026'''
print(extractor.invoke({'text': invoice_text}))

# ---------------------------------------------
# 2) Tool-calling agent
# ---------------------------------------------
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent

@tool
def search_orders(customer_id: str, status: str = 'open') -> list[dict]:
    '''Return orders for a given customer (mocked).'''
    return [{ 'id': 'o1', 'total': 49.95, 'status': status, 'customer': customer_id }]

@tool
def cancel_order(order_id: str) -> dict:
    '''Cancel an order. Requires explicit confirmation.'''
    return { 'id': order_id, 'status': 'cancelled' }

agent = create_react_agent(llm, [search_orders, cancel_order])
result = agent.invoke({'messages': [('human', 'Show me Alices open orders and cancel order o1.')]})
print(result['messages'][-1].content)

# ---------------------------------------------
# 3) RAG pipeline over a folder of docs
# ---------------------------------------------
from langchain_community.document_loaders import DirectoryLoader, TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

# Index once
docs = DirectoryLoader('./docs', glob='**/*.md', loader_cls=TextLoader).load()
chunks = RecursiveCharacterTextSplitter(chunk_size=900, chunk_overlap=120).split_documents(docs)
vs = Chroma.from_documents(chunks, OpenAIEmbeddings(model='text-embedding-3-small'),
                            persist_directory='./vector-store')

retriever = vs.as_retriever(search_kwargs={'k': 4})

def format_docs(docs):
    return '\n\n'.join(f'[doc {i+1}] {d.page_content[:1200]}' for i, d in enumerate(docs))

rag_prompt = ChatPromptTemplate.from_messages([
    ('system', 'Answer using ONLY the provided context. Cite [doc N] for every claim. '
               'If the answer is not in the context, say so.'),
    ('human',  'Question: {question}\n\nContext:\n{context}'),
])

rag_chain = (
    { 'context': retriever | format_docs, 'question': RunnablePassthrough() }
    | rag_prompt
    | llm
    | StrOutputParser()
)

print(rag_chain.invoke('What is our refund policy for in-store purchases?'))

Why it matters

Every \"production\" LangChain chain belongs behind the same guard rails as the rest of your API: rate limits, per-user concurrency, eval coverage, and structured output validation. The library makes prototyping fast; treating its output as data you parse (not text you trust) is what gets you to a release.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Customer-support RAG over your docs, ticket-triage agent, code-explainer.
Try it Yourself »

Discussion

Loading…