langchain
БесплатноБез исполняемых скриптовНе проверенBuild LLM-powered applications with LangChain. Use when a user asks to create AI chains, build RAG pipelines, implement agents with tools, set up document…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
LangChain
Overview
Build production-grade LLM applications using LangChain's composable framework. This skill covers chains, agents, retrieval-augmented generation (RAG), tool integration, memory, and deployment — using the LangChain 1.x API: LCEL for chains and create_agent for agents. The old LLMChain, AgentExecutor and ConversationBufferMemory live in the separate langchain-classic package; do not use them in new code.
Instructions
Step 1: Project Setup
Determine the user's runtime (Python or TypeScript) and initialize the project:
Python:
pip install langchain langchain-openai # langchain-core comes with it
# For RAG:
pip install langchain-chroma langchain-text-splitters
# For document loading (loaders live in langchain-community, which is being sunset;
# prefer a standalone integration package when one exists for your source):
pip install langchain-community pypdf
TypeScript:
npm install langchain @langchain/core @langchain/openai zod
# For RAG:
npm install @langchain/community @langchain/textsplitters
# Agents in JS: import { createAgent, tool } from "langchain"
Verify the LLM provider API key is set:
echo $OPENAI_API_KEY # or ANTHROPIC_API_KEY, etc.
Step 2: Understand LCEL (LangChain Expression Language)
All modern LangChain code uses LCEL — the pipe (|) operator for composing runnables:
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant specialized in {domain}."),
("human", "{question}")
])
chain = prompt | ChatOpenAI(model="gpt-5.5") | StrOutputParser()
result = chain.invoke({"domain": "Python", "question": "Explain decorators"})
Key LCEL concepts:
- Runnables: Any component that implements
.invoke(),.stream(),.batch() - Pipe operator:
a | bmeans output ofafeeds intob - RunnablePassthrough: Pass input through unchanged
- RunnableLambda: Wrap any function as a runnable
- RunnableParallel: Run multiple chains simultaneously
Step 3: Implement Core Patterns
Simple Chain
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_template("Summarize this text in {language}: {text}")
llm = ChatOpenAI(model="gpt-5.5") # or init_chat_model("anthropic:claude-sonnet-5-5")
chain = prompt | llm
result = chain.invoke({"language": "Spanish", "text": "..."})
Structured Output
from pydantic import BaseModel, Field
class ExtractedInfo(BaseModel):
name: str = Field(description="Person's full name")
role: str = Field(description="Job title or role")
sentiment: str = Field(description="Overall sentiment: positive, negative, neutral")
llm_structured = llm.with_structured_output(ExtractedInfo)
chain = prompt | llm_structured
# Returns ExtractedInfo object, not raw text
Retrieval-Augmented Generation (RAG)
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain_core.runnables import RunnablePassthrough
# Load and split documents
loader = PyPDFLoader("docs/manual.pdf")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = splitter.split_documents(docs)
# Create vector store
vectorstore = Chroma.from_documents(splits, OpenAIEmbeddings())
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
# RAG chain
rag_prompt = ChatPromptTemplate.from_template(
"Answer based on context:\n\n{context}\n\nQuestion: {question}"
)
def format_docs(docs):
return "\n\n".join(d.page_content for d in docs)
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| rag_prompt
| llm
| StrOutputParser()
)
answer = rag_chain.invoke("What is the return policy?")
Tool-Calling Agent
from langchain.agents import create_agent
from langchain.tools import tool
@tool
def search_database(query: str) -> str:
"""Search the product database for matching items."""
return f"Found 3 results for '{query}'"
@tool
def calculate_discount(price: float, percent: float) -> float:
"""Calculate discounted price."""
return price * (1 - percent / 100)
# create_agent (LangChain 1.x) replaces AgentExecutor and langgraph.prebuilt.create_react_agent.
# The model is a "provider:model" string or a chat model instance.
agent = create_agent(
model="openai:gpt-5.5",
tools=[search_database, calculate_discount],
system_prompt="You are a shopping assistant. Use the tools for prices.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "Find laptops under $1000
Установить langchain в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл langchain?
Build LLM-powered applications with LangChain. Use when a user asks to create AI chains, build RAG pipelines, implement agents with tools, set up document loaders, create vector stores, build conversational AI, implement prompt templates, chain LLM calls, add memory to chatbots, or orchestrate language model workflows. Covers LangChain 1.x (Python and TypeScript) with LCEL, create_agent, structured output, tool calling, retrieval, and production patterns.
Как установить скилл langchain?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл langchain запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic