Inferensys

Prompt

GraphQL Query Repair Prompt

A practical prompt playbook for using the GraphQL Query Repair Prompt in production AI workflows. Designed for API developers who need to fix generated GraphQL queries with invalid field names, missing required arguments, or type mismatches using corrective examples and schema introspection.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the production context, ideal user, and boundary conditions for deploying a GraphQL query repair prompt.

This prompt is for production engineers and API developers who generate GraphQL queries through LLMs and need a reliable repair step when queries fail validation. Use it when a generated query references fields that do not exist in the target schema, omits required arguments, passes arguments of the wrong type, or nests selections incorrectly. The prompt works by providing the model with schema introspection results and few-shot examples of broken-to-fixed query pairs. It is designed to be called after a query fails client-side or server-side validation, not as a first-pass query generator.

The ideal user has access to the target GraphQL schema's introspection output—typically the result of a standard introspection query—and a record of the exact validation error returned by the server. The prompt requires three concrete inputs: the invalid query string, the schema introspection JSON, and the validation error message. Without all three, the model lacks the grounding necessary to produce a correct repair. The repair itself is a structural operation: renaming fields to match the schema, adding missing required arguments, coercing argument types, and fixing nested selection sets. It is not a semantic rewrite or query optimization step.

You should not use this prompt when the schema is unavailable, when the query is intentionally exploratory, or when the failure is due to authentication, rate limiting, or network errors rather than structural query problems. This prompt is also inappropriate for queries that are syntactically valid but semantically wrong—for example, a query that returns an empty result because it filters on a non-existent value. In those cases, the problem is in the application logic, not the query structure. For high-risk production environments, always validate the repaired query against the schema before execution and log both the original error and the repair diff for auditability.

PRACTICAL GUARDRAILS

Use Case Fit

Where the GraphQL Query Repair Prompt works and where it introduces unacceptable risk. Use these cards to decide if this prompt belongs in your production pipeline or if you need a different approach.

01

Good Fit: Schema-Aware Repair

Use when: The generated query fails validation against a known GraphQL schema, and the introspection results are available. Guardrail: Always provide the relevant schema subset as [SCHEMA_CONTEXT] so the model can map invalid fields to valid ones, not guess.

02

Bad Fit: Business Logic Errors

Avoid when: The query is syntactically valid but returns the wrong business result (e.g., filtering by the wrong status enum). Guardrail: This prompt repairs structure and types, not semantic intent. Route intent errors to a separate clarification or human-review workflow.

03

Required Input: Introspection Context

Risk: Without the schema, the model will hallucinate valid field names or argument types. Guardrail: The prompt requires [SCHEMA_CONTEXT] containing the relevant types, fields, and enums from introspection. Never run repair against a schema the model hasn't seen in the prompt.

04

Operational Risk: Repair Loop Amplification

Risk: A repair prompt that introduces new errors can trigger infinite retry loops, consuming tokens and latency budget. Guardrail: Set a maximum of 2 repair attempts. After that, log the failure, cache the original query, and escalate to a human or fallback static query.

05

Bad Fit: Complex Authorization Rules

Avoid when: The query needs row-level security, scope limiting, or user-specific field masking. Guardrail: The repair prompt does not understand your authz layer. Apply authorization directives and filters in the application layer after the query is structurally valid.

06

Good Fit: Pre-Execution Validation Gate

Use when: You have a GraphQL server that rejects invalid queries with clear error messages. Guardrail: Feed the server's error response directly into the prompt as [ERROR_CONTEXT]. This grounds the repair in the actual failure, not a generic description of what might be wrong.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for repairing invalid GraphQL queries using schema introspection results and corrective examples.

This prompt template is designed to repair a generated GraphQL query that has failed validation against a target schema. It expects the invalid query, the schema introspection results (types, fields, arguments, enums), and the specific validation error message. The model is instructed to produce a corrected, valid query and explain each change it made. The template uses few-shot examples to teach the model common repair patterns: fixing misspelled field names, adding missing required arguments, correcting type mismatches, and removing nonexistent fields.

text
You are a GraphQL query repair assistant. Your task is to fix an invalid GraphQL query so that it passes validation against the provided schema.

