import os
from youdotcom import You
with You(api_key_auth=os.getenv("YDC_API_KEY"), timeout_ms=60_000) as you:
res = you.answer(query="What caused the 2008 financial crisis?")
print(res.answer)
That prints a markdown answer with inline [[1, 2]] citations. The sources behind
them are on the response:
for citation in res.citations or []:
print(citation.source, citation.excerpts)
Two things about that snippet worth knowing up front:
timeout_ms is doing real work. Without it, requests inherit httpx's 5
second default, and answer takes longer than that. See Timeouts.
The key is explicit here, but it doesn't have to be. Pass
api_key_auth=None, or omit it, to read YDC_API_KEY from the environment.
See Authentication for the resolution order.
The APIs
Every method is a direct call on You, and every one has an _async twin with
the same signature.
search() and answer() normalize their enum-typed parameters, so plain
strings work in any case. country="us" and safesearch="STRICT" are both
accepted. Elsewhere, pass the value as the API spells it (all lowercase) or
import the enum from youdotcom.models.
The snippets below assume the Quickstart client is in scope as you.
Answer
A synthesized answer with citations, grounded in live web results.
res = you.answer(
query="What are the tradeoffs of vector vs. keyword search?",
freshness="month",
safesearch="strict",
include_domains=["arxiv.org"],
)
res.answer # markdown, with inline [[n]] citations
res.citations # [AnswerCitation(source, excerpts)]
res.results.web # results used during synthesis
Search
Ranked web and news results.
res = you.search(
query="EU AI Act enforcement timeline",
count=10,
country="us",
freshness="week",
)
for hit in res.results.web or []:
print(hit.title, hit.url)
include_domains restricts results to an allowlist; exclude_domains and
boost_domains filter and re-rank. include_domains cannot be combined with
either of the others. The API returns 422 if you try. Search also supports
search operators.
Page content extraction
extraction is on by default: a plain you.search(query=...) sends
extraction_mode="highlights", so query-relevant excerpts land in
contents.highlights and snippets are omitted. Pass extraction=None
for a plain snippets-only search, or an Extraction object for either
mode. Two modes:
import os
from youdotcom import You
from youdotcom.models import Extraction, ExtractionFormat, ExtractionMode
with You(api_key_auth=os.getenv("YDC_API_KEY"), timeout_ms=60_000) as you:
# Query-relevant excerpts in `contents.highlights` (snippets are omitted).
res = you.search(
query="latest quantum computing breakthroughs",
extraction=Extraction(
extraction_mode=ExtractionMode.HIGHLIGHTS,
),
)
for hit in res.results.web or []:
print(hit.title, hit.url, hit.contents.highlights if hit.contents else None)
# Full HTML and/or Markdown in `contents.html` / `contents.markdown`.
res = you.search(
query="latest quantum computing breakthroughs",
extraction=Extraction(
extraction_mode=ExtractionMode.FULL_PAGE,
full_page={"extraction_formats": [ExtractionFormat.MARKDOWN]},
),
)
You can also pass a dict matching ExtractionTypedDict — the SDK
normalizes at the method layer. extraction replaces the deprecated
livecrawl / livecrawl_formats parameters. Passing both raises
ValueError, and top-level crawl_timeout is ignored (stripped from
the request body) when extraction_mode == "highlights". Unknown keys
inside extraction raise ValidationError locally, matching the
server's 422.
In full_page mode, the optional extraction_source field selects where
content comes from: "blend" (the default) serves cached content when
available and crawls the page live otherwise, "cache" returns cached
content only (contents is omitted for results with none), and "fetch"
always crawls the page live.
In highlights mode, the optional highlights object carries
total_max_tokens, capping highlight tokens across the whole response
(1024–8192 when set). Omit it for the provider's default; out-of-range
values raise ValidationError locally, mirroring the server's 422.
Knowledge results
knowledge is on by default: a plain you.search(query=...) sends
knowledge="core" and gets cards backed by licensed data providers —
encyclopedias, market-data firms, reference publishers — in their own
section. Pass knowledge=None to skip them.
import os
from youdotcom import You
with You(api_key_auth=os.getenv("YDC_API_KEY"), timeout_ms=60_000) as you:
res = you.search(
query="what is the capital of France",
knowledge="core",
)
if res.results:
for card in res.results.knowledge or []:
print(card.title)
print(card.description)
print([credit.name for credit in card.attribution])
"core" is the only value the API accepts; anything else raises
ValidationError locally, mirroring the server's 422. Results are limited
to those relevant to the query, up to 25, and when none are relevant the API
omits the section entirely — so results.knowledge is None rather than an
empty list. Iterate with or [].
count caps the web and news sections, not knowledge. Attribution entries
are credits rather than citations: each names a provider and carries no URL.
as_of, when present, is the YYYY-MM-DD date the card's underlying data
covers.
Extract
Clean Markdown or HTML for one web page or PDF, by URL. Use it when you already
have the URL; it replaces contents for new integrations.
import os
from youdotcom import You
with You(api_key_auth=os.getenv("YDC_API_KEY"), timeout_ms=60_000) as you:
page = you.extract(
url="https://arxiv.org/pdf/2310.06825",
full_page={"extraction_formats": ["markdown"]},
parse_effort="lite", # PDFs only: skip the per-page charge for text-based PDFs
)
if page.contents and page.contents.full_page:
print(page.contents.full_page.markdown[:500])
extraction_source picks where content comes from: "blend" (the default)
serves the cache and crawls on a miss, "cache" never crawls, and "fetch"
always crawls. timeout (2–100 seconds, default 30) bounds the whole request;
the SDK waits 10 seconds longer than it unless you set timeout_ms. When nothing
could be extracted, every field on the response is None. Errors raise
ExtractError; see Errors.
Contents
Clean HTML or Markdown for a list of URLs. For new integrations, prefer
Extract.
pages = you.contents(
urls=["https://example.com", "https://you.com"],
formats=["markdown"],
)
for page in pages:
print(page.url, page.title)
print(page.markdown)
formats accepts html and markdown. The metadata format is deprecated and will be removed in a future major release.
Use max_age to reject cached content older than a given number of seconds.
Research
Multi-step research with reasoning and cited sources. Higher effort levels run
more searches and take longer.
res = you.research(
input="Compare the unit economics of the major cloud providers",
research_effort="deep", # lite | standard | deep | exhaustive | frontier
)
print(res.output.content)
for source in res.output.sources or []:
print(source.url)
you.finance_research() is the finance-tuned counterpart, taking
research_effort of deep or exhaustive. Both research methods accept
output_schema for structured JSON output — the same schema works on both
endpoints, with every effort level on the finance side. (you.research()
accepts output_schema only with standard, deep, or exhaustive;
sending it with research_effort="lite" returns a 422.)
Deep and exhaustive runs can take minutes, and frontier runs far longer. For
anything beyond standard, use background mode.
Async
Every method has an _async variant. Use async with so both transports are
released on exit.
import asyncio
import os
from youdotcom import You
async def main():
async with You(api_key_auth=os.getenv("YDC_API_KEY"), timeout_ms=60_000) as you:
res = await you.answer_async(query="What is retrieval-augmented generation?")
print(res.answer)
asyncio.run(main())
Rather than holding a request open for minutes, background mode submits the task
and returns immediately. The helpers in youdotcom.research_helpers cover the
common shapes.
Submit and wait. Handles submission, streaming, and the final fetch:
from youdotcom.research_helpers import research_and_wait
detail = research_and_wait(
you,
input="Survey the state of solid-state battery commercialization",
research_effort="exhaustive",
)
print(detail.status, detail.result)
The wait is bounded automatically: 10 minutes for standard, deep, and
exhaustive, 4 hours for frontier. Pass timeout_s to override. It raises
TimeoutError if no terminal event arrives, and RuntimeError if the task ends
in a non-completed state.
from youdotcom.research_helpers import stream_research
for evt in stream_research(you, task_id=task.task_id):
print(evt.event, evt.data)
if evt.event in ("response.done", "complete", "completed", "error", "failed", "cancelled"):
break
stream_research() yields RawStreamEvent objects, whose .event is the raw
event name as a str and whose .data is the parsed JSON payload (or the raw
string when a frame is not valid JSON, which it tolerates). Since 3.1.2 both
methods tolerate event names outside the documented set — you.stream_research_task()
surfaces an unenumerated name as a plain str rather than raising — so the
remaining difference is which frames reach you: stream_research() yields
data-less frames (a bare event: ping heartbeat, or one carrying only
id:/retry:), whereas you.stream_research_task() silently drops them and
requires every frame to carry an id and a JSON-object data. Prefer
stream_research() when you need every frame, including keep-alives. Pass
from_id to resume a stream after a disconnect.
Each helper has an _async twin: research_and_wait_async,
research_background_async, poll_research_task_async, stream_research_async.
Authentication
The API key is sent as the X-API-Key header. How it's resolved:
api_key_auth
Behavior
omitted, or None
Reads YDC_API_KEY, then the legacy YOU_API_KEY_AUTH
a non-empty string, or a callable returning one
That key is used; no environment lookup
"" or blank, or a callable returning an empty string
Raises ValueError
Every endpoint requires a key, so an empty string is never valid. It means a key
was expected and none arrived. The SDK raises rather than reading the
environment, since falling back would run the request under whatever identity
the environment happens to hold instead of the one the code asked for.
In practice that shows up as os.getenv("YDC_API_KEY", "") with the variable
unset. Use os.getenv("YDC_API_KEY"). None is how you ask for the lookup.
A callable is resolved on each request, so it can return a rotating key.
Errors
Every API error subclasses YouError, which carries .message,
.status_code, .body, .headers, and .raw_response. The typed subclasses
below add a parsed .data.
from youdotcom.errors import (
PaymentRequiredResponseError,
UnauthorizedResponseError,
YouError,
)
try:
res = you.answer(query="...")
except UnauthorizedResponseError:
... # 401, bad or missing key
except PaymentRequiredResponseError as e:
print(e.data.message, e.data.upgrade_url) # 402, out of credits
except YouError as e:
print(e.status_code, e.body) # anything else from the API
Answer and search share one set of error classes; research, finance research,
contents, and the task endpoints each raise their own, so you can catch a 422
from research without catching one from search.
Extract raises one class, ExtractError, for every error the Extract API
returns (402, 422, 500, 502, 503, 504). Branch on its stable code
(invalid_url, pdf_too_large, site_blocked, timeout, ...), and check
retryable; see ExtractError for the codes.
401, 403, and a 402 answered by the API gateway raise the shared
UnauthorizedResponseError, ForbiddenResponseError, and
PaymentRequiredResponseError.
import os
from youdotcom import You
from youdotcom.errors import ExtractError
with You(api_key_auth=os.getenv("YDC_API_KEY"), timeout_ms=60_000) as you:
try:
page = you.extract(url="https://example.com/report.pdf")
except ExtractError as e:
print(e.code, e.retryable, e.request_id)
Two errors sit outside that table: ResponseValidationError when a response
doesn't match its model, and httpx.RequestError (and subclasses) for transport
failures such as connection resets and timeouts.
Configuration
Retries
The SDK does not retry by default. Opt in per call or for the whole client:
import os
from youdotcom import You
from youdotcom.utils import BackoffStrategy, RetryConfig
retries = RetryConfig(
"backoff",
BackoffStrategy(initial_interval=500, max_interval=10_000, exponent=1.5, max_elapsed_time=60_000),
retry_connection_errors=True,
)
with You(api_key_auth=os.getenv("YDC_API_KEY"), retry_config=retries, timeout_ms=60_000) as you: # whole client
res = you.search(query="...", retries=retries) # or one call
Retries apply to 429, 500, 502, 503, and 504, except on extract, which
doesn't retry 502: that status means the page itself can't be extracted.
Timeouts
Set one. With no timeout_ms, requests inherit the underlying httpx client's
default of 5 seconds, which is far too short for answer, research, and
finance_research. Those endpoints routinely take tens of seconds, so a call
without a timeout will raise httpx.ReadTimeout before the API responds.
timeout_ms applies to the whole client or to a single call:
import os
from youdotcom import You
with You(api_key_auth=os.getenv("YDC_API_KEY"), timeout_ms=60_000) as you:
answer = you.answer(query="...") # inherits 60s
results = you.search(query="...", timeout_ms=10_000) # this call only
Search and contents are fast enough for the default. Extract sets its own: with
no timeout_ms, it waits 10 seconds longer than its timeout parameter
(default 30), so the API's own timeout error arrives first. Research in background mode
is the exception: the helpers under
Long-running research manage their own deadlines, so
timeout_s there bounds the wait rather than timeout_ms.
Attribution
Every SDK request emits an X-Client-Info header so the analytics layer can
split SDK traffic from MCP traffic. The wire format is:
The leading sdk token names the channel, matching the mcp and skill
tokens other You.com surfaces emit. The calling language stays recoverable
from ua= (python/… here, node/… from the TypeScript SDK), and the SDK's
own version travels in the User-Agent (youdotcom-python-sdk/<version>).
Identify your application with app_name / app_version, which populate the
client= segment, and optionally app_title / app_url:
import os
from youdotcom import You
with You(
api_key_auth=os.getenv("YDC_API_KEY"),
app_name="acme-bot",
app_version="2.4.0",
app_title="Acme Bot",
app_url="https://acme.example",
timeout_ms=60_000,
) as you:
res = you.search(query="...")
All four are optional and keyword-only; existing call sites are unaffected.
When app_name is
unset the client= segment is dropped entirely, so a request from an
undeclared caller is simply sdk; ua=python/… httpx/….
Values must be printable ASCII excluding ;, and app_name / app_version
additionally exclude / since they are joined as <name>/<version>. Passing
app_version without app_name is an error, since a bare version has nowhere
to go. Invalid values raise ValueError at construction time.
The MCP-specific X-MCP-Attribution header is never set by the SDK — it is
assembled on the MCP server, which is the only layer that can populate its
keyless / payment / ip flags accurately.
Servers
search, contents, and extract go to https://ydc-index.io. Everything else goes to
https://api.you.com: answer, research, finance_research, and the research
task endpoints. The SDK routes each call for you. To point one call
elsewhere, at a proxy or a test server, pass server_url to the method:
res = you.search(query="...", server_url="http://localhost:18080")
The constructor's server_url sets the default host, which affects the
api.you.com endpoints. Because search, contents, and extract have their own
per-operation default, they are unaffected by it; override those per call.
Custom HTTP client
Pass any httpx.Client / httpx.AsyncClient to control proxies, TLS, custom
headers, or connection limits:
import os
import httpx
from youdotcom import You
http_client = httpx.Client(proxy="http://localhost:8030", headers={"x-team": "search"})
with You(api_key_auth=os.getenv("YDC_API_KEY"), client=http_client) as you:
...
http_client.close() # a transport you supply is yours to close
You can also pass anything satisfying the HttpClient / AsyncHttpClient
protocols in youdotcom.httpclient to wrap requests with your own logic. Note
that a transport you supply is yours to close. The SDK only closes the ones it
creates.
Resource management
You holds open connections and has no public close(), so use it as a context
manager. Both transports are released on exit.
import os
from youdotcom import You
with You(api_key_auth=os.getenv("YDC_API_KEY")) as you:
...
# or: async with You(api_key_auth=os.getenv("YDC_API_KEY")) as you:
An instance is not reusable after the block exits, including for calls of the
other flavor. Use one instance per sync/async flavor.
Debug logging
Set YOU_DEBUG=1 for request and response logging, or pass your own logger:
import logging
import os
from youdotcom import You
with You(api_key_auth=os.getenv("YDC_API_KEY"), debug_logger=logging.getLogger("youdotcom")) as you:
...
Authorization, X-API-Key, Cookie, and Set-Cookie are redacted. Request
and response bodies are not, and may carry sensitive data. Don't enable debug
logging in production, and don't commit debug logs to version control.
Documentation
API reference: endpoints, parameters, response schemas
Starts the Go mock server, sets up a virtualenv, runs the suite, and cleans up.
Pass --cleanup to remove the virtualenv afterwards. See
tests/README.md for running pieces of it directly.
Drift detection
This SDK is hand-maintained rather than generated, so scripts/check_drift.py
enforces what code generation used to guarantee: it diffs the published OpenAPI
specs against the SDK surface (endpoints, server URLs, enum values, request
parameters, response fields) and runs on every PR plus weekly.
Python SDK for Firecrawl: search, scrape, parse, crawl, map, and interact with the web, run Agent and Monitor jobs, and search scientific papers (PubMed, bioRxiv, medRxiv, arXiv)