Using the agent client in custom functions
The agent client (CLIENTS.agent_client) lets custom functions in Map UDF and Reduce UDF steps access the SuperApp AI agent, the agent system underlying agent mode v2. Use the client to ask about the step’s input files, extract structured records, and check the results. Unlike the LLM client, the agent client handles the work around each call for you:
-
Attachments — The client attaches the step’s input files to the request. You don’t read, upload, or attach files yourself.
-
Schema validation — Extraction results are validated against the schema you provide, and invalid responses get one correction attempt before the call fails.
-
Output files — Validated extraction results are written to the step output automatically, with page provenance preserved.
-
Context — The client groups related model calls into threads, which are sequences of calls that share context. Follow-up calls in a thread reuse the files attached to its first message instead of uploading them again.
Using the agent client
The agent client is opt-in. Connect with Instabase Support to get set up for access.
The agent client is available in Map UDF and Reduce UDF steps. Review the following usage guidance.
-
Position Map UDF or Reduce UDF steps using the client after any Process files step in your flow. Process files is required to support human review or if the session uses OCR text.
Use a Map UDF to work with one input file or one combined packet at a time. Use a Reduce UDF when one function call must work with all the step’s inputs. To give the model every file in a packet at once, see Processing packets. -
Add your Python function to the flow scripts and register it with
@register_fn(provenance=False)frominstabase.provenance.registration. -
Include
CLIENTSin the step formula and add a matching parameter to the function signature. For example, set the Map UDF formula toextract_statement(INPUT_RECORD, CLIENTS). The examples on this page name the parameterclients, so they access the agent client asclients.agent_client. End the signature with**kwargs. The step passes extra keyword arguments to every registered function, and a function without**kwargsfails with anunexpected keyword argumenterror. For the other variables you can pass, see Map UDF and Reduce UDF. -
Check that the agent client is available. If it isn’t available for a run, such as when it isn’t enabled,
clients.agent_clientisNone: -
Create a session with
clients.agent_client.for_inputs(). By default, the session uses the Map UDF input or all Reduce UDF inputs. See Configuring a session. -
Call a session method:
-
extract_async()orextract()extracts records against a schema and writes them to the step output automatically. -
validate_async()orvalidate()checks extracted values against the source files and writes the verdicts to the step output. -
generate()waits for an answer and returns it to your code so it can decide what to do next. This method doesn’t create an output file.
For longer runs, use
extract_async()andvalidate_async(). They queue the work and return immediately, and the step waits for the work to finish before it writes the output.extract()andvalidate()wait for each result. -
Configuring a session
A session is the object that for_inputs() returns. You make every agent client call through a session. The session holds the settings that apply to each of its calls: which input files to attach, the extraction schema, any instructions, and how the session uses threads. You set them when you create the session, and the session keeps them for every call it makes, so you don’t pass them again to generate(), extract(), or validate().
for_inputs() accepts these arguments:
Selecting sources
Pass a subset of inputs as the first argument to attach only those files. input_sources() returns a handle for each source file in the custom function’s input, including each file in a combined packet. In the following example, SCHEMA is an extraction schema as described in Defining a schema.
An empty selection fails. It doesn’t fall back to all inputs.
Selecting sources controls which files the session attaches. It doesn’t hide files that are already in a shared thread. If the model must see only the selected files, use a new thread, for example with conversation_share="per_record" or set_channel_id(). See Managing threads.
Adding instructions
Provide task-specific instructions with either skill_text or skill_path, not both. The client sends the instructions on every call, including follow-up and correction calls.
To use a file, save a .md or .txt file in the flow’s scripts folder so that it’s packaged with the app. Set skill_path to the file’s path relative to the flow directory. For example, if the scripts folder is extract.udf, use skill_path="extract.udf/skill.md".
The file must be UTF-8 text. If the file is missing or isn’t valid UTF-8, the call fails before any request is sent.
Setting the model, reasoning effort, and timeout
for_inputs() doesn’t accept a model, reasoning effort, or timeout. Instead, pass model, reasoning_effort, and timeout_seconds to each call. generate(), extract(), extract_async(), validate(), and validate_async() accept these optional keyword arguments:
For example, to extract at high reasoning effort and allow the extraction to run for up to 30 minutes:
Making decisions based on document content
Use generate() when your custom function needs to ask about a document before it decides what to do next. For example, you can check what kind of document a file is, then extract it or skip it. generate() sends your prompt with the session’s input files attached, waits for the response, and returns it to your code. It doesn’t write anything to the step output.
generate() waits for each response, use it only for branching decisions—when your code needs the answer to continue. For extraction and validation, use extract_async() and validate_async() instead. They queue the work so that your custom function doesn’t wait, and the step writes the results when the work finishes.The following Map UDF asks whether each input file is a bank statement. If it is, the custom function extracts it. If it isn’t, the custom function writes a note that explains why the file was skipped. The response_schema argument makes the model return its answer as JSON that the code can read. Set the Map UDF formula to extract_if_statement(INPUT_RECORD, CLIENTS).
The response is in response["output_text"]. With response_schema, it’s JSON text, so read it with json.loads(). Without response_schema, it’s plain text. To keep a response for a later step, return it as a file through out_files.
STATEMENT_SCHEMA is defined in Extracting structured records.
Generation options
In addition to model, reasoning_effort, and timeout_seconds, generate() accepts these optional keyword arguments. Input selection and instructions belong to for_inputs().
Each item in files or additional_files is a dictionary with filename, mime_type, and data (the file content as bytes).
Extracting structured records
To extract records, pass a schema to for_inputs(), then call one of these methods:
-
extract_async()queues the extraction and returns immediately so your custom function can continue. Use this method unless your code needs the extracted values, especially for longer runs. -
extract()waits for the result and returns it.
In both cases, the step writes the validated records to the step output after your custom function finishes. You don’t need to return them, and returning None doesn’t discard them. Return out_files only for additional files your custom function creates, such as a report. See How the step writes output.
Both methods accept the optional model, reasoning_effort, and timeout_seconds arguments.
The following Map UDF extracts one bank statement record from each input file. Set the Map UDF formula to extract_statement(INPUT_RECORD, CLIENTS).
Defining a schema
The simplest schema maps class names to fields, and each field to an example value. Example values guide the model; they don’t set field types.
The client converts example values as follows:
Lists of numbers, lists that mix objects and strings, nested lists, and nested objects inside table rows aren’t supported.
If you pass fields without a class name, such as {"bank_name": "", "account_number": ""}, the fields belong to a default class named Document.
Using an explicit class schema
To set field types or give the model per-field guidance, define each class with a fields list:
Each class accepts these keys:
Each field definition accepts these keys:
The client treats a class as an explicit schema when it contains a fields, description, or class_id key. If your example schema has a field with one of those names, pass it with examples=SCHEMA instead of schema=SCHEMA. Don’t pass both arguments.
Setting the number of records per source
allow_multiple_records controls how many records the client can extract from each source file:
With allow_multiple_records=True, a source file with no records is left out of the extraction output. Manual files returned by the custom function are unaffected. If no source produces a record, the step writes no extraction file.
With allow_multiple_records=False, zero or several records for any source file fails the extraction.
Extracting multiple files in a Reduce UDF
A Reduce UDF session includes all the step’s inputs by default. The client finds those inputs without consuming the INPUT_RECORDS iterator, so you can still iterate over it in your code. Set the Reduce UDF formula to extract_documents(INPUT_RECORDS, CLIENTS).
All selected inputs must fit within the attachment limits. If they don’t, the call fails before the request is sent. The client doesn’t drop or truncate files to fit.
Extracting case fields
Case fields hold values that describe a whole packet instead of one document in it, such as the applicant’s name across a loan application. To extract case fields, pass a list of case field definitions to case_schema. Each definition accepts the same keys as an explicit field definition.
To extract or validate only some case fields, pass their names to case_fields, for example case_fields=["applicant_name"]. When a session has case_schema, the results returned by extract() include a case_fields key.
Using OCR text
By default, the client sends the source files without OCR text, and extracted fields have no bounding boxes. To return bounding boxes—which can be useful for highlighting the location of extracted text on a document in review—set use_ocr=True to attach the OCR text from the Process files step. The step writes the boxes to the output file with the extracted values.
The model places the boxes from the OCR text, so a box shows approximately where a value appears. It isn’t guaranteed to match the exact position of each word.
use_ocr is on and an input has no readable OCR text from the Process files step, the call fails.Reading extraction results
extract() returns the session’s current records under the records key. Each record contains:
Field values are plain data. The agent client doesn’t return page numbers or bounding boxes to your code. The step adds page provenance when it writes the output file, and with use_ocr=True, it also writes the bounding boxes that review uses to highlight extracted values.
Each full extraction replaces the session’s previous results.
Checking extracted results
The agent client offers three ways to check extraction results. Choose based on how independent the check must be and what you want to happen with the result:
Validating extracted fields
validate_async() and validate() ask the model to check the session’s extracted values against the source files and return a verdict for each field. validate_async() queues the validation after any queued extraction, so you can call it immediately after extract_async():
The session must have extracted values before validation runs. validate() waits for the result and returns it under the validation_results key. For each record, the result lists each field with these keys:
The step writes the verdicts to the output file with the extracted records.
To validate only some fields, pass their names in fields. To validate case fields, pass their names in case_fields. Both methods also accept model, reasoning_effort, and timeout_seconds, and amend.
Asking the model to recheck its extraction
Set qa_follow_up=True on extract_async() to run a second pass after the extraction. The second pass uses a built-in prompt that asks the model to review its extraction against the source files, correct errors or omissions, and return a complete result. The second result replaces the first and is written to the step output.
The second pass continues from the first extraction, so it’s a self-review, not an independent check. You don’t need to set amend=True for the second pass. The client chooses how to continue from the first extraction. qa_follow_up is available only on extract_async().
Getting an independent review
For a second opinion, ask the model to check the results in a new thread. The review doesn’t inherit the extraction thread’s history, so it doesn’t repeat the extraction’s assumptions. The extracted records are kept for output.
The following example reads the app’s conversation ID from the agent_v2_channel_id runtime key and calls set_channel_id() to start the new thread. For details, see Starting a new thread.
Set the Map UDF formula to extract_and_review(INPUT_RECORD, CLIENTS, CONFIG).
The step writes both the extraction output and the review file. Keep these points in mind:
-
Include the values to check in the review prompt. The new thread doesn’t see the earlier prompts or responses.
-
The review response doesn’t change extracted values or fail the step. To act on it, correct the fields, or raise an error to fail the step.
-
Later
generate()calls in the session continue the review thread. To start another independent review, callset_channel_id()again. -
Instructions from
skill_textorskill_pathare sent with the review too, so write them to allow verification tasks.
Correcting extracted fields
You can correct extracted values by asking the model to re-extract specific fields, or by editing the values in your code.
Re-extracting specific fields
To re-extract specific fields after an initial extraction, call extract() again with fields. The named fields are replaced and other fields stay unchanged. The step writes the corrected result.
You can name a table field, such as fields=["transactions"]. This replaces the whole table, not individual rows or cells.
Re-extracting fields requires the session to contain exactly one record, for example a Map UDF session over a single file with allow_multiple_records=False. If the session contains several records, such as records from a combined packet, the call fails. To correct those records, edit the values instead.
Editing extracted values
To change values in your code, such as to normalize a format, call set_extraction(data). It replaces field values in records the session already extracted, and the step writes the edited result. This works for sessions with any number of records.
data uses the same format that extract() returns:
The client finds each record by its source_id and record_id together. The class_name must match the extracted record, and fields must contain every field the record has. Records you leave out stay unchanged. You can’t use set_extraction() to add, delete, or reclassify records.
The following example edits only the bank statement records in a packet:
New values are checked against the field’s data type. An edited value doesn’t keep the bounding boxes of the original value.
How the step writes output
After your custom function finishes running, the step:
-
Writes any manual files returned through
out_files. -
Waits for all queued extraction and validation to finish.
-
Writes the extracted records and any validation verdicts to IBMessage (
.ibmsg) files. A Map UDF writes one file, named after the input’s output file name. A Reduce UDF writes one file for each source file that has records, named after that source file.
The step returns manual files first, followed by extraction files in the order the sessions were created. If a manual file has the same name as an extraction file, the extraction file replaces it.
In a Reduce UDF, returning None normally copies the input files to the step output. When the custom function has started extraction, the step writes only the extraction output and doesn’t copy the inputs, even if no records were extracted.
Each source file can belong to only one extraction session. In a Map UDF, create a single extraction session and reuse it for follow-up calls.
Processing packets
To make every file in a packet available to a single Map UDF function call, configure the flow as Process files > Combine > Map UDF. Use this pattern when the model needs the full packet as context, such as classifying related documents together.
For more about Combine settings in packet flows, see Packet processing flows.
Configure the Combine step as follows:
Same-file and join-field combining take precedence over combining all records, so both must be turned off.
Connect the Combine output to the Map UDF. Combine produces one combined_files.ibmsg file that references every source. It doesn’t merge the files into one PDF. The Map UDF runs once for the combined file.
per_job thread sharing, steps in the same run also share context.With the default input selection, the session attaches every source in the packet to the first message:
allow_multiple_records controls the number of records per source file, not the number of attached files. Set it to False to require one record per source while still attaching the whole packet.
Sharing a thread across Map UDF calls with per_step or per_job doesn’t give the model the full packet up front, because each call attaches only its own input. Use Combine when the model needs every file in the first message.
To attach part of the packet, pass handles from input_sources() to for_inputs(). A Reduce UDF can attach all its inputs in one session without Combine.
Managing threads
The agent client organizes model calls in three layers:
-
Conversation — A container on the platform that holds threads. Conversation IDs begin with
conv_. App and deployment runs get a conversation automatically, and sessions use it without any setup. If your custom function needs the ID, read it from theagent_v2_channel_idruntime key. The key isn’t set for every run, so check that it’s present before you use it. -
Thread — A sequence of model calls inside a conversation. The first call in a thread attaches the source files, and follow-up calls in the same thread reuse those attachments.
-
Session — The object that
for_inputs()returns. A session sends its calls to one thread at a time.
A conversation can contain many threads, and several sessions can share one thread. A session can move to a new thread without losing its results.
Each follow-up call in a thread builds on the thread’s first message and its response. Don’t rely on the model seeing the answers to earlier follow-up calls. Extraction and validation calls also send the current extracted values with each request. For generate(), include any earlier results the model needs in your prompt.
Sharing threads between sessions
conversation_share controls which sessions share a thread. The run’s conversation determines where threads are created, and conversation_share determines which sessions share a thread within it. It doesn’t change the input selection or schema.
per_job setting, calls run one at a time, and later records can see context from earlier ones. Use none or per_record when records must be processed independently or in parallel.Continuing the agent’s working session
By default, each extraction or validation call is a new turn in the thread. To continue the agent’s working session from the thread’s first message instead, pass amend=True to extract(), extract_async(), validate(), or validate_async(). The agent keeps what it already read.
Keep these points in mind:
-
An amended call isn’t an independent review. For a second opinion not influenced by the thread’s context, use a new thread.
-
If the thread has no first message yet, the call runs as a normal first turn.
-
In a shared thread, the working session and its accumulated context are shared too.
Starting a new thread
To start a new thread in a conversation, pass its ID to the channel_id argument of for_inputs(), or call set_channel_id() on an existing session. The session attaches the selected inputs to the new thread’s first message. Passing the same ID again starts another new thread.
Use the conversation ID from the agent_v2_channel_id runtime key.
Switching threads keeps the session’s extracted results, input selection, schema, and instructions. If you queued extraction with extract_async(), the switch waits for it to finish first.
To return to the thread that conversation_share chooses, call set_channel_id(None).
Continuing a recorded thread
conversation_id and set_conversation_id() continue a thread that the agent client started earlier in the same run, instead of starting a new one. Inputs already in the thread aren’t attached again. set_conversation_id(None) returns to the thread that conversation_share chooses.
Continuing a thread works only when the client recorded the conversation’s thread for the same user and run, and the record hasn’t expired. A conversation created elsewhere can’t be continued, even if it has only one thread. In most cases, use conversation_share or channel_id instead.
Limits and failure behavior
Keep the following limits and failure rules in mind when you design your custom function. The agent client never silently drops files or returns partial results to stay within a limit. The call fails instead.
-
Attachments — A session can attach at most 100 files, counting source files, prior extraction, and OCR attachments. The client reserves one additional attachment for the schema and extracted values it sends.
-
Sessions — Each custom function call can create at most 128 sessions.
-
File size — With the agent client enabled, Agent Mode app runs accept up to 100 files, with each file up to 1 GiB and up to 2 GiB in total. Other ways of uploading files keep their own limits. See Preparing large files.
-
Timeouts — Extraction calls time out after four hours by default, and
generate()and validation calls after 840 seconds. Queued extraction counts against the step timeout, including time spent waiting in the queue and uploading files. A Reduce UDF step has no overall time limit by default, but each call still has its own timeout. -
Queued extraction failures — If queued extraction fails, the step fails, even if the custom function catches an error from a later call. Manual files already written aren’t removed.
-
Custom function errors and timeouts — If the custom function raises an error or the step times out, the client cancels queued and in-progress calls and the step fails. Manual files already written aren’t removed.
-
Caught errors — If you catch an error from
extract(), the session keeps its previous results.
Preparing large files
To prepare large files for the agent client, turn off OCR in the Process files step. Files processed without OCR have no OCR text, so you can’t use use_ocr=True with them. For other file size and page limits, see File upload limitations.
