Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Epoch SDK core contracts

This Python implementation lives in the public, multi-language EpochSDK repository. contracts/openapi.json at the repository root is the shared API contract for every language client and MCP. Backend owns native REST APIs, controllers, persistence and StratifyX generation; service repositories own server graphs. The stateful adapter calls the existing EpochAI supervisor through LangGraph SDK; it does not import the conversation application's Python code.

Python 3.12 is the first client implementation. The package name is epoch-sdk and its import is epoch_sdk. It supplies executable contracts, an access checker, output-value validation and the supervisor/MCP adapter. The adapter handles native communication, execution selection and explicit saved-output reads. Research publishes a saved answer with named table, JSON and text parts. Prepared-study execution remains a separate direct Backend operation. Readable operation IDs let notebook and explicit workflow-MCP clients attach after disconnecting.

The v1 API: one URL and an API key

Epoch calls Epoch's public v1 API. It needs only an API key, read from EPOCH_API_KEY (and EPOCH_API_URL when set). Each method is one v1 operation, plus wait and rows, which repeat reads for you. Calls that start work send an Idempotency-Key, so a retried call attaches to the work it already started. Answering questions and saving a dataset are sent once, because the server does not deduplicate them: if a reply is lost, read the research or dataset again.

Install it from PyPI. Its StratifyX and source-connection dependencies come with it:

pip install "epoch-sdk>=0.1.0a40"
from epoch_sdk import Epoch

epoch = Epoch()
research = epoch.research.create(
    task="Compare MSFT and SPY volatility in 2025.",
    outputs=[{"name": "summary", "type": "text", "instructions": "Explain it briefly."}],
)
research = epoch.research.wait(research.id)  # until it finishes or asks a question
if research.status == "completed":
    ref = research.result.response
    answer = epoch.responses.get(ref.id, version=ref.version)

In a terminal or a notebook, wait prints the research's log as it works: a line for each finished step, with the step in progress as the last line and a running timer. These are the same lines the API Playground shows and the epoch CLI prints. In a terminal they go to stderr, so your own output stays clean:

research · req_7b375f4da93c9b5bcb14b6c874832fc4
00:00  ✓  Question received
00:04  ✓  Search dataset
00:50  ✓  Built MSFT and SPY volatility in 2025                           38.0s
01:12  ✓  Ran MSFT and SPY volatility in 2025                             18.1s
01:14  ✓  Answer saved · rsp_cbf5d11e1eb4 · version 1
          Finished in 1 min 15 s

log=False turns it off, log=True prints it anywhere (finished lines only, without colour, when nobody is watching) and a file object receives it instead. NO_COLOR is respected. executions.wait logs a run the same way, from reading it. See the notebook.

research.events(id) streams progress and resumes after the last event if the connection drops; stopping never cancels the research. research.answer, executions.create/wait, responses.table/rows, files.upload and datasets.prepare/save cover the other v1 operations. Failures raise EpochApiError (an EpochError) with the API's status, code and request id. The direct EpochClient below remains for Epoch's own apps (ENG-2520 tracks moving it onto v1).

Sign in through your browser

Instead of an API key, people can sign in once from the command line:

epoch login     # opens your browser; --no-browser prints the link instead
epoch logout    # revokes the sign-in and removes it from this computer

epoch login signs in to the API in EPOCH_API_URL (or --api-url). Each API publishes where to sign in (RFC 9728 protected resource metadata at /.well-known/oauth-protected-resource), so the API URL alone picks the right environment's user pool. To sign in elsewhere, set both EPOCH_SIGN_IN_DOMAIN and EPOCH_SIGN_IN_CLIENT_ID (or --sign-in-domain and --client-id). It keeps only the sign-in's refresh token: in your system keychain with the keychain extra installed (pip install "epoch-sdk[keychain]"), otherwise in ~/.config/epoch/credentials.json, which only you can read. Set EPOCH_CREDENTIAL_STORE=file to always use the file. No token is printed.

Afterwards Epoch() with no API key uses the sign-in. It gets short-lived Epoch access tokens for the v1 API and renews them as they expire. When the sign-in ends, run epoch login again. The direct EpochClient still takes a token; it gains the sign-in when it moves onto v1 (ENG-2520).

One research session

Install the notebook or terminal presentation extra and use:

result = await epoch.run(request, operation_id="msft-quality-2025")

The SDK renders live Epoch activity, collects explicit replies, resumes the same native checkpoint and displays the saved answer once. The returned result stays ordinary Python data. await epoch.run(operation_id="msft-quality-2025") reconnects after a kernel/process restart. The explicit workflow MCP consumes that same headless session core; the default composable MCP uses the separate specialist interface. See interactive sessions.

