SDKs
Python SDK
The sproutsdata package for Python: sync and async clients for every Sprouts Data API call, with typed models, paging, retries, typed errors and tools for AI models.
sproutsdata is the official Python client for the Sprouts Data API. It has a sync client and an async one with the same methods, returns typed pydantic models, follows cursors for you, retries what is safe to repeat, and raises typed exceptions for error answers.
Install#
pip install sproutsdataThe SDK needs Python 3.11 or newer. It depends on httpx and pydantic 2. The LangChain adapter is a separate package: see LangChain.
Create a client#
import os
from sproutsdata import SproutsData
client = SproutsData(api_key=os.environ["SPROUTS_API_KEY"])Use the client as a context manager, or call client.close(), to release its connections. Nothing is sent until the first call.
| Argument | What it sets | Default |
|---|---|---|
api_key | Your API key, sk_dsp_live_…. | The SPROUTS_API_KEY environment variable |
base_url | The API's address. Must be https://. | SPROUTS_BASE_URL, else the production API |
timeout | Seconds to wait for each answer. | 60.0 |
max_retries | Retries after the first attempt, where repeating is safe. | 2 |
default_headers | Headers sent on every call. The SDK's own headers, Origin and Referer are refused. | None |
http_client | Your own httpx client. It must not follow redirects, and the SDK leaves it open. | The SDK's own |
on_response | Called with the ResponseInfo (status, request id, rate limit, headers) of each success. | None |
A missing or malformed key, or a retired sk_dsp_test_ key, raises ClientValidationError. Every method also takes request_id and timeout, and billed and keyed methods take idempotency_key. client.with_options(timeout=..., max_retries=..., default_headers=..., on_response=...) returns a client with other settings over the same connections, for one call or a group of calls.
Async#
AsyncSproutsData takes the same arguments and has every method, awaited. Its iter_* methods are async generators:
import asyncio
import os
from sproutsdata import AsyncSproutsData
async def main() -> None:
async with AsyncSproutsData(api_key=os.environ["SPROUTS_API_KEY"]) as client:
page = await client.search(query="fintech companies in Germany")
print(page.total)
async for hit in client.iter_search(query="fintech companies in Germany", max_results=100):
print(hit.id)
asyncio.run(main())Search#
page = client.search(
query="payments companies in Germany with 500 to 5000 staff",
category="company",
mode="auto",
limit=10,
)
floor = "+" if page.total_is_estimate else ""
print(f"{page.total}{floor} matches, {page.meta.credits_charged} credits")
for hit in page.results:
record = hit.model_extra or {}
print(hit.id, record.get("account_name"), record.get("domain"), hit.score)- A row is a pydantic model with
id,categoryandscore; the record's own fields are inhit.model_extra. categoryiscompany(the default),person, a document category (patent,academic_report,news_article,market_report,trend,funding_round,job_opening) orauto.modeisauto(the default), which turns the words into filters and is billed as an AI search, orfast, billed as a basic search. See Search.- Company and person searches take
filtersasDiscoverFiltersor a mapping with the same keys; each document category takes its own model. The filter and sort models are insproutsdata.types:
from sproutsdata.types import DiscoverFilters, RangeFilter, SortClause, TermsFilter
page = client.search(
query="payments",
filters=DiscoverFilters(
industry=TermsFilter(include=["Software & Technology"]),
employee_count=RangeFilter(gte=500, lte=5000),
),
sort=[SortClause(field="employee_count", direction="desc")],
)A request the API would refuse is refused locally with ClientValidationError, naming the field, before anything is sent.
similar(anchors=[...], combine=..., filters=..., limit=...) finds look-alike companies. An anchor is a domain string or a mapping with value, by and weight.
Paging#
Each iter_* method follows next_cursor for you and yields rows, not pages. max_results caps how many it yields:
for hit in client.iter_search(query="fintech companies in Germany", max_results=200):
print(hit.id)The paged calls and their iterators: iter_search, iter_similar, iter_filter_values, iter_document_filter_values, relationships.iter_find, relationships.iter_reach, org_chart.iter_people, runs.iter_list, runs.iter_results, enrichment.iter_list, enrichment.iter_results, lists.iter_items, history.iter_list, feedback.iter_list and credits.iter_transactions. To page by hand, send next_cursor back as cursor= with the same arguments. See Pagination.
Vocabularies and coverage#
These calls are free:
filter_values(name, search=..., page=...)anddocument_filter_values(category, name, search=...): the values a filter accepts.sorts(category): the fields a category can be sorted by.coverage(category=..., segment=...): what the index holds;report.total_for("company")reads one total.
Record lookup#
client.entities has one method per category: companies, persons, patents, trends, academic_reports, news, market_reports, fundings and job_openings. Each takes the identifiers as its first argument.
lookup = client.entities.companies(["stripe.com", "adyen.com"], by="domain")
for value in lookup.missing():
print("not found:", value)
stripe = lookup.get("stripe.com")
if stripe is not None and stripe.found:
for company in stripe.records():
print(company.model_dump(exclude_none=True))by defaults to "auto" on every lookup; pass by="id" for record ids. hit.lookup_ref() turns a search row into a LookupRef with category, by and value, the identifier to look it up by. A person row's id is not a lookup key.
Relationships and org charts#
client.relationships answers who connects to whom:
find(...)anditer_find(...): people who connect two companies (relation="between_companies"), or a company and named institutions (via_institution), or a question in words (query=).reach(person=..., target_company=...)anditer_reach(...): whom one person, named by LinkedIn URL, can reach at a company.institutions(companies=[...]): the employers and schools two companies share.ask(query=...): any of these, asked in words.queryis keyword-only.
connected = client.relationships.find(
relation="between_companies",
companies=[{"value": "stripe.com", "by": "domain"}, {"value": "adyen.com", "by": "domain"}],
)
for person in connected.results:
print(person.full_name, [via.name for via in person.via])client.org_chart counts one company's people, named by exactly one of domain, linkedin_url or company_ref: retrieve (the department and seniority grid), departments, locations, people and iter_people (who one cell counts), and the free taxonomy(). Filters go in filters=; the org chart's retired keyword arguments are refused with the name of their replacement.
from sproutsdata import OrgChartCompanyAmbiguousError
try:
chart = client.org_chart.retrieve(domain="stripe.com")
except OrgChartCompanyAmbiguousError as exc:
print([candidate["company_ref"] for candidate in exc.candidates])
else:
for cell in chart.cells:
print(cell.department.label, cell.seniority.label, cell.count)Agent runs#
client.runs starts an agent run and reads it. A run needs a key with dsp.agents.write.
handle = client.runs.create(
query="Series B fintechs in the Nordics with an in-house ML team",
effort="standard",
)
run = client.runs.wait(handle.run_id)
if run.status == "completed":
for row in client.runs.iter_results(run.run_id):
print(row.get("account_name"), row.get("domain"))effortisquick,basic,standard(the default),detailed,maximumorauto. The earlier names are still accepted.createstarts a new run every time: the API reads no key on a start. It is retried only when it surely never ran; when it may have (a500, a504, no answer), it raises, and you checkruns.list()before starting again.wait(run_id, poll_interval=3.0, max_wait_seconds=900.0)polls until the run iscompleted,failedorcancelled, and returns it. Pastmax_wait_seconds(Nonewaits indefinitely) it raisesWaitTimeoutError, whoselastis the last state seen; the run goes on.events(run_id)yields the run's server-sent events.retrieve,list,iter_list,cancelandresultscomplete the set. See Agent runs.- While a run goes,
resultsanditer_resultsserve the rows checked so far and stop there; resume later with the page'snext_cursor. A run cancelled after a read that returned rows is charged its tier.
Contact enrichment#
client.enrichment finds work emails and phone numbers for people. Starting needs dsp.enrichment.write; reading needs dsp.enrichment.read.
people = [
{"full_name": "Jane Doe", "company_domain": "stripe.com", "external_id": "crm-1"},
{"linkedin_url": "https://www.linkedin.com/in/jane-doe-example", "external_id": "crm-2"},
]
found = client.enrichment.lookup(items=people, fields=["EMAIL"])
for row in found.results:
print(row.outcome, row.fields["EMAIL"].value)
handle = client.enrichment.create(items=people, fields=["EMAIL", "PHONE"], name="Prospects")
job = client.enrichment.wait(handle.job_id)
for row in client.enrichment.iter_results(handle.job_id):
print(row.idx, row.outcome)lookup answers up to 20 people in the call; create starts a job for more, and wait polls it for up to 30 minutes by default. Only values newly found are charged. See Contact enrichment.
Lists and exports#
from sproutsdata import ExportFile, ListNameTakenError
try:
saved = client.lists.create(name="Fintech targets", category="company")
except ListNameTakenError:
saved = next(each for each in client.lists.list().results if each.name == "Fintech targets")
client.lists.add_items(saved.id, items=[{"category": "company", "id": "stripe.com"}])
result = client.lists.export(saved.id)
if isinstance(result, ExportFile):
csv_text = result.csv
else:
client.exports.wait(result.job.job_id)
csv_text = client.exports.download(result.job.job_id)client.lists:list,create,rename,delete,items,iter_items,add_items,remove_itemsandexport. A request adds or removes up to 1,000 items.client.search_export(items=[...])exports rows a search returned.- An export answers
ExportFile(the CSV at once) orExportJob(a job to wait for and download). See Lists and exports.
Credits, usage and feedback#
These calls are free.
wallet = client.credits.retrieve()
print(wallet.available, wallet.reserved, wallet.status)
if not wallet.can_afford(10):
print("not enough credits")
quote = client.credits.quote(operation="agent_run", effort="detailed")
for entry in client.credits.iter_transactions(max_results=20):
print(entry.created_at, entry.kind, entry.credits)client.credits:retrieve,quote,transactionsanditer_transactions.client.history:listanditer_list(past calls, filtered byaction_type,from_andto),retrieve(run_id)(one call in full; the id is a string) andmetrics(from_=..., to=...).client.feedback:create(target=..., subject_ref=..., tags=..., expected=...),list,iter_list,tags, andvotes.cast(request_id=..., level=..., vote=..., entity_category=...)/votes.list(request_id=...).
Credits are bought in the dashboard, not through the API.
Errors#
Every exception is a SproutsDataError. An error answer from the API raises an APIStatusError subclass with status_code, code, title, detail, next_step, request_id, retry_after and body. Branch on exc.code, then on the class, and log request_id.
from sproutsdata import (
APIStatusError,
AuthenticationError,
InsufficientCreditsError,
RateLimitError,
)
try:
page = client.search(query="fintech companies in Germany")
except InsufficientCreditsError as exc:
print("need", exc.required_credits, "have", exc.available_credits)
except RateLimitError as exc:
print("rate limited; retry after", exc.retry_after, "seconds")
except AuthenticationError as exc:
print("key refused; request id:", exc.request_id)
except APIStatusError as exc:
print(exc.status_code, exc.code, exc.detail, exc.request_id)| Exception | When |
|---|---|
ClientValidationError | Refused before sending. Also a ValueError. |
APIConnectionError, APITimeoutError | No answer arrived. reached_server says whether the request may have arrived anyway. |
AuthenticationError | 401: the key is missing, unknown, revoked or expired, or was sent from a browser. |
PermissionDeniedError, WorkspaceRequiredError | 403: the key lacks the scope this call needs. |
InsufficientCreditsError, WalletFrozenError | 402: the workspace cannot pay. Never retried. |
InvalidRequestError | 400 or 422. Subclasses: OrgChartCompanyAmbiguousError, CursorInvalidError, CursorExpiredError, PaginationDepthExceededError. |
NotFoundError, ResultsExpiredError | 404, or 410 when a run's or job's rows are no longer kept. |
ConflictError, ListNameTakenError | 409. |
RateLimitError, ConcurrencyLimitError | 429. A concurrency limit is never retried. |
FeatureNotAvailableError | 501: the API cannot do this yet. |
ServiceUnavailableError, CreditsRefusedError | 503: nothing ran and nothing was charged. |
UpstreamTimeoutError | 504 from the API: the work did not finish in time. |
GatewayError | 408, 502 or 504 from a gateway in front of the API: whether the work ran is unknown. |
InternalServerError | 500. |
APIResponseValidationError | A success answer the SDK could not read. |
WaitTimeoutError, ExportFailedError | A wait gave up (last holds the last state), or an export job failed. |
See Errors for the codes.
Retries and timeouts#
- What is retried depends on what repeating the call costs. A call that provably never arrived is retried. Billed reads (search, look-alikes, lookups, relationships, org charts), the enrichment calls and
feedback.createcarry an idempotency key, so one that may have arrived without an answer is retried with the same key: the API charges it once and starts nothing twice.runs.createtakes no key, so it is not repeated once it may have arrived.lists.createandlists.deleteare not repeated once they may have arrived; their error hasreached_server=True. - How: up to
max_retries(default 2), with exponential backoff and jitter from 0.5 to 8 seconds. ARetry-Afterof up to 60 seconds is waited in full; a longer one is raised at once, with the value onretry_after. - Never retried: 400, 401, 402, 403, 404, 409, 422 and 501 answers, among others.
- Timeouts: 60 seconds for each answer, 10 seconds to connect.
- Waits:
runs.waitandexports.waitgive up after 900 seconds by default,enrichment.waitafter 1,800.
Tools for AI models#
sproutsdata.tools gives a model three tools, sprouts_search, sprouts_similar and sprouts_entity_lookup, with the same schemas and results as the MCP server's search, similar_companies and record_lookup tools. It builds tool definitions for OpenAI and Anthropic and runs the calls a model makes, without importing either provider's SDK.
from sproutsdata.tools import Toolset
tools = Toolset(client, max_results=10)
openai_tools = tools.openai() # or tools.openai(api="responses")
anthropic_tools = tools.anthropic()
result = tools.run("sprouts_search", {"query": "payments companies in Germany"})handle_openai_tool_calls(message) and handle_anthropic_tool_use(message) run every tool call in a model's reply and return the messages to send back. What a model can fix comes back to it as {"error": {...}}; a rejected key, a missing scope or a lack of credits is raised. AsyncToolset does the same over AsyncSproutsData.
Pydantic AI, the OpenAI Agents SDK and LlamaIndex each take a tool defined by a JSON Schema, so sproutsdata.tools serves them directly.
LangChain#
pip install langchain-sproutsdataimport os
from langchain_sproutsdata import SproutsDataRetriever, sproutsdata_tools
tools = sproutsdata_tools(api_key=os.environ["SPROUTS_API_KEY"])
retriever = SproutsDataRetriever(api_key=os.environ["SPROUTS_API_KEY"], k=5)sproutsdata_tools() returns the three tools as LangChain tools, sharing one sync and one async client. It takes client and async_client, or api_key, base_url, timeout and max_retries, plus include, fixed, defaults, max_results (1 to 25) and baseline_filters. SproutsDataRetriever returns search results as LangChain documents, with the whole row under metadata["record"].