## INPUT
- Invalid Query:
```graphql
[INVALID_QUERY]
  • Schema Introspection Result (JSON):
json
[SCHEMA_INTROSPECTION_JSON]
  • Validation Error:
code
[VALIDATION_ERROR_MESSAGE]

REPAIR RULES

  1. Only use field names, argument names, and types that exist in the provided schema introspection.
  2. If a required argument is missing, add it with a sensible placeholder value (e.g., "PLACEHOLDER" for strings, 0 for Ints, true/false for Booleans).
  3. If a field name is misspelled, correct it to the closest matching field in the schema.
  4. If a field does not exist and no close match is found, remove that field and its sub-selection entirely.
  5. If an argument value has the wrong type, coerce it to the correct type if possible; otherwise, replace it with a placeholder.
  6. Preserve the original query structure, aliases, and fragments as much as possible.
  7. Do not add new fields or functionality beyond what is necessary to fix the error.

EXAMPLES

Example 1: Misspelled Field Name

Invalid Query:

graphql
query {
  user(id: "1") {
    fullname
    email
  }
}

Schema (relevant): User type has fields: id, fullName, email Error: Cannot query field "fullname" on type "User". Did you mean "fullName"? Fixed Query:

graphql
query {
  user(id: "1") {
    fullName
    email
  }
}

Explanation: Corrected fullname to fullName based on schema suggestion.

Example 2: Missing Required Argument

Invalid Query:

graphql
query {
  search {
    results {
      title
    }
  }
}

Schema (relevant): search(term: String!) returns SearchResult Error: Field "search" argument "term" of type "String!" is required, but it was not provided. Fixed Query:

graphql
query {
  search(term: "PLACEHOLDER") {
    results {
      title
    }
  }
}

Explanation: Added missing required argument term with a placeholder value.

Example 3: Nonexistent Field

Invalid Query:

graphql
query {
  product(sku: "ABC") {
    name
    manufacturer
    weight
  }
}

Schema (relevant): Product type has fields: name, brand, price Error: Cannot query field "manufacturer" on type "Product". and Cannot query field "weight" on type "Product". Fixed Query:

graphql
query {
  product(sku: "ABC") {
    name
    brand
    price
  }
}

Explanation: Removed nonexistent fields manufacturer and weight. No close match found in schema.

OUTPUT FORMAT

Return a JSON object with the following structure:

json
{
  "fixed_query": "<the complete corrected GraphQL query as a string>",
  "changes": [
    {
      "type": "field_rename | field_removal | argument_added | argument_type_coerced | type_coercion",
      "location": "<path to the changed element, e.g., query.user.fullName>",
      "original": "<original value or description>",
      "replaced_with": "<new value or description>",
      "reason": "<brief explanation referencing the schema or error>"
    }
  ],
  "still_has_placeholders": true_or_false
}

CONSTRAINTS

  • Do not modify the query if it is already valid.
  • If the error cannot be resolved with the provided schema, set fixed_query to an empty string and explain why in the first change entry.
  • Always validate that the fixed query uses only types and fields present in the introspection result.
  • If you must use a placeholder value, set still_has_placeholders to true.

CURRENT TASK

Repair the invalid query above using the provided schema introspection and error message.

To adapt this template for your own system, replace the four bracketed placeholders before sending it to the model. [INVALID_QUERY] should contain the full GraphQL query string that failed validation. [SCHEMA_INTROSPECTION_JSON] must be the JSON output of a standard GraphQL introspection query against the target endpoint—include at minimum the types array with name, fields, and inputFields for relevant types. [VALIDATION_ERROR_MESSAGE] should be the exact error string returned by your GraphQL validator. If your validator returns multiple errors, concatenate them with newlines. The examples inside the prompt are fixed and should not be replaced; they teach the model the repair patterns. If your domain has different common failure modes (e.g., fragment spread errors, directive misuse), add one or two domain-specific examples following the same format. Keep the total prompt under 3000 tokens to leave room for the introspection JSON, which can be large. For high-risk production use where a bad repair could corrupt data, always run the fixed_query through your GraphQL validator before execution and flag any output where still_has_placeholders is true for human review.

After copying this template, wire it into a repair harness that validates the returned fixed_query against your schema before accepting it. If validation fails again, you can feed the new error back into the prompt for a second repair attempt, but limit retries to a maximum of two to avoid infinite loops. Log every repair attempt with the original query, the error, the fixed query, and the list of changes for auditability. For queries that touch write operations (mutations), require explicit human approval before execution regardless of validation success.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the GraphQL Query Repair Prompt. Each variable must be populated before the prompt is assembled and sent to the model. Validation notes describe how to programmatically verify the input before execution.

PlaceholderPurposeExampleValidation Notes

[FAULTY_QUERY]

The generated GraphQL query string that failed validation or execution

query { user(id: 1) { name email } }

Must be a non-empty string. Parse as GraphQL document node; if parsing fails, skip repair and return raw parse error to upstream caller.

[ERROR_MESSAGE]

The exact error returned by the GraphQL server or schema validator

Cannot query field "email" on type "User". Did you mean "emails"?

Must be a non-empty string. If null or empty, the repair prompt should fall back to schema-only validation mode.

[SCHEMA_INTROSPECTION_JSON]

Full introspection query result for the target GraphQL endpoint

{ "__schema": { "types": [...] } }

Must be valid JSON and conform to the GraphQL introspection result structure. Validate presence of __schema.types array. If missing, abort repair and request schema fetch.

[REPAIR_EXAMPLES]

Array of few-shot input-output pairs showing correct repair patterns

[{"faulty": "...", "error": "...", "repaired": "..."}]

Must be a JSON array with 2-5 objects, each containing faulty, error, and repaired string fields. Validate each repaired field parses as valid GraphQL against the provided schema before prompt assembly.

[NEGATIVE_EXAMPLES]

Array of examples showing incorrect repairs that should be avoided

[{"faulty": "...", "bad_repair": "...", "why_bad": "..."}]

Must be a JSON array with 1-3 objects. Each must include why_bad explanation string. If empty array, negative example section is omitted from the prompt.

[OUTPUT_SCHEMA]

Expected JSON structure for the repair response

{ "repaired_query": "string", "changes": [{"field": "...", "from": "...", "to": "..."}], "confidence": "high|medium|low" }

Must be a valid JSON Schema object or example structure. Validate that repaired_query and changes are present in the schema definition. Confidence enum values must be explicitly listed.

[MAX_RETRY_DEPTH]

Maximum number of repair attempts before escalating to human review

3

Must be a positive integer between 1 and 5. If the repair loop exceeds this count, log the full attempt history and route to the human review queue.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the GraphQL Query Repair Prompt into a production application with validation, retries, and schema-aware guardrails.

The GraphQL Query Repair Prompt is designed to sit inside a repair loop that activates after a generated or user-submitted query fails initial validation against the target GraphQL schema. The harness should catch the validation error, extract the error details (invalid field names, missing required arguments, type mismatches), and pass them alongside the original query and the relevant schema introspection results into the prompt. This is not a prompt you fire once and forget—it is a corrective step in a multi-stage pipeline where the primary goal is to reduce manual intervention and retry overhead while never silently accepting a query that still fails schema validation.

Integration flow: (1) The application receives a GraphQL query string. (2) Validate it against the live schema using a server-side validator like graphql-js's validate function or your API gateway's schema enforcement. (3) If validation passes, execute the query. (4) If validation fails, collect the error messages, the offending query, and a compact schema representation (types, fields, required arguments, enums) from introspection. (5) Populate the prompt template's [INVALID_QUERY], [VALIDATION_ERRORS], and [SCHEMA_CONTEXT] placeholders. (6) Call the model with the repair prompt. (7) Extract the repaired query from the model's structured output. (8) Re-validate the repaired query against the schema. (9) If it passes, execute it. If it fails again, either retry with enriched error context or escalate to a human review queue with the full failure history. Never execute a query that hasn't passed schema validation.

Model choice and configuration: Use a model with strong code and structured output capabilities. Set temperature low (0.0–0.2) to minimize creative drift in query structure. Require structured output matching a schema like { repaired_query: string, changes: [{ field: string, original: string, repaired: string, reason: string }] } so you can log exactly what was changed and why. Retry budget: Cap repair attempts at 2–3 before escalating. Each retry should include the new validation errors, not just the original ones. Logging: Log the original query, validation errors, schema snapshot hash, repaired query, changes array, and final validation result. This audit trail is essential for debugging repair failures and detecting schema drift where the introspection data no longer matches the live schema.

Failure modes to instrument: Watch for (a) the model hallucinating field names that don't exist in the schema, (b) removing required arguments instead of providing valid values, (c) changing query semantics while making it syntactically valid, and (d) producing a repaired query that passes validation but returns empty or wrong data. Instrument an eval step that compares the repaired query's field selection against the original intent where possible. Human review trigger: If the repair loop exhausts its retry budget, surface the full repair attempt history to a developer queue. Include the original query, each repair attempt, the validation errors at each step, and the schema context used. This gives the human reviewer enough context to either manually fix the query or identify a schema documentation gap that confused the model.

Schema context sizing: GraphQL schemas can be large. Don't dump the entire introspection result into [SCHEMA_CONTEXT]. Extract only the types, fields, arguments, and enums relevant to the query's root types and the fields referenced in the error messages. A good heuristic: include the full type definitions for any type mentioned in a validation error, plus the query, mutation, or subscription root types. This keeps token usage manageable and focuses the model on the parts of the schema that matter for the repair. If the schema is small enough to fit entirely within the context window, include it all to avoid missing indirect type dependencies.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required fields, types, and validation rules for the repaired GraphQL query response. Use this contract to validate the model's output before passing it to a GraphQL execution engine.

Field or ElementType or FormatRequiredValidation Rule

repaired_query

string

Must parse as valid GraphQL. Validate against the provided schema using a standard GraphQL parser. No markdown fences allowed.

repair_log

array of objects

Each object must contain 'original_fragment' (string), 'issue' (string), and 'fix_description' (string). Array must not be empty if changes were made.

repair_log[].original_fragment

string

Must be a substring of the [MALFORMED_QUERY] input. If not found, flag for human review.

repair_log[].issue

string

Must match one of the allowed values: 'invalid_field', 'missing_argument', 'type_mismatch', 'deprecated_field', 'syntax_error'.

repair_log[].fix_description

string

Must be a non-empty string describing the corrective action taken. Should reference the specific schema type or field used for the fix.

confidence_score

number

If present, must be a float between 0.0 and 1.0. A score below 0.8 should trigger a human review step before the query is executed.

hallucinated_field_warning

boolean

If true, the 'repaired_query' must be blocked from automatic execution and routed for human approval. This flag indicates the fix involved adding a field not directly suggested by the schema.

PRACTICAL GUARDRAILS

Common Failure Modes

GraphQL query repair fails in predictable ways. These are the most common production failure modes and the guardrails that catch them before they corrupt downstream systems.

01

Hallucinated Field Names

What to watch: The model invents plausible field names that don't exist in the schema, especially for nested types or deprecated fields. This happens most often when the schema introspection result is truncated or the model defaults to common naming conventions. Guardrail: Validate every field path against the introspection result before repair. Use a field-existence check that rejects unknown fields and feeds the valid field list back into the repair prompt as a constraint.

02

Missing Required Arguments

What to watch: The repair prompt fixes field names but omits required arguments like id, first, or filter that the schema mandates. This is common when the original broken query also lacked those arguments, so the model has no example to copy. Guardrail: Extract required arguments from the introspection result for every field in the query. Run a schema-aware validator that flags missing non-null arguments and injects them with placeholder values or explicit error markers before retry.

03

Type Mismatch in Argument Values

What to watch: The model supplies string values for Int fields, omits list wrappers for array arguments, or passes objects where scalars are expected. These type errors survive JSON parse but fail GraphQL execution. Guardrail: Coerce argument types against the schema's type definitions before sending the query. Use explicit type-casting rules: parse strings to Int/Float, wrap scalars in lists when the schema expects [String], and reject object values for scalar fields.

04

Over-Correction of Valid Queries

What to watch: The repair prompt aggressively rewrites valid parts of the query, introducing new errors while fixing old ones. This happens when the few-shot examples are too broad or the model treats the entire query as suspect. Guardrail: Diff the original query against the repaired query and only accept changes to fields or arguments that failed validation. Use a field-level repair scope: fix only the invalid paths, leave the rest untouched. Test with a golden set of valid queries to measure over-correction rate.

05

Introspection Context Drift

What to watch: The repair prompt uses stale or incomplete introspection data, causing it to reject valid new fields or accept deprecated ones. This is common in CI/CD pipelines where the schema evolves faster than the cached introspection result. Guardrail: Version-lock the introspection result with a schema hash and compare it before every repair run. If the hash has changed, refresh the introspection context and re-run the repair. Log schema version mismatches as a separate alert.

06

Fragment and Inline Fragment Collapse

What to watch: The model flattens named fragments or inline fragments incorrectly, losing type conditions or duplicating fields across union members. This breaks queries that rely on fragment-based polymorphism. Guardrail: Preserve fragment structure during repair unless the fragment itself is invalid. Validate that ... on Type conditions match actual schema types. If flattening is necessary, expand fragments explicitly and verify that field access respects the type condition.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the GraphQL Query Repair Prompt's output quality before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Schema Compliance

All field names, argument names, and types in the repaired query exist in the provided [SCHEMA_INTROSPECTION_JSON].

The repaired query contains a field or argument not present in the schema introspection.

Parse the output query into an AST. For each field and argument node, verify its path exists in the [SCHEMA_INTROSPECTION_JSON] using a deterministic lookup script.

Required Argument Inclusion

All non-nullable arguments defined in the schema for the target fields are present in the repaired query.

A non-nullable argument from the schema is missing from the repaired query, which would cause a server-side validation error.

Extract the set of required arguments from the schema introspection for each field in the query. Assert that the repaired query's arguments are a superset of this set.

Type Coercion Correctness

Argument values are coerced to the correct GraphQL scalar type (e.g., String, Int, Float, Boolean, ID) as defined in the schema.

A value is provided with the wrong JSON type, such as a string for an Int argument or an unquoted ID value.

Validate the JSON type of each argument value in the repaired query against the expected GraphQL scalar type from the schema introspection.

Structural Integrity

The repaired query is a syntactically valid GraphQL document that parses without errors.

The output is not parseable as GraphQL, containing syntax errors like unbalanced braces, invalid characters, or malformed directives.

Run a standard GraphQL parser (e.g., graphql-js) on the output string. The test passes if the parse function returns a valid DocumentNode without throwing an error.

No Hallucinated Additions

The repair only modifies the parts of the [ORIGINAL_QUERY] that were invalid. It does not add new, unrelated fields or alter the query's intent.

The repaired query includes new top-level fields, sub-fields, or arguments that were not in the original query and are not required to fix a specific error.

Diff the AST of the [ORIGINAL_QUERY] and the repaired query. Flag any added nodes that do not correspond to a documented error in the [ERROR_LOG].

Error Log Correlation

Every change made to the original query directly addresses at least one specific error described in the [ERROR_LOG].

A modification is made that cannot be traced back to any error message in the provided log, indicating a speculative or unnecessary change.

For each AST diff, require a comment or traceability mapping in the output (if requested) that links the change to a specific error ID or message from the [ERROR_LOG].

Intent Preservation

The repaired query requests the same underlying data as the original, flawed query, with no semantic drift.

The repaired query changes the selection set to request different entities or relationships, altering the fundamental meaning of the original request.

Execute both the original (if partially valid) and repaired queries against a mock server. Compare the set of root field names and key entity identifiers requested. They must be semantically equivalent.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Integrate a full [INTROSPECTION_JSON] block as context. Add a strict [OUTPUT_SCHEMA] requiring the model to return a JSON object with original_query, repaired_query, and changes array. Implement a post-processing harness that parses the output and validates the repaired_query against your actual GraphQL schema using a library like graphql-js. Add a retry loop: if validation fails, feed the error back into the prompt as a new [VALIDATION_ERROR] variable.

Watch for

  • Large introspection schemas can blow out your context window; consider compressing or filtering it first.
  • Silent failures where the model returns a syntactically valid query that doesn't do what the user intended.
  • Performance bottlenecks from synchronous validation in high-throughput systems.
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.