Renewing tokens on a server

EpochClient.connect and SupervisorClient.connect take token as a string, or as a function (async or plain) that returns the current token:

client = EpochClient.connect(graph_url=graph, backend_url=backend, token=delegated_tokens.current)

The SDK reads the token for every graph, Backend and document request. A stream that is already open keeps the token it started with, so renewal never interrupts it. The token goes only to the graph and Backend hosts. Connect once per user and request, and never share a provider between users. A string token behaves as before.

SDK workflows and composable MCP

Notebook and terminal callers keep EpochClient.run, execute, resume, status and read for the research/published-answer workflow.

The default MCP exposes composable tools, including two specialist interfaces: epoch_inspect_source and epoch_build_study. Codex or Claude chooses the sequence and answers directly. Native data lookup and source inspection make no generative model call; exact retained source references can be reused across studies. Only explicitly selected study authoring or a program's declared llm_call invokes a model. The retired audit specialist and model-facing response-inspection/publication/dashboard-editor chain are not available. No Epoch supervisor or publication is required by the default MCP.

Public web sources and Build dataset

The usual entry is a question. Exa discovers relevant URLs and reads their page content; callers do not need to know the URLs beforehand. Review the returned source list and retained text, then use the same preparation lifecycle as documents to choose fields and save a table or JSON.

from stratifyx.types import WebResearchRequest

research = await tools.start_web_research(WebResearchRequest.model_validate({
    "request_id": "python-release-review-1",
    "input": {"kind": "search", "query": "Python 3.13.0 official release date"},
    "content": {},
}))
# Poll this exact reference until ready; no repeat search is needed.
research = await tools.web_research(research.read_ref)
for source in research.sources:
    print(source.url, source.state)
    if source.state == "read":
        page = await tools.read_web_source(source.source_ref)

Search optionally accepts include_domains for hostname/path limits. When particular pages were supplied, input kind="pages" accepts urls and an optional question; it skips discovery. The single-URL input remains supported. content.snapshot_as_of requests a UTC historical cutoff, while discovery still uses current search ranking. Never combine it with max_age_hours. A missing historical page is unavailable, not evidence that its facts did not exist.

prepare_web_dataset takes the generated DatasetBuildRequest with input {"kind":"web_read","read_ref":research.read_ref} and a reviewed schema. Use document_preparation and act_document_preparation for the shared status/review/recovery lifecycle. Build creates an unsaved preview; explicit Save publishes reusable data; acquisition never replaces the schema editor or saves a dataset by itself. Saved evidence includes exact source references, SHA-256 digests, quotation text and UTF-8 byte offsets. read_web_source reopens retained bytes without another provider call.

The equivalent MCP entry points are epoch_start_web_research, epoch_web_research, epoch_read_web_source, epoch_act_web_research and epoch_prepare_web_dataset. Explicit acquisition/extraction uses the configured EpochAI origin; all retained reads and saved outputs use native Backend ownership.

For supported completed results, application/notebook and MCP clients share the same native extension methods:

  • extension_inputs(execution_id, tables=[...]) reads exact types, flat enum references and the frozen executed source. It returns metadata, not sample rows.
  • save_extension(thread_id, source_execution_id=..., tables=[...], source=..., name=..., description=...) compiles and saves supplied EpochScript as an immutable definition. This call uses no authoring model and runs no study.
  • execute_extension(CreateSdkExecutionRequest(...)) starts or attaches one operation. Supply the saved extension's study_id, the original source_execution_id, explicit input_tables, parameters={} when no engine period is needed, and a readable operation_id for reconnecting.
  • extension_status(operation_id) only reads that operation. The original and derived execution IDs remain separate. Numerical status is distinct from response_phase; confirmed declared destinations appear in extension_outputs.
  • response(response_id, version=...), response_table(...) and extension_presentation(pin) read exact saved outputs. Presentation edit zero is a real pin; it is never replaced by a latest-version lookup.

MCP exposes epoch_extension_inputs, epoch_save_extension and epoch_execute_extension over these same methods. Use epoch_status with kind="extension" and operation_id. Use epoch_read with kind="response" and its answer revision (optionally table, offset, page_size), or kind="presentation" with the returned publication/catalog/edit pin.

The calling coding agent can author the program itself. Tables, JSON and native reporters calculate directly in Backend. An explicit llm_call returns text that response_text, Markdown or executive_summary can consume independently or together, sharing one bounded cached generation. There is no supervisor, vendor query or original-study rerun when using explicit input_tables. A response table does not force a matching dashboard table, and dashboard-only work creates no artificial answer. An unsupported source/type remains an explicit capability error.

