### Example: Deductions table with structured output Source: https://docs.instabase.com/automate/llms-custom-functions Reads a file from context['file_path'], uses the file client to get content, and calls generate_content with a prompt, file data, and a response schema to return a deductions table. Handles missing clients by returning None. ```python file_path = context['file_path'] clients = context.get('clients', {}) file_client = clients.get('ibfile') llm_client = clients.get('llm_client') if llm_client is None or file_client is None: return None # or your fallback when the LLM client isn't available file_content, err = file_client.read_file(file_path) resp_text = llm_client.generate_content( prompt='Return the deductions table. remove any extra symbols from the amount deducted', file_data=file_content, mime_type='application/pdf', file_path=file_path, response_schema={ "type": "array", "items": { "type": "object", "properties": { "description": {"type": "string"}, "amount deducted": {"type": "float"}, }, }, "description": "deductions table" } ) return resp_text ``` -------------------------------- ### Install instabase-aihub with pip Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/2-prepare Install the instabase-aihub module from PyPI using pip. ```bash pip install instabase-aihub ``` -------------------------------- ### Example response for listing files in a batch Source: https://docs.instabase.com/api-sdk/api-reference/batches/list-files Example JSON response from the list files endpoint, showing file nodes with metadata, permissions, pagination token, and has_more flag. ```json { "nodes": [ { "full_path": "/path/to/document1.pdf", "metadata": { "node_type": "file", "size": 1024, "modified_timestamp": 1647532800 }, "perms": { "can_read": true, "can_write": true, "can_delete": true }, "name": "document1.pdf" }, { "full_path": "/path/to/document2.pdf", "metadata": { "node_type": "file", "size": 2048, "modified_timestamp": 1647619200 }, "perms": { "can_read": true, "can_write": false, "can_delete": false }, "name": "document2.pdf" } ], "next_page_token": "eyJwYWdlIjogMn0=", "has_more": true } ``` -------------------------------- ### Example output from automate_with_sdk.py Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/4-automate Example output from running automate_with_sdk.py. Shows the sequence of status messages and the extracted fields for two receipt files. The STOPPED_AT_CHECKPOINT status indicates the app wants human review of some values. ```text creating an empty batch uploading two files to the batch running the app checking the app status until it finishes status: RUNNING status: RUNNING status: RUNNING status: STOPPED_AT_CHECKPOINT fetching the app results file name: receipt-a.jpg Total_Amount: 164.46 Vendor: Flo's Greasy Spoon Diner Date: 07/25/2025 Transaction_ID: N/A Vendor_Address: 123 Main St Springfield, Missouri Subtotal: 152.99 Tax: 11.47 Tip: N/A Receipt_Item_Details: [{"Description": "Beluga Caviar", "Quantity": "1", "Amount": "150.0"}, {"Description": "Cherry Coke", "Quantity": "1", "Amount": "2.99"}] --- file name: receipt-b.jpg Total_Amount: 9619.21 Vendor: CJ's Burger Shack Date: 07/16/2025 Transaction_ID: N/A Vendor_Address: 17 Montgomery Road Dallas, Texas Subtotal: 9204.99 Tax: 414.22 Tip: N/A Receipt_Item_Details: [{"Description": "Lg Basket Fries", "Quantity": "6", "Amount": "5.99"}, {"Description": "Bot Roman\u00e9e-Conti", "Quantity": "1", "Amount": "9199.00"}] --- ``` -------------------------------- ### Full Pagination Example for /api/v1/flow_binary/results (Python) Source: https://docs.instabase.com/api-sdk/api-reference/legacy/run-results-endpoint Iterates through all pages of results by updating file_offset based on the last record's file_index. Continues until the response is empty. Requires the same setup as the basic request. ```python url = url_base + '/api/v1/flow_binary/results' args = { 'ibresults_path': "/jaydoe/my_repo/fs/Instabase Drive/flow_proj/out/batch.ibflowresults", 'options': { 'refined_phrases_features': ['provenance_info'], 'include_page_layouts': True, }, 'file_offset': 0 } json_data = json.dumps(args) headers = { 'Authorization': 'Bearer {0}'.format(token) } r = requests.post(url, data=json_data, headers=headers) resp_data = json.loads(r.content) # Parse through pages until no more pages left to look through all_records = [resp_data.get('records', [])] while len(resp_data) > 0: # Retrieve the last file_index from the last record returned next_file_offset = resp_data['records'][-1]['file_index'] + 1 args['file_offset'] = next_file_offset json_data = json.dumps(args) r = requests.post(url, data=json_data, headers=headers) resp_data = json.loads(r.content) resp_records = resp_data.get('records', []) all_records.extend(resp_records) ``` -------------------------------- ### Example response for listing runs Source: https://docs.instabase.com/api-sdk/api-reference/runs/list-runs Example 200 response showing a run object with fields such as id, status, timestamps, and tags. ```json { "runs": [ { "id": "run_9f8b7c6d5e4a3b2c1d0e", "status": "CANCELLED", "start_timestamp": 1685606400000000000, "finish_timestamp": 1685608200000000000, "msg": "User cancelled the run due to incorrect input parameters.", "batch_id": 42, "input_dir": "/data/input/batch_42", "app_id": "app_1234567890abcdef", "deployment_id": "deploy_0987654321fedcba", "tags": [ "urgent", "test-run" ] } ] } ``` -------------------------------- ### Troubleshoot installation with verbose pip commands Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/2-prepare Re-run pip with maximum verbosity (-v -v -v) to diagnose installation problems. Use the first command for a fresh install and the second for an upgrade. ```bash pip install -v -v -v instabase-aihub ``` ```bash pip install --upgrade -v -v -v instabase-aihub ``` -------------------------------- ### Successful run response Source: https://docs.instabase.com/api-sdk/api-reference/runs/run-app Example response returned when the run starts successfully. The status field indicates the run state, and the response includes the run ID, timestamps, batch ID, input directory, app ID, deployment ID, and tags. ```json { "id": "a3f1c9d2-4b7e-4f8a-9d3e-2b7f9c1a5e6d", "status": "COMPLETE", "start_timestamp": 1711929600000000000, "finish_timestamp": 1711933200000000000, "msg": "Run completed successfully.", "batch_id": 98765, "input_dir": "/instabase/drive/projects/input_data", "app_id": "528c36e8-ac5b-490d-a41b-7eec9c404b87", "deployment_id": "d4f7a9b3-1c2e-4d5f-8a9b-7c3d2e1f0a4b", "tags": [ "invoice-processing", "priority-high" ] } ``` -------------------------------- ### Example 200 response for get run results Source: https://docs.instabase.com/api-sdk/api-reference/runs/get-run-results Example 200 response for a successful get run results request. Shows the run status, file documents with extracted fields, case_info with edit history, and the has_more flag indicating pagination. Field names in the response may be converted to valid Python variable names (e.g., 'due date' becomes 'due_date'). ```json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "status": "COMPLETE", "message": "Completed single_flow", "start_timestamp": 1765912514238248700, "finish_timestamp": 1765912529614834000, "batch_id": "1235", "files": [ { "original_file_name": "test.png", "input_file_path": "instabase-sandbox-org/test-org/fs/Instabase Drive/app-runs/a1b2c3d4-e5f6-7890-abcd-ef1234567890/input/test.png", "documents": [ { "fields": [ { "field_name": "employers_address_and_ZIP_code", "value": "123 STREET RD ANYWHERE, USA,12345", "type": "TEXT" } ], "class_name": "Wage And Tax Statement", "page_numbers": [ 1, 2 ] } ] }, { "original_file_name": "test2.png", "input_file_path": "instabase-sandbox-org/test-org/fs/Instabase Drive/app-runs/a1b2c3d4-e5f6-7890-abcd-ef1234567890/input/test2.png", "documents": [ { "fields": [ { "field_name": "sex", "value": "Male", "type": "TEXT" } ], "class_name": "Driver License", "page_numbers": [ 1 ] } ] } ], "keys": [ { "custom": {} } ], "case_info": { "fields": [ { "name": "Employee_Address", "value": "123 STREET RD ANYWHERE, USA,12345", "input_fields": [ { "record_index": 0, "refined_phrase_name": "employers_address_and_ZIP_code" } ], "chosen_field": { "record_index": 0, "refined_phrase_name": "employers_address_and_ZIP_code" }, "edit_history": [ { "timestamp": "08/27/2025 00:58:39", "user_id": "john.doe_instabase.com", "modifications": [ { "message": "Edited to \"123 STREET RD ANYWHERE, USA,12345\"" } ] } ] }, { "name": "Sex", "value": "Male", "input_fields": [ { "record_index": 0, "refined_phrase_name": "sex" } ], "chosen_field": { "record_index": 0, "refined_phrase_name": "sex" } } ] }, "has_more": false } ``` -------------------------------- ### Check installed SDK version with pip show Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/2-prepare Display the installed version of the instabase-aihub SDK. ```bash pip show instabase-aihub ``` -------------------------------- ### List batches response example Source: https://docs.instabase.com/api-sdk/api-reference/batches/list-batches Example response body returned when the request is successful (HTTP 200). It contains a list of batch objects with properties such as id, name, workspace, mount_point, repo_owner, batch_owner, created_at_ms, updated_at_ms, and path_suffix. ```json { "batches": [ { "id": 1024, "name": "InvoiceProcessingBatch_April2024", "workspace": "FinanceTeamWorkspace", "mount_point": "shared_drive_01", "repo_owner": "finance_dept", "batch_owner": "alice.smith_acme.com", "created_at_ms": 1711804800000, "updated_at_ms": 1711891200000, "path_suffix": "invoices/2024/april" } ] } ``` -------------------------------- ### Successful response JSON for get batch Source: https://docs.instabase.com/api-sdk/api-reference/batches/get-batch Example of a 200 response when the batch is successfully retrieved. The response includes fields such as id, name, workspace, mount_point, repo_owner, batch_owner, created_at_ms, updated_at_ms, and path_suffix. ```json { "id": 1, "name": "string", "workspace": "string", "mount_point": "string", "repo_owner": "string", "batch_owner": "string", "created_at_ms": 1, "updated_at_ms": 1, "path_suffix": "string" } ``` -------------------------------- ### Check Python version with python3 --version Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/2-prepare Check that Python 3.7 or later is installed before installing the AI Hub SDK. ```bash python3 --version ``` -------------------------------- ### 202 Accepted response body for run deployment Source: https://docs.instabase.com/api-sdk/api-reference/runs/run-deployment Example 202 Accepted response body after successfully initiating a deployment run. Shows a cancelled run along with the run ID, start and finish timestamps, message, batch ID, input directory, app ID, deployment ID, and tags. Note that timestamps are in Unix time nanoseconds. ```json { "id": "a3f1c9e2-7b4d-4f8a-9c2e-5d6f7a8b9c0d", "status": "CANCELLED", "start_timestamp": 1686806400000000000, "finish_timestamp": 1686810000000000000, "msg": "Run was cancelled by user request.", "batch_id": 98765, "input_dir": "acme/MarketingTeam/fs/GoogleDrive/ProjectX/InputFiles/", "app_id": "app-4f7e2d9c-1234-5678-9abc-def012345678", "deployment_id": "01902d6f-bb35-74cb-bd27-c09b38bbf20a", "tags": [ "urgent", "Q2-report" ] } ``` -------------------------------- ### Run an app with cURL Source: https://docs.instabase.com/api-sdk/api-reference/runs/run-app Use this cURL command to start an automation app run by providing a batch ID and app name. The request requires the Authorization, IB-Context, and Content-Type headers. Replace the placeholders with your actual values. ```bash curl "${API_ROOT}/v2/apps/runs" \ -H "Authorization: Bearer ${API_TOKEN}" \ -H "IB-Context: ${IB_CONTEXT}" \ -H "Content-Type: application/json" \ -d '{ "batch_id": , "app_name": "" }' ``` -------------------------------- ### Process case kwargs JSON Source: https://docs.instabase.com/flow/guides/packet-processing-flows Example kwargs for the Process case step, setting input_folder, output_folder, case_program_path, and settings. The case_program_path typically points to modules/case.refiner/prog/case.ibrefiner. ```json { "kwargs": { "input_folder": "s4_combine", "output_folder": "s5_case", "case_program_path": "modules/case.refiner/prog/case.ibrefiner", "settings": {} }, "option": { "internalName": "process_case", "name": "Process Case" } } ``` -------------------------------- ### Import pandas and print a Series Source: https://docs.instabase.com/automate/custom-functions Example of importing the pandas library and printing a Series. Demonstrates the use of supported external libraries in custom functions. ```python import pandas as pd print(pd.Series([1,2,3])) ``` -------------------------------- ### Start multipart upload session with cURL Source: https://docs.instabase.com/api-sdk/api-reference/batches/create-multipart-upload-session Use this cURL command to start a multipart upload session for files larger than 10 MB. Replace with the target batch ID and set the API_TOKEN and IB_CONTEXT environment variables. The request body requires batch_id, filename, and file_size in bytes. ```bash curl "${API_ROOT}/v2/batches/multipart-upload" \ -H "Authorization: Bearer ${API_TOKEN}" \ -H "IB-Context: ${IB_CONTEXT}" \ -H "Content-Type: application/json" \ -d '{ "batch_id": , "filename": "large-file.pdf", "file_size": 15728640 }' ``` -------------------------------- ### Successful response for create batch Source: https://docs.instabase.com/api-sdk/api-reference/batches Example 200 response body showing the unique identifier for the created batch. ```json { "id": 1024 } ``` -------------------------------- ### Successful response from /run/sync Source: https://docs.instabase.com/api-sdk/api-reference/legacy/run-app-endpoint Example successful response from the /run/sync endpoint. The response body is a JSON object containing extracted fields, job metadata, and file processing details; fields not found are returned as empty strings. ```json HTTP STATUS CODE 200 { 'response': { 'records': [ { 'output_file_path': 'IBMSG_FILE_PATH', 'results': [ { 'key': 'EXTRACTION_FIELD', 'value': 'EXTRACTION_VALUE', 'field_type': 'STRING', 'model_confidence': 0.9 } ], 'record_index': 0, 'file_name': 'PATH_TO_chips.jpg', 'document_path': 'PATH_TO_chips.jpg', 'flow_index': 0, 'file_index': 0, 'is_manually_reviewed': false, 'current_step_index': 2, 'is_human_corrected': false, 'absolute_ibocr_path': 'OCR_PATH', 'was_classified': false, 'is_finalized': true } ], 'binary_path': 'IBFLOWBIN_PATH', 'job_id': '53275652-abc8-479e-89f2-ccb12af401a0', 'num_tasks': 1, 'has_more_tasks': false, 'next_offset': 1, 'can_resume': false, 'on_last_resumable_step': false } } ``` -------------------------------- ### Complete test program Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/3-test The full program that imports the SDK, initializes the client, creates a batch, and prints success messages. Includes comments explaining each step. ```python # make the AI Hub SDK available for use from aihub import AIHub # initialize the "client" variable as an instance of the AIHub class, # configured with authorization details for our AI Hub account client = AIHub(api_root="PASTE YOUR API ROOT HERE", api_key="PASTE YOUR API KEY HERE", ib_context="PASTE YOUR IB-CONTEXT HERE") # create a new batch called "test batch" in the # "SDK-Tutorial" workspace create_batch_resp = client.batches.create(name="test batch", workspace="SDK-Tutorial") # If the batch was created successfully, the program prints the # messages below and quits normally. If it wasn't created successfully, # Python automatically prints an error message and quits the program. print("Successfully created a batch.") print("The AI Hub SDK is installed, authorized, and ready to use.") ``` -------------------------------- ### Get run status response example Source: https://docs.instabase.com/api-sdk/api-reference/runs/get-run-status Example JSON response returned by the Get run status endpoint. The status field can be CANCELLED, COMPLETE, FAILED, PAUSED, RUNNING, or STOPPED_AT_CHECKPOINT. finish_timestamp is null if the run is still in progress. ```json { "id": "string", "status": "CANCELLED", "start_timestamp": 1, "finish_timestamp": 1, "msg": "string", "batch_id": 1, "input_dir": "string", "app_id": "string", "deployment_id": "string", "tags": [ "string" ] } ``` -------------------------------- ### Complete SDK script to initialize client, create batch, upload files, run app, and get results Source: https://docs.instabase.com/api-sdk/apps-sdk Use this complete script to initialize the SDK client, create a batch, upload local files, run an automation app, poll its status until complete, and retrieve results. The files are opened in binary mode and added to the batch. The script returns app run results as a Python dictionary. Requires valid API key, and optionally an api_root and ib_context. ```python import os import time from aihub import AIHub # initialize the SDK client client = AIHub(api_root=, api_key=, ib_context=) # create a batch batch = client.batches.create(name=) # add files to the batch file_paths = [, ] for path in file_paths: with open(path, 'rb') as file: client.batches.add_file(batch_id=batch.id, file_name=os.path.basename(path), file=file) run = client.apps.runs.create(app_name=, owner=, batch_id=batch.id) # repeatedly check run status until run is complete status = client.apps.runs.status(run.id) while status.status == 'RUNNING': time.sleep(5) # polling interval in seconds status = client.apps.runs.status(run.id) # get app run results results = client.apps.runs.results(run.id) ``` -------------------------------- ### Hello, SDK user in Go Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/1-intro Go program that prints 'Hello, SDK user' to the console. Shown as a comparison to Java and Python versions. ```Go package main import "fmt" func main() { fmt.Println("Hello, SDK user") } ``` -------------------------------- ### Sample package.json for custom library solution Source: https://docs.instabase.com/flow/custom-functions/dev-packages Example metadata file for a developer package named ib_classifier_docsplitting. Includes required fields (name, version, descriptions, authors, accelerator_type, industry, business_vertical, package_type, function_type) and optional fields (icon_url, beta, encryption_config). ```json { "name": "ib_classifier_docsplitting", "version": "1.0.1", "short_description": "Classifier for variable-length document bundles", "long_description": "The docsplitting classifier learns to split a PDF bundle of documents, and predict the class of each document. Import FirstPageDocsplittingClassifier from docsplit_classifier in the solution.", "authors": [ "Instabase" ], "accelerator_type": [ "package" ], "industry": [], "business_vertical": [], "package_type": [ "integration" ], "function_type": [ "machine learning" ], "icon_url": "icon.png", "beta": true, "encryption_config": { "encryption_type": "v1" } } ``` -------------------------------- ### Hello, SDK user in Java Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/1-intro Java program that prints 'Hello, SDK user' to the console. Shown as a comparison to Go and Python versions. ```Java public class HelloSdkUser { public static void main(String[] args) { System.out.println("Hello, SDK user"); } } ``` -------------------------------- ### Hello, SDK user in Python Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/1-intro Python program that prints 'Hello, SDK user' to the console. Shown as a comparison to Go and Java versions. ```Python print("Hello, SDK user") ``` -------------------------------- ### Test the SDK by creating a batch Source: https://docs.instabase.com/api-sdk Creates a test batch and prints the result. If the output includes id= and no errors, the SDK is working as expected. ```python batch = client.batches.create(name='test-batch') print(batch) ``` -------------------------------- ### Python dict type example Source: https://docs.instabase.com/flow/step-config-reference/creating-validation-checkpoints Example of a Python dict type used in a type validation condition. It maps keys to values. ```python { "key1": "val1", "key2": "val2", "key3": "val3" } ``` -------------------------------- ### Initialize AIHub client with authorization details Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/3-test Instantiates the AIHub class with api_root, api_key, and ib_context. Replace the placeholder values with your actual authorization details. ```python client = AIHub(api_root="PASTE YOUR API ROOT HERE", api_key="PASTE YOUR API KEY HERE", ib_context="PASTE YOUR IB-CONTEXT HERE") ``` -------------------------------- ### GET /api/v2/batches Source: https://docs.instabase.com/api-sdk/api-reference/batches/list-batches This snippet documents the GET /api/v2/batches endpoint, which returns a list of batches with optional query parameters for filtering and pagination. ```APIDOC ## [GET] /api/v2/batches ### Description Returns a list of batches. Use query parameters to filter results. ### Method GET ### Endpoint /api/v2/batches ### Parameters #### Query Parameters - **workspace** (string) - Optional - Filter to batches in the specified workspace. - **username** (string) - Optional - Filter to batches created by the specified username (user ID). - **limit** (integer) - Optional - If paginating results, specify how many batches to return. - **offset** (integer) - Optional - If paginating results, specify the offset of the returned list. #### Headers - **IB-Context** (string) - Optional - Typically your organization ID. See Authorization and context identification for details. ### Authentication Authorization: Bearer - Bearer HTTP authentication. ### Request Example ``` curl "${API_ROOT}/v2/batches" \ -H "Authorization: Bearer ${API_TOKEN}" \ -H "IB-Context: ${IB_CONTEXT}" \ -G \ --data-urlencode "workspace=my-workspace" \ --data-urlencode "limit=100" ``` ### Response #### Success Response (200) - **batches** (list of objects) - Optional - List of batches. See response schema for each batch object. #### Response Example ``` { "batches": [ { "id": 1024, "name": "InvoiceProcessingBatch_April2024", "workspace": "FinanceTeamWorkspace", "mount_point": "shared_drive_01", "repo_owner": "finance_dept", "batch_owner": "alice.smith_acme.com", "created_at_ms": 1711804800000, "updated_at_ms": 1711891200000, "path_suffix": "invoices/2024/april" } ] } ``` ``` -------------------------------- ### Azure storage account connection string sample Source: https://docs.instabase.com/api-sdk/api-reference/legacy/mount-endpoint Sample connection string structure for an Azure storage account with default configurations. Connection strings can embed a different subset of fields. ```text DefaultEndpointsProtocol=[http|https];AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=[core.windows.net] ``` -------------------------------- ### Example dictionary with nested fields Source: https://docs.instabase.com/flow/step-config-reference/creating-validation-checkpoints Example dictionary showing a nested field structure where a specific nested field (doubleNestedField3) might be flagged as invalid. ```json { "field1": "value 1", "field2": "value 2", "field3": { "nestedField3": { "doubleNestedField3": "value 3" } } } ``` -------------------------------- ### Complete automate_with_sdk.py program Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/4-automate Complete version of automate_with_sdk.py that moves all imports to the top and adds explanatory comments. Replace the placeholder values for API Root, API Key, IB-Context, and the paths to receipt-1.jpg and receipt-2.jpg. The third use case expects and builds on this code. ```python # prepare to use standard Python libraries import sys import time # prepare to use the SDK # and an exception that the SDK throws when authorization fails from aihub import AIHub from aihub.exceptions import UnauthorizedException # authorize the SDK client = AIHub(api_root="PASTE YOUR API ROOT HERE", api_key="PASTE YOUR API KEY HERE", ib_context="PASTE YOUR IB-CONTEXT HERE") print("creating an empty batch") try: # make an empty batch with a specific name in a specific workspace create_batch_resp = client.batches.create( name="receipt batch", workspace="SDK-Tutorial") except UnauthorizedException: # exit the program while printing a user-friendly error message and # instructions on how to fix the problem sys.exit("ERROR: SDK not authorized. " "Are the API ROOT, API KEY, and IB-Context values correct?") # store batch_id in an easy-to-read variable, since we'll use it several times batch_id = create_batch_resp.id print("uploading two files to the batch") # upload the first file to the batch client.batches.add_file(batch_id=batch_id, file_name="receipt-a.jpg", file=open("PATH/ON/YOUR/COMPUTER/TO/receipt-1.jpg", "rb")) # upload a second file to the batch client.batches.add_file(batch_id=batch_id, file_name="receipt-b.jpg", file=open("PATH/ON/YOUR/COMPUTER/TO/receipt-2.jpg", "rb")) print("running the app") # trigger an app run, specifying which app, who wrote it, and which batch it should process run_resp = client.apps.runs.create(app_name="Meal Receipt", owner="Instabase", batch_id=batch_id) print("checking the app status until it finishes") while True: # loop until explicitly told to leave the loop time.sleep(3) # pause a few seconds between each app status check status_resp = client.apps.runs.status(run_resp.id) # get the app status print(f"status: {status_resp.status}") # update the user on the app status if status_resp.status not in ["PENDING", "RUNNING"]: # these statuses mean the app is still running break # the app is done, so stop looping print("fetching the app results") results_resp = client.apps.runs.results(run_resp.id) # get the app results for file in results_resp.files: # iterate across all processed files print(f"file name: {file.original_file_name}") for document in file.documents: # iterate across all documents in a file for field in document.fields: # iterate across all fields in a document print(f" {field.field_name}: {field.value}") # print the field name and value print("---") # visual separator between files ``` -------------------------------- ### Quick start intra-class prioritization function Source: https://docs.instabase.com/automate/packet-schema Minimal intra-class prioritization function that selects the first document for each class. Use as a starting point when built-in strategies don't match your business rules. ```python def intraclass_udf(docs, keys): result = {} for class_name, class_docs in docs.items(): if class_docs: result[class_name] = class_docs[0]['index'] return result ``` -------------------------------- ### Initialize the AI Hub client Source: https://docs.instabase.com/api-sdk/apps-sdk Import the AIHub module and initialize a client with your API root, API key, and optional IB context. ```APIDOC ## Initialize the AI Hub client ### Description Import the AIHub module and create a client instance to interact with the AI Hub API. ### Method Constructor ### Endpoint `AIHub(api_root, api_key, ib_context)` ### Parameters - `api_root` (str) - Optional - The root URL of your AI Hub API. For organization accounts with a custom domain, use your organization's root API URL (e.g., `https://my-org.instabase.com/api`). If no custom domain, omit this parameter. - `api_key` (str) - Required - Your API token. - `ib_context` (str) - Optional but recommended - The value for the `IB-Context` header included with all API requests. Set to your organization ID. ### Request Example ```python client = AIHub(api_root=, api_key=, ib_context=) ``` ### Response No response body. The client is initialized for subsequent API calls. ``` -------------------------------- ### Poll batch job response example Source: https://docs.instabase.com/api-sdk/api-reference/batches/poll-batches-job Example response body returned when the batch job has completed. The state field can be COMPLETE, FAILED, CANCELLED, RUNNING, or PENDING, and the message provides additional status information. ```json { "state": "COMPLETE", "message": "string" } ``` -------------------------------- ### Create an empty batch Source: https://docs.instabase.com/api-sdk/sdk-for-beginners/3-test Creates a batch named 'test batch' in the 'SDK-Tutorial' workspace. The workspace must exist or the code fails. ```python client.batches.create(name="test batch", workspace="SDK-Tutorial") ``` -------------------------------- ### GET /api/v2/apps/runs/:run_id Source: https://docs.instabase.com/api-sdk/api-reference/runs/get-run-status This snippet documents the GET endpoint for retrieving the status of a run. It includes the endpoint path, authentication requirements, path parameters, headers, and the full response schema with all possible status values. ```APIDOC ## GET /api/v2/apps/runs/:run_id ### Description Get the status of a run. ### Method GET ### Endpoint /api/v2/apps/runs/:run_id ### Authentication Authorization: Bearer HTTP authentication. ### Parameters #### Path Parameters - **run_id** (string) - Required - The run ID. #### Headers - **IB-Context** (string) - Optional - Typically your organization ID. See Authorization and context identification for details. ### Request Example ``` curl "${API_ROOT}/v2/apps/runs/" \ -H "Authorization: Bearer ${API_TOKEN}" \ -H "IB-Context: ${IB_CONTEXT}" ``` ### Response #### Success Response (200) - **id** (string) - Optional - Run ID of the run. - **status** (enum) - Optional - Status of the run. Possible values: `CANCELLED`, `COMPLETE`, `FAILED`, `PAUSED`, `RUNNING`, `STOPPED_AT_CHECKPOINT`. - **start_timestamp** (long) - Optional - When the run started, in Unix time nanoseconds. - **finish_timestamp** (long or null) - Optional - When the run finished, in Unix time nanoseconds. `null` if run is still in progress. - **msg** (string or null) - Optional - Message about the run. - **batch_id** (integer or null) - Optional - The batch ID used as input for this run. - **input_dir** (string or null) - Optional - The path of the input folder used for this run. - **app_id** (string or null) - Optional - The app ID of the app that was run. - **deployment_id** (string or null) - Optional - The deployment ID used for this run. - **tags** (list of strings or null) - Optional - List of string tags attached to this run. #### Response Example ``` { "id": "string", "status": "CANCELLED", "start_timestamp": 1, "finish_timestamp": 1, "msg": "string", "batch_id": 1, "input_dir": "string", "app_id": "string", "deployment_id": "string", "tags": [ "string" ] } ``` ``` -------------------------------- ### Create a batch and upload files with client.batches.create() and client.batches.add_file() Source: https://docs.instabase.com/api-sdk/apps-sdk Create a batch with client.batches.create() and upload files to it with client.batches.add_file(). The batch ID remains constant so you can repeatedly use all files in the batch as app input. The name parameter is required and has a maximum length of 255 characters. The file_paths parameter is a list of paths to local files, even if there is only one path. ```python # create a batch batch = client.batches.create(name=) # add files to the batch file_paths = [, ] for path in file_paths: with open(path, 'rb') as file: client.batches.add_file(batch_id=batch.id, file_name=os.path.basename(path), file=file) ``` -------------------------------- ### cURL: Upload part to multipart session Source: https://docs.instabase.com/api-sdk/api-reference/batches/upload-multipart-part Uploads a part of a file to the multipart upload session. The part size must match the part_size from the Start multipart upload session call, except for the final part which can be smaller. Parts must be uploaded with consecutive part numbers starting at 1. ```bash curl -X PUT "${API_ROOT}/v2/batches/multipart-upload/sessions//parts/1" \ -H "Authorization: Bearer ${API_TOKEN}" \ -H "IB-Context: ${IB_CONTEXT}" \ -H "Content-Type: application/octet-stream" \ --data-binary "@part1.bin" ``` -------------------------------- ### POST API_ROOT//run/sync Source: https://docs.instabase.com/api-sdk/api-reference/legacy/run-app-endpoint Runs an app in memory synchronously, processing a list of files and returning extracted results in the response. No input or output data is persisted. ```APIDOC ## POST API_ROOT//run/sync ### Description Runs an app in memory by sending a synchronous request. The request body must be JSON-encoded. Neither input file contents nor the app run's results are saved; results are only available in the API response. ### Method POST ### Endpoint API_ROOT//run/sync ### Parameters #### Request Body - **files** (list) - Required - A list of files to process. Each file is represented by a `file_name` : `file_content` dictionary. - **file_name** (string) - Required - The name of the file to be processed. - **file_content** (Base64 encoding) - Required - Base64 representation of the content of the file. ### Request Example ```python encoded_string = base64.b64encode(open('file_name.jpg', 'rb').read()).decode('utf-8') url = f'{API_ROOT}/{APP_ID}/run/sync' run_app_payload = { 'files': [{ 'file_name': 'chips.jpg', 'file_content': encoded_string, }] } API_HEADERS = { 'Authorization': f'Bearer {API_KEY}', 'IB-Context': '' } run_app_resp = requests.post(url, data=run_app_payload, headers=API_HEADERS) print(f'Job Results: {run_app_resp.json()}') ``` ### Response #### Success Response (200) The response body is a JSON object containing all extracted fields. Extracted fields depend on how the app is built; if a field isn't found, an empty string `''` is returned. The response includes a `response` object with records, binary_path, job_id, num_tasks, has_more_tasks, next_offset, can_resume, and on_last_resumable_step. #### Response Example ```json { 'response': { 'records': [ { 'output_file_path': 'IBMSG_FILE_PATH', 'results': [ { 'key': 'EXTRACTION_FIELD', 'value': 'EXTRACTION_VALUE', 'field_type': 'STRING', 'model_confidence': 0.9 } ], 'record_index': 0, 'file_name': 'PATH_TO_chips.jpg', 'document_path': 'PATH_TO_chips.jpg', 'flow_index': 0, 'file_index': 0, 'is_manually_reviewed': false, 'current_step_index': 2, 'is_human_corrected': false, 'absolute_ibocr_path': 'OCR_PATH', 'was_classified': false, 'is_finalized': true } ], 'binary_path': 'IBFLOWBIN_PATH', 'job_id': '53275652-abc8-479e-89f2-ccb12af401a0', 'num_tasks': 1, 'has_more_tasks': false, 'next_offset': 1, 'can_resume': false, 'on_last_resumable_step': false } } ``` ``` -------------------------------- ### Import modules and initialize the AIHub client Source: https://docs.instabase.com/api-sdk/apps-sdk Import the required Python modules and initialize the AIHub client. The client is used to interact with the API through Python objects and methods. The api_root parameter is optional for organization accounts with a custom domain; otherwise omit it. The api_key is required, and ib_context is recommended and sets the IB-Context header to your organization ID. ```python import os import time from aihub import AIHub ``` ```python # initialize the SDK client client = AIHub(api_root=, api_key=, ib_context=) ``` -------------------------------- ### Register function in validations.py Source: https://docs.instabase.com/flow/step-config-reference/creating-validation-checkpoints Example register function in validations.py that maps function names to their implementations, including the new function 'new_fn'. ```python def register() -> Dict[Text, Any]: return { 'always_fail': { 'fn': always_fail }, 'always_pass': { 'fn': always_pass }, ..., 'new_fn': { 'fn': new_fn } } ``` -------------------------------- ### POST /api/v1/flow_binary/results Source: https://docs.instabase.com/api-sdk/api-reference/legacy/run-results-endpoint Documentation for the deprecated Get run results endpoint, which retrieves app run results via a POST request. ```APIDOC ## POST /api/v1/flow_binary/results ### Description This endpoint retrieves the results of an app run by sending a POST request to `URL_BASE/api/v1/flow_binary/results` with the request body encoded as JSON. It is deprecated and not actively maintained. ### Method POST ### Endpoint `URL_BASE/api/v1/flow_binary/results` ### Parameters #### Request Body - **ibresults_path** (string) - Required - The path to a `batch.ibflowresults` file. - **options** (Dict) - Optional - JSON dictionary with options to return additional metadata. Possible values: `include_checkpoint_results`, `provenance_info`, `include_page_layouts`. - **include_page_layouts** (Boolean) - Optional - Whether to include `page_layout` information about the original input document. Defaults to `false`. - **include_checkpoint_results** (Boolean) - Optional - Whether to include validation information in the response. Defaults to `false`. - **refined_phrases_features** (List[string]) - Optional - Experimental for AI Hub. Include entry `'provenance info'` in list to include extracted word position information. - **internal_keys** (Boolean) - Optional - Include hidden fields (i.e. fields with field names that start with `__`). - **file_offset** (integer) - Optional - Initial file index to start returning results from. Use this when dealing with large results that are paginated and exceed the default limit of 20 that is returned by the API. Defaults to 0. ### Request Example ```json { "ibresults_path": "path/to/batch.ibflowresults", "options": { "include_checkpoint_results": true, "provenance_info": true, "include_page_layouts": true }, "include_page_layouts": false, "include_checkpoint_results": false, "refined_phrases_features": ["provenance info"], "internal_keys": false, "file_offset": 0 } ``` ### Response #### Success Response (200) The response contains the run results. The exact structure is not specified in the source. #### Response Example No response example is provided in the source. ### Error Handling No error handling information is provided in the source. ``` -------------------------------- ### Go POST to create a batch Source: https://docs.instabase.com/api-sdk Sends a POST request with a JSON payload to the batches endpoint. Requires environment variables API_ROOT, API_TOKEN, and IB_CONTEXT to be set. The API returns the ID of the newly created batch. ```go package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { jsonData, _ := json.Marshal(map[string]string{"name": "test"}) apiRootUrl := os.Getenv("API_ROOT") req, _ := http.NewRequest( "POST", apiRootUrl+"/v2/batches", bytes.NewBuffer(jsonData)) req.Header.Set("Authorization", "Bearer "+os.Getenv("API_TOKEN")) req.Header.Set("IB-Context", os.Getenv("IB_CONTEXT")) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() bodyBytes, _ := io.ReadAll(resp.Body) fmt.Println(string(bodyBytes)) } ``` -------------------------------- ### Validation file top-level shape Source: https://docs.instabase.com/flow/guides/packet-processing-flows Top-level shape of the validation file. The mode is "case" and validation_rules is an empty array in this example. ```json { "mode": "case", "metadata": {}, "validation_rules": [] } ``` -------------------------------- ### Sample scope configuration: Organization admin Source: https://docs.instabase.com/admin/security/oauth-providers Grants all permissions. Use this scope value to assign the organization admin role to a token. ```text 00000000-0000-0000-0000-000000000800 ```