import {z} from 'zod' export type FieldWrapper = {empty?: boolean | undefined}; export type EnhancePostRequest = {type?: ('Person' | 'Organization') | undefined, id?: string | undefined, name?: FieldWrapper | undefined, url?: FieldWrapper | undefined, location?: string | undefined, ip?: string | undefined, phone?: string | undefined, description?: string | undefined, email?: FieldWrapper | undefined, employer?: string | undefined, title?: string | undefined, school?: string | undefined, customId?: string | undefined, size?: number | undefined, threshold?: number | undefined, refresh?: boolean | undefined, search?: boolean | undefined, nonCanonicalFacts?: boolean | undefined, jsonmode?: (' ' | 'extended') | undefined, filter?: string | undefined, filterExclude?: string | undefined}; export type CreateApiKgV3EnhanceArgs = {body: EnhancePostRequest}; export type CreateApiKgV3EnhanceOptions = {baseUrl?: string | undefined, tokenscheme?: string | undefined, fetch?: typeof fetch | undefined}; export const fieldWrapper = z.object({empty: z.boolean().optional()}); export const requestContext: z.ZodType = z.object({query: z.union([z.object({type: z.string().optional(), location: z.string().optional(), ip: z.string().optional(), phone: z.string().optional(), description: z.string().optional()}), z.object({type: z.string().optional(), location: z.string().optional(), ip: z.string().optional(), phone: z.string().optional(), description: z.string().optional(), email: fieldWrapper.optional(), employer: z.string().optional(), title: z.string().optional(), school: z.string().optional()})]).optional(), query_ctx: z.record(z.string(), z.object({})).optional(), threshold: z.lazy(() => requestContext.optional()), customId: z.lazy(() => requestContext.optional())}); export const objectNode = z.object({}); export const refreshDebugInformation = z.object({url: z.string().optional(), hasResult: z.boolean().optional(), lastCrawlTime: z.number().int().optional(), message: z.string().optional()}); export const delta = z.object({}); export const data = z.object({score: z.number().optional(), entity: objectNode.optional(), errors: z.array(z.string()).optional(), refreshInfo: z.record(z.string(), refreshDebugInformation).optional(), refreshDelta: delta.optional(), entity_ctx: z.record(z.string(), z.object({})).optional()}); export const searchCandidate = z.object({mlScore: z.number().optional(), baseMlScore: z.number().optional(), debugInfo: refreshDebugInformation.optional()}); export const enhanceResponse = z.object({version: z.number().int().optional(), hits: z.number().int().optional(), kgversion: z.string().optional(), request_ctx: requestContext.optional(), data: z.array(data).optional(), errors: z.array(z.string()).optional(), searchInfo: z.record(z.string(), searchCandidate).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Enhance * * POST /kg/v3/enhance */ export const createApiKgV3Enhance = async (args: CreateApiKgV3EnhanceArgs, options?: CreateApiKgV3EnhanceOptions) => { const {baseUrl = "https://llm.diffbot.com/api/v1/web_search", fetch: fetchFn = fetch, tokenscheme} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (tokenscheme !== undefined) query.set("token", tokenscheme) const url = `${baseUrl.replace(/\/+$/, '')}/kg/v3/enhance${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(enhanceResponse, await res.json()) };