Skip to navigation
Opt-in Enterprise

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

Before you begin

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.

  1. 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.
  2. Add your Python function to the flow scripts and register it with @register_fn(provenance=False) from instabase.provenance.registration.

  3. Include CLIENTS in the step formula and add a matching parameter to the function signature. For example, set the Map UDF formula to extract_statement(INPUT_RECORD, CLIENTS). The examples on this page name the parameter clients, so they access the agent client as clients.agent_client. End the signature with **kwargs. The step passes extra keyword arguments to every registered function, and a function without **kwargs fails with an unexpected keyword argument error. For the other variables you can pass, see Map UDF and Reduce UDF.

  4. Check that the agent client is available. If it isn’t available for a run, such as when it isn’t enabled, clients.agent_client is None:

    if clients.agent_client is None:
    raise RuntimeError("The agent client isn't available for this flow.")
  5. 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.

  6. Call a session method:

    • extract_async() or extract() extracts records against a schema and writes them to the step output automatically.

    • validate_async() or validate() 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() and validate_async(). They queue the work and return immediately, and the step waits for the work to finish before it writes the output. extract() and validate() 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:

ArgumentTypeDescription
inputslistOptional first positional argument. Input payloads, input paths, or source handles to include. Default: the Map UDF input or all Reduce UDF inputs.
schemadictExtraction schema. Required for extract() and extract_async(). See Defining a schema.
examplesdictExample-based schema. Use instead of schema when field names conflict with explicit schema keys.
case_schemalistCase field definitions for values that describe the whole packet. See Extracting case fields.
allow_multiple_recordsbooleanAllow zero or more records for each source file. Default: False. See Setting the number of records per source.
skill_textstringInstructions sent with every call.
skill_pathstringPath to a .md or .txt file of instructions, relative to the flow directory. See Adding instructions.
use_ocrbooleanAttach OCR text to each call and return field bounding boxes. Default: False. See Using OCR text.
conversation_sharestringHow the session shares threads. Default: per_job. See Sharing threads between sessions.
channel_idstringConversation ID to start a new thread in. See Starting a new thread.
conversation_idstringConversation ID whose recorded thread to continue. Can’t be combined with channel_id. See Continuing a recorded thread.

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.

selected_sources = clients.agent_client.input_sources()[:2]
if selected_sources:
session = clients.agent_client.for_inputs(
selected_sources,
schema=SCHEMA,
allow_multiple_records=True,
)
session.extract_async("Classify and extract only the selected sources.")

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:

ArgumentTypeDescription
modelstringModel to use for this call. Default: superagent-pro. superagent-pro allows the SuperApp AI agent to choose the best model for each task.
Other models available for model vary by organization. For details about the models available in your organization, connect with Instabase Support.
reasoning_effortstringReasoning effort for this call: low, medium, high, xhigh, or max. Supported levels depend on the model. If omitted, superagent-pro chooses the reasoning effort for each task, and other models use their default level.
timeout_secondsnumberMaximum time allowed for this call, in seconds. Must be a positive, finite number. Default: four hours for extract() and extract_async(), and 840 seconds for the other methods. The step’s own time limit still applies.

For example, to extract at high reasoning effort and allow the extraction to run for up to 30 minutes:

session.extract_async(
"Extract the bank statement fields.",
reasoning_effort="high",
timeout_seconds=1800,
)

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.

Because 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).

import json
from instabase.provenance.registration import register_fn
DOCUMENT_CHECK = {
"type": "object",
"properties": {
"is_bank_statement": {"type": "boolean"},
"reason": {"type": "string"},
},
"required": ["is_bank_statement", "reason"],
"additionalProperties": False,
}
@register_fn(provenance=False)
def extract_if_statement(input_record, clients, **kwargs):
session = clients.agent_client.for_inputs(schema=STATEMENT_SCHEMA)
response = session.generate(
"Is this document a bank statement? Explain your answer in one sentence.",
response_schema=DOCUMENT_CHECK,
)
answer = json.loads(response["output_text"])
if not answer["is_bank_statement"]:
return {
"out_files": [
{
"filename": input_record["output_filename"] + ".skipped.txt",
"content": answer["reason"].encode("utf-8"),
}
]
}
session.extract_async("Extract the bank statement fields.")
return None

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().

