Version wire schemas and adapt to a canonical server shape

Version wire schemas and adapt to a canonical server shape

●3 ●61
calendar_today • schedule3 min read
— Originally published at chriseugenerodriguez.com

Prerequisites

  • Familiarity with OpenAI function calling or Structured Outputs and JSON payloads.
  • A server-side request boundary where model proposals (function_call or structured output JSON) are parsed before business logic runs.

Implementation decision

  • Define explicit, versioned wire schemas (v1, v2, …) that the model sees and that drive the model toward a particular JSON shape.
  • Implement a strict validator for each wire version (additionalProperties:false, required fields explicit). Validation is used only to decide whether the incoming proposal matches that version’s contract.
  • Implement an adapter that recognizes known wire shapes and maps them into one canonical internal object. The adapter encodes the compatibility policy: how to rename fields, default missing values, and convert null unions into application semantics.

Expected result

  • The server can accept both v1 and v2 payloads during a migration window and produce the same canonical object for downstream code.
  • Tests can assert acceptance, rejection reasons (missing required fields, additionalProperties violations), canonical normalization outcomes, and adapter throw-on-unrecognized-shape behavior.

One limitation

  • This approach requires you to pick and maintain adapter logic. If you rely on complex JSON Schema features disallowed by Structured Outputs, you must move that logic into the adapter. The adapter’s policies (how long to accept an old wire version, whether to synthesize fields) are organizational choices you must document and test.

(Verified implementation example is inserted by the server.)

Working example

export const v1FunctionSchema = {
  type: 'object',
  additionalProperties: false,
  required: ['orderId', 'items'],
  properties: {
    orderId: { type: 'string' },
    items: {
      type: 'array',
      items: {
        type: 'object',
        additionalProperties: false,
        required: ['id', 'qty'],
        properties: {
          id: { type: 'string' },
          qty: { type: 'number' }
        }
      }
    }
  }
};

export const v2FunctionSchema = {
  type: 'object',
  additionalProperties: false,
  required: ['order_id', 'items', 'priority'],
  properties: {
    order_id: { type: 'string' },
    items: {
      type: 'array',
      items: {
        type: 'object',
        additionalProperties: false,
        required: ['id', 'qty'],
        properties: {
          id: { type: 'string' },
          qty: { type: 'number' }
        }
      }
    },
    priority: { type: ['boolean', 'null'] }
  }
};

function matchesType(value, typeDef) {
  if (Array.isArray(typeDef)) return typeDef.some((t) => matchesType(value, t));
  if (typeDef === 'null') return value === null;
  if (typeDef === 'string') return typeof value === 'string';
  if (typeDef === 'number') return typeof value === 'number' && Number.isFinite(value);
  if (typeDef === 'boolean') return typeof value === 'boolean';
  if (typeDef === 'array') return Array.isArray(value);
  if (typeDef === 'object') return value !== null && typeof value === 'object' && !Array.isArray(value);
  return false;
}

function checkObject(value, schema, path) {
  if (!matchesType(value, schema.type)) {
    return { ok: false, reason: `${path || 'root'} must be ${Array.isArray(schema.type) ? schema.type.join('|') : schema.type}` };
  }

  const properties = schema.properties || {};
  const required = schema.required || [];

  if (schema.additionalProperties === false) {
    for (const key of Object.keys(value)) {
      if (!Object.hasOwn(properties, key)) {
        return { ok: false, reason: `${path || 'root'} additional property: ${key}` };
      }
    }
  }

  for (const key of required) {
    if (!Object.hasOwn(value, key)) {
      return { ok: false, reason: `${path || 'root'} missing required: ${key}` };
    }
  }

  for (const [key, propSchema] of Object.entries(properties)) {
    if (!Object.hasOwn(value, key)) continue;
    const child = value[key];
    const childPath = path ? `${path}.${key}` : key;

    if (propSchema.type === 'array') {
      if (!Array.isArray(child)) return { ok: false, reason: `${childPath} must be array` };
      for (let i = 0; i < child.length; i++) {
        const item = child[i];
        if (propSchema.items?.type === 'object') {
          const result = checkObject(item, propSchema.items, `${childPath}[${i}]`);
          if (!result.ok) return result;
        } else if (!matchesType(item, propSchema.items?.type)) {
          return { ok: false, reason: `${childPath}[${i}] wrong type` };
        }
      }
      continue;
    }

    if (propSchema.type === 'object') {
      const result = checkObject(child, propSchema, childPath);
      if (!result.ok) return result;
      continue;
    }

    if (!matchesType(child, propSchema.type)) {
      return { ok: false, reason: `${childPath} wrong type` };
    }
  }

  return { ok: true };
}

export function validateStrict(args, schema) {
  return checkObject(args, schema, '');
}

export function isRejectedBySchema(args, schema) {
  const result = validateStrict(args, schema);
  return result.ok ? { rejected: false } : { rejected: true, reason: result.reason };
}

export function adaptToCanonical(args) {
  if (args && typeof args === 'object' && !Array.isArray(args)) {
    if (Object.hasOwn(args, 'orderId')) {
      return {
        orderId: String(args.orderId),
        items: Array.isArray(args.items)
          ? args.items.map((item) => ({ id: String(item.id), qty: Number(item.qty) }))
          : [],
        priority: false
      };
    }

    if (Object.hasOwn(args, 'order_id')) {
      return {
        orderId: String(args.order_id),
        items: Array.isArray(args.items)
          ? args.items.map((item) => ({ id: String(item.id), qty: Number(item.qty) }))
          : [],
        priority: args.priority === null ? false : Boolean(args.priority)
      };
    }
  }

  throw new Error('unrecognized argument shape: cannot adapt');
}

export function vetModelFunctionCall(argumentsJSON, schema) {
  let parsed;
  try {
    parsed = JSON.parse(argumentsJSON);
  } catch {
    return { accepted: false, reason: 'invalid JSON' };
  }

  const validation = validateStrict(parsed, schema);
  if (!validation.ok) return { accepted: false, reason: validation.reason };

  return { accepted: true, canonical: adaptToCanonical(parsed) };
}

Read the full article: https://chriseugenerodriguez.com/blog/evolving-function-schemas-without-breaking-live-conversations

Want more #ai deep dives?

Join 6,178+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

A Textile Mill's Dyehouse Ramp Curve: Get One Step Wrong and the Sheet Belongs to the Master

aiomniu - Oct 18

The Sovereign Vault — A Comprehensive Guide to Protocol-Driven AI

Ken W. Algerverified - Jun 4

How AI Is Changing Web Development, and What Developers Still Need to Understand

Daniel Decker - Nov 10

Dozens of email accounts: learning AI coding tools as a student

rahuldk1105 - Oct 27
chevron_left
1.3k Points • 64 Badges
Santa Monica, CA • chriseugenerodriguez.com
48Posts
0Comments
12Connections
10 years fe

Related Jobs

View all jobs →

Commenters (This Week)

7 comments
7 comments
2 comments

Contribute meaningful comments to climb the leaderboard and earn badges!