New SDK research can author its calculations, requested text and native output sinks in one ordinary study. Backend completes those outputs after calculation; the supervisor does not publish again. An explicit saved-input report is used for later work over an earlier completed execution, including numerical analysis of finalized trading results. An accepted single-text SDK request with no computation can instead complete from its ordinary final reply automatically. This does not replace missing computed outputs or a failed native publication.

An ordinary ResearchCompleted.reusable_study retains its actual completed source identity. execute/execute_saved reuse the saved definition with the requested period, captured actual simulation settings and declared parameter bindings. An explicit execution override retains ordinary override semantics. Required output completion and answer pins are observed through the same native operation. No report template or extra permission flag is invented.

ResearchCompleted.reusable_study retains a native report_template for an original-plus-report result. execute/execute_saved with that reference run a new original and its frozen report once, without a supervisor. The original job and report child have distinct IDs; response/presentation pins belong to the report. Native MCP replay uses epoch_execute_extension with report_template instead of input_tables. Period changes require captured permission; costs and declared original parameters remain captured. Response-plan attachment, APIs and replay are retired (ENG-3105); existing saved answers remain readable directly without replay.

The current package requires the normal generated native >=3.3.0rc41,<4 package, including Backend-owned research-to-extension links and report replay. Controlled transport checks and real service/notebook/MCP/ClientPortal acceptance are distinct evidence; historical milestone records do not prove a newer build.

See the public interface for the 12 tools, service boundaries and upgrade instructions. The old workflow MCP is retained only as python -m epoch_sdk.workflow_mcp.

Use the actual core contract

RunRequest, IngestRequest, fresh/cursor fetch, refresh, acceptance and errors are executable Pydantic models. They reject unknown fields and type coercion, validate exact output/column names, and preserve descriptions and standard JSON Schema. These models preserve the earlier draft API's domain-error envelope. The current supervisor adapter exposes native clarification as NeedsInput and supports answering/resuming the same thread. The earlier terminal-only design is superseded; the draft contract is being reconciled with this direction.

../../contracts/openapi.json contains the shared request/error models, historical illustrative /v1 bindings, and source-owned native /api/v1/integration operation projections. Native schema names have a Native_ prefix and identify the original Backend DTO. The wrapper calls the existing Backend and LangGraph origins.

The draft had omitted the agreed saved-study reference and execution parameters. RunRequest now permits either study_id or source_execution_id, with optional parameters.period and parameters.execution. These use the generated StratifyX DatePeriodConfig and ExecutionOptions models and Backend's own wire schemas; arbitrary named parameters or another study id inside parameters are rejected. Resolve omitted defaults/relative dates before freezing the Backend binding. Refresh can use those same supported parameter types; changing study logic is a new definition/revision, not an ordinary refresh.

from epoch_sdk import RunRequest
from epoch_sdk.parsing import parse_request

request = parse_request(RunRequest, '''{
  "task": "Compare annual sales for the approved company dataset in 2024",
  "outputs": [{
    "name": "annual_sales",
    "type": "table",
    "schema": [
      {"name": "year", "type": "int64", "description": "Calendar year"},
      {"name": "sales", "type": "float64", "unit": "USD"}
    ]
  }],
  "parameters": {"period": {"start": "2024-01-01", "end": "2024-12-31"}}
}''')

This example parses a declaration. Submit it with await epoch.research(request, operation_id="annual-sales") using an EpochClient connected to the two services. Malformed declarations fail before a service call. Research builds/analyses through the supervisor and returns a saved answer; execute_saved starts or attaches to a prepared study execution. See the current flow.

Verify locally

Install the reviewed native StratifyX wheel through its existing package workflow, then install python/epoch-sdk[mcp,terminal,notebook,test] in your isolated Python environment. Never edit or vendor the generated StratifyX models. From the repository root:

python3 tools/sync_native_parameters.py --check
python3 tools/check_python_contracts.py
python3 tools/validate_saved_output_contract.py
python3 -m pytest python/epoch-sdk/tests

tools/sync_native_parameters.py checks the packaged snapshot against the shared native parameter contract. Its optional --backend-openapi input refreshes from a reviewed Backend export; no Backend checkout is needed for ordinary client checks. tools/check_python_contracts.py checks Python conformance without rewriting the shared contract. Standard JSON Schema 2020-12 and local references are supported; remote schema references are never fetched.

See shared dataset review for agent configuration, explicit result decisions, notebook/terminal input and MCP continuation.

Check real API availability

