A LangChain tool with a Pydantic input schema checks a company in its official register and hands errors back to the model as text. Written against langchain 1.5.2 and langchain-core 1.8.5, 26 November 2026.
In LangChain 1.x a tool is a BaseTool built with the @tool decorator, and an agent comes from create_agent, which returns a compiled graph with a model node and a tools node. This page defines one tool that calls GET /companies/search, gives it a typed input schema that refuses a bad call before any request is made, and returns JSON text a model can read. It was written against langchain 1.5.2 and langchain-core 1.8.5 (installed from PyPI on 26 November 2026). The tool was run against the live API; the model loop needs your own model key and was not run.
pip install langchain httpx pydantic # plus the package of your model provider export PROMETIAM_API_KEY=rk_live_demo_publichn # or your own rk_live_ key
The file below defines the input schema, the tool and a build_agent function. The schema is a Pydantic model with a validator: a call that gives both a name and a number, or neither, is rejected as a validation error before the request goes out.
import json
import os
import time
import httpx
from langchain.agents import create_agent
from langchain.tools import ToolException, tool
from pydantic import BaseModel, Field, model_validator
BASE = os.environ.get("PROMETIAM_BASE_URL", "https://api.prometiam.com/functions/v1/risk-api")
class CompanyCheckInput(BaseModel):
"""Which company to look up."""
country: str = Field(min_length=2, max_length=2, description="Two-letter country code, for example ES, FR or GB.")
name: str | None = Field(default=None, description="Company name. Give this or company_number.")
company_number: str | None = Field(default=None, description="National register number (exact). Give this or name.")
@model_validator(mode="after")
def one_of(self):
if bool(self.name) == bool(self.company_number):
raise ValueError("Give exactly one of name or company_number.")
return self
def _get(params: dict) -> httpx.Response:
key = os.environ.get("PROMETIAM_API_KEY")
if not key:
raise ToolException("PROMETIAM_API_KEY is not set in the environment of the tool.")
for attempt in range(2):
res = httpx.get(f"{BASE}/companies/search", params=params, headers={"Authorization": f"Bearer {key}"}, timeout=15)
if res.status_code != 429 or attempt == 1:
return res
time.sleep(min(int(res.headers.get("Retry-After") or 5), 30))
return res
@tool(args_schema=CompanyCheckInput)
def company_check(country: str, name: str | None = None, company_number: str | None = None) -> str:
"""Look up a company in the official register of one country. Returns legal name, register number,
status, legal form, founding date and VAT number as JSON. Fields are null where the register publishes none."""
params = {"country": country.upper(), "limit": 3}
params["company_number" if company_number else "name"] = company_number or name
try:
res = _get(params)
except httpx.HTTPError as exc:
raise ToolException(f"Network error: {type(exc).__name__}. Try again later.")
if res.status_code == 401:
raise ToolException("The API key is missing, wrong or expired. Tell the user; do not retry.")
if res.status_code == 429:
raise ToolException(f"Rate limited. Retry after {res.headers.get('Retry-After', 'a few')} seconds.")
if res.status_code >= 400: # includes 403 upgrade_required
err = res.json().get("error", {})
raise ToolException(f"{err.get('code', res.status_code)}: {err.get('message', 'The API refused the call.')}")
data = res.json()["data"]
if not data:
return json.dumps({"found": False, "message": "No company matched in this country. Do not guess; ask for the register number."})
top = data[0]["match_score"]
return json.dumps(
{
"found": True,
"ambiguous": sum(1 for c in data if c["match_score"] == top) > 1,
"companies": [
{
"legal_name": c["company_name"],
"register_number": c["company_number"],
"status": c["status"],
"legal_form": c["legal_form"],
"founding_date": c["founding_date"],
"vat_number": c["vat_number"],
"vat_number_source": c["vat_number_source"],
"match_score": c["match_score"],
}
for c in data
],
},
ensure_ascii=False,
)
# Hand a ToolException back to the model as the tool result instead of ending the run.
company_check.handle_tool_error = True
company_check.handle_validation_error = True
SYSTEM_PROMPT = (
"You check companies against official registers with the company_check tool. "
"Report only what the tool returns. Fields can be null where a register publishes none. "
"If several companies match equally, list them and ask which one is meant. "
"Never state that a company is safe or approved; a person decides."
)
def build_agent(model):
return create_agent(model=model, tools=[company_check], system_prompt=SYSTEM_PROMPT)
Two LangChain details matter. A tool returns a string, so the function serialises its small object with json.dumps. And an exception ends the run unless the tool says how to handle it: the two assignments before SYSTEM_PROMPT set handle_tool_error and handle_validation_error, so a ToolException becomes the tool's result text and the model can explain the failure to the user.
On 26 November 2026 the tool was called the way an agent calls it, company_check.invoke({"country": "FR", "company_number": "552032534"}), against the live API with the demo key. A register number is an exact match, so match_score is null and ambiguous is false:
{
"found": true,
"ambiguous": false,
"companies": [
{
"legal_name": "DANONE",
"register_number": "552032534",
"status": "active",
"legal_form": "SA",
"founding_date": "1955-01-01",
"vat_number": "FR27552032534",
"vat_number_source": "rule",
"match_score": null
}
]
}
The founding date is printed as served. The VAT number is rule: the French key and SIREN, format right, not confirmed. A name search for "Inditex" in Spain the same day returned three companies and ambiguous: true, because two of them score 100 on the name; the tool leaves the choice to the agent and the user.
Reading the tool's own attributes confirms the schema LangChain gives the model: company_check.name is company_check, and company_check.args lists country (two characters), name and company_number, the last two nullable with default None.
Pass the tool to create_agent. The model is a string such as "provider:model-name" (it needs that provider's integration package and key) or a chat model object you build yourself:
from company_check import build_agent
agent = build_agent("provider:model-name") # your provider and model
result = agent.invoke(
{"messages": [{"role": "user", "content": "Is the company with SIREN 552032534 still active?"}]}
)
print(result["messages"][-1].content)
To prove the code loads without a model key, the agent was built on 26 November 2026 with GenericFakeChatModel from langchain_core, an empty stand-in that never answers. The result is a CompiledStateGraph whose nodes are __start__, model, tools and __end__.
The agent.invoke snippet was not run. It calls a model, and this page's author did not use a model key. The tool it calls was run.
The rows below were checked against a local test server that answers as the API does, so the live service is never made to fail on purpose.
| Answer from the API | What the tool returns to the model |
|---|---|
401 unauthorized | Text: "The API key is missing, wrong or expired. Tell the user; do not retry." |
403 upgrade_required | Text: upgrade_required: and the API's own message. The key's plan does not include what was asked. |
429 with Retry-After | The tool sleeps for the seconds given (at most 30), tries once more, then returns "Rate limited. Retry after n seconds." |
200 with an empty data | JSON with "found": false and a message telling the model not to guess. |
| Both name and number, or neither | LangChain's "Tool input validation error", before any request. |
limit=3 adds nothing.X-Credits-Cost from the response headers if you want the agent run to report its spend.rk_live_demo_publichn without signing up: 30 calls a minute and 1,000 a day, shared by all visitors, for company search, records, VAT, LEI, insolvency and coverage.upgrade_required on it, and this tool does not call them.SYSTEM_PROMPT in the sample tells it never to call a company safe or approved.GET /account shows them).vat_number_source is register where the register publishes the number and rule where the number is built from the register identifier by the country's rule: the format is right, the registration is not confirmed. For an EU number, check it with GET /vat/{number}.entity_class (the sample does not forward it; add it to the mapping if you need it). A name can match several companies, so the tool sets ambiguous and the agent asks the user to choose.To skip the tool code, use the prometiam-risk-mcp server, which exposes company search, records, events, insolvency, VAT, LEI and sanctions screening (beta) as ready-made tools. See the MCP server and the use case for AI agents. The same tool for other stacks: OpenAI Agents SDK and Vercel AI SDK.
The free trial lasts 14 days and includes 500 credits. A card is required and nothing is charged during the trial; it then continues as Starter (EUR 9.99/month) unless you cancel.