Contract Testing for LLM APIs: Schemas, Mocks, Error Cases, and SDK Upgrades
API testingLLM integrationssoftware qualitydeveloper workflows

Contract Testing for LLM APIs: Schemas, Mocks, Error Cases, and SDK Upgrades

PPowerLabs Editorial Team
2026-12-02
7 min read

A reusable checklist for testing LLM API schemas, mocks, tool calls, errors, rate limits, and SDK upgrades before production.

Contract testing gives LLM integrations a repeatable way to detect breaking changes before they affect users. This checklist covers response schemas, tool calls, authentication, rate limits, error handling, mocks, and SDK upgrades so your team can test an AI API integration as a dependable software boundary rather than relying on a few successful prompts.

Overview

An LLM API contract is the set of assumptions your application makes about a provider or gateway. Those assumptions may include the request shape, required headers, accepted model identifiers, response fields, streamed event formats, tool-call arguments, error codes, retry behavior, and usage metadata. Some assumptions are documented by the provider; others are embedded in your SDK, adapters, serializers, validation rules, and application logic.

Contract testing checks those assumptions with small, deterministic tests. It is different from evaluating whether a model gives a good answer. A quality evaluation asks whether an output is useful or accurate. A contract test asks whether the integration still behaves in the way the application expects. Both belong in production AI workflows, but they catch different classes of failure.

For an LLM app, start by separating the contract into four layers:

  • Transport: URL, method, authentication, headers, timeouts, streaming, and content types.
  • Request: model selection, messages, generation settings, response-format options, tools, and metadata.
  • Response: content, finish or stop status, tool calls, usage fields, refusal or safety fields, and streamed chunks.
  • Failure behavior: validation errors, authentication failures, throttling, timeouts, server errors, and malformed provider responses.

Keep provider-specific behavior behind an adapter when possible. Your application can then test one internal interface while separate contract suites verify each provider, model family, or gateway. This approach also makes model migrations and SDK upgrades easier to review. For related release controls, see Prompt Versioning and Change Management and the production model selection decision matrix.

Checklist by scenario

1. Before implementing a new integration

  • Write down the internal request and response interface your application needs.
  • Record required authentication headers, base URLs, API versions, and timeout defaults.
  • Define which response fields are required, optional, nullable, or ignored.
  • Decide whether your application supports streamed output, tool calls, structured output, or all three.
  • Specify how the adapter maps provider errors into stable internal categories such as invalid request, unauthorized, throttled, timed out, unavailable, and unknown.
  • Create at least one fixture for a normal text response and one for an empty or partial response.

2. Before a staging deployment

  • Run a valid request using the same request builder and serializer used in production.
  • Validate the response against a schema, not just a non-empty string assertion.
  • Test a request with a tool definition and verify the tool name, arguments, and call identifier.
  • Test streaming if enabled, including chunk ordering, termination, and assembly into the expected final object.
  • Confirm that secrets are supplied through configuration and are not present in logs, snapshots, or fixtures.
  • Check that retries do not duplicate an operation that has side effects.

3. Before an SDK upgrade

  • Read the SDK migration notes and compare request and response types with your stored contract.
  • Run the existing contract suite against the old and new dependency versions.
  • Inspect serialized requests rather than assuming equivalent SDK methods produce equivalent payloads.
  • Compare exception classes, status-code handling, retry defaults, timeout units, and stream event types.
  • Review changes to tool-call and structured-output helpers, which can alter field names or nesting.
  • Build the application with strict type checking and treat newly optional or newly required fields as review items.
  • Deploy first to an isolated environment with representative but non-sensitive fixtures.

4. Before a model or provider migration

  • Run the same contract suite against every target model or provider adapter.
  • Separate schema compatibility from behavioral quality. A response can be schema-valid while still requiring a quality evaluation.
  • Test context limits, unsupported parameters, tool support, structured responses, and streaming independently.
  • Compare usage accounting only when the application depends on it for budgets, quotas, or reporting.
  • Verify fallback behavior if the primary model is unavailable or throttled.

5. When an integration test fails

  • Save the sanitized request, response, status code, headers that are safe to retain, SDK version, adapter version, and test identifier.
  • Classify the failure as transport, schema, authentication, throttling, timeout, provider behavior, or test-fixture drift.
  • Reproduce with a minimal request before changing production code.
  • Check whether the failure is intermittent and whether a retry would be safe.
  • Update the contract only after confirming that the new behavior is intended and supported.

Provider compatibility comparison

Provider documentation and SDK behavior change, so use this table as a review framework rather than a permanent ranking.

