Use SettleGrid Tools in LangChain Agents
Install the langchain-settlegrid package, discover monetized tools from the SettleGrid marketplace, and pass them to any LangChain agent. Full TypeScript and Python examples included.
In this guide
Install the Package
Install the langchain-settlegrid package alongside LangChain core. Run npm install langchain-settlegrid @langchain/core for TypeScript or pip install langchain-settlegrid langchain-core for Python. The package has a single peer dependency on @langchain/core version 0.1.0 or later.
If you do not have a SettleGrid account, sign up at settlegrid.ai/register. You need a consumer API key (starts with sg_) for each tool you want to use. Generate keys from the tool's page in your SettleGrid dashboard — each key is scoped to a single tool for security.
The package exports two main classes: SettleGridToolkit for discovering tools, and SettleGridTool for wrapping individual tools. Both integrate natively with LangChain's tool interface, so discovered tools work with any LangChain agent, chain, or executor.
Initialize the Toolkit and Discover Tools
Create a SettleGridToolkit instance with your API key. The toolkit provides a discoverTools() method that queries the SettleGrid Discovery API and returns an array of LangChain Tool objects. Each tool is ready to use — its name, description, and call method are all wired up.
You can discover tools by keyword (e.g., "weather", "sentiment"), by category (e.g., "data", "nlp"), or both. The Discovery API returns tool metadata including pricing, ratings, and developer information. The toolkit converts this metadata into LangChain tools with descriptions that help the LLM choose the right tool.
If you already know which tool you want, skip discovery and use toolkit.createTool(slug, description) to create a tool directly. This is useful for hardcoded integrations where you always want a specific tool.
Create an Agent with SettleGrid Tools
Pass the discovered tools to any LangChain agent. The tools work with createToolCallingAgent, createReactAgent, AgentExecutor, and any other LangChain agent type. The LLM sees the tool descriptions from SettleGrid and decides when to call each tool based on the user's query.
When the agent calls a tool, the SettleGridTool._call() method sends the request to SettleGrid's proxy at /api/proxy/{slug}. The proxy authenticates the request, checks your balance, forwards to the upstream tool, records the invocation, and deducts the cost from your balance. All of this happens transparently — the agent just gets the tool's response.
For multi-tool workflows, discover tools from multiple categories and pass them all to the agent. The agent will select the appropriate tool based on the query. SettleGrid handles billing for each tool independently, so you can mix tools from different developers with different pricing models in the same agent.
Run Queries and Handle Billing
Run your agent with any query and the tools will be called as needed. After each tool call, you can access billing metadata on the tool instance via tool.lastInvocationMeta. This includes the cost in cents and the round-trip latency in milliseconds.
For production applications, implement balance monitoring. The SettleGrid API provides endpoints to check your current balance, set up auto-reload (via Stripe), and configure spending alerts. You can also set hard spending limits per tool to prevent runaway costs in agent loops.
Handle billing errors gracefully. If your balance is insufficient, the proxy returns a 402 status with a clear error message including the required and available amounts. Your application should catch this error and either top up the balance or inform the user. The SettleGridTool throws an Error with the upstream status and message, which LangChain's error handling can catch and retry.
View Usage in the Dashboard
Every tool call made by your LangChain agent is logged in the SettleGrid dashboard at settlegrid.ai/dashboard. The dashboard shows invocation history, cost per call, latency percentiles, error rates, and daily spend trends. You can filter by tool, date range, and status.
Export your usage data via the SettleGrid API for integration with your analytics stack. The GET /api/v1/invocations endpoint returns detailed records for each call, including the tool slug, cost, latency, status, and timestamp. This data is useful for cost attribution in multi-tenant applications.
Set up webhook notifications for billing events. SettleGrid can notify your application when your balance drops below a threshold, when a payment fails, or when a tool's pricing changes. Configure webhooks in your dashboard settings to automate balance management and alerting.
Code Examples
TypeScript: Discover and use tools
TypeScriptimport { SettleGridToolkit } from 'langchain-settlegrid'
import { ChatOpenAI } from '@langchain/openai'
import { AgentExecutor, createToolCallingAgent } from 'langchain/agents'
import { ChatPromptTemplate } from '@langchain/core/prompts'
// Initialize toolkit
const toolkit = new SettleGridToolkit({
apiKey: process.env.SETTLEGRID_API_KEY!,
})
// Discover tools by keyword
const tools = await toolkit.discoverTools('weather')
// Create a LangChain agent with discovered tools
const llm = new ChatOpenAI({ model: 'gpt-4o' })
const prompt = ChatPromptTemplate.fromMessages([
['system', 'You are a helpful assistant with access to real-time tools.'],
['human', '{input}'],
['placeholder', '{agent_scratchpad}'],
])
const agent = createToolCallingAgent({ llm, tools, prompt })
const executor = new AgentExecutor({ agent, tools })
const result = await executor.invoke({
input: 'What is the weather in Tokyo right now?',
})
console.log(result.output)
// Check billing metadata for the last tool call
for (const tool of tools) {
if (tool.lastInvocationMeta) {
console.log(`${tool.name}: ${tool.lastInvocationMeta.costCents}c`)
}
}TypeScript: Direct tool creation
TypeScriptimport { SettleGridToolkit } from 'langchain-settlegrid'
const toolkit = new SettleGridToolkit({
apiKey: process.env.SETTLEGRID_API_KEY!,
})
// Create a tool directly when you know the slug
const weatherTool = toolkit.createTool(
'weather-lookup',
'Get current weather conditions for any city worldwide',
5 // 5 cents per call
)
// Use the tool directly
const result = await weatherTool.invoke('{"city": "New York"}')
console.log(result)
console.log('Cost:', weatherTool.lastInvocationMeta?.costCents, 'cents')Python: LangChain with SettleGrid
Pythonfrom langchain_core.tools import Tool
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate
import requests
# Discover tools from SettleGrid
def discover_settlegrid_tools(api_key: str, query: str = ""):
resp = requests.get(
"https://settlegrid.ai/api/v1/discover",
params={"q": query, "limit": "10"},
)
data = resp.json()["data"]["tools"]
tools = []
for t in data:
def make_call(slug, key):
def call(input_str: str) -> str:
r = requests.post(
f"https://settlegrid.ai/api/proxy/{slug}",
json={"input": input_str},
headers={"x-api-key": key},
)
return r.text
return call
tools.append(Tool(
name=t["slug"],
description=t["description"],
func=make_call(t["slug"], api_key),
))
return tools
# Discover and create agent
tools = discover_settlegrid_tools("sg_your_api_key", "weather")
llm = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools)
result = executor.invoke({"input": "Weather in London?"})
print(result["output"])Ready to integrate?
Sign up for SettleGrid, get your API key, and start using paid tools in LangChain. Free tier includes 50,000 operations per month.