ArgumentTypeDescription
response_schemadictJSON schema for structured output. The structured result is returned as JSON text in output_text.
fileslistAttachments to send with this call instead of the session’s input files.
additional_fileslistAttachments to send with this call in addition to the session’s input files.

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).

from instabase.provenance.registration import register_fn
STATEMENT_SCHEMA = {
"Bank statement": {
"bank_name": "",
"account_number": "",
"transactions": [{"date": "YYYY-MM-DD", "amount": ""}],
}
}
@register_fn(provenance=False)
def extract_statement(input_record, clients, **kwargs):
session = clients.agent_client.for_inputs(schema=STATEMENT_SCHEMA)
session.extract_async("Extract the bank statement fields.")
return None

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.

SCHEMA = {
"Bank statement": {
"bank_name": "",
"account_number": "",
"transactions": [{"date": "YYYY-MM-DD", "amount": ""}],
},
"Invoice": {
"invoice_number": "",
"line_items": ["Item description"],
},
}

The client converts example values as follows:

Example valueResulting field
A string, number, or booleanText field. A number or date example is still extracted as text.
NoneText field that can be absent or empty in the source.
A list of stringsText list field.
A list of objectsTable field. Each object property becomes a text column.

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:

SCHEMA = {
"Bank statement": {
"description": "A monthly statement for a single bank account.",
"fields": [
{"name": "bank_name"},
{
"name": "account_number",
"data_type": "TEXT",
"description": "The account number printed in the statement header.",
"prompt": "Preserve leading zeros.",
},
{
"name": "account_holders",
"data_type": "TEXT_LIST",
"description": "The name of each person the account belongs to.",
},
{
"name": "transactions",
"data_type": "OBJECT_LIST",
"description": "Every transaction in the statement.",
"prompt": "Include transactions that continue onto later pages.",
"prompt_schema": [
{"name": "date", "data_type": "TEXT", "description": "Transaction date as YYYY-MM-DD."},
{"name": "payee", "data_type": "TEXT"},
{"name": "amount", "data_type": "TEXT", "description": "Withdrawals are negative."},
],
},
{
"name": "fee_schedule",
"data_type": "TABLE",
"description": "The table of account fees, if the statement has one.",
},
],
},
"Invoice": {
"fields": [{"name": "invoice_number", "data_type": "TEXT"}],
},
}

Each class accepts these keys:

KeyDescription
fieldsList of field definitions.
descriptionDescription of the class.

Each field definition accepts these keys:

KeyDescription
nameField name. Required.
data_typeThe field’s data type, which sets the format of the extracted value. Default: TEXT.
• TEXT — A string.
• TEXT_LIST — A list of strings.
• OBJECT_LIST — A list of objects with the columns defined in prompt_schema. Without prompt_schema, extracted like TABLE.
• TABLE — A list of rows, each a list of strings.
• ENUM — A string.
• VISION — A string.
descriptionWhat the field contains. The client sends it to the model with the field.
promptExtraction instructions for this field. The client sends them to the model with the field’s description.
prompt_schemaFor an OBJECT_LIST field, the list of columns in each object. Each column accepts name (required), data_type, and description. Columns are extracted as text.

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:

SettingRecords required for each source file
False (default)Exactly one record, belonging to one of the schema’s classes.
TrueZero or more records, each belonging to one of the schema’s classes. The same class can repeat.

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).

from instabase.provenance.registration import register_fn
@register_fn(provenance=False)
def extract_documents(input_records, clients, **kwargs):
session = clients.agent_client.for_inputs(
schema=SCHEMA,
allow_multiple_records=True,
skill_text="Keep each statement or invoice separate. Preserve source pages.",
)
session.extract_async("Classify and extract every source file.")
return None

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.

