LangChain Cheatsheet

LangChain simplifies building AI applications using large language models (LLMs) by providing an intuitive interface for connecting to state-of-the-art models like GPT-4 and optimizing them for custom applications. It supports chains combining multiple models and modular prompt engineering for more impactful interactions.

Key Features

  • Reusable Components: LangChain offers reusable components like LLMs, prompt templates, external tools, and memory, making it easy to mix and match components for rapid prototyping and seamless integration of new capabilities.
  • Pre-built Chains: LangChain provides pre-built chains for common tasks, such as summarization, question answering, and document retrieval.
  • Data-aware and Agentic Models: LangChain makes models data-aware and agentic for more dynamic interactions.
  • External Tools Integration: LangChain supports integration with external tools, such as document loaders and vector stores for similarity search.
  • Memory Management: LangChain includes tools for managing conversation memory, allowing for context-aware interactions.

Code Snippets

1. Creating a Custom Tool

from langchain.tools import StructuredTool, BaseTool
from langchain.agents import initialize_agent, AgentType

# Define and use a custom text processing tool
def text_processing(string: str) -> str:
    """Process the text"""
    return string.lower()

text_processing_tool = StructuredTool.from_function(text_processing)

# Initialize and use an agent with the custom tool
agent = initialize_agent(AgentType.CONVERSATION, tools=[text_processing_tool])

2. Creating a Custom Chain

from langchain.prompts import PromptTemplate
from langchain.chains import ConversationChain, summarize, question_answering
from langchain.schema import StrOutputParser

# Define and use a chain for summarizing customer feedback
feedback_summary_prompt = PromptTemplate.from_template(
    """You are a customer service manager. Given the customer feedback, it is your job to summarize the main points.
    Customer Feedback: {feedback}
    Summary:"""
)

# Define and use a chain for drafting a business email response
email_response_prompt = PromptTemplate.from_template(
    """You are a customer service representative. Given the summary of customer feedback,
    it is your job to draft a business email response.
    Customer Feedback: {feedback}
    Email Response:"""
)

# Create a fully functional agent
agent = initialize_agent(AgentType.CONVERSATION, prompts=[feedback_summary_prompt, email_response_prompt])

3. Using Memory

from langchain.memory import ConversationBufferMemory

# Initialize conversation buffer memory
memory = ConversationBufferMemory(memory_key="chat_history")

# Add messages to the conversation memory
memory.chat_memory.add_user_message("Hi!")
memory.chat_memory.add_ai_message("Welcome How can I help you?")

# Load memory variables if any
memory.load_memory_variables({"chat_history": "Human: Hi!\nAI: Welcome How can I help you?"})

Additional Resources

  • LangChain Cheatsheet: A comprehensive and user-friendly GitHub repository that provides a curated collection of code snippets, examples, and explanations to help users understand and leverage the various features and functionalities of LangChain effectively[1].
  • LangChain Cheat Sheet: A detailed cheat sheet that covers the key features and simple code snippets to get started with LangChain[2].
  • LangChain Expression Language Cheatsheet: A quick reference for all the most important LCEL primitives, including invoke, batch, and stream operations[4].
  • LangChain 101 Course: A comprehensive course that covers the basics of LangChain, including creating custom tools and agents for specialized tasks[5].