LangChain is a framework for building applications with LLMs - chains of operations, memory, tools!
1pip install langchain langchain-openai langchain-anthropic1from langchain_openai import ChatOpenAI
2from langchain_anthropic import ChatAnthropic
3from langchain_core.messages import HumanMessage, SystemMessage
4
5# OpenAI
6llm = ChatOpenAI(model="gpt-5", temperature=0.7)
7
8# Anthropic
9llm = ChatAnthropic(model="claude-sonnet-4-6")
10
11# Simple invocation
12messages = [
13 SystemMessage(content="You are a Safari expert."),
14 HumanMessage(content="Tell me about elephants.")
15]
16
17response = llm.invoke(messages)
18print(response.content)1from langchain_core.prompts import ChatPromptTemplate
2
3# Template with variables
4prompt = ChatPromptTemplate.from_messages([
5 ("system", "You are an expert in {field}."),
6 ("human", "Tell me about {topic}.")
7])
8
9# Formatting
10formatted = prompt.format_messages(
11 field="wildlife",
12 topic="wildebeest migration"
13)
14
15response = llm.invoke(formatted)1from langchain_core.output_parsers import StrOutputParser
2
3# Simple chain: prompt -> model -> parser
4chain = prompt | llm | StrOutputParser()
5
6# Run
7result = chain.invoke({
8 "field": "Safari",
9 "topic": "lions"
10})
11print(result)1from langchain_core.pydantic_v1 import BaseModel, Field
2from langchain_core.output_parsers import JsonOutputParser
3
4# Structure definition
5class AnimalInfo(BaseModel):
6 name: str = Field(description="Animal name")
7 habitat: str = Field(description="Habitat")
8 diet: str = Field(description="Diet")
9 population: int = Field(description="Population")
10
11# Parser
12parser = JsonOutputParser(pydantic_object=AnimalInfo)
13
14# Prompt with format instruction
15prompt = ChatPromptTemplate.from_messages([
16 ("system", "Return information about the animal in JSON format."),
17 ("human", "{format_instructions}\n\nAnimal: {animal}")
18])
19
20chain = prompt | llm | parser
21
22result = chain.invoke({
23 "animal": "African elephant",
24 "format_instructions": parser.get_format_instructions()
25})
26print(result) # {'name': 'African elephant', ...}1from langchain_community.chat_message_histories import ChatMessageHistory
2from langchain_core.runnables.history import RunnableWithMessageHistory
3
4# Message history
5history = ChatMessageHistory()
6
7# Chain with memory
8chain_with_history = RunnableWithMessageHistory(
9 chain,
10 lambda session_id: history,
11 input_messages_key="input",
12 history_messages_key="history"
13)
14
15# First message
16response1 = chain_with_history.invoke(
17 {"input": "I'm on a Safari in Kenya"},
18 config={"configurable": {"session_id": "abc123"}}
19)
20
21# Second message - the model remembers context
22response2 = chain_with_history.invoke(
23 {"input": "What animals can I see here?"},
24 config={"configurable": {"session_id": "abc123"}}
25)