CASE_SCHEMA = [
{
"name": "applicant_name",
"data_type": "TEXT",
"description": "The applicant's full name, as it appears across the packet.",
},
]
session = clients.agent_client.for_inputs(
schema=SCHEMA,
case_schema=CASE_SCHEMA,
allow_multiple_records=True,
)
session.extract_async("Classify and extract every document, then fill in the case fields.")

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.

If 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:

KeyDescription
source_idID of the source file the record came from.
record_idStable ID of the record.
class_nameClass the record belongs to.
fieldsExtracted field values, keyed by field name.

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:

MethodWhat it doesResult
validate_async() or validate()Asks the model for a verdict on each extracted field.Verdicts are written to the step output with the records.
extract_async(qa_follow_up=True)Has the model review its own extraction and return a corrected result.The corrected result replaces the first extraction.
A review in a new threadAsks the model to check the values without the extraction’s history.Your custom function decides what to do with the response.

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():

from instabase.provenance.registration import register_fn
@register_fn(provenance=False)
def extract_and_validate(input_record, clients, **kwargs):
session = clients.agent_client.for_inputs(schema=STATEMENT_SCHEMA)
session.extract_async("Extract the bank statement fields.")
session.validate_async(
"Check that the account number matches the statement header "
"and that every transaction has a date and an amount."
)
return None

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:

KeyDescription
field_nameThe field that was checked.
validFalse if the field has any failure or critical alert. A field with only warning alerts is valid.
validation_alertsThe model’s findings. Each alert has an alert_level of warning, failure, or critical, and a msg that explains the finding.

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.

session.extract_async("Extract the bank statement fields.", qa_follow_up=True)

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).

import json
from instabase.provenance.registration import register_fn
@register_fn(provenance=False)
def extract_and_review(input_record, clients, config, **kwargs):
channel_id = config.get("keys", {}).get("custom", {}).get("agent_v2_channel_id")
if channel_id is None:
raise RuntimeError("No conversation is available to start a review thread in.")
session = clients.agent_client.for_inputs(schema=STATEMENT_SCHEMA)
extracted = session.extract("Extract the bank statement fields.")
# Start a new thread in the same conversation. Extracted records are kept.
session.set_channel_id(channel_id)
review = session.generate(
"Independently verify these values against the attached files. "
"Don't assume they're correct. For each discrepancy, list the source, "
"record, field, and evidence.\n"
+ json.dumps(extracted["records"])
)
return {
"out_files": [
{
"filename": input_record["output_filename"] + ".review.txt",
"content": review["output_text"].encode("utf-8"),
}
]
}

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, call set_channel_id() again.

  • Instructions from skill_text or skill_path are 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.

session.extract("Extract this bank statement.")
session.extract(
"Recheck the account number against the statement header. Preserve leading zeros.",
fields=["account_number"],
)

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:

KeyDescription
recordsRequired. The records to edit. Each record must have exactly the keys source_id, record_id, class_name, and fields.
case_fieldsOptional. Only for sessions with case_schema. Every case field, each exactly once, as extract() returned them. Case field values are strings, so pass list and table values as JSON text.

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:

result = session.extract("Extract every document in this packet.")
edits = []
for record in result["records"]:
account_number = record["fields"].get("account_number")
if record["class_name"] == "Bank statement" and account_number:
record["fields"]["account_number"] = account_number.replace(" ", "")
edits.append(record)
if edits:
session.set_extraction({"records": edits})

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:

  1. Writes any manual files returned through out_files.

  2. Waits for all queued extraction and validation to finish.

  3. 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:

SettingValue
Combine same file records from different branchesNo
Join Field GroupsEmpty
Combine all file records from different branchesYes
Output File Name if combine all file recordscombined_files

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.

Combine merges every file in the run. Run each packet in a separate app or deployment run so unrelated files don’t end up in the same packet. With the default 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:

