AI / LangGraph LangChain Interview questions
How do you create custom tools?
There are three ways to create custom tools in LangChain, in order of increasing complexity: the @tool decorator, StructuredTool.from_function(), and subclassing BaseTool.
@tool decorator — simplest approach for single-string input tools:
from langchain_core.tools import tool
@tool
def get_word_count(text: str) -> int:
"""Counts the number of words in the provided text. Use when asked about word count."""
return len(text.split())
# Tool name: 'get_word_count', description from docstring
print(get_word_count.invoke("Hello world")) # 2
StructuredTool.from_function() — for tools with multiple inputs:
from langchain_core.tools import StructuredTool
from pydantic import BaseModel
class MultiplyInput(BaseModel):
a: float
b: float
def multiply(a: float, b: float) -> float:
"""Multiplies two numbers together."""
return a * b
multiply_tool = StructuredTool.from_function(
func=multiply,
name="multiply",
description="Multiplies two numbers together.",
args_schema=MultiplyInput,
)
BaseTool subclass — for full control, async support, and complex logic:
from langchain_core.tools import BaseTool
class DatabaseQueryTool(BaseTool):
name = "database_query"
description = "Query the internal product database. Input should be a SQL WHERE clause."
def _run(self, query: str) -> str:
return db.execute(f"SELECT * FROM products WHERE {query}")
async def _arun(self, query: str) -> str:
return await db.async_execute(query)
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
