langchain
Framework for building applications with large language models and chains.
What this skill does
# langchain
## Purpose
LangChain is a Python framework for developing applications that integrate large language models (LLMs) into workflows, enabling the creation of chains that combine multiple LLMs or tools for tasks like question answering or data processing.
## When to Use
Use LangChain when building AI-powered apps that require chaining LLMs, such as integrating multiple models for complex queries, or when you need to handle external data sources with LLMs. Apply it for rapid prototyping of AI agents, like chatbots that fetch real-time data, or for ML operations in aimlops clusters where scalable LLM workflows are needed.
## Key Capabilities
- **Chain Building**: Create sequences of LLMs using classes like `LLMChain`; for example, combine a prompt template with an LLM call.
- **Tool Integration**: Supports integrations with APIs like OpenAI via `OpenAI` class; handle vector stores with `FAISS` for semantic search.
- **Prompt Management**: Use `PromptTemplate` to define and render prompts dynamically, e.g., with variables for user input.
- **Agent Frameworks**: Build agents with tools using `AgentType.ZERO_SHOT_REACT`, allowing dynamic tool selection based on LLM output.
- **Async Support**: Leverage asynchronous chains for scalable applications, such as processing multiple queries concurrently.
## Usage Patterns
To use LangChain, install it via `pip install langchain`, then import and configure components. For basic chains, create an LLM instance and link it to prompts or tools. Pattern: Initialize an LLM with an API key, build a chain, and run it in a loop for iterative tasks. For agents, define tools and let the agent decide actions based on input.
## Common Commands/API
- **Installation and Setup**: Run `pip install langchain[all]` to include extras; set environment variables like `export OPENAI_API_KEY=your_key` for authentication.
- **Basic Chain Example**:
```python
from langchain.llms import OpenAI
from langchain.chains import LLMChain
llm = OpenAI(model_name="gpt-3.5-turbo")
chain = LLMChain(llm=llm, prompt="What is {topic}?")
result = chain.run(topic="LangChain")
```
- **API Endpoints**: When using LangChain with external services, call endpoints like `https://api.openai.com/v1/chat/completions` via LangChain wrappers; pass headers with auth tokens.
- **Config Formats**: Use YAML for chain configurations, e.g., in a file:
```
chains:
- name: simple_chain
llm: OpenAI
prompt: "Summarize {text}"
```
Load with `from langchain.utilities import load_config`.
- **CLI Commands**: For LangChain CLI (if extended), use `langchain serve` to run chains as services, or debug with `langchain debug --chain my_chain` to trace executions.
## Integration Notes
Integrate LangChain with other tools by wrapping them as callable functions. For example, to add a database query tool, use `Tool.from_function` and pass it to an agent. Set env vars for keys, e.g., `$OPENAI_API_KEY` for OpenAI models or `$SERPAPI_API_KEY` for search integrations. When combining with aimlops cluster tools, ensure compatibility by using LangChain's callback system for logging; import `from langchain.callbacks import get_openai_callback` to track token usage. For vector databases, integrate with Pinecone by initializing `from langchain.vectorstores import Pinecone` and providing your API key via env var.
## Error Handling
Handle errors by wrapping chain runs in try-except blocks, e.g.:
```python
try:
result = chain.run(input_data)
except ValueError as e:
print(f"Invalid input: {e}")
except Exception as e:
print(f"General error: {e} - Check API key or network")
```
Common issues include API rate limits (check with `if e.status_code == 429: retry()`), invalid API keys (verify `$OPENAI_API_KEY` is set), or chain misconfigurations (use `chain.validate()` if available). Log errors using LangChain's handlers for debugging in production.
## Concrete Usage Examples
1. **Simple Question-Answering Chain**: Build a chain to answer questions using an LLM and a vector store. First, set `export OPENAI_API_KEY=your_key`. Then:
```python
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
qa_chain = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff")
answer = qa_chain.run({"query": "What is LangChain?"})
```
This fetches relevant documents and generates a response.
2. **Agent for Web Search**: Create an agent that uses tools for web searches. Set `export SERPAPI_API_KEY=your_key`. Code:
```python
from langchain.agents import AgentType, load_tools, initialize_agent
from langchain.llms import OpenAI
tools = load_tools(["serpapi"])
agent = initialize_agent(tools, OpenAI(), agent=AgentType.ZERO_SHOT_REACT)
response = agent.run("Search for latest AI news")
```
The agent dynamically queries the web and returns results.
## Graph Relationships
- Related to cluster: aimlops (e.g., shares tools for ML operations).
- Connected via tags: langchain (self), llm (links to other LLM tools), ai-framework (connects to frameworks like Hugging Face).
- Dependencies: Requires OpenAI or similar APIs, integrates with vector stores like FAISS or Pinecone.
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.