|
| 1 | +import { Tool } from "effect/ai"; |
| 2 | + |
| 3 | +type Json = unknown; |
| 4 | +type JsonObject = { [key: string]: Json }; |
| 5 | + |
| 6 | +const isObject = (value: Json): value is JsonObject => |
| 7 | + typeof value === "object" && value !== null && !Array.isArray(value); |
| 8 | + |
| 9 | +const isNullSchema = (value: Json) => |
| 10 | + isObject(value) && value.type === "null" && Object.keys(value).length === 1; |
| 11 | + |
| 12 | +const isBareAnyOf = (value: Json): value is { anyOf: Array<Json> } => |
| 13 | + isObject(value) && Array.isArray(value.anyOf) && Object.keys(value).length === 1; |
| 14 | + |
| 15 | +// A `Schema.fromJsonString` fallback. Advertised beside object shapes, it invites stringified input. |
| 16 | +const isJsonStringSchema = (value: Json) => |
| 17 | + isObject(value) && value.type === "string" && value.contentMediaType === "application/json"; |
| 18 | + |
| 19 | +const SAFE_INTEGER_BOUNDS: Record<string, number> = { |
| 20 | + maximum: Number.MAX_SAFE_INTEGER, |
| 21 | + minimum: Number.MIN_SAFE_INTEGER, |
| 22 | +}; |
| 23 | + |
| 24 | +const compact = (schema: Json, optional: boolean): Json => { |
| 25 | + if (Array.isArray(schema)) return schema.map((item) => compact(item, false)); |
| 26 | + if (!isObject(schema)) return schema; |
| 27 | + const required = new Set(Array.isArray(schema.required) ? schema.required : []); |
| 28 | + let result: JsonObject = {}; |
| 29 | + for (const [key, value] of Object.entries(schema)) { |
| 30 | + if (key === "additionalProperties" && value === true) continue; |
| 31 | + if (SAFE_INTEGER_BOUNDS[key] === value) continue; |
| 32 | + result[key] = |
| 33 | + key === "properties" && isObject(value) |
| 34 | + ? Object.fromEntries( |
| 35 | + Object.entries(value).map(([name, property]) => [ |
| 36 | + name, |
| 37 | + compact(property, !required.has(name)), |
| 38 | + ]), |
| 39 | + ) |
| 40 | + : compact(value, false); |
| 41 | + } |
| 42 | + if (Array.isArray(result.anyOf)) { |
| 43 | + const branches = result.anyOf |
| 44 | + .flatMap((branch) => (isBareAnyOf(branch) ? branch.anyOf : [branch])) |
| 45 | + .filter((branch) => !(optional && isNullSchema(branch)) && !isJsonStringSchema(branch)); |
| 46 | + const { anyOf: _anyOf, ...rest } = result; |
| 47 | + const only = branches.length === 1 ? branches[0] : undefined; |
| 48 | + result = isObject(only) ? { ...only, ...rest } : { ...rest, anyOf: branches }; |
| 49 | + } |
| 50 | + return result; |
| 51 | +}; |
| 52 | + |
| 53 | +/** |
| 54 | + * The input schema T3 advertises for a tool. Drops JSON noise that every thread pays for: |
| 55 | + * `additionalProperties: true`, safe-integer bounds, nested `anyOf`, JSON-string fallbacks, and |
| 56 | + * the `null` branch of optional properties. Decoding still uses the full schema. |
| 57 | + */ |
| 58 | +export const advertisedJsonSchema = (tool: Tool.Any) => |
| 59 | + compact(Tool.getJsonSchema(tool), false) as ReturnType<typeof Tool.getJsonSchema>; |
0 commit comments