Skip to main content

Create Schema Service

The CreateSchemaService provides functionality to automatically generate document schemas from files. It analyzes documents and extracts structured field definitions, enabling automated schema creation for downstream Text Extraction and Text Classification services.

Quick Start

CreateSchemaService service = CreateSchemaService.builder()
.apiKey(WATSONX_API_KEY)
.projectId(WATSONX_PROJECT_ID)
.baseUrl(CloudRegion.DALLAS)
.cosUrl(CosUrl.US_SOUTH)
.documentReference(CONNECTION_ID, BUCKET_NAME)
.build();

var properties = CreateSchemaParameters.builder()
.languages(Language.ENGLISH)
.mode(Mode.HIGH_QUALITY)
.removeUploadedFile(true)
.timeout(Duration.ofMinutes(10))
.build();

var result =
service.uploadCreateSchemaAndFetch(new File("path/to/invoice.pdf"), properties);

System.out.println("Document Type: " + result.schema().documentType());
System.out.println("Description: " + result.schema().documentDescription());
System.out.println("Schema: " + result.schema());
// → Document Type: Invoice
// → Description: A vendor-issued invoice listing purchased items, prices, and payment information.
// → Schema: Complete schema

Overview

The CreateSchemaService enables you to:

  • Automatically generate document schemas with field definitions from documents.
  • Upload local files or input streams directly to COS before schema creation.
  • Extract grounding hints with bounding box coordinates for field localization.
  • Configure OCR settings for language, rotation correction, and processing mode.
  • Control extraction quality, page limits, and semantic model configuration.

Service Configuration

Basic Setup

CreateSchemaService service = CreateSchemaService.builder()
.apiKey(WATSONX_API_KEY)
.projectId(WATSONX_PROJECT_ID)
.baseUrl(CloudRegion.DALLAS)
.cosUrl(CosUrl.US_SOUTH)
.documentReference(CONNECTION_ID, BUCKET_NAME)
.build();

Using a Separate COS Authenticator

If your Cloud Object Storage uses different credentials than your watsonx.ai service, provide a dedicated cosAuthenticator:

CreateSchemaService service = CreateSchemaService.builder()
.apiKey(WATSONX_API_KEY)
.cosAuthenticator(IBMCloudAuthenticator.withKey(COS_API_KEY)) // separate COS authenticator
.projectId(WATSONX_PROJECT_ID)
.baseUrl(CloudRegion.DALLAS)
.cosUrl(CosUrl.US_SOUTH)
.documentReference(CONNECTION_ID, BUCKET_NAME)
.build();

Builder Parameters

ParameterTypeRequiredDescription
apiKeyStringConditionalAPI key for IBM Cloud authentication
authenticatorAuthenticatorConditionalCustom authentication (alternative to apiKey)
cosAuthenticatorAuthenticatorNoSeparate authenticator for COS operations (defaults to main authenticator)
projectIdStringConditionalProject ID where schema creation will be performed
spaceIdStringConditionalSpace ID (alternative to projectId)
baseUrlString/CloudRegionYeswatsonx.ai service base URL
cosUrlString/CosUrlYesCloud Object Storage base URL
documentReferenceCosReferenceYesConnection ID and bucket name for input documents
timeoutDurationNoRequest timeout (default: 60 seconds)
logRequestsBooleanNoEnable request logging (default: false)
logResponsesBooleanNoEnable response logging (default: false)
httpClientHttpClientNoCustom HTTP client
verifySslBooleanNoSSL certificate verification (default: true)
versionStringNoAPI version override

Either apiKey or authenticator must be provided. Either projectId or spaceId must be specified.


Examples

The simplest way to create a schema is to use the uploadCreateSchemaAndFetch method. This uploads a file and generates the schema in one call.

From a local file:

var result = service.uploadCreateSchemaAndFetch(new File("invoice.pdf"));
System.out.println("Document Type: " + result.schema().documentType());
System.out.println("Description: " + result.schema().documentDescription());
System.out.println("Schema: " + result.schema());
// → Document Type: Invoice
// → Description: A vendor-issued invoice ...
// → Schema: Complete schema

With parameters:

