- Docs
- Guides
- Build with Enigma
- Python SDK
Configure the client and read responses
Set up the client, read what a search returns, handle errors, and page through connections.
Configure the client
Section titled “Configure the client”ClientConfig takes these fields:
| Field | Default | Meaning |
|---|---|---|
enigma_api_key |
Required | Your Enigma API key |
query_strategy |
ServiceStrategy |
The strategy that turns questions into queries (see Choose a strategy) |
tier |
AccessTier.REDISTRIBUTION |
Your key’s access tier, which local strategies write queries for (see Access tiers) |
url |
https://api.enigma.com/graphql |
The GraphQL endpoint |
auto_inject_id_and_typename |
True |
Adds id and __typename to the inline fragments and connection nodes a query selects (see The shape of data) |
auto_inject_page_info |
False |
Adds pageInfo { hasNextPage endCursor } to every connection a query selects that doesn’t already select pageInfo (see Paginate) |
customize_headers_callback |
None |
A function that takes the default request headers and returns headers to add or replace. A header returned with an empty value is removed. It applies to searches only (see the note after this table). |
The client doesn’t apply customize_headers_callback to its request for the API schema (see Schema checks and several tiers) or to the hosted query service.
Client lifecycle
Section titled “Client lifecycle”- Create one
Clientand reuse it for all your requests. It keeps connections open until you close it, either withasync with Client(config) as client:or withawait client.aclose(). Closing the client also closes its strategy. - All methods are asynchronous. In a Jupyter notebook, which already runs an event loop, replace
asyncio.run(main())withawait main(). Start Jupyter from a shell whereENIGMA_API_KEYis set. - Use a client from one event loop. Don’t share it across threads that each run their own loop.
Run searches concurrently
Section titled “Run searches concurrently”One client can run many searches at once:
import asyncioimport os
from enigma_api_client import Client, ClientConfig
async def main(): config = ClientConfig(enigma_api_key=os.environ["ENIGMA_API_KEY"]) async with Client(config) as client: prompts = ["Tell me about Chipotle", "Tell me about Sweetgreen", "Tell me about Shake Shack"] responses = await asyncio.gather(*(client.search(prompt=p) for p in prompts), return_exceptions=True) for prompt, response in zip(prompts, responses): if isinstance(response, Exception): print(prompt, "failed:", type(response).__name__) else: print(prompt, response.status_code)
asyncio.run(main())return_exceptions=True keeps one failed search from hiding the others’ results.
Your plan’s rate limits cap searches per second and, on some plans, per day. To cap how many calls run at once, use an asyncio.Semaphore. That keeps bursts down but doesn’t enforce a rate.
Timeouts
Section titled “Timeouts”The client waits up to 60 seconds for the API, and ServiceStrategy waits up to 30 seconds for the hosted query service. A timeout raises httpx.TimeoutException.
Read the response
Section titled “Read the response”client.search() returns a SearchResponse:
| Field | Holds |
|---|---|
status_code |
The HTTP status of the API’s answer |
data |
The GraphQL data object, or None |
errors |
The GraphQL errors list, or None |
extensions |
The GraphQL extensions object, or None |
unavailable_data |
For a question: the parts Enigma can’t answer (see Unavailable data) |
raw_body |
The response body as text |
headers |
The HTTP response headers, looked up case-insensitively, such as Retry-After |
response.is_success() is true when the API answers with a 2xx status and no errors, and neither of these applies:
- HTTP 206. Some values the API computes in the background, such as some counts, weren’t ready, so the API left them null. The rest of
datais filled in, so you can still use a 206 answer. Before you treat a response as failed, check whetherresponse.status_codeis 206 and readresponse.errors. - A failed background task. The answer’s
extensionsreport a background task that failed, was canceled, or ran out of credits.
To have the API wait up to 25 seconds for background values before it answers, the client adds the max_background_task_wait and max_call_duration query parameters to the URL. If ClientConfig.url already sets either one to a non-blank value, the client sends the URL as written and adds neither.
The shape of data
Section titled “The shape of data”searchreturns a list of entities.__typenamesays what each one is:Brand,LegalEntity,OperatingLocation,Person, orAddress.- A
Brandis a business as its customers know it, such as Chipotle. - A
LegalEntityis a company as a government registers it, such as Chipotle Mexican Grill, Inc. - An
OperatingLocationis one place where a brand does business, such as a store. - The data model describes them in full.
- A
- Related data comes as connections:
{"edges": [{"node": {...}}, ...]}. Each connection returns one page (see Paginate). - A question that names several businesses, people, or street addresses can get several searches, under the keys
search,search2, andsearch3ofdata(see Generate queries from questions). - A question that counts the businesses of a category, overall or in a place, as in “How many coffee shops are in Denver?”, gets
aggregate, an object of counts such aslocationsCountandbrandsCount. - Where a count of a brand’s locations appears depends on the strategy that writes the query (see Choose a strategy):
- From a template (
ServiceStrategy’s default, orTemplateStrategy): aslocationsCounton the brand insearch, with one search per brand (search,search2, and so on). - From
GenerativeStrategy, orServiceStrategy(query_strategy="generative"): aslocationsCountinaggregate, with oneaggregateper brand (aggregate,aggregate2, and so on).
- From a template (
GenerativeStrategy,ServiceStrategy(query_strategy="generative"), andAgentStrategyhave an LLM write the whole query, including its keys. With these strategies, read every key ofdata.
The client adds fields to what you asked for:
idand__typenameon the inline fragments (... on Brand { ... }) and connection nodes the query selects. The client skips:- An inline fragment that carries a directive, such as
@includeor@skip. - A connection node when the node or its
edgescarries a directive. - An entity selected only through a named fragment at the top of
search, as insearch(...) { ...BrandFields }.
- An inline fragment that carries a directive, such as
__url:- On each brand, legal entity, and operating location that has an
idand a__typename: a link to its profile in the Enigma Console. - On a person: a link to the brand the person appears under, or to Enigma’s website when the person appears under none.
- On each brand, legal entity, and operating location that has an
To get __url for a selection the client skips, select id and __typename in it yourself.
To send your query exactly as written, set auto_inject_id_and_typename=False. A query that selects a connection node with no id, such as the MediaContent nodes of isMentionedInMediaContents, fails unless you do.
With auto_inject_id_and_typename=False, a brand, legal entity, or operating location gets __url only when your query selects its id and __typename, and a person only when your query selects its __typename.
The GraphQL query in the quickstart returns:
{ "search": [ { "id": "825ce859-b742-49cb-9787-b9b32f674f25", "__typename": "Brand", "names": {"edges": [{"node": {"id": "000000d0-0003-cd02-0000-0a8000000000", "__typename": "BrandName", "name": "CHIPOTLE MEXICAN GRILL"}}]}, "websites": {"edges": [{"node": {"id": "0000002a-0010-60fa-0000-0a8000000000", "__typename": "Website", "website": "https://www.chipotle.com"}}]}, "__url": "https://console.enigma.com/profile/brand/825ce859-b742-49cb-9787-b9b32f674f25" } ]}Handle errors
Section titled “Handle errors”Errors reach you in these ways:
- When the SDK can’t generate a query,
client.search(prompt=...)raisesEnigmaClientException(see Generation errors). - An error status from the API doesn’t raise. It comes back in the response, so check
response.is_success(). - A network failure reaching the API or the hosted query service raises an
httpxexception (see API and network errors). - An Enigma API key or custom header value that an HTTP header can’t carry as written, such as one with a newline or a trailing space, raises
ValueError(see API and network errors).
import asyncioimport os
from enigma_api_client import Client, ClientConfig, EnigmaClientException
async def main(): config = ClientConfig(enigma_api_key=os.environ["ENIGMA_API_KEY"]) async with Client(config) as client: try: response = await client.search(prompt="List coffee shops in Denver") except EnigmaClientException as exc: print(exc.error_code, exc) return if not response.is_success(): print("HTTP", response.status_code, response.errors)
asyncio.run(main())The example prints the error message, which is useful while you develop. In production, log the exception type and error_code instead, because the message can quote values from the query.
Generation errors
Section titled “Generation errors”When the SDK can’t generate a query, client.search(prompt=...) raises EnigmaClientException, whose error_code is an EnigmaClientErrorCode.
With ServiceStrategy, the default, the code is always INVALID_QUERY, including when the hosted service fails with HTTP 401, 429, or 5xx. To tell these failures apart, read the exception:
- When the service answers with an error status,
exc.status_codeholds it andexc.headersholds its response headers. The message readsEnigma API returned HTTP <status>:followed by the start of its answer. - When the service answers with a GraphQL error, the message starts
Enigma API GraphQL error:. - Retry when the status is 429 or 5xx. When
exc.headers.get("Retry-After")gives a number of seconds, wait that long first.
For the preceding example, the message begins Enigma API returned HTTP 400 and explains that listing businesses by category is not supported.
Local strategies use these codes:
| Code | Meaning |
|---|---|
INVALID_QUERY |
The question or the generated query is unusable |
UNSUPPORTED_DATA_REQUESTED |
Enigma doesn’t serve what the question asks for, or the question needs a query the SDK refuses (see Generate queries from questions and GenerativeStrategy) |
GENERATE_QUERY_CALLBACK_NOT_CONFIGURED |
An LLM API key is missing, or the provider is misconfigured |
TRANSIENT_PROVIDER_ERROR |
The LLM provider timed out, rate limited the call, or failed with a 5xx error; retry with backoff |
PROVIDER_ERROR |
Any other LLM provider failure, such as HTTP 401 or 403. Retrying won’t help. |
AgentStrategy also raises PROVIDER_ERROR when the SDK has no API schema for your tier (see Schema checks and several tiers). In that case, a retry helps only if the schema fetch failure was temporary.
For a provider failure, exc.status_code holds the provider’s HTTP status when it reported one.
The SDK never raises RESTRICTED_DATA_REQUESTED or INVALID_VARIABLES; they exist for applications that enforce their own policies.
enigma_api_client exports two subclasses of EnigmaClientException, both with the code INVALID_QUERY:
TruncatedOutputError: the LLM hit its output limit. It happens again with the same model and question, so don’t retry with the same model.UnrepairedQueryError:GenerativeStrategyorAgentStrategywrote a query that failed the schema check even after repair. It carries.draft,.errors, and.tier, and you can pass it to anotherGenerativeStrategyasgenerate_query(prompt, prior_attempt=exc)to start from that draft. Its message quotes values from the generated query, so log the exception type anderror_coderather thanstr(exc).
Unavailable data
Section titled “Unavailable data”When a question asks for data Enigma doesn’t serve, the rest of the question is still answered, and response.unavailable_data lists what was left out, one entry per item:
field: what was left out.reason:contractualwhen your tier isn’t served the data, andout_of_scopeotherwise, for example when Enigma doesn’t have it.message: why.
“What is Chipotle’s annual revenue?” with a redistribution key returns the brand and this entry:
[{"field": "revenue", "reason": "contractual", "message": "Revenue and other card-derived financials are not served due to contractual restrictions."}]“Tell me about Chipotle, including any lawsuits against it” lists lawsuits as out_of_scope.
API and network errors
Section titled “API and network errors”- An error status from the API doesn’t raise. Check
response.is_success()andresponse.status_code, and see Response status codes. A 400 or 402 can mean the account has no credits left. - A 429 means you went over a rate limit. Wait at least the number of seconds in its
Retry-Afterheader,response.headers.get("Retry-After"), before you retry. Stop after a few retries, because a 429 can also mean you have used your daily limit. - A response body that isn’t a JSON object, such as a gateway’s error page, comes back with
dataset toNone, an error inerrors, and the body inraw_body, sois_success()is false. - An API key or header value an HTTP header can’t carry as written, such as one with a newline or a trailing space, raises
ValueErrornaming the header, before the API request is sent. - Network failures, from the API or the hosted query service, raise
httpxexceptions such ashttpx.TimeoutExceptionandhttpx.ConnectError.
Paginate
Section titled “Paginate”Each connection returns one page. To read every page, select pageInfo { hasNextPage endCursor } on the connection and send the same query again with after: set to the last endCursor:
import asyncioimport os
from enigma_api_client import Client, ClientConfig
QUERY = """query Locations($name: String!, $cursor: String) { search(searchInput: { name: $name, entityType: BRAND, conditions: { limit: 1 } }) { ... on Brand { operatingLocations(first: 100, after: $cursor) { edges { node { addresses(first: 1) { edges { node { fullAddress } } } } } pageInfo { hasNextPage endCursor } } } }}"""
async def main(): config = ClientConfig(enigma_api_key=os.environ["ENIGMA_API_KEY"]) async with Client(config) as client: cursor, addresses = None, [] while True: response = await client.search(query=QUERY, variables={"name": "Sweetgreen", "cursor": cursor}) if not response.is_success(): raise RuntimeError(f"HTTP {response.status_code}: {response.errors}") locations = response.data["search"][0]["operatingLocations"] for edge in locations["edges"]: for address in edge["node"]["addresses"]["edges"]: addresses.append(address["node"]["fullAddress"]) if not locations["pageInfo"]["hasNextPage"]: break cursor = locations["pageInfo"]["endCursor"] print(len(addresses), "addresses")
asyncio.run(main())- Start with
cursorset toNone. - Use
hasNextPageto decide whether more pages exist. A full page doesn’t mean there are more. - Keep the connection’s
firstandconditions(with itsfilterandorderBy) the same on every page, because a cursor is only valid for the arguments it came from. ClientConfig(auto_inject_page_info=True)addspageInfo { hasNextPage endCursor }to every connection that doesn’t already selectpageInfo, in every query the client sends, including generated ones.- Generated queries already select page info on:
- A brand’s affiliated brands (
Brand.affiliatedBrands) and a legal entity’s parent and subsidiary legal entities (LegalEntity.legalEntities).GenerativeStrategyandAgentStrategyadd this page info only once they have the API schema for your tier. - The government record pages, which a local strategy adds only once it has that schema (see Records and the API schema).
Brand.operatingLocations, in the template that lists a brand’s locations.registrationsInState, in the legal entity lookup, when it lists registrations in several states. The registrations of those states share one page.
- A brand’s affiliated brands (
- To read more pages of a generated query:
- Get the query with
generate_query. - Add
after: $cursorto the connection. - Declare
$cursor: Stringwith the query’s other variables, as the preceding example does. If the query declares no variables yet, add($cursor: String)after its name, or begin it withquery ($cursor: String) {when it has no name.
- Get the query with
rolesdoesn’t paginate (see Rules the API enforces at execution).