Compatibility concernProvider or gateway AProvider or gateway BWhat to test
AuthenticationHeader and token rulesHeader and token rulesMissing, expired, and malformed credentials
Request schemaMessage and parameter formatMessage and parameter formatRequired fields, rejected fields, and serialization
Tool callingName, arguments, identifiersName, arguments, identifiersValid calls, invalid arguments, and multiple calls
StreamingChunk and termination eventsChunk and termination eventsAssembly, disconnects, and incomplete streams
Errors and limitsStatus and provider error shapeStatus and provider error shapeThrottling, timeout, validation, and server errors

Keep this comparison in version control beside the adapter tests. It becomes a useful decision record when an integration changes.

What to double-check

API contract template

For each endpoint, model, or adapter, record a compact contract that reviewers can understand:

Contract: text-generation-adapter-v1
Request:
  required: messages, model
  optional: temperature, tools, response_format
  headers: authorization, content-type
Response:
  required: output or tool_calls, termination_status
  optional: usage, request_id, safety_metadata
Errors:
  invalid_request, unauthorized, throttled, timeout, unavailable
Operational:
  timeout: documented application limit
  retries: only for safe and retryable failures
  logging: sanitize prompts, outputs, and credentials

The exact fields should reflect your application, not a generic provider example. Mark fields as required only when application logic truly depends on them. If usage metadata is useful but not essential, treat its absence differently from a missing generated message.

Mock-response library structure

Mocks should represent response shapes and failure modes that your application must handle. A practical structure might look like this:

test-fixtures/llm/
  provider-a/
    valid-text.json
    valid-tool-call.json
    streamed-chunks.json
    malformed-response.json
    throttled-error.json
    timeout.json
  provider-b/
    valid-text.json
    valid-tool-call.json
  shared/
    expected-internal-response.json

Keep provider fixtures separate from normalized internal fixtures. This lets tests prove both sides of the adapter: the provider payload is parsed correctly, and the application receives the stable shape it expects. Never use real credentials or unnecessary personal data in fixtures. The PII redaction checklist can help establish safer test data practices.

Required error cases

At minimum, test malformed JSON, missing required response fields, an unexpected tool name, invalid tool arguments, a rejected request parameter, an authentication failure, a throttled request, a connection timeout, an interrupted stream, and a provider-side server error. Assert both the internal error category and the operational result: whether the request is retried, surfaced to a user, placed in a queue, or recorded for investigation.

Common mistakes

  • Testing only successful text. A happy-path response does not verify tool calls, streams, usage fields, or failure handling.
  • Asserting exact prose. Contract tests should focus on structure and protocol behavior. Use separate evaluation tests for wording, factuality, tone, and task quality.
  • Trusting SDK abstractions completely. An SDK may rename fields, apply defaults, convert exceptions, or hide raw response details. Test the serialized boundary where practical.
  • Making every field mandatory. Optional metadata can disappear during a provider change without breaking the core feature. Define the minimum viable contract.
  • Retrying every error. Invalid requests and authentication failures usually require correction, not repetition. Retry policy should be explicit and safe for the operation.
  • Using live calls for every test. Live tests are useful for smoke checks, but deterministic mocks are faster, safer, and easier to diagnose for most contract cases.
  • Updating fixtures without reviewing the contract. A changed snapshot can conceal a breaking response change. Require a reason and review for every fixture update.
  • Ignoring prompt and tool versioning. A schema-compatible API can still behave differently when prompts, tool definitions, or parsing rules change. Track those inputs alongside code versions; see the prompt rollback workflow.

When to revisit

Re-run the full checklist before every SDK upgrade, provider API version change, model migration, adapter refactor, staging deployment, or change to tool and structured-output schemas. Also revisit it after a failed integration test, an unexplained increase in retries, a new authentication method, or a change to rate-limit handling.

As a maintenance practice, review provider documentation, SDK conventions, response schemas, deprecation notices, and representative test examples each quarter or whenever a provider releases a new API version. A quarterly review does not replace event-driven testing; it is a prompt to look for quiet drift in assumptions that have not yet caused a failure.

Use this closing workflow:

  1. Export the current contract and identify changed inputs.
  2. Run valid, malformed, timed-out, throttled, authentication, tool-call, and streaming tests.
  3. Compare old and new SDK or provider behavior at the adapter boundary.
  4. Review fixture changes and confirm that no sensitive data was introduced.
  5. Run staging smoke tests, inspect sanitized traces, and record the release decision.
  6. Update the contract, mocks, and migration notes only after the new behavior is understood.

For broader operational coverage, pair contract tests with AI workflow observability and the guidance on reliable LLM tool calling. Contract testing will not prevent every model-quality issue, but it gives developers a controlled way to catch integration breakage before it becomes a production surprise.

Related Topics

#API testing#LLM integrations#software quality#developer workflows
P

PowerLabs Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.