from instabase.provenance.registration import register_fn
@register_fn(provenance=False)
def extract_packet(input_record, clients, **kwargs):
session = clients.agent_client.for_inputs(
schema=SCHEMA,
allow_multiple_records=True,
conversation_share="per_record",
skill_path="extract.udf/skill.md",
)
session.extract_async("Classify and extract every document in this packet.")
return None

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 the agent_v2_channel_id runtime 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.

Conversation (conv_...)
├── Thread A ← extraction calls from a session
└── Thread B ← the same session's review calls, after set_channel_id()

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.

SettingThread behavior
noneEach call runs independently, with no shared history, and attaches the session’s files again.
per_recordEach session gets a private thread. For example, one thread for each Map UDF input or combined packet. Follow-up calls in that session reuse the thread.
per_stepSessions in the same step and run share a thread.
per_job (default)Sessions in all steps that use per_job within the same run share a thread.
When threads are shared, including with the default 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.

session.extract_async("Extract every document in this packet.")
session.extract_async("<your follow-up instructions>", amend=True)

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.

Troubleshooting

ErrorCause and resolution
<function>() got an unexpected keyword argument '_FN_CONTEXT_KEY'The function signature doesn’t accept extra keyword arguments. Add **kwargs to the end of the signature.
Specify skill_path or skill_text, not bothPass only one instruction argument to for_inputs().
Specify schema or examples, not bothPass only one schema argument to for_inputs().
Agent Mode v2 supports at most 100 source, prior-extraction and OCR attachmentsThe session selects too many files. Select fewer sources or split the work across sessions.
This step writes one output file per input: reuse the existing extraction sessionA Map UDF created a second extraction session. Reuse the first session.
Another extraction session already owns <files>; reuse it or select other inputsTwo extraction sessions selected the same source file. Select different sources for each session.
Generation input routing is owned by the session; use for_inputs and settersgenerate() received an unsupported argument. Set inputs and instructions with for_inputs().
Extraction input/schema routing is owned by the session; use for_inputs and settersextract() or extract_async() received an unsupported argument. Set inputs, the schema, and instructions with for_inputs().
channel_id must be an API-issued SuperApp Conversation ID beginning with conv_The ID passed to channel_id isn’t a valid conversation ID. Use the agent_v2_channel_id runtime key.
Partial extraction is not supported while several documents are collectedextract() was called with fields on a session that holds several records. Use set_extraction() instead.
Partial extraction requires an existing classextract() was called with fields before a full extraction. Call extract() without fields first.
Validation requires a completed extraction or loaded extraction values in this packet sessionvalidate() was called before the session had extracted values. Extract first, or use validate_async() after extract_async().
No extraction to editset_extraction() was called before the session had extracted values. Extract first.
Expected a records viewset_extraction() received something other than a dictionary with a records list, or a case_fields key on a session without case_schema. See Editing extracted values.
Invalid record editA record passed to set_extraction() has keys other than source_id, record_id, class_name, and fields.
Value edits must retain the record field setA record passed to set_extraction() added or removed fields. Keep every field and change only values.
Record edits require unique existing source, record, and class identitiesA record passed to set_extraction() is new, duplicated, or has a different class. Edit only the records that extract() returned.
Different source files would share the output file <name>Two source files in a Reduce UDF have the same file name, so their extraction files would collide. Rename one of the input files.
Source-backed extraction requires ingestion to ibmsg/ibdoc firstAn input to an extraction session couldn’t be processed. Place this step after Process files in the flow.
use_ocr is on, but the OCR lines of an input record could not be readAn input has no OCR text. Place this step after Process files in the flow, or set use_ocr=False.
Conversation has no uniquely known completed rootThe conversation passed to conversation_id has no recorded thread to continue, or has more than one. Use channel_id to start a new thread instead.
Managed Agent Mode v2 sessions require a Flow v3 execution scopeThe custom function isn’t running in a Map UDF or Reduce UDF step.