Skip to content

Documentation

Python SDK: Ai: analysis and transformation

ctx.ai() runs through the platform and consumes the workspace AI budget unless extract() has a verified cache hit. Every method is synchronous. The platform selects the model; the script selects tier and effort.

Examples are fragments inside def run(ctx):. All SDK methods are synchronous; do not add await.

Before the first call

  • A run can make up to eight AI calls. Send no more than 48 KB per call. For a large page, select the relevant fragment with the regular SDK methods first.
  • Calls use the workspace AI budget. Actual usage appears in limits and the operation log; script execution time is accounted for separately. A verified extract() cache hit reuses a recipe without a new AI call.
  • Do not include passwords, tokens, or personal data. Never send the result of ctx.credential() to AI.
  • An offline agent cannot make an AI call without the platform. Keep the verified rules in code if collection must work autonomously.

Tier and effort

Parameter Values When to use it
tier small, medium, large From a short record to complex analysis or code repair.
effort low, medium, high, extra_high Higher effort may take more time and tokens.

Defaults are small and medium; repair() defaults to large and high. The platform chooses the model, so a script does not specify its name.

Methods

analyze

ctx.ai().analyze(content, question, tier='small', effort='medium') -> str

Argument Type Required Purpose
content str | bytes Yes Supplied content; method limits apply.
question str Yes Question about the supplied content.
tier str No, see the signature default AI tier: small/medium/large.
effort str No, see the signature default Effort: low/medium/high/extra_high.

Result: str.

Answers a question about the supplied content as text. It may be wrong; verify facts before saving records.

result = ctx.ai().analyze('sku,price\nA-1,1250', 'Which column contains the price?')

transform

ctx.ai().transform(data, shape, instruction='', tier='small', effort='medium') -> dict[str, Any]

Argument Type Required Purpose
data Any Yes Data to transform.
shape dict[str, Any] Yes Desired result structure.
instruction str No, see the signature default Additional transformation instruction.
tier str No, see the signature default AI tier: small/medium/large.
effort str No, see the signature default Effort: low/medium/high/extra_high.

Result: dict[str, Any].

Transforms a dictionary into the requested shape and returns the transformed dict itself. Validate required fields before ctx.emit().

result = ctx.ai().transform(
    {'title': 'Product', 'price': '1 250 RUB'},
    {'title': 'string', 'price': 'number'},
)

find

ctx.ai().find(html, description, tier='small', effort='medium') -> dict[str, str]

Argument Type Required Purpose
html str Yes HTML string, not a file path or download URL.
description str Yes Description of the desired element.
tier str No, see the signature default AI tier: small/medium/large.
effort str No, see the signature default Effort: low/medium/high/extra_high.

Result: dict[str, str].

Suggests a CSS selector for an element using HTML and a description. Returns selector and reason; verify the selector on the page.

result = ctx.ai().find('<button class="next">Next</button>', 'Next page button')

repair

ctx.ai().repair(source, error, goal, tier='large', effort='high') -> str

Argument Type Required Purpose
source str Yes Python source for analysis; not executed automatically.
error str Yes Error explanation without private data.
goal str Yes Expected purpose of the correction.
tier str No, see the signature default AI tier: small/medium/large.
effort str No, see the signature default Effort: low/medium/high/extra_high.

Result: str.

Returns a proposed fix for the supplied Python source. It does not save or publish a new version. Review the result and run a trial.

result = ctx.ai().repair('def run(ctx):\n    pass', 'Element not found', 'Collect the product name')

document_rows

ctx.ai().document_rows(document, sheet=0) -> dict[str, Any]

Argument Type Required Purpose
document Document Yes A Document object, not a file path.
sheet int | str No, see the signature default Zero-based sheet index or exact name.

Result: dict[str, Any].

Plans table rows and header from cell shapes without revealing values to an external model. Returns ready, needs_range, or incomplete; select the range manually for the latter two.

document = ctx.documents().from_url(ctx.param('file_url'), 'prices.csv')
result = ctx.ai().document_rows(document, 0)
if result.get('status') == 'ready':
    for row in result.get('records', []):
        ctx.emit(row)

extract

ctx.ai().extract(input, schema, options=None) -> dict[str, Any]

Argument Type Required Purpose
input str | list | dict | Document Yes Table, JSON/row array, or verified Document.
schema dict[str, Any] Yes Explicit expected-field schema.
options dict[str, Any] | None No, see the signature default Extraction options: key, expected_rows, and explicit mappings if needed.

Result: dict[str, Any].

Extract fresh records using a validated, cached table recipe. Supported inputs: a single HTML table without merged cells, a JSON record array, rows, or one complete document worksheet. Read CSV bytes with documents().from_bytes() first. Select multiple worksheets and ambiguous columns explicitly. Arbitrary page cards and unstructured PDF text require preprocessing.

result = ctx.ai().extract(
    [['SKU', 'Price'], ['A-1', '1 250,50']],
    {'sku': {'type': 'string', 'unique': True}, 'price': {'type': 'decimal', 'min': 0}},
    {'key': 'supplier-prices', 'expected_rows': 1},
)
for record in result.get('records', []):
    ctx.emit(record, record['sku'])

records contains fresh values from this run even when the recipe came from cache. cache_hit and ai_used show whether the model was called. To map columns explicitly, set column on fields and header_row in options; indices start at zero. Check ambiguous column mappings manually.

If the service is unavailable or returns an invalid response, the SDK throws an error. Check a suggested selector, transformation, or code fix in a trial run before publishing the script.

Lifecycle · Limits and balance

Errors and execution context

All calls are synchronous. Invalid arguments or malformed source data can raise ValueError/TypeError; a platform refusal or unavailable service raises RuntimeError. Missing elements/values return None or an empty collection only where explicitly documented. Do not convert every exception into an empty successful result. External-service methods are unavailable in export transformations; see transformation limits and environment.