var parameters = CreateSchemaParameters.builder()
.mode(Mode.HIGH_QUALITY)
.languages(Language.ENGLISH)
.enableGrounding(true)
.maxPagesToProcess(10)
.build();

var result = service.uploadCreateSchemaAndFetch(new File("invoice.pdf"), parameters);

Automatic file cleanup

Set removeUploadedFile(true) to delete the uploaded file from COS asynchronously after schema creation completes:

var parameters = CreateSchemaParameters.builder()
.mode(Mode.HIGH_QUALITY)
.languages(Language.ENGLISH)
.removeUploadedFile(true)
.build();

service.uploadCreateSchemaAndFetch(new File("invoice.pdf"), parameters);

Note: removeUploadedFile is only supported with the synchronous variants. For other cases, call service.deleteFile(BUCKET_NAME, fileName) manually after processing.

Grounding Hints

When enableGrounding(true) is set, you get field localization data with bounding box coordinates:

var parameters = CreateSchemaParameters.builder()
.mode(Mode.HIGH_QUALITY)
.enableGrounding(true)
.build();

var result = service.uploadCreateSchemaAndFetch(new File("invoice.pdf"), parameters);
GroundingHints hints = result.groundingHints();
List<Double> bbox = hints.bbox("invoice_number");
// Returns [x1, y1, x2, y2] where (x1,y1) is top-left, (x2,y2) is bottom-right

Using Generated Schema for Extraction

Generated schemas can be used directly with the Text Extraction Service for structured data extraction.

Complete workflow example:

// Step 1: Set up Create Schema Service
CreateSchemaService createSchemaService = CreateSchemaService.builder()
.apiKey(WATSONX_API_KEY)
.projectId(WATSONX_PROJECT_ID)
.baseUrl(CloudRegion.DALLAS)
.cosUrl(CosUrl.US_SOUTH)
.documentReference(CONNECTION_ID, BUCKET_NAME)
.build();

// Step 2: Generate schema from a sample document
var schemaResult = createSchemaService.uploadCreateSchemaAndFetch(
new File("invoice.pdf"),
CreateSchemaParameters.builder()
.languages(Language.ENGLISH)
.mode(Mode.HIGH_QUALITY)
.timeout(Duration.ofMinutes(10))
.removeUploadedFile(true)
.build()
);

// Step 3: Set up Text Extraction Service
TextExtractionService textExtractionService = TextExtractionService.builder()
.apiKey(WATSONX_API_KEY)
.projectId(WATSONX_PROJECT_ID)
.baseUrl(CloudRegion.DALLAS)
.cosUrl(CosUrl.US_SOUTH)
.documentReference(CONNECTION_ID, BUCKET_NAME)
.resultReference(CONNECTION_ID, RESULT_BUCKET_NAME)
.build();

// Step 4: Use the generated schema for extraction
TextExtractionParameters extractionParams = TextExtractionParameters.builder()
.languages(Language.ENGLISH)
.mode(Mode.HIGH_QUALITY)
.timeout(Duration.ofMinutes(10))
.removeUploadedFile(true)
.kvpMode(KvpMode.GENERIC_WITH_SEMANTIC)
.semanticConfig(
TextExtractionSemanticConfig.builder()
.schemas(schemaResult.schema()) // Use the auto-generated schema
.build()
)
.build();

// Step 5: Extract data from documents using the schema
String extractedData = textExtractionService.uploadExtractAndFetch(
new File("invoice.pdf"),
extractionParams
);

System.out.println("Extracted Data:\n" + extractedData);
// → Extracted Data:
// → ## VENDOR NAME
// → Invoice Number: INV-12345
// → Date: 2024-01-15
// → Total Amount: $1,234.56
// → ...

Key benefits of this approach:

  • Automatic field detection: No need to manually define schema fields
  • Consistent extraction: The same schema can be reused across similar documents
  • Reduced setup time: Generate schemas from sample documents in minutes
  • Improved accuracy: Schemas are optimized for your specific document types

Best practices:

  1. Use representative samples: Generate schemas from documents that contain all expected fields
  2. Enable grounding: Use enableGrounding(true) to verify field locations
  3. Reuse schemas: Save generated schemas and reuse them for batch processing
  4. Validate results: Review the generated schema before using it in production

