Metadata-Version: 2.5
Name: ascend-marketplace
Version: 0.3.0
Summary: Ascend Marketplace: the official Python client for Forge: generate realistic datasets from a prompt, then fetch their data, ERD, overview, rules and payload APIs.
Project-URL: Homepage, https://forge.adept-techsolutions.com
Project-URL: Documentation, https://forge-backend.adept-techsolutions.com/api/public/v1/openapi.json
Project-URL: Repository, https://github.com/AdeptTechSolutions/forge-sdk-python
Project-URL: Changelog, https://github.com/AdeptTechSolutions/forge-sdk-python/blob/main/CHANGELOG.md
Author: Adept Tech Solutions
License-Expression: MIT
License-File: LICENSE
Keywords: api,erd,forge,sdk,synthetic data,test data
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.6
Requires-Dist: typing-extensions>=4.7
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# Ascend Marketplace: Forge for Python

The official Python client for **Forge**, the Ascend Marketplace service that
generates realistic, rule-checked datasets from a plain-English prompt. Describe
the data you want, and Forge returns the data, an ERD, a quality overview, and
the rules it was verified against. It can also publish payload APIs over the data.

```bash
pip install ascend-marketplace
```

```python
from ascend_marketplace import Forge

API_KEY = "fsk_live_..."  # your platform key

forge = Forge(
    api_key=API_KEY,
    base_url="http://localhost:8080",  # local control plane
)

ws = forge.workspaces.create(name="Healthcare")
run = forge.runs.create_and_wait(
    prompt="Hospital claims DB with patients, providers, claims and payments",
    workspace_id=ws.id,
    project_name="Claims",
    generation_hints={"default_rows_per_table": 500},
)

db = run.database
print(db.erd().mermaid)
for rule in db.rules().rules:
    print(rule.id, rule.outcome)
for row in db.tables["patients"].rows():
    print(row)
```

Python 3.10 or later. The only dependencies are `httpx` and `pydantic`.

## Contents

