PHP SDK: Ai: Help with Collection and Data Processing
$ctx->ai() helps interpret page content, transform a record, find an element, and prepare a repair for an algorithm. Calls run in the platform core: the service key and internal model selection are not available to a scenario.
The platform uses leading models available at the time. Choose small, medium, or large, and the platform selects a suitable model. You can change the tier without rewriting the algorithm.
Before your first call
- Each provider request consumes the AI budget of the workspace that owns the site. Input and output token usage appears in limits and the transaction log. Normal scenario execution time is also counted.
- A run can make no more than eight AI calls. Each call accepts up to 48 KB of data. For larger pages, first select the relevant fragment with ordinary SDK methods.
- Do not include passwords, tokens, or personal data in a request. Site keys known to the platform are blocked before transmission.
- AI calls are unavailable when an agent is offline or when replaying a run. Keep proven logic in PHP for reliable scheduled collection.
Tier and effort
| Parameter | Values | When to choose |
|---|---|---|
$tier |
small, medium, large |
small for short pages and simple records; medium for ambiguous structure; large for complex code repair. |
$effort |
low, medium, high, extra_high |
Higher effort may take more time and tokens. Start with medium; use extra_high for particularly difficult cases. |
Defaults are small and medium, except for repair(), which defaults to large and high. Cost depends on actual token use. The budget is reserved before a request, and unused funds are released afterward. If the budget is insufficient, the scenario receives a clear error and no request is sent.
analyze()
analyze(string $content, string $question, string $tier = 'small', string $effort = 'medium'): string
Ask a question about page content or data you have already obtained. The method returns answer text.
$html = $ctx->http()->get($ctx->param('catalog_url'))->body;
$answer = $ctx->ai()->analyze($html, 'Where is the product price on this page?');
$ctx->log($answer);
An answer may be inaccurate. Check actual values before writing product records.
transform()
transform(array $data, array $shape, string $instruction = '', string $tier = 'small', string $effort = 'medium'): array
Provide the original record, an example of the required structure, and an instruction. The method returns an array in data; missing facts should not be invented.
$raw = ['title' => 'Belt', 'cost' => '1,250 RUB'];
$shape = ['name' => '', 'price_rub' => 0];
$item = $ctx->ai()->transform($raw, $shape, 'Store the price as a numeric value in rubles');
$ctx->emit($item, 'belt-1');
For a stable input structure, ordinary PHP transformation is faster and cheaper. AI helps when input records differ significantly.
find()
find(string $html, string $description, string $tier = 'small', string $effort = 'medium'): array
Suggests a CSS selector for an element in the supplied HTML. The result contains selector and reason. If no element is found, selector is empty.
$html = $ctx->http()->get($ctx->param('product_url'))->body;
$match = $ctx->ai()->find($html, 'Button for the next page', 'medium', 'high');
if ($match['selector'] !== '') {
$node = $ctx->dom($html)->q($match['selector']);
$nextUrl = $node?->abs();
}
Check the suggested selector on the current page and other list pages. A suggestion does not replace pagination testing.
repair()
repair(string $source, string $error, string $goal, string $tier = 'large', string $effort = 'high'): string
Returns suggested corrected PHP code. It saves nothing and does not change the active scenario version. Review the code, run a trial, and publish a new version through the editor.
$source = (string) $ctx->param('algorithm_source', '');
$error = (string) $ctx->param('last_error', '');
if ($source !== '' && $error !== '') {
$suggestion = $ctx->ai()->repair(
$source,
$error,
'Visit every catalog page and collect products',
'large',
'extra_high'
);
$ctx->log($suggestion);
}
repair() is usually best used while debugging: source code and the error must be available to the scenario through its parameters or another permitted source. Do not pass the result of credential() to AI.
Errors and billing
The SDK throws an exception if the service is unavailable or returns an invalid answer. Requests rejected by the service are not charged. If a response cannot be confirmed after a network failure, the reservation remains until reconciliation to prevent an incorrect charge or duplicate payment. When a response is received, actual token use is charged even if a suggested selector or code needs more work.
SDK reference · Limits and balance
extract
extract(array|string|Document $input, array $schema, array $options = []): array
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()->fromBytes() first. Select multiple worksheets and ambiguous columns explicitly. Arbitrary page cards and unstructured PDF text require preprocessing.
$result = $ctx->ai()->extract([
['sku', 'price', 'currency'],
['001', '1250.50', 'RUB'],
], [
'sku' => ['type' => 'string', 'unique' => true],
'price' => ['type' => 'decimal', 'min' => 0],
'currency' => 'string',
], ['key' => 'supplier-prices', 'expected_rows' => 1]);
foreach ($result['records'] as $record) {
$ctx->emit($record, $record['sku']);
}
The result includes records, cache_hit, ai_used, recipe_id, revision, validated_rows. A cache hit reuses a recipe, not yesterday's values. It sends no AI request and creates no new AI reservation. Generation or repair consumes actual AI usage; execution time and other resources are billed normally. Fully explicit header_row plus column for every field requires no model from the first call. Row and column indices start at zero.
Field types: string, decimal, integer, boolean; constraints: required (default true), unique, min, max. Semantic roles: sku, name, price, stock, currency, url. Unknown meanings require explicit column mapping; the model does not guess them from private values.
The model receives only fixed role codes and cell types, never source values, headers, personal data, URLs or user field names. It proposes numerical header/column coordinates. Trusted code independently verifies the mapping and every row. Generated executable code is never run. At most two proposals per repair, within the shared eight-provider-request limit per run.
Recipes are scoped by workspace, site, key, schema, format and validator version. They expire 180 days after their last successful use; failures do not renew them. Expired recipes require rebuilding. Known format variants can be reused. All rows undergo required/type/range/uniqueness/width checks. A row count below 70% of the previous validated amount requires a completeness check and explicit expected_rows. Only a reliable source total or expected-item list can establish completeness; structural validity alone cannot.
Per-call input bounds: 2 MiB, 5000 rows, 100 columns, 30 fields. Process larger inputs in batches and verify each batch count explicitly. Normalize ambiguous thousands separators, currency suffixes and numbers with more than two fractional digits before extraction. Incomplete documents, merged cells and formula errors require explicit selection and verification.