Managing Requests

Use deleteRequest to cancel or remove a schema creation job. Pass hardDelete(true) to also remove the job metadata:

CreateSchemaResponse response = service.uploadAndStartCreateSchema(new File("invoice.pdf"));

boolean deleted = service.deleteRequest(
response.metadata().id(),
CreateSchemaDeleteParameters.builder()
.hardDelete(true)
.build()
);

System.out.println("Deleted: " + deleted);
// → Deleted: true

Deleting a non-existent ID returns false.


Schema Creation Parameters

CreateSchemaParameters controls how schema creation is performed per request.

Builder Reference

ParameterTypeDescription
modeModeProcessing quality: STANDARD (faster) or HIGH_QUALITY (more accurate, slower)
ocrModeOcrModeOCR processing mode: DISABLED, ENABLED, FORCED, or AUTO. Defaults to DISABLED when unset. Use AUTO to let the service choose automatically
autoRotationCorrectionBooleanAutomatically correct document rotation before OCR
languagesLanguage...Expected languages in the document (ISO 639)
additionalPromptInstructionsStringCustom instructions to guide schema generation
enableGroundingBooleanInclude bounding box coordinates for field localization
maxPagesToProcessIntegerMaximum number of pages to analyze for schema creation
semanticConfigCreateSchemaSemanticConfigSemantic model configuration
removeUploadedFileBooleanDelete the uploaded file from COS after schema creation (synchronous only)
documentReferenceCosReferenceOverride the default COS connection and bucket for this request
timeoutDurationOverride the service-level timeout for this request (synchronous only)
projectIdStringOverride the default Project ID
spaceIdStringOverride the default Space ID
transactionIdStringRequest tracking ID

Processing Modes

ValueDescription
Mode.STANDARDFaster processing with standard accuracy
Mode.HIGH_QUALITYSlower processing with higher accuracy and better field detection

OCR Modes

ValueSent to APIDescription
OcrMode.AUTO"" (empty)Service automatically selects the best OCR option
OcrMode.DISABLED"disabled"OCR is disabled. The document must contain native text
OcrMode.ENABLED"enabled"OCR is applied when the service determines it is needed
OcrMode.FORCED"forced"OCR is always applied regardless of document content

Using a Custom Foundation Model

Override the default model (mistral-small-3-1-24b-instruct-2503) with defaultModelName:

CreateSchemaSemanticConfig semanticConfig = CreateSchemaSemanticConfig.builder()
.defaultModelName("mistralai/mistral-medium-2505")
.build();

CreateSchemaParameters parameters = CreateSchemaParameters.builder()
.mode(Mode.HIGH_QUALITY)
.semanticConfig(semanticConfig)
.build();

var result =
service.uploadCreateSchemaAndFetch(new File("invoice.pdf"), parameters);

CreateSchemaResponse

Returned by startCreateSchema, uploadAndStartCreateSchema, and fetchRequest.

FieldTypeDescription
metadata().id()StringUnique identifier for the schema creation request
metadata().createdAt()StringTimestamp when the request was created
metadata().modifiedAt()StringTimestamp of the last update
metadata().projectId()StringProject ID associated with the request
entity().results()CreateSchemaResultThe current schema creation result
entity().documentReference()DataReferenceReference to the input document in COS
entity().parameters()ParametersParameters used for this schema creation

CreateSchemaResult

FieldTypeDescription
status()StringCurrent status: submitted, running, completed, or failed
runningAt()StringTimestamp when processing started
completedAt()StringTimestamp when processing completed or failed
numberPagesProcessed()IntegerNumber of pages processed
totalPages()IntegerTotal number of pages in the document
schema()SchemaThe generated document schema with field definitions
groundingHints()GroundingHintsField localization data with bounding boxes (if enabled)
error()ErrorError details if status is failed

Schema

FieldTypeDescription
documentType()StringThe identified document type (e.g., "Invoice", "Contract")
documentDescription()StringA natural language description of the document
fields()Map<String, KvpField>Map of field names to field definitions

KvpField

Each field in the schema contains:

FieldTypeDescription
description()StringNatural language description of the field
example()StringExample value for the field