Add a company check tool to your AI agent: LangChain

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.

The tool

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.

The real result

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.

Register it with the agent

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.

Errors become text for the model

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 APIWhat the tool returns to the model
401 unauthorizedText: "The API key is missing, wrong or expired. Tell the user; do not retry."
403 upgrade_requiredText: upgrade_required: and the API's own message. The key's plan does not include what was asked.
429 with Retry-AfterThe tool sleeps for the seconds given (at most 30), tries once more, then returns "Rate limited. Retry after n seconds."
200 with an empty dataJSON with "found": false and a message telling the model not to guess.
Both name and number, or neitherLangChain's "Tool input validation error", before any request.

What a call costs

  • The tool calls one company search: 1 credit per call. limit=3 adds nothing.
  • Nothing is charged for a failed call (401, 403, 429, 5xx).
  • Plans: Starter EUR 9.99 a month, 1,000 credits; Professional EUR 29.99, 10,000; Scale EUR 99.99, 50,000; Enterprise priced to order. The 14-day free trial needs a card, charges nothing during the trial, includes 500 credits and continues as Starter unless you cancel.
  • Read X-Credits-Cost from the response headers if you want the agent run to report its spend.

The demo key

  • Anyone can use the public demo key 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.
  • Sanctions screening, people and company events return 403 upgrade_required on it, and this tool does not call them.
  • Because the key is shared, expect an occasional 429 from the daily cap. An agent that runs unattended needs a key of your own.

Guardrails

  • Read the key from the environment inside the tool. It is not a field of the input schema, not in the prompt and not in the system prompt, so the model never holds it.
  • The agent reports what the register says and a person decides. SYSTEM_PROMPT in the sample tells it never to call a company safe or approved.
  • Sanctions screening is beta. As a second tool, a hit is a prompt for a person to review, never a verdict; a clear result means only that no match was found in the lists checked on the date shown.
  • Use one key per agent, with only the scopes it needs (GET /account shows them).
  • LangChain agents can pause for human approval through middleware. This tool only reads; put an approval step in front of any tool you add that changes something.

Scope limits an agent should know

  • Coverage differs by country. The tool works for every live country, and the fields it returns are null where the register publishes none. The API documentation lists what each country serves.
  • 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}.
  • What a register lists differs by country, and each record carries 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.

Or use the MCP server

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.

Related pages

Sign up · API documentation

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.

Frequently asked questions

Does the tool need a paid plan?
No. The public demo key covers company search with a shared cap of 30 calls a minute and 1,000 a day, which is enough to build and test. Production use needs a key of your own: the 14-day free trial needs a card and includes 500 credits.
Why a search and not the one-call company check?
GET /companies/check returns the record, officers, owners, insolvency notices and a sanctions screen in one answer, and costs up to 6 credits for a full check by company number (7 by name). A first-pass identity tool needs only the record, so the search at 1 credit is the cheaper fit. Swap the URL and the mapping when your agent needs the full check.
Why return a JSON string and not a dictionary?
A LangChain tool result becomes the content of a tool message, which is text. Returning json.dumps of a small object keeps the field names the model should quote.
What does handle_tool_error change?
Without it a ToolException ends the agent run. With it the exception message becomes the tool result and the model can tell the user that the key was refused or the call was rate limited.
Is the answer a decision about the company?
No. It is what the register says today. The agent reports it and a person decides.