Install the clients extra and use the existing development origins explicitly:

epoch-api-check --backend-url "$EPOCH_BACKEND_URL" --graph-url "$EPOCH_GRAPH_URL"

The command uses the actual generated StratifyX health client and LangGraph assistant discovery client. It starts no thread, study, ingestion or engine job, prints no credentials, and returns nonzero for missing capabilities. It defaults to the existing epoch-ai graph; use --graph-id or EPOCH_GRAPH_ID for another registered graph. A public health response proves connectivity only. Pass --study-id for an existing caller-owned definition and configure a bearer token to check protected Backend access as well; connectivity alone never passes the complete check. This diagnostic creates no thread or execution. The optional --attempt-id checks the older draft controller only when explicitly requested. Use EPOCH_TOKEN (or EPOCH_ACCESS_TOKEN) and LANGGRAPH_API_KEY in the environment; credentials must not be put in URLs. This package does not load another application's .env or mutate its installed SDK.

See the architecture notes for client/service ownership. The native adapter uses existing supervisor and Backend study/execution APIs. The older attempt-route check is relevant only to that draft API and is not a prerequisite for the native communication adapter. The checker reports availability; it does not start missing services. Additional recovery and retention work is separate.

PostgreSQL source connections

The epoch-source-connections dependency is a small typed client package owned by EpochBackend. Configure EpochClient.connect with the Python gateway URL that serves /api/v1/sources and proxies the native APIs. Source methods use the same authenticated HTTP lifetime as the existing client.

from epoch_sources.models import PrepareSnapshot, ReviewSnapshot, StartSync, StreamRef

connections = await client.list_source_connections()
connection = await client.source_connection(connections.items[0].connection_ref)
sync = await client.start_source_sync(connection.connection_ref, StartSync(request_id="refresh-001"))
status = await client.source_sync(connection.connection_ref, sync.sync_ref)
# Poll deliberately. Prepare only after state == "succeeded".
prepared = await client.prepare_source_snapshot(connection.connection_ref, sync.sync_ref,
    PrepareSnapshot(request_id="inspect-001", stream=StreamRef(namespace="research", name="prices"),
                    name="Captured prices"))
reviewed = await client.review_source_snapshot(prepared.snapshot.snapshot_ref,
    ReviewSnapshot.model_validate({"decision": {"action": "save",
        "draft_ref": prepared.snapshot.draft_ref, "name": "Captured prices"}}))

Starting a sync explicitly reads PostgreSQL. Never replay an unconfirmed request. Preparation reads the successful S3 generation once and retains an immutable Epoch file. Repeating preparation can use that file after later full refreshes. Calendar-date study mappings require explicit time meaning, timezone, date interpretation and information availability in the native DatasetTableSchema. An ordinary knowledge dataset has no automatic study source.

MCP exposes connection reads, discovery, selection, sync start/status/cancel, snapshot preparation/review and deletion. Credentials enter through the UI or typed SDK only. The same connection/snapshot references reopen in a fresh MCP process. Another owner's references return not_found.

The source package and native SDK preview wheels must accompany an unpublished SDK candidate; none of these preview artifacts is published by acceptance tests. The retained local demonstration and real-service receipts live outside the repository, including credentials and the resource cleanup ledger.

Platform file previews and versioned edits

A connected EpochClient or AgentToolsClient exposes client.file_edits. For a standalone file client, use epoch_sdk.PlatformFilesClient(api_url, token=token_or_async_provider). Request/response models live in epoch_sdk.platform_file_models and follow the packaged Platform-owned OpenAPI snapshot. Native file APIs and their generated StratifyX types remain unchanged.

from epoch_sdk import PlatformFilesClient
from epoch_sdk.platform_file_models import FileEditRequest, TextEdit

files = PlatformFilesClient(api_url, token=token_provider)
try:
    options = await files.edit_options(original_ref)
    latest = options.latest
    saved = await files.save(original_ref, FileEditRequest(
        request_id=save_id, base_version=latest.version,
        base_content_sha256=latest.file.content_sha256,
        edit=TextEdit(kind="text", content="# Updated notes\n"),
    ))
finally:
    await files.aclose()

Check options.kind before editing. grid reads typed bounded pages. Cell saves use exact lexical numeric strings, booleans, strings and explicit nulls, with zero-based data rows and optional worksheet names per change. Formula cells are read-only; caches are not recalculated. latest resolves the latest saved version; history includes Original (version 0). Retain the returned saved.file.file_ref for immutable content, study and citation inputs. The original reference still reads the uploaded bytes.