- [Authentication](#authentication)
- [Configuration](#configuration)
- [Runs: auto and manual mode](#runs-auto-and-manual-mode)
- [Reading results](#reading-results)
- [Exports](#exports)
- [Share links](#share-links)
- [Sharing with other accounts](#sharing-with-other-accounts)
- [Databases and pushes](#databases-and-pushes)
- [Attaching files](#attaching-files)
- [Payload APIs](#payload-apis)
- [Run steps](#run-steps)
- [Credits](#credits)
- [Webhooks](#webhooks)
- [Errors](#errors)
- [Retries, idempotency and timeouts](#retries-idempotency-and-timeouts)
- [Pagination](#pagination)
- [Async](#async)
- [Examples](#examples)

## Authentication

Create a **platform key** (`fsk_live_...`) in Forge under **Settings → Developer**.
API access must first be enabled for your account. Each key carries scopes,
such as `runs:write` or `data:read`, and can be confined to particular
workspaces or IP addresses.

```bash
export FORGE_API_KEY="fsk_live_..."
```

The key is only ever sent in the `Authorization` header, and only over HTTPS.
`repr(forge)` masks it. Each key includes a checksum, so a mistyped or truncated
key raises `APIKeyFormatError` before any request is made. A data-plane key
(`fpk_...`) is refused with an explanation: it only calls published payload
APIs.

## Configuration

```python
forge = Forge(
    api_key="fsk_live_...",       # default: FORGE_API_KEY
    base_url="https://...",       # default: FORGE_BASE_URL, else production
    timeout=60.0,                 # seconds per request
    max_retries=2,
    default_headers={"X-My-Trace": "abc"},
    http_client=httpx.Client(proxy="http://proxy:3128"),  # optional
)
```

Use `with Forge(api_key=API_KEY, base_url=...) as forge:` (or `forge.close()`) to release connections.

## Runs: auto and manual mode

A run takes about a minute for a simple dataset and up to about ten minutes for
a complex one. `runs.create` returns as soon as the run is accepted. Its
`links` are valid from that moment, and return their data once the run
completes.

**Auto mode** (the default) answers the run's own questions. Clarifications get
the recommended option, and the compiled rules are approved. Every assumption is
recorded in `run.auto_decisions`. Tune it with `auto_policy`:

```python
run = forge.runs.create_and_wait(
    prompt="...",
    workspace_id=ws.id,
    auto_policy={"clarifications": "recommended", "rule_approval": "approve",
                 "rule_conflict": "drop_first", "max_auto_rounds": 5},
    metadata={"client_ref": "ticket-123"},  # echoed back on every read
)
```

`create_and_wait` long-polls until the run finishes. If the run fails, it
raises `RunFailedError`, whose `code` (for example `UNANSWERABLE_CLARIFICATION`)
and `auto_decisions` say what happened.

**Manual mode** pauses so that you, or a person you ask, can decide:

```python
run = forge.runs.create_and_wait(prompt="...", workspace_id=ws.id, interaction_mode="manual")
while run.is_awaiting_input:
    pending = run.pending_input
    if pending.type == "clarification":
        answers = [q.get("recommended") or q["options"][0] for q in pending.questions]
        forge.runs.answer(run.id, answers)
    else:  # rule_approval
        forge.runs.approve_rules(run.id)  # or edit_rules(run.id, remove_rule_ids=[...])
    run = forge.runs.wait(run.id)
```

To change a dataset later, or ask a question about it, start a follow-up:
`forge.runs.follow_up(run.id, prompt="How many male patients are there?")`.
When it completes, a question's outcome is in `run.answer`.

## Reading results

```python
result = run.result()          # tables, row counts, verification verdict, links
db = run.database              # or forge.dataset(database_id)

db.get()                       # tables with typed columns, DDL
db.schema()                    # the DDL as a string
db.erd()                       # entities, relationships, Mermaid source
db.overview()                  # totals, quality gauges, per-column profiles
db.rules()                     # each rule and whether it held
db.data()                      # every table inline (up to 10,000 rows / 10 MB)
for row in db.tables["claims"].rows():   # any size, a page at a time
    ...
```

Row values are strings, exactly as stored (`"00123"` keeps its zeros). Use the
ERD's column types, or a Parquet or JSON export, for typed values. If a dataset
is too large to inline, `db.data()` raises `PayloadTooLargeError`; its `links`
point at the exports and the per-table rows.

## Exports

```python
export = forge.exports.create_and_wait(db.id, format="parquet")   # csv, json, jsonl, parquet, sql
export.download("claims.parquet")                                  # or a directory, or None for bytes

forge.exports.download_now(db.id, format="csv", path="small.zip")  # synchronous, up to 25 MB
```

The download URL is presigned and lasts 15 minutes. `download()` fetches a
fresh URL first and never sends your API key to the storage host. Export files
are kept for seven days.

## Share links

A browser-viewable, read-only link to the ERD, overview and rules. It never
includes row data.

```python
link = db.share(views=["erd", "overview", "rules"], ttl_hours=24)
print(link.url)
```

## Sharing with other accounts

Share a workspace, a project or one dataset with another Forge account by its
email, the same as the app's share dialog. `"read"` lets them look; `"write"`
also lets them prompt, which spends *their* credits. A share on a level reaches
everything beneath it, and sharing again with the same person changes their
permission. The key needs `shares:write` to share and `shares:read` to list.

```python
share = forge.shares.share_workspace(ws.id, email="ali@example.com", permission="write")
forge.shares.share_project(ws.id, project.id, email="sara@example.com")      # read by default
forge.shares.share_database(db.id, email="omar@example.com", permission="read")

for s in forge.shares.list_for_workspace(ws.id):    # owner only
    print(s.grantee_email, s.permission)
forge.shares.update(share.id, permission="read")     # owner only
forge.shares.revoke(share.id)                        # owner revokes, or a grantee leaves

# The other side: everything shared with your account.
for s in forge.shares.incoming():
    print(s.resource_type, s.resource_name, "from", s.owner_email)
```

## Databases and pushes

Connect your own databases, generate data shaped like one of their schemas, and
push a generated dataset into any schema of a connected database - or a new one.
The same as the app's Connections page, "Add schema" and Push button. The key
needs `connections:read` (browse, read schemas, follow pushes) and
`connections:write` (connect, change, push). Credentials are write-only.

```python
conn = forge.connections.create(
    ws.id, name="Analytics", engine="POSTGRES", host="db.example.com", database="analytics",
    username="loader", password=os.environ["DB_PASSWORD"],
    read_only=False, push_target=True,   # allow pushes into it
)                                        # dialled first: saved only if it answers
print(forge.connections.schemas(ws.id, conn.id))           # ["public", "sales", ...]
print(forge.connections.schema_ddl(ws.id, conn.id, "sales").ddl)

# Generate from that schema: its tables, columns and keys are read and attached
# to the prompt as CREATE TABLE statements, like "Add schema" in the app.
run = forge.runs.create_and_wait(
    prompt="Generate 1,000 customers with their orders", workspace_id=ws.id,
    schema_sources=[{"connection_id": conn.id, "schema": "sales"}],
)

# Push the dataset into a new schema and wait for it to land.
push = run.database.push(conn.id, target_schema="forge_demo", create_target_schema=True)
print(push.status, push.rows_done, push.tables_done)   # raises PushFailedError on failure
```

`forge.pushes.create(...)` returns at once; follow it with `pushes.get`,
`pushes.wait` or `pushes.list(workspace_id)`, and stop it with `pushes.cancel`.
Leave `target_schema` out for the connection's default schema, and pass
`create_tables=False` to load into tables that already exist.

## Attaching files

Attach files to a prompt as you would in the app's prompt box - a schema, a
data dictionary, sample rows, a spec. Give paths (or `(filename, bytes)`) as
`files`: each is checked against the app's limits, uploaded, and attached, and
if the run is then refused the uploads are deleted again. Their text is added to
the prompt the run is given; the stored prompt stays what you wrote.

```python
run = forge.runs.create_and_wait(
    prompt="Generate claims data matching this schema",
    workspace_id=ws.id,
    files=["./claims_schema.sql", "./business_rules.pdf"],
)
forge.runs.follow_up(run.run_id, prompt="Add these refund rules", files=[("refunds.md", text.encode())])
```

The limits are the app's, and `forge.attachments.limits()` lists them:
accepted extensions (`sql`, `ddl`, `txt`, `md`, `markdown`, `json`, `yaml`,
`yml`, `csv`, `tsv`, `pdf`, `docx`), at most 10 MB a file, 10 files a prompt
(counting `schema_sources`) and 200,000 characters of text in all. Text must be
UTF-8; a PDF or Word file has its text read out of it. A file belongs to the
first run started with it, and one no run uses is deleted after 24 hours.

To manage uploads yourself, `forge.attachments.upload(path)` returns an
`Attachment` whose `id` goes in `attachment_ids`, and
`forge.attachments.delete(id)` removes one no run has sent. When retrying a
start with your own `idempotency_key`, pass `attachment_ids` rather than
`files`: uploading again would make it a different request. Scope `runs:write`.

## Payload APIs

```python
endpoint = forge.endpoints.create_and_wait(db.id, prompt="Customers in Lahore, newest first")
print(endpoint.draft.sample)
endpoint = forge.endpoints.refine_and_wait(endpoint.id, correction="also add their phone number")
endpoint = forge.endpoints.approve(endpoint.id, name="lahore-customers")
print(endpoint.url)   # call it with a data-plane (fpk_) key
forge.endpoints.call(endpoint.id, limit=10)
```

## Run steps

```python
log = forge.runs.events(run.id)
for step in log.steps:
    print(step.label, step.took, step.details)
    for answer in step.answered:
        print("  ", answer.question, "->", answer.answer)
```

The steps are what the run page's timeline shows: each step's sentence, the
lines under it ("New data with fresh rules", "Needs your input"), how long it
took ("<1s", "5s"), and any questions it asked with their answers. `took` is
`None` while a step is still running; call again to see the steps added since.

## Credits

```python
credits = forge.credits()
print(credits.remaining_credits, credits.granted_credits)
for entry in credits.credit_history:
    print(entry.created_at, entry.type, entry.amount, entry.reason, entry.by)

usage = forge.usage.get()
print(usage.credits.balance, usage.credits.can_spend, usage.month.runs_started.api)
for entry in forge.usage.ledger():
    print(entry.created_at, entry.type, entry.amount, entry.balance_after, entry.by)
```

What the Credits page shows: the remaining credits, what was granted, and the
credit history (top-ups and removals by an administrator, newest first).
`forge.usage.get()` adds whether a new run would be accepted, this month's runs
started per channel and API requests, and the limits that apply;
`forge.usage.ledger()` pages through the same top-ups and removals. Needs
`usage:read`.

## Webhooks

```python
hook = forge.webhooks.create(url="https://example.com/forge", events=["run.completed", "run.failed"])
print(hook.secret)  # shown once: store it
```

Verify each delivery against the **raw** request body. You don't need an API
key to do this:

```python
from ascend_marketplace import verify_webhook, WebhookVerificationError

event = verify_webhook(raw_body, request.headers["Forge-Signature"], secret)  # tolerance=300 s
if event.type == "run.completed":
    ...
```

Deduplicate deliveries on `event.id` (the `Forge-Event-Id` header). Payloads
carry ids, status and links, never generated data. See
[`examples/webhook_receiver_fastapi.py`](examples/webhook_receiver_fastapi.py).

## Errors

Every API error raises a subclass of `APIError` with `.status`, `.code` and
`.request_id`. Branch on `.code`, and quote `.request_id` when you contact
support.

| Status | Exception | Typical codes |
|---|---|---|
| 400 | `BadRequestError` | `MALFORMED_REQUEST` |
| 401 | `AuthenticationError` | `INVALID_API_KEY`, `API_KEY_EXPIRED`, `API_KEY_REVOKED` |
| 402 | `InsufficientCreditsError` | `INSUFFICIENT_CREDITS` |
| 403 | `PermissionDeniedError` | `INSUFFICIENT_SCOPE`, `API_ACCESS_SUSPENDED`, `IP_NOT_ALLOWED` |
| 404 | `NotFoundError` | `NOT_FOUND`: also returned for another account's resources |
| 409 | `ConflictError` | `RUN_NOT_READY`, `RUN_NOT_AWAITING_INPUT`, `CONFLICT` |
| 413 | `PayloadTooLargeError` | `PAYLOAD_TOO_LARGE` (see `.links`) |
| 422 | `ValidationError` | `VALIDATION_FAILED` (see `.errors`), `IDEMPOTENCY_CONFLICT` |
| 429 | `RateLimitError` | `TOO_MANY_REQUESTS`, `TOO_MANY_LIVE_RUNS`, `QUOTA_EXCEEDED` |
| 5xx | `InternalServerError` | `INTERNAL_ERROR`, `SERVICE_UNAVAILABLE` |
| none | `APIConnectionError`, `APITimeoutError` | the request got no answer |

The helpers that wait raise `RunFailedError`, `RunCancelledError`,
`ExportFailedError`, `EndpointBuildFailedError` and `WaitTimeoutError`. They
all subclass `ForgeError`.

## Retries, idempotency and timeouts

- The SDK retries rate limits (`TOO_MANY_REQUESTS`), 502/503/504 responses and
  dropped connections up to `max_retries` times. It uses exponential backoff
  with jitter, and waits for the `Retry-After` time when the server sends one.
  It does not retry `TOO_MANY_LIVE_RUNS` or `QUOTA_EXCEEDED`, since waiting a
  few seconds won't clear them.
- Requests that start work (runs, follow-ups, exports, endpoint builds and
  refinements) get an `Idempotency-Key` automatically, and the same key is
  reused on every retry, so the work never starts twice. Pass
  `idempotency_key=` to make your own retries safe as well.
- Other POST requests (answers, rule decisions, cancel) are retried only when
  the request never reached the server.
- Long-polls extend their own timeout by the time the server holds them.
- When the API marks a route as deprecated, the SDK issues a
  `ForgeDeprecationWarning`.

## Pagination

List methods return a page. Iterate it to go through every item, fetching
further pages as needed:

```python
for run in forge.runs.list(status="COMPLETED"):
    ...
page = forge.runs.list(size=50)
page.data, page.total_elements, page.has_next_page(), page.next_page()
```

## Async

`AsyncForge` has the same methods; await them.

```python
import asyncio
from ascend_marketplace import AsyncForge

async def main() -> None:
    async with AsyncForge(
        api_key=API_KEY,
        base_url="http://localhost:8080",  # local control plane
    ) as forge:
        run = await forge.runs.create_and_wait(prompt="...", workspace_id="...")
        print((await run.database.erd()).mermaid)
        async for row in run.database.tables["patients"].rows():
            ...

asyncio.run(main())
```

## Examples

The [`examples/`](examples) folder has runnable scripts:

- `generate_and_download.py`: prompt → data → Parquet file
- `manual_mode.py`: answer clarifications and review rules yourself
- `webhook_receiver_fastapi.py`: verify and handle webhook deliveries
- `export_parquet.py`: export an existing dataset

## Versioning

SemVer. Versions `0.x` and `1.x` target the API at `/api/public/v1`. See
[CHANGELOG.md](CHANGELOG.md).

## Development

```bash
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
python scripts/unasync.py        # after editing anything in forge/_async
pytest                           # unit tests (no network)
mypy && ruff check src scripts tests
```

The sync client in `forge/_sync` is generated from `forge/_async`, so don't
edit it by hand. `openapi/public-v1.json` is the API contract that
`tests/test_openapi_coverage.py` checks the SDK against. Refresh it with
`python scripts/sync_openapi.py`.
