Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

937 B
Raw Blame
import type { GenerateObjectSchema } from '@lobechat/model-runtime';
import { z } from 'zod';

export interface BuildSchemaOptions {
  description?: string;
  name: string;
  strict?: boolean;
}

const pickMainSchema = (result: any, name: string) => {
  if (result?.$defs?.[name]) {
    return result.$defs[name];
  }
  if (result?.definitions?.[name]) {
    return result.definitions[name];
  }

  return result;
};

export const buildGenerateObjectSchema = (
  schema: z.ZodTypeAny,
  options: BuildSchemaOptions,
): GenerateObjectSchema => {
  const fullSchema = z.toJSONSchema(schema, { target: 'draft-7' });

  const jsonSchema = pickMainSchema(fullSchema, options.name);
  if (jsonSchema.type === 'object') {
    jsonSchema.additionalProperties = false;
  }

  return {
    description: options.description,
    name: options.name,
    schema: jsonSchema,
    strict: options.strict ?? true,
  } satisfies GenerateObjectSchema;
};