LangChain Tools
Ready-made LangChain tools for JavaScript and Python: one monitor tool per engine, plus task and credit tools.
Install
npm install @answerline/sdk @answerline/langchain # or: pip install answerline answerline_langchain
Example
import { Client } from "@answerline/sdk";
import { createTools } from "@answerline/langchain";
const tools = createTools(new Client({ apiKey: process.env.API_KEY! }));
// → monitor_chatgpt, monitor_google, ..., create_async_task, get_task_status, get_credits
createTools(client) returns a monitor tool per engine (monitor_chatgpt, monitor_google_news, …) plus create_async_task, get_task_status and get_credits, bindable to any chat model or agent.
Task payloads are validated against their engine's request schema before sending, so a malformed task from a model fails locally.
Packages
| Package | Language | Status | Depends on |
|---|---|---|---|
@answerline/langchain |
JavaScript / TypeScript | Published on npm | @answerline/sdk, @langchain/core ^1.2.11, zod ^4.6.5 (peer), Node 20+ |
answerline-langchain |
Python 3.10+ | Published on PyPI | answerline SDK, langchain-core >=1.6.3, pydantic >=2.13.5 |
Both packages expose the same tools with the same names and schemas. Install the JavaScript package with:
npm install @answerline/sdk @answerline/langchain @langchain/core zod
Install the Python package with pip install answerline answerline-langchain. The Python section also shows how to give a Python agent the same capability with a small hand-written tool over REST.
The tools
createTools(client, { engines }) (JavaScript) and create_tools(client, engines=...) (Python) return a list of LangChain structured tools:
| Tool | Calls | Input |
|---|---|---|
monitor_chatgpt |
POST /v1/monitor/chatgpt |
prompt, country, optional include, legacy, disableWebSearch |
monitor_perplexity, monitor_gemini, monitor_copilot, monitor_grok |
POST /v1/monitor/<engine> |
prompt, country, optional include (flags per engine schema) |
monitor_ai_mode |
POST /v1/monitor/aimode |
prompt, and country or gl; optional hl, location, uule, include |
monitor_google |
POST /v1/monitor/google |
query with country or gl, or a Google url; optional pages, include.aioverview |
monitor_google_news |
POST /v1/monitor/google/news |
query, and country or gl; optional pages |
create_async_task |
POST /v1/async/task |
taskType, payload, optional priority (1 to 10), idempotencyKey, webhook.url |
get_task_status |
GET /v1/async/task/{id} |
taskId |
get_credits |
GET /v1/credits |
none |
Tool descriptions and input schemas are generated from the API’s OpenAPI document, so the field descriptions the model reads are the API’s own. Schemas are strict: unknown fields are rejected, “either of” rules such as country or gl are enforced, and create_async_task validates payload against the schema of the chosen taskType. A malformed call fails validation locally, before any request or charge.
Choosing engines
engines takes task types: CHATGPT, GEMINI, PERPLEXITY, COPILOT, AIMODE, GOOGLE, GOOGLE_NEWS, GROK. It defaults to all of them. Perplexity and Grok are paused for now and coming back soon; until then calls to them are refused and not billed. Narrowing it has two effects: only those monitor tools are returned, and create_async_task only accepts those task types. Passing an unknown task type, or an empty list, throws (Error in JavaScript, ValueError in Python) when the tools are created.
Fewer tools make agents cheaper and less prone to picking the wrong one. A research agent that should compare assistants needs CHATGPT, GEMINI and COPILOT; a search agent needs GOOGLE and AIMODE; a news agent needs GOOGLE_NEWS.
What tools cost
Monitor tools are synchronous calls and add 7 credits to the engine’s price, plus 18.9 per results page on Google Search and Google News:
| Tool call | Credits |
|---|---|
monitor_chatgpt |
13.2, or 20.2 with include.rawResponse or shopping |
monitor_gemini |
12 |
monitor_copilot |
54.3 |
monitor_ai_mode |
44.8, +37.8 per expanded product cluster |
monitor_google (first page) |
44.8, +37.8 per extra page, +18.9 with the AI Overview |
monitor_google_news (first page) |
27.9, +20.9 per extra page |
create_async_task |
Engine price without the surcharge, charged only if the task completes |
get_task_status, get_credits |
No engine run |
The tools of paused engines are refused and not billed until those engines are back.
An agent loop can call tools many times, so give it a budget: include get_credits and tell it the maximum number of engine calls in the system prompt.
JavaScript
Tools on an agent
The tools are standard StructuredToolInterface objects, so they work with any LangChain agent or with bindTools on a chat model. With LangChain’s createAgent (LangChain agents documentation, checked 2026-09-17):
import { Client } from "@answerline/sdk";
import { createTools } from "@answerline/langchain";
import { createAgent } from "langchain";
const client = new Client({ apiKey: process.env.API_KEY! });
const tools = createTools(client, { engines: ["CHATGPT", "GEMINI"] });
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools,
systemPrompt: [
"You research how AI assistants present brands.",
"Call get_credits first. Make at most 6 monitor calls, one at a time.",
"Always report the cited URLs from result.sources.",
].join(" "),
});
const out = await agent.invoke({
messages: [{ role: "user", content: "How do ChatGPT and Gemini answer 'best password manager for families' in the US? Which brands and domains appear?" }],
});
console.log(out.messages.at(-1)?.content);
The langchain package and a provider package for your model are separate installs; any tool-calling model works.
Client options that matter for agents
The tools call through the SDK client you pass, so its options apply:
const client = new Client({
apiKey: process.env.API_KEY!,
syncTimeoutMs: 360_000, // monitor tools can take up to five minutes
maxRetries: 2, // 429s and safe failures retried with backoff
});
A synchronous call holds one of your plan’s concurrency slots. Agent frameworks that run tool calls in parallel can exceed your concurrency and get CONCURRENT_LIMIT_EXCEEDED. Ask the agent to call engines one at a time, or see rate limits and concurrency.
Error handling
Tools do not swallow errors. An ApiError from the SDK is rethrown as an Error whose message is the SDK’s message plus the JSON error body, for example:
403 INSUFFICIENT_CREDITS (request 7c1e…): {"error":{"code":"INSUFFICIENT_CREDITS","message":"…"}}
Timeouts and network failures are rethrown as <tool name> failed: <message>. The original error is kept as cause, so your code can still check err.cause instanceof ApiError and read err.cause.code or err.cause.meta.requestId. How the model sees the failure depends on your agent runtime’s tool-error handling; the message is written to be readable by a model so it can fix arguments or stop.
Async tasks from an agent
For work that should not block the conversation, the agent can queue tasks and check back:
const [createTask, getStatus] = ["create_async_task", "get_task_status"].map(
(name) => tools.find((t) => t.name === name)!,
);
const created = (await createTask.invoke({
taskType: "CHATGPT",
payload: { prompt: "best CRM for a 5-person team", country: "US" },
idempotencyKey: "crm-us-2026-09-17",
webhook: { url: "https://example.com/hooks/answers" },
})) as { task: { id: string } };
const status = await getStatus.invoke({ taskId: created.task.id });
With a webhook URL, your application receives the finished task, verified with verifyWebhook from @answerline/sdk (webhooks guide), and can hand the result back to the agent in a later turn. This suits long-running assistants: the agent plans the prompt set, your code runs it as tasks at the lower task price, and the agent analyzes the results.
Recipe: Next.js route with a scoped agent
Keep the key server-side and give each route only the tools it needs:
// app/api/brand-check/route.ts
import { Client } from "@answerline/sdk";
import { createTools } from "@answerline/langchain";
import { createAgent } from "langchain";
const client = new Client({ apiKey: process.env.API_KEY! });
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: createTools(client, { engines: ["GEMINI"] }),
systemPrompt: "Answer only from monitor_gemini results. Make one call. List cited domains.",
});
export async function POST(req: Request) {
const { brand, category } = await req.json();
const out = await agent.invoke({
messages: [{ role: "user", content: `Does Gemini mention ${brand} for "best ${category}" in the US?` }],
});
return Response.json({ answer: out.messages.at(-1)?.content });
}
Gemini calls cost 12 credits each here. Make sure your hosting allows a request to run for several minutes, or switch to create_async_task and a webhook.
Python
answerline-langchain exposes create_tools(client, engines=None), returning BaseTool instances built with StructuredTool.from_function and handle_tool_error=True. API errors (ApiError) and transport errors (TimeoutError, ConnectionError) are converted to ToolException, so the model receives the error text, including the error code and body, as the tool result rather than the run crashing.
Usage with LangChain’s create_agent (LangChain agents documentation, checked 2026-09-17):
import os
from answerline import Client
from answerline_langchain import create_tools
from langchain.agents import create_agent
tools = create_tools(Client(os.environ["API_KEY"]), engines=["CHATGPT", "GOOGLE_NEWS"])
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=tools,
system_prompt="Call get_credits first, make at most 4 monitor calls, and cite URLs.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "What does ChatGPT recommend for CRM software for agencies, and which of those brands are in the news?"}]})
A hand-written tool over REST
Without the package, a Python agent can call the REST endpoint through its own tool. This covers the most common need, a single engine call:
import os
import httpx
from langchain_core.tools import tool
api = httpx.Client(
base_url="https://api.answerline.dev",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
timeout=httpx.Timeout(30.0, read=360.0),
)
@tool
def monitor_chatgpt(prompt: str, country: str = "US") -> dict:
"""Ask ChatGPT a prompt in the given market (ISO 3166-1 alpha-2 country code).
Returns the answer text and the cited sources."""
res = api.post("/v1/monitor/chatgpt", json={"prompt": prompt, "country": country})
if res.status_code >= 400:
return {"error": res.json().get("error", res.text), "status": res.status_code}
result = res.json()["result"]
return {"text": result["text"], "sources": [s["url"] for s in result.get("sources", [])]}
Returning a compact dict instead of the full result keeps the context window small. Pass monitor_chatgpt in tools like any other tool; the request fields for other engines are on the engine pages, for example Gemini and Google News. Errors come back as data the model can read, mirroring what the packaged tools do.
Design tips for agents that use live answers
- Return fewer fields. Full results include sources and entities; leave
include.rawResponseoff unless the agent needs it. - Separate exploration from tracking. Let the agent pick prompts and interpret answers interactively with monitor tools, then run the chosen prompt set on a schedule as batches from code. Tasks are cheaper by at least 7 credits each and do not depend on the agent loop.
- Pin the market. Tell the agent which
countryto use; answers differ by market, and an agent left to choose will vary it between runs. - Log request ids. Error messages include the request id; keep them in traces so failures can be investigated.
For a narrative walkthrough, see giving a LangChain agent live AI answers; for the underlying API calls, start at the quickstart.
Questions
Are the LangChain packages published?
Yes. The JavaScript package @answerline/langchain is on npm and the Python package answerline-langchain is on PyPI.
Which tools does createTools return?
One synchronous monitor tool per engine (monitor_chatgpt, monitor_gemini, monitor_perplexity, monitor_copilot, monitor_ai_mode, monitor_google, monitor_google_news, monitor_grok), plus create_async_task, get_task_status and get_credits. Perplexity and Grok are paused for now and coming back soon; calls to their tools are refused and not billed.
How do I limit which engines an agent can call?
Pass engines, for example createTools(client, { engines: ["CHATGPT", "GEMINI"] }) in JavaScript or create_tools(client, engines=["CHATGPT", "GEMINI"]) in Python. Only the matching monitor tools are returned, and create_async_task accepts only those task types.
What happens when a tool call fails?
In JavaScript the tool throws an Error whose message includes the API status, error code, request id and error body. In Python the tool raises a ToolException with the same information and handle_tool_error is enabled, so the message is returned to the model as the tool result.
How much does an agent tool call cost?
Monitor tools are synchronous calls: the engine's price plus 7 credits, and on Google Search and Google News 18.9 more per results page, for example 13.2 for ChatGPT or 27.9 for one page of Google News. create_async_task costs the engine's price without the surcharge, and get_credits and get_task_status do not run an engine.
Does the model get validated inputs?
Yes. Tool input schemas are generated from the API's OpenAPI request schemas, unknown fields are rejected, and an async task's payload is validated against the request schema of its taskType before any request is sent.
Other integrations
TypeScript / JavaScript SDK
The official npm SDK: typed monitor and task methods, batches, webhooks and error classes for Node and edge runtimes.
Python SDK
The official Python SDK: monitor calls, async tasks and batches with the same response shapes as the REST API.
Hosted MCP Server
Give Claude, Cursor or any MCP client search and AI-answer tools with one configuration line.
n8n Community Node
Use AnswerLine in n8n workflows: run monitors, queue tasks and read credits as native nodes.
Zapier App
Trigger Zaps from AI answers: Run Monitor for quick calls, Create Task with a webhook callback for long-running engines.