preview reports conversion state. async with files.content(ref, byte_range="bytes=0-65535") as result exposes status, headers and an async byte iterator without buffering the complete file. Set preview=True for the converted preview's content.

Mutation failures are never automatically retried. Keep the exact body and request ID after an uncertain result, then explicitly call save again. PlatformFileError preserves the server status/code and Retry-After. A stale base requires resolving the working draft; a new request ID cannot fix it. Opening, reading or saving a file starts no AI or provider writeback. Applications own account-scoped draft/cache cleanup and token renewal.

await files.image_preview(ref) opts into HEIC/HEIF and TIFF previews as ordered PNG pages, with dimensions, size and SHA-256 for each. Read one with async with files.content(ref, image_page=2) as result. The existing PDF preview contract is unchanged. Conversion starts on explicit preview access, never on upload, and starts no AI.

PlatformFilesClient also provides explicit native source reads through begin_document_read, document_read, document_content and document_passage. Closed Platform-owned models preserve heading/attachment metadata and optional exact original-byte positions. A position is omitted when decoded HTML or MIME text cannot map to one source span; the block citation remains valid. Reading is an explicit operation, with no automatic request retries.

Weekly allowance refusals use HTTP 403 and USAGE_LIMIT_REACHED. Catch epoch_sdk.UsageLimitReached to read meter and resets_at; the SDK stops retries, event streams and wait loops for this outcome. The CLI prints the reset time, or preserves the structured error with --json.

A study still completes when its new AI text is skipped. Its existing text value is empty and optional ai_text metadata records status: skipped, reason: usage_limit and resets_at. Tables, JSON and charts remain available. New v1 readers send Epoch-Features: ai-text-skipped-v1. Clients without that capability receive the empty text without new members, preserving older strict answer models. Cached real text can still be reused at the limit.

Platform sharing controls

The generated epoch_sdk.shares_api client follows Platform's source-owned conversation-sharing contract. Existing operation names are preserved. These examples use a signed-in owner's token; the Terminal's existing public viewer is not changed by this SDK addition.

from epoch_sdk.shares_api import AsyncEpochShares
from epoch_sdk.shares_api.types import ChangeShareAccessRequest

platform = AsyncEpochShares(base_url="https://api.dev.epoch.trade", token=token)
history = await platform.studies_shares.list_published_share_versions(share_id)
request = ChangeShareAccessRequest(
    expected_access_version=last_read.access_version,
    audience="named_subjects", subjects=["reader@example.com"],
)
await platform.studies_shares.change_who_can_open_a_share_link(
    share_id, **request.model_dump(exclude_none=True), request_options={"max_retries": 0},
)
await platform.studies_shares.select_published_share_version(
    share_id, snapshot_version=selected_version, expected_current_version=current_version,
    request_options={"max_retries": 0},
)
received = await platform.studies_shares.list_received_thread_shares()

On 409, refetch and have the owner review the conflict before retrying. Request models preserve required compare-and-set versions and closed fields. Unavailable history entries have a reason instead of counts and cannot be selected. Saving a study to Space, invitation email and automatic publication are separate features.

Metadata

Release files for epoch-sdk 0.1.0a58

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for epoch-sdk 0.1.0a58
File Size Uploaded Provenance Actions
epoch_sdk-0.1.0a58.tar.gz 457.7 kB With provenance Details for epoch_sdk-0.1.0a58.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for epoch-sdk 0.1.0a58
File Interpreter ABI Platform Actions
epoch_sdk-0.1.0a58-py3-none-any.whl Python 3 none any Details for epoch_sdk-0.1.0a58-py3-none-any.whl

Total release size: 974.8 kB

Release files / epoch_sdk-0.1.0a58.tar.gz

Download URL epoch_sdk-0.1.0a58.tar.gz
Size 457.7 kB
Tags Source
SHA-256 checksum
How to use checksums
abb368d463319d0deccf788b3e94dce50e6001f583a003d273e4d7a7f6ae5439
BLAKE2b-256 checksum
How to use checksums
4176dfab48c21a9fdae0a389931814b672c65a0da55a1156f55ec27fd376acc9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / epoch_sdk-0.1.0a58-py3-none-any.whl

Download URL epoch_sdk-0.1.0a58-py3-none-any.whl
Size 517.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
855a47b38e3d8d39be9c1819e510490defd1c483d5e8765442fc0aaa9e5cdf64
BLAKE2b-256 checksum
How to use checksums
ee7d4fde20b253b79331204dd72616f6437e4b7425895c724afbeed8a1e4397a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for epoch-sdk 0.1.0a58

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for epoch_sdk-0.1.0a58.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page