Inferensys

Prompt

Null and Empty Value Handling Prompt for Optional Arguments

A practical prompt playbook for using Null and Empty Value Handling Prompt for Optional Arguments in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the exact job this prompt performs, the ideal user, and the constraints that make it the right tool.

This prompt is for backend and platform engineers who need to validate tool call arguments generated by an LLM before those arguments are dispatched to an internal or external API. Its specific job is to resolve ambiguity in optional fields: it decides whether a field that is empty, null, or missing should be omitted from the final payload, explicitly set to null, or replaced with a safe default value. This decision is made by comparing the generated argument against the target tool's API contract, which you provide as part of the input. The goal is to prevent the 400 Bad Request errors and silent state corruption that occur when an LLM guesses incorrectly about how an API handles absent versus null optional parameters.

Use this prompt when your application constructs tool call payloads from LLM outputs and the downstream API has strict, documented behavior for optional fields. It is most valuable when the API contract distinguishes between 'field not present' and 'field present with a null value'—a common source of bugs in REST and GraphQL APIs. The prompt requires you to supply the raw generated arguments, the complete API schema for the target tool (including which fields are optional, their types, and any default values), and a set of business rules that might override the schema (e.g., 'if the user's role is viewer, the access_level field must be omitted'). You should not use this prompt for simple APIs where all optional fields can be safely omitted, or for workflows where the LLM's output is already guaranteed to be schema-valid by a prior step. In those cases, a simpler required-field check or a direct schema validation prompt is more efficient.

This prompt is a pre-execution guardrail, not a repair tool. It assumes the tool call arguments have already passed a basic schema conformance check and that the only remaining ambiguity is how to handle optional fields that are empty, null, or missing. If the input arguments contain hard validation errors—such as a required field that is missing, a string where an integer is expected, or an enum value that is not in the allowed set—this prompt will not fix them. Instead, it will flag those issues and recommend that the payload be sent to a dedicated repair prompt or rejected outright. The output is a structured decision for each optional field: omit, send_null, or set_default, along with a corrected payload and an audit trail explaining each choice. For high-risk write operations, you should route the corrected payload to a human approval step before execution, not rely solely on this automated normalization.

Before integrating this prompt, confirm that your downstream API documentation clearly specifies null handling for every optional field. If the API's behavior is undocumented or inconsistent, the prompt's decisions will be based on inference rather than contract, which increases the risk of errors. In those cases, pair this prompt with a test harness that sends the corrected payload to a sandbox or staging endpoint and validates the response. Also, log every normalization decision so that when an API changes its null-handling behavior, you can trace which past tool calls might be affected. This prompt is a precision instrument for a specific failure mode; use it when optional-field ambiguity is the known bottleneck, not as a general-purpose argument cleaner.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational risks you accept by deploying it.

01

Good Fit: Pre-Execution API Sanitization

Use when: you have a tool call payload generated by an LLM and need to normalize optional fields before hitting a strict REST or GraphQL API. Why: prevents 400 errors from empty strings where null or omission is required.

02

Bad Fit: Complex Business Logic Defaults

Avoid when: the correct default for an empty field depends on cross-field state, user roles, or database lookups. Risk: the prompt will hallucinate a plausible but wrong default. Guardrail: move stateful defaults into application code, not the prompt.

03

Required Input: API Contract Specification

Risk: without the target API's schema, the model guesses nullability rules. Guardrail: always provide a JSON Schema snippet or a structured table of field names, types, and nullability as part of [CONTEXT]. The prompt is only as good as the contract it validates against.

04

Operational Risk: Silent Data Corruption

Risk: the prompt normalizes an empty string to null, but the downstream system treats null as 'do not update' while an empty string means 'clear this field'. Guardrail: log the pre- and post-normalization payload for audit. Never let this prompt be the final step before a destructive write without a human review path.

05

Operational Risk: Type Coercion Drift

Risk: the model coerces an empty string `

06

Bad Fit: Real-Time, Low-Latency Pipelines

Avoid when: you need sub-50ms validation on a hot path. Why: an LLM call adds unacceptable latency and cost per tool invocation. Guardrail: use this prompt for offline analysis or high-value transactions. For real-time, implement deterministic null-handling rules in your API gateway.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that decides whether to omit, send as null, or substitute a default for empty optional fields in a tool call payload.

This prompt template is designed to sit between argument construction and tool execution. It receives a partially filled tool call payload and the target tool's API contract, then normalizes every optional field according to the contract's declared nullability, default values, and omission rules. The goal is to prevent 400 errors, unintended null writes, and default-value surprises before the call leaves your system.

text
You are a tool call argument normalizer. Your job is to inspect a proposed tool call payload and enforce the correct handling of optional fields based on the tool's API contract.

## INPUT
Tool Name: [TOOL_NAME]
Tool Description: [TOOL_DESCRIPTION]
Parameter Schema (JSON Schema subset): [PARAMETER_SCHEMA]
Proposed Arguments (JSON): [PROPOSED_ARGUMENTS]

## RULES
1. For each field in the parameter schema, determine whether it is required or optional based on the schema's `required` array.
2. For each optional field:
   - If the field is absent from the proposed arguments and the schema declares a `default`, insert the default value.
   - If the field is absent and no default is declared, omit the field entirely (do not send `null`).
   - If the field is present but set to `null`, `""`, `[]`, or `{}`:
     - If the schema explicitly allows `null` (type array includes `"null"`), keep it as `null`.
     - If the schema does not allow `null` and no default is declared, omit the field.
     - If the schema does not allow `null` but a default is declared, replace with the default.
3. For required fields, never omit them. If a required field is missing, null, or empty, flag it as an error—do not guess.
4. Do not add fields that are not declared in the parameter schema.
5. Preserve all valid, non-empty values exactly as provided.

## OUTPUT SCHEMA
Return a JSON object with exactly these keys:
- `normalized_arguments`: The corrected arguments object ready for tool dispatch.
- `changes`: An array of change records, each with `field`, `action` (one of: "omitted", "set_default", "kept_null", "flagged_missing_required"), and `reason`.
- `valid`: Boolean. `true` if all required fields are present and non-empty after normalization, `false` otherwise.
- `errors`: Array of error strings for missing required fields or schema violations that cannot be repaired.

## EXAMPLES
[EXAMPLES]

## CONSTRAINTS
[CONSTRAINTS]

Adapt this template by replacing the placeholders. [PARAMETER_SCHEMA] should be a JSON Schema subset that includes at minimum type, properties, and required for each parameter. [PROPOSED_ARGUMENTS] is the raw output from your argument-filling prompt or agent step. [EXAMPLES] should include at least two few-shot demonstrations: one where an empty optional string is correctly omitted, and one where a null-allowed field is preserved. [CONSTRAINTS] can specify additional business rules such as "never default limit to more than 100" or "always omit callback_url in staging environments." After generating the normalized payload, always validate it against the original schema with a deterministic JSON Schema validator before dispatch. For high-risk write operations, route the changes array to a human review queue or an audit log rather than silently applying defaults.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Null and Empty Value Handling Prompt. Wire these into your tool-call validation harness before execution.

PlaceholderPurposeExampleValidation Notes

[TOOL_CALL_PAYLOAD]

The complete tool call arguments object generated by the model, including optional fields that may be null, empty string, or missing

{"user_id": "abc", "nickname": null, "bio": ""}

Must be valid JSON. Parse before passing to this prompt. Reject if unparseable.

[TOOL_SCHEMA]

The JSON Schema or OpenAPI parameter definition for the target tool, marking which fields are required vs optional and their expected types

{"type": "object", "properties": {"nickname": {"type": ["string", "null"]}}, "required": ["user_id"]}

Must include required array and type constraints. Schema must match the tool version being called.

[NULL_HANDLING_POLICY]

Instruction defining how to treat null vs missing vs empty string for optional fields: omit, send as null, or substitute a default

omit_null_fields

Must be one of: omit_null_fields, send_null, substitute_default, or reject. Policy must align with downstream API contract.

[DEFAULT_VALUE_MAP]

A mapping of optional field names to their default values when substitution is the chosen policy

{"nickname": "User", "bio": ""}

Only required when NULL_HANDLING_POLICY is substitute_default. Keys must match optional field names in TOOL_SCHEMA.

[REQUIRED_FIELDS]

Explicit list of field names that must be present and non-null, overriding schema-level optional markers if stricter enforcement is needed

["user_id", "email"]

Optional. Use when business rules are stricter than the API schema. Must be a subset of schema properties.

[EMPTY_STRING_TREATMENT]

Rule for handling empty strings in optional fields: treat as null, keep as empty string, or reject

treat_as_null

Must be one of: treat_as_null, keep_empty, or reject. Defaults to treat_as_null if not specified.

[OUTPUT_FORMAT]

Desired structure for the normalized payload output: full_payload, delta_only, or validation_report

full_payload

Must be one of: full_payload, delta_only, validation_report. full_payload returns the complete cleaned arguments object.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the null and empty value handling prompt into a production tool-calling pipeline with validation, retries, and audit logging.

The null and empty value handling prompt operates as a pre-execution gate within your tool-calling pipeline. It should be invoked after the model generates a tool call payload but before that payload is dispatched to the downstream API. The harness receives the raw tool call arguments, the tool's JSON Schema or API contract, and any business-level defaults configuration. Its job is to normalize optional fields—deciding whether to omit them entirely, send them as explicit null, or substitute a configured default—so that the downstream API receives a payload that matches its expectations and avoids 400 errors from malformed optional parameters.

To wire this into an application, implement a middleware function that intercepts the tool call object. Pass the arguments block, the tool_schema (including which fields are optional and their types), and a defaults_map (key-value pairs for fallback values) into the prompt. The prompt returns a structured JSON object with normalized_arguments, a transformations array explaining each decision (e.g., 'omitted empty string for optional field X', 'substituted default for null field Y'), and a confidence score. Your harness should validate this output against the original schema to confirm no required fields were accidentally dropped. If the confidence score falls below a configured threshold (e.g., 0.85), route the payload to a human review queue or a clarification prompt instead of executing the tool call.

For production resilience, wrap the normalization step in a retry loop with exponential backoff. Log every transformation decision alongside the original and normalized payloads for auditability—this is critical when debugging why a downstream API rejected a call. If the normalization prompt itself fails or times out, fall back to a deterministic rule-based normalizer that strips empty strings from optional fields and applies your defaults map directly. Avoid executing tool calls with un-normalized optional arguments, as even a single empty string where an API expects omission can cascade into state corruption or confusing user-facing errors. Finally, integrate the transformations output into your observability stack so that support engineers can trace exactly which fields were modified and why.

IMPLEMENTATION TABLE

Expected Output Contract

The prompt must return a structured decision for each optional field. Use this contract to validate the output before passing arguments to the downstream API.

Field or ElementType or FormatRequiredValidation Rule

field_decisions

array of objects

Must be a non-empty array. Each element must match the FieldDecision schema.

field_decisions[].field_name

string

Must exactly match one of the optional field names provided in [OPTIONAL_FIELDS_SCHEMA].

field_decisions[].action

enum: omit | send_null | substitute_default | ask_user

Must be one of the four allowed actions. No other values permitted.

field_decisions[].value

any or null

Required when action is substitute_default. Must match the type declared in [OPTIONAL_FIELDS_SCHEMA]. Must be null when action is omit or send_null.

field_decisions[].reasoning

string

Must be a non-empty string explaining the decision. Max 280 characters. Must reference [CONTEXT] or [API_CONTRACT].

unresolved_fields

array of strings

Must list any optional fields not present in field_decisions. Empty array if all fields are covered.

confidence_score

number (0.0 - 1.0)

Must be a float between 0.0 and 1.0. Score below 0.7 should trigger a retry or human review in the harness.

PRACTICAL GUARDRAILS

Common Failure Modes

Handling null, empty, and missing optional arguments in tool calls is a primary source of 400 errors and silent misbehavior. These cards cover the most common failure patterns and how to guard against them before execution.

01

Empty String Sent Instead of Omitted Field

What to watch: The model sends "optional_field": "" when the API contract requires the field to be omitted entirely if no value is present. This causes schema validation failures or unintended overwrites. Guardrail: Add explicit instructions in the tool description: 'If no value is available, omit the field entirely. Do not send empty strings.' Validate with a pre-execution check that strips empty strings from optional fields before dispatch.

02

Null Sent When API Expects Omission

What to watch: The model sends "optional_field": null but the downstream API treats explicit null as a value that overwrites existing data, while omission preserves it. This is common in PATCH operations. Guardrail: Define a per-field policy in the tool schema: 'null means set to null, omission means no change.' Add a pre-flight transformer that removes null-valued optional fields when the API contract requires omission.

03

Required Field Treated as Optional by the Model

What to watch: The model omits a required field because the user didn't provide it, assuming the field is optional. The tool call fails with a 400 error before any business logic runs. Guardrail: Mark required fields explicitly in the tool schema with "required": true. Add a pre-execution completeness check that rejects calls with missing required fields and returns a structured error for retry or clarification.

04

Default Value Substitution Without API Awareness

What to watch: The model invents a default value (e.g., "limit": 10) when the field should be left empty to trigger server-side default behavior. This overrides intended server defaults and produces unexpected results. Guardrail: Document server-side defaults in the tool description. Instruct the model: 'Do not guess default values. Omit optional fields unless the user explicitly provides a value.' Validate that no invented defaults appear in the payload.

05

Boolean Optional Field Defaulting to False

What to watch: The model sends "enabled": false for an optional boolean when the field should be omitted, causing the API to interpret it as an explicit disable rather than 'use default.' Guardrail: For boolean optional fields, specify in the schema description: 'Omit this field unless the user explicitly requests true or false. Do not default to false.' Add a pre-execution rule that flags boolean fields present without explicit user intent.

06

Array Field Sent as Empty Instead of Omitted

What to watch: The model sends "tags": [] when no tags are specified, but the API treats an empty array as 'clear all tags' while omission means 'leave tags unchanged.' Guardrail: Distinguish between 'set to empty' and 'do not modify' in the tool description. Use a sentinel or explicit flag if the API requires it. Validate that empty arrays in optional fields are either intentional or stripped before dispatch.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test whether the Null and Empty Value Handling Prompt correctly decides to omit, send as null, or substitute a default for optional fields before a tool call is dispatched. Each criterion targets a specific failure mode that causes 400 errors or malformed payloads in production.

CriterionPass StandardFailure SignalTest Method

True Optional Field Omission

Field marked as optional in [TOOL_SCHEMA] with no value provided is omitted from the output payload entirely.

Field appears with an empty string, null, or placeholder value like 'N/A'.

Provide a partial input with only required fields. Assert the optional field key is absent in the output JSON.

Explicit Null Preservation

Field marked as nullable in [TOOL_SCHEMA] with an explicit null input is passed as null in the output.

Null is converted to an empty string, the field is omitted, or a default is substituted against the schema contract.

Provide an input where [OPTIONAL_ARG] is explicitly null. Assert the output contains '"field": null'.

Default Value Substitution

Field with a defined [DEFAULT_VALUE_MAP] and an empty or missing input is populated with the specified default.

Field is omitted, sent as null, or populated with a hallucinated value not in the default map.

Provide an input missing a field that has a default in [DEFAULT_VALUE_MAP]. Assert the output contains the exact default value.

Empty String Normalization

An empty string for an optional field is treated according to [EMPTY_STRING_POLICY]: omitted if 'omit', converted to null if 'nullify', or kept if 'allow'.

Empty string is passed through when policy is 'omit', or removed when policy is 'allow'.

Test each policy variant with an empty string input. Assert output matches the configured behavior for that field.

Required Field Non-Interference

Required fields from [TOOL_SCHEMA] are never omitted, nullified, or defaulted, even if the input value is empty.

A required field is dropped or replaced with a default because the input was empty, causing a downstream 400 error.

Provide an input with an empty required field. Assert the prompt flags it as a validation error rather than silently altering it.

Nested Optional Field Handling

Optional fields inside nested objects follow the same omit/null/default rules as top-level fields, preserving the parent object structure.

An entire parent object is dropped because one nested optional field was empty, or a nested required field is incorrectly defaulted.

Provide a partial nested object. Assert the parent key is present with only the provided nested fields, and missing optional nested fields are handled correctly.

Array Element Null Handling

Null or empty elements inside an optional array are handled per [ARRAY_NULL_POLICY]: stripped, kept as null, or replaced with a default.

Null elements are silently dropped when policy is 'keep', or kept when policy is 'strip', causing downstream array index errors.

Provide an array input with a mix of valid and null elements. Assert the output array matches the configured policy for null elements.

Schema Type Coercion Avoidance

No type coercion is performed on optional fields. A missing string field is not replaced with an empty string unless [EMPTY_STRING_POLICY] explicitly allows it.

A missing integer field is defaulted to 0, or a missing boolean is defaulted to false without explicit configuration.

Provide an input missing an optional integer field with no default configured. Assert the field is omitted, not set to 0.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a simple JSON schema for your tool's optional fields. Replace [TOOL_SCHEMA] with a minimal schema listing only the fields your tool accepts. Use [ARGUMENTS] as the raw payload from the model. Keep the output format simple: a flat object with resolved_arguments and warnings. Skip the audit_trail field during prototyping.

code
You are a tool argument normalizer. Given the tool schema below and the arguments provided, resolve null, empty string, and missing optional fields according to the schema's defaults. If a field is optional and missing, omit it. If it is optional and null, treat it as omitted unless the schema specifies a default. If it is optional and an empty string, substitute the schema default or omit if no default exists.

Schema: [TOOL_SCHEMA]
Arguments: [ARGUMENTS]

Return JSON: {"resolved_arguments": {...}, "warnings": [...]}

Watch for

  • Schema drift when you add new optional fields without updating the prompt
  • Empty string vs. null confusion if your schema doesn't define defaults explicitly
  • Over-normalization that strips intentional nulls meant to clear a value in a PATCH operation
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.