- Docs
- Guides
- Build with Enigma
- Python SDK
Generate queries from questions
The questions the SDK answers, the four strategies that turn them into GraphQL, and the data each access tier returns.
Most snippets on this page show only what changes from the quickstart programs. Run the snippets in this guide explains how to run them.
A question passed as client.search(prompt=...) must name what it is about. Every strategy answers these kinds of questions:
| Kind of question | Example |
|---|---|
| A business’s profile, by name or website | “What does Sweetgreen do?”, “Enrich company data for hubspot.com” |
| A business’s locations in a city or state | “Find Costco locations in Spokane” |
| One location of a business, by street address | “Is the Costco at 12020 N Newport Hwy, Spokane, WA still open?” |
| What is at a street address | “What is at 350 Fifth Ave, New York, NY?” |
| A person and the businesses tied to them | “What businesses is Jane Doe associated with?” |
| A company’s officers, owners, and related companies | “Who runs Airbnb?”, “Who owns Shake Shack?” |
| A legal entity’s registrations, taxpayer identification numbers (TINs), and bankruptcies | “Is Zoom Video Communications Inc registered in Delaware?” |
| Sanctions and watchlist screening | “Screen Sweetgreen for sanctions” |
| How many businesses of a category are in a place, or how many locations a brand has | “How many pharmacies are in Montana?”, “How many Wendy’s restaurants are there in Ohio?” |
| Government records of a business, person, or address | “Show business licenses held by Walgreens”, “Show SAM.gov registrations for Lockheed Martin” (see Get government records) |
| Up to three businesses or people at once | “Compare Starbucks and Dunkin” |
- TINs and watchlist entries are left out for
AccessTier.REDISTRIBUTIONand listed inunavailable_data, so a screening question returns the business without them (see Access tiers). - A question about a street address alone needs address lookups, which are on by default when the API supports them for your tier (see Look up an address).
- A count by category needs a business type the SDK can map to an industry code. The default and
TemplateStrategymap a fixed list of common types by name, such as pharmacies, dentists, and coffee shops, and refuse any other.GenerativeStrategy,AgentStrategy, andServiceStrategy(query_strategy="generative")let the LLM pick the code, so check the code in the query.
The strategies differ in speed, in what they need, and in how they handle a question outside this table (see Choose a strategy).
A question that names several businesses, people, or street addresses can get several searches, all run in one query:
- Each business or street address the question names gets a search. A person named with their company (“Jane Doe at Sweetgreen”) or a single street address given for a business (“the Starbucks at 1 Main St”) shares that business’s search.
- Each person the question names with no company gets a search.
A refused question raises EnigmaClientException from client.search, and no query runs (see Generation errors). Refused questions include these:
- A question that needs more than three searches or counts, such as one naming more than three businesses. A generated query runs at most three; the government-record searches the SDK adds don’t count (see Get government records).
- A question in which any one of its searches would be refused on its own. The whole question is refused, not only that search.
- A request to list businesses by category (“List coffee shops in Denver”).
The limit of three applies to searches and counts, not to names. In a template query (from ServiceStrategy’s default or TemplateStrategy), a lookup of one location of a business, or of an address, gets one search for each entry in the question’s longest list. That list can be of businesses, people, streets, cities, or states, and in an address lookup also of units or ZIP codes (see How template queries read places). So “the Starbucks at 1 Main St in Boston and 2 Elm St in Cambridge” gets two searches. A question about “the Starbucks at 1 Main St, 2 Elm St, 3 Oak St, and 4 Pine St in Boston” names one business but needs four searches, so it is refused.
When a question asks for data Enigma doesn’t serve, such as lawsuits, that part is left out and listed in unavailable_data.
Choose a strategy
Section titled “Choose a strategy”A strategy turns each question into a GraphQL query. The default runs on Enigma’s servers. The other three are local strategies: they run on your machine and call an LLM with your own account.
| Strategy | How it writes the query | What you need | Speed |
|---|---|---|---|
ServiceStrategy (default) |
On Enigma’s hosted query service, an LLM picks one of Enigma’s tested query templates and fills it in | Your Enigma API key | Fast |
TemplateStrategy |
An LLM picks one of Enigma’s tested query templates and fills in the names and places | An LLM API key | Fast |
GenerativeStrategy |
An LLM writes the whole query; the SDK checks it against the API schema and repairs it | An LLM API key | Slower |
AgentStrategy |
A Claude agent on Amazon Bedrock reads Enigma’s query reference and writes the query | AWS credentials with Bedrock access, and enigma-api-client[anthropic] |
Slowest, often tens of seconds |
When to use each:
- Start with the default. Its queries come from tested templates, so the fields a kind of question returns are predictable. A question no template fits gets the closest one, usually the business’s profile, which may answer it only in part.
- When the default’s answer misses part of what you asked, such as a state, and
unavailable_datadoesn’t list it,ServiceStrategy(query_strategy="generative", enigma_api_key=...)has the hosted service write the whole query instead of picking a template. For example, it can narrow a person’s businesses to one state (“businesses registered to Jane Doe in Pennsylvania”), where a template lists that person’s businesses in every state. Review the queries it writes. - To generate queries with your own LLM account, use
TemplateStrategyin place of the default andGenerativeStrategyin place of the hosted generative option. SettierinClientConfigto your key’s tier (see Access tiers). - When the other strategies still leave something out and you can wait tens of seconds, try
AgentStrategy. The agent reads Enigma’s GraphQL reference and its examples as it works. - For card transactions, your tier must be
AccessTier.EXTERNAL(see Access tiers). Use any strategy exceptAgentStrategy. - For a pipeline that asks the same kind of question many times, generate the query once, review it, and run it with your own variables (see See and reuse a generated query).
To use a strategy other than the default, pass it to ClientConfig:
from enigma_api_client.strategies import TemplateStrategy
config = ClientConfig( enigma_api_key=os.environ["ENIGMA_API_KEY"], query_strategy=TemplateStrategy(),)ServiceStrategy
Section titled “ServiceStrategy”ServiceStrategy sends your question to Enigma’s hosted query service, authenticated with your Enigma API key, and returns the query the service writes. client.search then runs it. The service reads your access tier from the key.
The service picks a template by default, as TemplateStrategy does. To have it write the whole query instead, create the strategy yourself with query_strategy="generative". A ServiceStrategy you create doesn’t take the key from ClientConfig: pass enigma_api_key=, or it reads ENIGMA_API_KEY.
from enigma_api_client.strategies import ServiceStrategy
strategy = ServiceStrategy(query_strategy="generative", enigma_api_key=os.environ["ENIGMA_API_KEY"])config = ClientConfig(enigma_api_key=os.environ["ENIGMA_API_KEY"], query_strategy=strategy)TemplateStrategy
Section titled “TemplateStrategy”An LLM reads the question, picks one of Enigma’s query templates, and extracts the names, places, and other values the template needs. The SDK then builds the GraphQL from the template, so the query’s fields always come from tested templates.
The templates cover:
- Brand profiles
- Brand lookups by website
- A brand’s locations
- A location’s profile
- Person searches
- Corporate officers
- Legal entity verification
- Contacts
- Watchlist screening
- Risk assessments
- Counts by category and place
- Counts of a brand’s locations
- Address lookups, when turned on (see Turn address lookups on or off)
- Card transactions, when your tier is
AccessTier.EXTERNAL(see Access tiers)
A brand, location, legal entity, officer, or person lookup returns a core set of fields plus only the data the question asks for: industry, website, phone, officers, bankruptcies, watchlist entries, TINs, registration details, locations, affiliates, alternate names, address, reviews, or headcount. Contact, watchlist, and risk lookups return the same fields whatever the question asks, apart from headcount and government records.
- A compliance question adds whichever of officers, TINs, watchlist entries, bankruptcies, and registration details the lookup can return (a location’s profile can return only registration details). A compliance question is one that mentions KYB, KYC, AML, compliance, due diligence, a background check, or vetting, or that asks to vet or screen the entity. A question that only asks to screen an entity or to run due diligence on it usually gets the watchlist or risk lookup instead.
- A question asking for everything about an entity adds all of this data that its lookup can return, except headcount. A question gets headcount only by asking for it, as in “how many employees”.
- With several businesses or people, the data the question asks for is added to each one’s search.
TemplateStrategy refuses a category listing with UNSUPPORTED_DATA_REQUESTED. It refuses with INVALID_QUERY a question that isn’t about a business, location, person, or address. With AccessTier.REDISTRIBUTION, it usually refuses a request for card transaction data the same way. Any other question that fits no template gets the closest one, usually the business’s profile.
| Argument | Default | Meaning |
|---|---|---|
anthropic_api_key |
ANTHROPIC_API_KEY |
The Anthropic API key, when llm_provider is not set |
model |
claude-haiku-4-5-20251001 |
The Anthropic model, when llm_provider is not set |
llm_provider |
None |
Another LLM provider (see LLM providers) |
shape_cache |
On, unless ENIGMA_SHAPE_CACHE_ENABLED turns it off |
Whether to answer a question that matches an earlier one’s pattern without an LLM call (see Query shape cache) |
shape_cache_max_shapes |
8192 | The most query shapes the cache keeps |
address_search |
ENIGMA_ADDRESS_SEARCH, else "auto" |
Whether the strategy writes address lookups (see Look up an address) |
How template queries read places
Section titled “How template queries read places”This section applies to template queries: those from ServiceStrategy’s default and from TemplateStrategy. In this section, a place is a city, a state, or, in an address lookup, a unit or a ZIP code.
Which lookups use places:
- A lookup of one location of a business, or of an address, searches by street, city, and state, and an address lookup also by unit and ZIP code. The next two lists say how a question’s lists of these values pair.
- A brand’s locations, counts of a brand’s locations, and counts by category are filtered by city and state. A count by category over several places is one count, not one per place. Each search or count matches every city it is given in every state it is given, so “coffee shops in Springfield, IL and Columbus, OH” also counts those in Springfield, OH.
- A legal entity lookup isn’t filtered by place. It lists each business’s registrations in the states the question gives that business, under
registrationsInStatein each of itsregisteredEntities. The rules in the next list decide which states each business gets. - Brand profiles, person searches, and officer, contact, watchlist, risk, and card transaction lookups don’t filter by place.
How places are matched to businesses, people, and streets:
- A lookup of one location of a business (“the Starbucks at 1 Main St”), or of an address, pairs places by position. The first city or state in a list goes with the first business or street, the second with the second, and so on. In an address lookup, units and ZIP codes pair the same way. Each position gets its own search, so a list of four streets gets four searches.
- Elsewhere, every place applies to each business or person. “Starbucks locations in Boston and Dunkin locations in Chicago” gets one search per brand, each covering both cities.
- To give each one its own place, say “respectively” (“Starbucks and Dunkin locations in Boston and Chicago, respectively”), or ask about them separately.
- When the question gives a place for some of them and none for another, each keeps its own. “Starbucks in Boston, Dunkin, and Peet’s in Chicago” searches Starbucks in Boston and Peet’s in Chicago, and doesn’t filter Dunkin by city.
- The rules apply to a question’s cities and to its states separately, so in one question each business can keep its own city while every state applies to each business.
How pairing by position works:
- A single business or person pairs with every street and every place in a list, and a single street pairs with every place. So “the Starbucks at 1 Main St in Boston and Cambridge” gets two searches, and so does “the Starbucks at 1 Main St and 2 Elm St”.
- Several businesses, people, or streets pair by position with a list of cities, states, units, or ZIP codes.
- A list of places can be longer than the list of businesses, people, or streets it pairs with. When the shorter list is of streets that all go with one business or person, that business or person is also searched in each extra place, without a street. In “the Starbucks at 1 Main St and 2 Elm St in Boston, Cambridge, and Somerville”, Starbucks goes with both streets and is also searched in Somerville. Otherwise, the extra place has nothing to pair with, and the question is refused.
- Outside a count question, a street that pairs with no business or person gets an address lookup of its own (see Look up an address). While address lookups are off, such a question is refused.
GenerativeStrategy
Section titled “GenerativeStrategy”One LLM call writes the whole query. It handles questions the templates don’t cover. GenerativeStrategy takes the same arguments as TemplateStrategy.
- The LLM works from an excerpt of Enigma’s GraphQL reference, example query patterns, and rules. The rules tell it to write the question’s values into the query text.
- The SDK checks the query against the API schema and the rules the API enforces at execution.
- The SDK fixes what it can without a model call. Otherwise, it makes one more LLM call to repair the query.
- The LLM can still choose fields that don’t answer the question, so review the queries it writes before you rely on them.
GenerativeStrategy raises UNSUPPORTED_DATA_REQUESTED instead of returning a query in these cases:
- Any search in the query is one of these:
- A person search by surname alone, when the question uses the word “surname”, “last name”, or “family name”.
- An employer identification number (EIN) written with its dash, such as
12-3456789, searched as a name. - A number of five or more digits from the question searched as a name, when the question names an identifier, such as a filing number or license number, unless the question introduces the number as a business’s name, as in “the store called 90210”.
- A wildcard name pattern, such as
Star%. - A street address searched as a name, when the question uses wording such as “tenants”, “occupants”, “located at”, “registered at”, “operating out of”, or “at this address”.
- The query is a category count the question didn’t ask for. That is, all of these hold:
- The query only counts businesses: every top-level field in it is an
aggregatecount. - Each count writes its search input into the query text, not into variables.
- No count names a business, website, person, phone number, id, or TIN.
- At least one count is by category.
- The question doesn’t ask for a count.
- The query only counts businesses: every top-level field in it is an
AgentStrategy
Section titled “AgentStrategy”A Claude agent, built with the Claude Agent SDK, reads Enigma’s GraphQL reference, examples, and notes on the schema’s fields, and writes the query. The SDK checks the agent’s answer against the API schema and applies the same checks as GenerativeStrategy, fixing what it can without a model call. AgentStrategy suits complex questions best and is the slowest strategy.
pip install "enigma-api-client[anthropic]"from enigma_api_client.strategies import AgentStrategy
config = ClientConfig(enigma_api_key=os.environ["ENIGMA_API_KEY"], query_strategy=AgentStrategy())The agent runs on Amazon Bedrock only:
- Credentials come from the standard AWS credential chain.
- The identity needs
bedrock:InvokeModelandbedrock:InvokeModelWithResponseStreamon the inference profile and on the foundation model in every region the profile routes to. - The default model is the US inference profile
us.anthropic.claude-haiku-4-5-20251001-v1:0. Passmodel=to change it. - The region comes from
region=, thenAWS_REGION, thenAWS_DEFAULT_REGION, and isus-east-1when none is set. Keep the region inside the profile’s geography. max_turns(default 8) limits each call’s agent turns, andmax_budget_usd(default 0.25) limits each call’s model spend in US dollars. A call that reaches either limit raisesINVALID_QUERY.
The agent runs the Claude Code CLI bundled with claude_agent_sdk as a subprocess:
- Its nonessential network traffic is turned off.
- Its only tool reads files inside the query reference bundled with the SDK. It has no shell, file writes, web access, or file attachments.
- Every environment variable it inherits is blanked, except basic process settings (such as
PATH,HOME, locale, and temporary directories), TLS and proxy settings, and the AWS credential chain. - It keeps no session transcript on disk.
The agent writes values into the query itself, so the query it returns has no variables.
When its answer still fails the schema check after the SDK’s fixes, AgentStrategy raises UnrepairedQueryError.
See and reuse a generated query
Section titled “See and reuse a generated query”strategy.generate_query(prompt) returns the query without running it:
import asyncioimport os
from enigma_api_client import Client, ClientConfigfrom enigma_api_client.strategies import ServiceStrategy
async def main(): key = os.environ["ENIGMA_API_KEY"] strategy = ServiceStrategy(enigma_api_key=key) async with Client(ClientConfig(enigma_api_key=key, query_strategy=strategy)) as client: generated = await strategy.generate_query("Tell me about Chipotle") print(generated.query) print(generated.variables) # {'searchInput': {'name': 'Chipotle', 'entityType': 'BRAND', 'conditions': {'limit': 1}}}
variables = {"searchInput": {**generated.variables["searchInput"], "name": "Sweetgreen"}} response = await client.search(query=generated.query, variables=variables) print(response.data["search"][0]["names"]["edges"][0]["node"]["name"]) # SWEETGREEN
asyncio.run(main())- Check a query before you reuse it with other variables. Any strategy can write some values from the question directly into the query text, where your variables don’t replace them:
- When a question names a state, a legal entity lookup writes that state into the query.
- A query that selects government records writes the searched name, person’s name, and address into its archive searches.
GenerativeStrategyis told to write every value into the query text, andAgentStrategyalways does.
- A template query numbers its variables like the keys of
data:searchInput,searchInput2, andsearchInput3. Other variables follow the same pattern, such aslocConditions2. - Call
generate_queryinside theasync withblock. A local strategy checks its query against the API schema, which theClientfetches with your key. - Called directly, a local strategy’s
generate_querywrites forAccessTier.REDISTRIBUTIONunless you pass your tier, as ingenerate_query(prompt, tier=AccessTier.EXTERNAL).client.searchpassesClientConfig.tierfor you.ServiceStrategyalways writes for your key’s tier.
generate_query returns a GenerateQueryResponse:
| Field | Holds |
|---|---|
query, variables |
The GraphQL query and its variables |
unavailable_data |
The parts of the question Enigma can’t answer |
deterministic_repair |
The kinds of fixes, comma separated, when the SDK fixed the query without a model call |
cache_rule |
"shape" when the query shape cache answered without an LLM call; other values report what the cache learned from the call |
records |
For a question asking for government records, from a local strategy: whether the SDK added record fields (see the list after this table) |
records takes these values:
selected: the SDK added record fields.no_schema: the SDK had no API schema yet (see Records and the API schema).no_entity: the query has no entity search to add them to, such as a count.already_selected: the query already selects records, or already uses a response key the SDK would add, such asarchiveRecords.invalid: the query doesn’t parse, or adding record fields would break a rule the query passes.
Access tiers
Section titled “Access tiers”The fields you can read depend on your API key’s access tier:
AccessTier.REDISTRIBUTIONis the narrowest tier.AccessTier.EXTERNALadds fields such as TINs, watchlist entries, and card transaction data.
The hosted service reads the tier from your key. A local strategy writes queries for the tier in ClientConfig.tier, which defaults to AccessTier.REDISTRIBUTION. Set it to your key’s tier:
from enigma_api_client import AccessTierfrom enigma_api_client.strategies import TemplateStrategy
config = ClientConfig( enigma_api_key=os.environ["ENIGMA_API_KEY"], query_strategy=TemplateStrategy(), tier=AccessTier.EXTERNAL,)If you keep the default tier, a local strategy writes queries that leave out fields a broader key could read. If you don’t know your key’s tier, ask Enigma support.
- A local strategy removes from the query each field the API doesn’t serve your tier, and lists it in
unavailable_datawith the reasoncontractual.enigma_api_client.restricted_fields_for(tier)returns those fields. - For
AccessTier.REDISTRIBUTION, once the SDK has the API schema (see Records and the API schema), a local strategy also leaves out the email addresses and phone numbers of the people in a company’s roles (emailAddressesandphoneNumbersunder a role), because the API answers a redistribution key with placeholder values for them. It lists a field it removed inunavailable_data, asRole.emailAddressesorRole.phoneNumberswith the reasoncontractual, only when the question asks for it and the query had selected it, as in “What is the email of Sweetgreen’s CFO?” answered by the contacts lookup. A location’s own phone numbers are real and stay. - To filter data before you pass it on to others, use
enigma_api_client.gate_blocked_fields(tier). It returns those fields plus, forAccessTier.REDISTRIBUTION, fields the API serves but a redistribution contract forbids. A local strategy doesn’t remove those extra fields, and the API can return them to your own queries too.
Schema checks and several tiers
Section titled “Schema checks and several tiers”- The SDK fetches the API schema for the
tierof the firstClientyou create in a process, with that client’s key, and checks generated queries against it. Settierbefore you create your firstClient. In a notebook, restart the kernel after you change it. - A later
Clientwith a differenttiergets no schema. On that client,AgentStrategyraisesPROVIDER_ERROR.TemplateStrategyandGenerativeStrategystill answer, with these differences:- Generated queries aren’t checked against the schema.
- Government records are left out.
- Address lookups are off unless you turn them on with
address_search=TrueorENIGMA_ADDRESS_SEARCH=on(see Turn address lookups on or off). - For
AccessTier.REDISTRIBUTION, role email addresses and phone numbers stay in the query, so the API answers them with placeholder values (see Access tiers).
To serve several tiers in one process, register a schema introspector with validation.set_schema_introspector before you create the first Client. An introspector is a function that takes an AccessTier and returns that tier’s schema.
The SDK calls it either on your event loop’s thread, blocking every search on that loop until it returns, or from a background thread with no context variables (contextvars) set. So the introspector must:
- Be synchronous and thread-safe.
- Return in bounded time.
- Not read context variables.
- Return
Nonewhen a fetch fails, as the following example does, so a failed fetch doesn’t raise fromclient.search.
import os
from enigma_api_client import AccessTier, validation
KEYS = { AccessTier.EXTERNAL: os.environ["ENIGMA_EXTERNAL_KEY"], AccessTier.REDISTRIBUTION: os.environ["ENIGMA_API_KEY"],}
def introspector(tier): key = KEYS.get(tier) if key is None: return None try: return validation.introspect_schema("https://api.enigma.com/graphql", key) except Exception: return None
validation.set_schema_introspector(introspector) # before you create the first ClientEach Client then gets the schema for its own tier.
The first time a tier’s schema is used after it is five minutes old, the SDK fetches it again in the background. Pass refresh_seconds= to set_schema_introspector to change that interval, or refresh_seconds=None to turn the refresh off.