ワンクリックで
langchain-tools
Guide to using tool integrations in LangChain including pre-built toolkits, Tavily, Wikipedia, and custom tools
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
メニュー
Guide to using tool integrations in LangChain including pre-built toolkits, Tavily, Wikipedia, and custom tools
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
SOC 職業分類に基づく
Using the Deep Agents CLI - terminal interface, persistent memory with AGENTS.md, project conventions, skills directories, and CLI commands.
Understanding Deep Agents framework - what they are, how to create them with createDeepAgent, and the agent harness architecture with built-in middleware for planning, filesystems, and subagents.
Creating and using custom skills with progressive disclosure, SKILL.md format, and the Agent Skills protocol in Deep Agents.
Using the Deep Agents CLI - terminal interface, persistent memory with AGENTS.md, project conventions, skills directories, and CLI commands.
Using FilesystemMiddleware with virtual filesystems, backends (State, Store, Filesystem, Composite), and context management for Deep Agents.
Using FilesystemMiddleware with virtual filesystems, backends (State, Store, Filesystem, Composite), and context management for Deep Agents.
| name | langchain-tools |
| description | Guide to using tool integrations in LangChain including pre-built toolkits, Tavily, Wikipedia, and custom tools |
| language | python |
Tools enable LLMs to interact with external systems, perform calculations, search the web, query databases, and more. They extend model capabilities beyond text generation, making agents truly actionable.
| Tool/Toolkit | Best For | Package | Key Features |
|---|---|---|---|
| Tavily Search | Web search | langchain-community | AI-optimized search API |
| Wikipedia | Encyclopedia queries | langchain-community | Wikipedia API access |
| DuckDuckGo Search | Privacy-focused search | langchain-community | No API key needed |
| ArXiv | Academic papers | langchain-community | Research paper search |
| Vector Store Tools | Semantic search | Based on vector store | Query your data |
| Custom Tools | Your specific needs | langchain-core | Define any function |
Choose Tavily if:
Choose Wikipedia if:
Choose Custom Tools if:
from langchain_community.tools.tavily_search import TavilySearchResults
import os
# Initialize Tavily (requires API key)
search_tool = TavilySearchResults(
max_results=3,
api_key=os.getenv("TAVILY_API_KEY"),
)
# Use directly
results = search_tool.invoke("Latest AI news")
print(results)
# Use with agent
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
model = ChatOpenAI(model="gpt-4")
agent = create_react_agent(model, [search_tool])
response = agent.invoke({
"messages": [{"role": "user", "content": "What's new in AI today?"}]
})
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
wikipedia = WikipediaQueryRun(
api_wrapper=WikipediaAPIWrapper(
top_k_results=3,
doc_content_chars_max=4000,
)
)
# Query Wikipedia
result = wikipedia.invoke("Artificial Intelligence")
print(result)
from langchain_community.tools import DuckDuckGoSearchRun
search_tool = DuckDuckGoSearchRun()
results = search_tool.invoke("LangChain framework")
print(results)
# With results object for more details
from langchain_community.tools import DuckDuckGoSearchResults
search_tool = DuckDuckGoSearchResults(max_results=5)
results = search_tool.invoke("Python programming")
from langchain_community.tools import ArxivQueryRun
arxiv_tool = ArxivQueryRun()
# Search academic papers
results = arxiv_tool.invoke("large language models")
print(results)
from langchain_core.tools import tool
from typing import Optional
@tool
def get_weather(location: str, unit: Optional[str] = "celsius") -> str:
"""Get the current weather for a location.
Args:
location: The city name, e.g., 'San Francisco'
unit: Temperature unit, either 'celsius' or 'fahrenheit'
"""
# Your implementation
data = fetch_weather(location, unit)
return f"The weather in {location} is {data['temp']}°{unit[0].upper()}"
# Use with agent
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
model = ChatOpenAI(model="gpt-4")
agent = create_react_agent(model, [get_weather])
response = agent.invoke({
"messages": [{"role": "user", "content": "What's the weather in London?"}]
})
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class WeatherInput(BaseModel):
location: str = Field(description="The city name")
unit: str = Field(default="celsius", description="Temperature unit")
@tool("get_weather", args_schema=WeatherInput)
def get_weather(location: str, unit: str = "celsius") -> str:
"""Get the current weather for a location."""
# Implementation
return f"Weather in {location}: 72°{unit[0].upper()}"
# Tool now has proper schema validation
from langchain_core.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Type
class DatabaseInput(BaseModel):
customer_id: str = Field(description="Customer ID to look up")
class DatabaseQueryTool(BaseTool):
name: str = "database_query"
description: str = "Query the customer database for information"
args_schema: Type[BaseModel] = DatabaseInput
def _run(self, customer_id: str) -> str:
"""Use the tool."""
# Your database logic
customer = db.get_customer(customer_id)
return str(customer)
async def _arun(self, customer_id: str) -> str:
"""Async version."""
# Async implementation
raise NotImplementedError("Async not implemented")
db_tool = DatabaseQueryTool()
from langchain_core.tools import create_retriever_tool
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import OpenAIEmbeddings
# Create vector store
vectorstore = InMemoryVectorStore.from_texts(
["LangChain is a framework...", "Agents use tools..."],
embedding=OpenAIEmbeddings(),
)
# Convert to tool
retriever_tool = create_retriever_tool(
vectorstore.as_retriever(),
name="knowledge_base",
description="Search the knowledge base for information about LangChain",
)
# Use in agent
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(model, [retriever_tool])
from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
# Define tools
search_tool = TavilySearchResults(max_results=3)
@tool
def calculator(expression: str) -> str:
"""Evaluate a mathematical expression.
Args:
expression: A mathematical expression to evaluate (e.g., "2 + 2")
"""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"Error: {str(e)}"
@tool
def custom_lookup(query: str) -> str:
"""Look up custom information.
Args:
query: The query to look up
"""
# Your custom logic
return f"Custom result for: {query}"
# Create agent with multiple tools
agent = create_react_agent(
ChatOpenAI(model="gpt-4"),
[search_tool, calculator, custom_lookup],
)
# Agent will choose appropriate tool(s)
response = agent.invoke({
"messages": [{
"role": "user",
"content": "Search for the population of Tokyo and calculate if it doubled"
}]
})
from langchain_core.tools import tool
import requests
@tool
def api_call(endpoint: str) -> str:
"""Call external API.
Args:
endpoint: API endpoint to call
"""
try:
response = requests.get(f"https://api.example.com/{endpoint}")
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return f"API error: {str(e)}"
# Error handling is critical for robust tools
# SQL Database Toolkit
from langchain_community.agent_toolkits import SQLDatabaseToolkit
from langchain_community.utilities import SQLDatabase
db = SQLDatabase.from_uri("sqlite:///example.db")
toolkit = SQLDatabaseToolkit(db=db, llm=model)
tools = toolkit.get_tools()
# Includes: query, schema info, query checker, etc.
# Use in agent
agent = create_react_agent(model, tools)
✅ Use pre-built tools
✅ Create custom tools
✅ Combine multiple tools
✅ Handle tool responses
❌ Execute arbitrary code safely
❌ Bypass authentication
❌ Guarantee tool selection
# ❌ OLD
from langchain.tools import WikipediaQueryRun
# ✅ NEW
from langchain_community.tools import WikipediaQueryRun
Fix: Use langchain-community for tools.
# ❌ Missing API key
tool = TavilySearchResults()
tool.invoke("query") # Error!
# ✅ Provide API key
import os
tool = TavilySearchResults(api_key=os.getenv("TAVILY_API_KEY"))
Fix: Set required API keys in environment variables.
# ❌ Model doesn't support tool calling
model = ChatOpenAI(model="gpt-3.5-turbo-instruct")
# This model doesn't support tools!
# ✅ Use tool-capable model
model = ChatOpenAI(model="gpt-4")
Fix: Use models that support function calling.
# ❌ Poor description
@tool
def tool1(x: int) -> int:
"""A tool""" # Too vague!
return x * 2
# ✅ Clear, specific description
@tool
def double_number(number: int) -> int:
"""Multiply a number by 2. Use this when the user wants to double a value.
Args:
number: The number to double
"""
return number * 2
Fix: Write clear docstrings that help the model know when to use the tool.
# ❌ Missing type hints
@tool
def my_tool(x): # No type hints!
return x
# ✅ Include type hints
@tool
def my_tool(x: str) -> str:
"""Process input.
Args:
x: Input string
"""
return x.upper()
Fix: Always include type hints for tool parameters.
# Community tools
pip install langchain-community
# Specific tools
pip install tavily-python # For Tavily
pip install wikipedia # For Wikipedia
pip install duckduckgo-search # For DuckDuckGo