UNPKG

@agentic/core

Version:

Agentic AI utils which work with any LLM and TypeScript AI SDK.

1,001 lines (986 loc) 30.3 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name); var __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)]; var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"]; var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn; var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) }); var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]); var __runInitializers = (array, flags, self, value) => { for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value); return value; }; var __decorateElement = (array, flags, name, decorators, target, extra) => { var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16); var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5]; var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []); var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() { return __privateGet(this, extra); }, set [name](x) { return __privateSet(this, extra, x); } }, name)); k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name); for (var i = decorators.length - 1; i >= 0; i--) { ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers); if (k) { ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x }; if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name]; if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y; } it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1; if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it); else if (typeof it !== "object" || it === null) __typeError("Object expected"); else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn); } return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target; }; var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); // src/parse-structured-output.ts import { jsonrepair, JSONRepairError } from "jsonrepair"; import { z } from "zod"; import { fromZodError } from "zod-validation-error"; // src/errors.ts var RetryableError = class extends Error { }; var AbortError = class extends Error { }; var ParseError = class extends RetryableError { }; var TimeoutError = class extends Error { }; // src/parse-structured-output.ts function parseStructuredOutput(value, outputSchema) { if (!value || typeof value !== "string") { throw new Error("Invalid output: expected string"); } const output = value; let result; if (outputSchema instanceof z.ZodArray || "element" in outputSchema) { result = parseArrayOutput(output); } else if (outputSchema instanceof z.ZodObject || "omit" in outputSchema) { result = parseObjectOutput(output); } else if (outputSchema instanceof z.ZodBoolean) { result = parseBooleanOutput(output); } else if (outputSchema instanceof z.ZodNumber || "nonnegative" in outputSchema) { result = parseNumberOutput(output, outputSchema); } else { result = output; } const safeResult = outputSchema.safeParse(result); if (!safeResult.success) { throw fromZodError(safeResult.error); } return safeResult.data; } function safeParseStructuredOutput(value, outputSchema) { if (!value || typeof value !== "string") { return { success: false, error: "Invalid output: expected string" }; } const output = value; try { const data = parseStructuredOutput(output, outputSchema); return { success: true, data }; } catch (err) { return { success: false, error: err.message }; } } function isEscaped(str, i) { return i > 0 && str[i - 1] === "\\" && !(i > 1 && str[i - 2] === "\\"); } function extractJSONFromString(input, jsonStructureType) { const startChar = jsonStructureType === "object" ? "{" : "["; const endChar = jsonStructureType === "object" ? "}" : "]"; const extractedJSONValues = []; let nestingLevel = 0; let startIndex = 0; const isInsideQuoted = { '"': false, "'": false }; for (let i = 0; i < input.length; i++) { const ch = input.charAt(i); switch (ch) { case '"': case "'": if (!isInsideQuoted[ch === '"' ? "'" : '"'] && !isEscaped(input, i)) { isInsideQuoted[ch] = !isInsideQuoted[ch]; } break; default: if (!isInsideQuoted['"'] && !isInsideQuoted["'"]) { switch (ch) { case startChar: if (nestingLevel === 0) { startIndex = i; } nestingLevel += 1; break; case endChar: nestingLevel -= 1; if (nestingLevel === 0) { const candidate = input.slice(startIndex, i + 1); const parsed = JSON.parse(jsonrepair(candidate)); if (parsed && typeof parsed === "object") { extractedJSONValues.push(parsed); } } else if (nestingLevel < 0) { throw new ParseError( `Invalid JSON string: unexpected ${endChar} at position ${i}` ); } } } } } if (nestingLevel !== 0) { throw new ParseError( "Invalid JSON string: unmatched " + startChar + " or " + endChar ); } return extractedJSONValues; } var BOOLEAN_OUTPUTS = { true: true, false: false, t: true, f: false, yes: true, no: false, y: true, n: false, "1": true, "0": false }; function parseArrayOutput(output) { try { const arrayOutput = extractJSONFromString(output, "array"); if (arrayOutput.length === 0) { throw new ParseError("Invalid JSON array"); } const parsedOutput = arrayOutput[0]; if (!Array.isArray(parsedOutput)) { throw new ParseError("Expected JSON array"); } return parsedOutput; } catch (err) { if (err instanceof JSONRepairError) { throw new ParseError(err.message, { cause: err }); } else if (err instanceof SyntaxError) { throw new ParseError(`Invalid JSON array: ${err.message}`, { cause: err }); } else { throw err; } } } function parseObjectOutput(output) { try { const arrayOutput = extractJSONFromString(output, "object"); if (arrayOutput.length === 0) { throw new ParseError("Invalid JSON object"); } let parsedOutput = arrayOutput[0]; if (Array.isArray(parsedOutput)) { parsedOutput = parsedOutput[0]; } if (!parsedOutput || typeof parsedOutput !== "object") { throw new ParseError("Expected JSON object"); } return parsedOutput; } catch (err) { if (err instanceof JSONRepairError) { throw new ParseError(err.message, { cause: err }); } else if (err instanceof SyntaxError) { throw new ParseError(`Invalid JSON object: ${err.message}`, { cause: err }); } else { throw err; } } } function parseBooleanOutput(output) { output = output.toLowerCase().trim().replace(/[!.?]+$/, ""); const booleanOutput = BOOLEAN_OUTPUTS[output]; if (booleanOutput === void 0) { throw new ParseError(`Invalid boolean output: ${output}`); } else { return booleanOutput; } } function parseNumberOutput(output, outputSchema) { output = output.trim(); const numberOutput = outputSchema.isInt ? Number.parseInt(output) : Number.parseFloat(output); if (Number.isNaN(numberOutput)) { throw new ParseError(`Invalid number output: ${output}`); } return numberOutput; } // src/utils.ts import dedent from "dedent"; // src/assert.ts function assert(value, message) { if (value) { return; } if (!message) { throw new Error("Assertion failed"); } throw typeof message === "string" ? new Error(message) : message; } // src/utils.ts import { default as default2 } from "delay"; var omit = (inputObj, ...keys) => { const keysSet = new Set(keys); return Object.fromEntries( Object.entries(inputObj).filter(([k]) => !keysSet.has(k)) ); }; var pick = (inputObj, ...keys) => { const keysSet = new Set(keys); return Object.fromEntries( Object.entries(inputObj).filter(([k]) => keysSet.has(k)) ); }; function pruneUndefined(obj) { return Object.fromEntries( Object.entries(obj).filter(([, value]) => value !== void 0) ); } function pruneNullOrUndefined(obj) { return Object.fromEntries( Object.entries(obj).filter( ([, value]) => value !== void 0 && value !== null ) ); } function pruneNullOrUndefinedDeep(obj) { if (!obj || Array.isArray(obj) || typeof obj !== "object") return obj; return Object.fromEntries( Object.entries(obj).filter(([, value]) => value !== void 0 && value !== null).map( ([key, value]) => Array.isArray(value) ? [ key, value.filter((v) => v !== void 0 && v !== null).map(pruneNullOrUndefinedDeep) ] : typeof value === "object" ? [key, pruneNullOrUndefinedDeep(value)] : [key, value] ) ); } function pruneEmpty(obj) { return Object.fromEntries( Object.entries(obj).filter(([, value]) => { if (value === void 0 || value === null) return false; if (typeof value === "string" && !value) return false; if (Array.isArray(value) && !value.length) return false; if (typeof value === "object" && !Array.isArray(value) && !Object.keys(value).length) { return false; } return true; }) ); } function pruneEmptyDeep(value) { if (value === void 0 || value === null) return void 0; if (typeof value === "string") { if (!value) return void 0; return value; } if (Array.isArray(value)) { if (!value.length) return void 0; value = value.map((v) => pruneEmptyDeep(v)).filter((v) => v !== void 0); if (!value || !Array.isArray(value) || !value.length) return void 0; return value; } if (typeof value === "object") { if (!Object.keys(value).length) return void 0; value = Object.fromEntries( Object.entries(value).map(([k, v]) => [k, pruneEmptyDeep(v)]).filter(([, v]) => v !== void 0) ); if (!value || !Object.keys(value).length) return void 0; return value; } return value; } function getEnv(name) { try { return typeof process !== "undefined" ? ( // eslint-disable-next-line no-process-env process.env?.[name] ) : void 0; } catch { return void 0; } } var noop = () => void 0; function throttleKy(ky, throttleFn) { return ky.extend({ hooks: { beforeRequest: [throttleFn(noop)] } }); } function sanitizeSearchParams(searchParams, { csv = false } = {}) { const entries = Object.entries(searchParams).flatMap(([key, value]) => { if (key === void 0 || value === void 0) { return []; } if (Array.isArray(value)) { return value.map((v) => [key, String(v)]); } return [[key, String(value)]]; }); if (!csv) { return new URLSearchParams(entries); } const csvEntries = {}; for (const [key, value] of entries) { csvEntries[key] = csvEntries[key] ? `${csvEntries[key]},${value}` : value; } return new URLSearchParams(csvEntries); } function stringifyForModel(jsonObject, replacer = null, space = 0) { if (jsonObject === void 0) { return ""; } if (typeof jsonObject === "string") { return jsonObject; } return JSON.stringify(jsonObject, replacer, space); } var dedenter = dedent.withOptions({ escapeSpecialCharacters: true }); function cleanStringForModel(text) { return dedenter(text).trim(); } function isAIFunction(obj) { if (!obj) return false; if (typeof obj !== "function") return false; if (!obj.inputSchema) return false; if (!obj.parseInput) return false; if (!obj.spec) return false; if (!obj.execute) return false; if (!obj.spec.name || typeof obj.spec.name !== "string") return false; return true; } function getErrorMessage(error) { if (!error) { return "unknown error"; } if (typeof error === "string") { return error; } const message = error.message; if (message && typeof message === "string") { return message; } try { return JSON.stringify(error); } catch { return "unknown error"; } } function getShortDateString(date = /* @__PURE__ */ new Date()) { return date.toISOString().split("T")[0]; } // src/zod-to-json-schema.ts import { zodToJsonSchema as zodToJsonSchemaImpl } from "openai-zod-to-json-schema"; function zodToJsonSchema(schema, { strict = false } = {}) { return omit( zodToJsonSchemaImpl(schema, { $refStrategy: "none", openaiStrictMode: strict }), "$schema", "default", "definitions", "description", "markdownDescription" ); } // src/schema.ts var schemaSymbol = Symbol("agentic.schema"); function isAgenticSchema(value) { return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "parse" in value; } function isZodSchema(value) { return !!value && typeof value === "object" && "_def" in value && "~standard" in value && value["~standard"]?.vendor === "zod"; } function asAgenticSchema(schema, opts = {}) { return isAgenticSchema(schema) ? schema : createAgenticSchemaFromZodSchema(schema, opts); } function asZodOrJsonSchema(schema) { return isZodSchema(schema) ? schema : schema.jsonSchema; } function createJsonSchema(jsonSchema, { parse = (value) => value, safeParse, source } = {}) { safeParse ??= (value) => { try { const result = parse(value); return { success: true, data: result }; } catch (err) { return { success: false, error: err.message ?? String(err) }; } }; return { [schemaSymbol]: true, _type: void 0, jsonSchema, parse, safeParse, _source: source }; } function createAgenticSchemaFromZodSchema(zodSchema, opts = {}) { return createJsonSchema(zodToJsonSchema(zodSchema, opts), { parse: (value) => { return parseStructuredOutput(value, zodSchema); }, source: zodSchema }); } var DEFAULT_SCHEMA_PREFIX = ` --- Respond with JSON using the following JSON schema: \`\`\`json`; var DEFAULT_SCHEMA_SUFFIX = "```"; function augmentSystemMessageWithJsonSchema({ schema, system, schemaPrefix = DEFAULT_SCHEMA_PREFIX, schemaSuffix = DEFAULT_SCHEMA_SUFFIX }) { return [system, schemaPrefix, stringifyForModel(schema), schemaSuffix].filter(Boolean).join("\n").trim(); } // src/create-ai-function.ts function createAIFunction({ name, description, inputSchema, strict = true, tags, execute }, executeArg) { assert(name, 'createAIFunction missing required "name"'); assert(inputSchema, 'createAIFunction missing required "inputSchema"'); assert( execute || executeArg, 'createAIFunction missing required "execute" function implementation' ); assert( !(execute && executeArg), 'createAIFunction: cannot provide both "execute" and a second function argument. there should only be one function implementation.' ); execute ??= executeArg; assert( execute, 'createAIFunction missing required "execute" function implementation' ); assert( typeof execute === "function", 'createAIFunction "execute" must be a function' ); const inputAgenticSchema = asAgenticSchema(inputSchema, { strict }); const parseInput = (input) => { if (typeof input === "string") { return inputAgenticSchema.parse(input); } else { const args = input.function_call?.arguments; assert( args, `Missing required function_call.arguments for function ${name}` ); return inputAgenticSchema.parse(args); } }; const aiFunction2 = (input) => { const parsedInput = parseInput(input); return execute(parsedInput); }; Object.defineProperty(aiFunction2, "name", { value: name, writable: false }); aiFunction2.inputSchema = inputSchema; aiFunction2.parseInput = parseInput; aiFunction2.execute = execute; aiFunction2.tags = tags; aiFunction2.spec = { name, description, parameters: inputAgenticSchema.jsonSchema, type: "function", strict }; return aiFunction2; } // src/fns.ts Symbol.metadata ??= Symbol.for("Symbol.metadata"); var _metadata = /* @__PURE__ */ Object.create(null); if (typeof Symbol === "function" && Symbol.metadata) { Object.defineProperty(globalThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); } var AIFunctionsProvider = class { _functions; /** * An `AIFunctionSet` containing all of the AI-compatible functions exposed * by this class. * * This property is useful for manipulating AI functions across multiple * sources, picking specific functions, ommitting certain functions, etc. */ get functions() { if (!this._functions) { const metadata = this.constructor[Symbol.metadata]; assert( metadata, "Your runtime does not appear to support ES decorator metadata: https://github.com/tc39/proposal-decorator-metadata/issues/14" ); const invocables = metadata?.invocables ?? []; const aiFunctions = invocables.map((invocable) => { const impl = this[invocable.methodName]; assert(impl); return createAIFunction(invocable, impl); }); this._functions = new AIFunctionSet(aiFunctions); } return this._functions; } /** * Returns the AIFunctions provided by this class filtered by the given tags. */ getFunctionsFilteredByTags(...tags) { return this.functions.getFilteredByTags(...tags); } /** * Returns the AIFunctions provided by this class which match a custom filter * function. */ getFunctionsFilteredBy(filterFn) { return this.functions.getFilteredBy(filterFn); } }; function aiFunction(args) { return (_targetMethod, context) => { const methodName = String(context.name); if (!context.metadata.invocables) { context.metadata.invocables = []; } assert(args.name, 'aiFunction requires a non-empty "name" argument'); context.metadata.invocables.push({ ...args, methodName }); context.addInitializer(function() { ; this[methodName] = this[methodName].bind(this); }); }; } // src/ai-function-set.ts var AIFunctionSet = class _AIFunctionSet { _map; _transformNameKeysFn; constructor(aiFunctionLikeObjects, { transformNameKeysFn = transformName } = {}) { this._transformNameKeysFn = transformNameKeysFn; const fns = aiFunctionLikeObjects?.flatMap((fn) => { if (fn instanceof AIFunctionsProvider) { return [...fn.functions]; } if (fn instanceof _AIFunctionSet) { return [...fn]; } if (isAIFunction(fn)) { return fn; } const fa = fn.functions ?? fn; if (fa) { try { const fns2 = [...fa]; if (fns2.every(isAIFunction)) { return fns2; } } catch { } } throw new Error(`Invalid AIFunctionLike: ${fn}`); }); if (fns) { for (const fn of fns) { if (!isAIFunction(fn)) { throw new Error(`Invalid AIFunctionLike: ${fn}`); } } } this._map = new Map( fns ? fns.map((fn) => [this._transformNameKeysFn(fn.spec.name), fn]) : null ); } get size() { return this._map.size; } add(fn) { this._map.set(this._transformNameKeysFn(fn.spec.name), fn); return this; } get(name) { return this._map.get(this._transformNameKeysFn(name)); } set(name, fn) { this._map.set(this._transformNameKeysFn(name), fn); return this; } has(name) { return this._map.has(this._transformNameKeysFn(name)); } clear() { this._map.clear(); } delete(name) { return this._map.delete(this._transformNameKeysFn(name)); } pick(...keys) { const keysToIncludeSet = new Set(keys.map(this._transformNameKeysFn)); return new _AIFunctionSet( Array.from(this).filter( (fn) => keysToIncludeSet.has(this._transformNameKeysFn(fn.spec.name)) ) ); } omit(...keys) { const keysToExcludeSet = new Set(keys.map(this._transformNameKeysFn)); return new _AIFunctionSet( Array.from(this).filter( (fn) => !keysToExcludeSet.has(this._transformNameKeysFn(fn.spec.name)) ) ); } map(fn) { return [...this.entries].map(fn); } /** * Returns a new AIFunctionSet containing only the AIFunctions in this set * matching the given tags. */ getFilteredByTags(...tags) { const tagsSet = new Set(tags); return this.getFilteredBy((fn) => fn.tags?.some((t) => tagsSet.has(t))); } /** * Returns a new AIFunctionSet containing only the AIFunctions in this set * matching a custom filter function. */ getFilteredBy(filterFn) { return new _AIFunctionSet(Array.from(this).filter((fn) => filterFn(fn))); } /** * Returns the functions in this set as an array compatible with OpenAI's * chat completions `functions`. */ get specs() { return this.map((fn) => fn.spec); } /** * Returns the functions in this set as an array compatible with OpenAI's * chat completions `tools`. */ get toolSpecs() { return this.map((fn) => ({ type: "function", function: fn.spec })); } /** * Returns the tools in this set compatible with OpenAI's `responses` API. * * Note that this is currently the same type as `AIFunctionSet.specs`, but * they are separate APIs which may diverge over time, so if you're using the * OpenAI `responses` API, you should reference this property. */ get responsesToolSpecs() { return this.specs; } get entries() { return this._map.values(); } [Symbol.iterator]() { return this.entries; } }; function transformName(name) { return name.toLowerCase(); } // src/echo.ts import { z as z2 } from "zod"; var _echo_dec, _a, _init; var EchoAITool = class extends (_a = AIFunctionsProvider, _echo_dec = [aiFunction({ name: "echo", description: "Echoes the input.", inputSchema: z2.object({ query: z2.string().describe("input query to echo") }) })], _a) { constructor() { super(...arguments); __runInitializers(_init, 5, this); } async echo({ query }) { return query; } }; _init = __decoratorStart(_a); __decorateElement(_init, 1, "echo", _echo_dec, EchoAITool); __decoratorMetadata(_init, EchoAITool); var echoAIFunction = createAIFunction( { name: "echo", description: "Echoes the input.", inputSchema: z2.object({ query: z2.string().describe("input query to echo") }) }, ({ query }) => { return query; } ); // src/message.ts var Msg; ((Msg2) => { function system(content, opts) { const { name, cleanContent = true } = opts ?? {}; return { role: "system", content: cleanContent ? cleanStringForModel(content) : content, ...name ? { name } : {} }; } Msg2.system = system; function developer(content, opts) { const { name, cleanContent = true } = opts ?? {}; return { role: "developer", content: cleanContent ? cleanStringForModel(content) : content, ...name ? { name } : {} }; } Msg2.developer = developer; function user(content, opts) { const { name, cleanContent = true } = opts ?? {}; return { role: "user", content: cleanContent ? cleanStringForModel(content) : content, ...name ? { name } : {} }; } Msg2.user = user; function assistant(content, opts) { const { name, cleanContent = true } = opts ?? {}; return { role: "assistant", content: cleanContent ? cleanStringForModel(content) : content, ...name ? { name } : {} }; } Msg2.assistant = assistant; function refusal(refusal2, opts) { const { name, cleanRefusal = true } = opts ?? {}; return { role: "assistant", refusal: cleanRefusal ? cleanStringForModel(refusal2) : refusal2, ...name ? { name } : {} }; } Msg2.refusal = refusal; function funcCall(funcCall2, opts) { return { ...opts, role: "assistant", content: null, function_call: funcCall2 }; } Msg2.funcCall = funcCall; function funcResult(content, name) { const contentString = stringifyForModel(content); return { role: "function", content: contentString, name }; } Msg2.funcResult = funcResult; function toolCall(toolCalls, opts) { return { ...opts, role: "assistant", content: null, tool_calls: toolCalls }; } Msg2.toolCall = toolCall; function toolResult(content, toolCallId, opts) { const contentString = stringifyForModel(content); return { ...opts, role: "tool", tool_call_id: toolCallId, content: contentString }; } Msg2.toolResult = toolResult; function getMessage(response) { const msg = response.choices[0].message; return narrowResponseMessage(msg); } Msg2.getMessage = getMessage; function narrowResponseMessage(msg) { if (msg.content === null && msg.tool_calls != null) { return Msg2.toolCall(msg.tool_calls); } else if (msg.content === null && msg.function_call != null) { return Msg2.funcCall(msg.function_call); } else if (msg.content !== null && msg.content !== void 0) { return Msg2.assistant(msg.content); } else if (msg.refusal != null) { return Msg2.refusal(msg.refusal); } else { console.log("Invalid message", msg); throw new Error("Invalid message"); } } Msg2.narrowResponseMessage = narrowResponseMessage; function isSystem(message) { return message.role === "system"; } Msg2.isSystem = isSystem; function isDeveloper(message) { return message.role === "developer"; } Msg2.isDeveloper = isDeveloper; function isUser(message) { return message.role === "user"; } Msg2.isUser = isUser; function isAssistant(message) { return message.role === "assistant" && message.content != null; } Msg2.isAssistant = isAssistant; function isRefusal(message) { return message.role === "assistant" && message.refusal !== null; } Msg2.isRefusal = isRefusal; function isFuncCall(message) { return message.role === "assistant" && message.function_call != null; } Msg2.isFuncCall = isFuncCall; function isFuncResult(message) { return message.role === "function" && message.name != null; } Msg2.isFuncResult = isFuncResult; function isToolCall(message) { return message.role === "assistant" && message.tool_calls != null; } Msg2.isToolCall = isToolCall; function isToolResult(message) { return message.role === "tool" && !!message.tool_call_id; } Msg2.isToolResult = isToolResult; function narrow(message) { if (isSystem(message)) { return message; } if (isDeveloper(message)) { return message; } if (isUser(message)) { return message; } if (isAssistant(message)) { return message; } if (isRefusal(message)) { return message; } if (isFuncCall(message)) { return message; } if (isFuncResult(message)) { return message; } if (isToolCall(message)) { return message; } if (isToolResult(message)) { return message; } throw new Error("Invalid message type"); } Msg2.narrow = narrow; })(Msg || (Msg = {})); export { AIFunctionSet, AIFunctionsProvider, AbortError, EchoAITool, Msg, ParseError, RetryableError, TimeoutError, aiFunction, asAgenticSchema, asZodOrJsonSchema, assert, augmentSystemMessageWithJsonSchema, cleanStringForModel, createAIFunction, createAgenticSchemaFromZodSchema, createJsonSchema, default2 as delay, echoAIFunction, extractJSONFromString, getEnv, getErrorMessage, getShortDateString, isAIFunction, isAgenticSchema, isZodSchema, noop, omit, parseArrayOutput, parseBooleanOutput, parseNumberOutput, parseObjectOutput, parseStructuredOutput, pick, pruneEmpty, pruneEmptyDeep, pruneNullOrUndefined, pruneNullOrUndefinedDeep, pruneUndefined, safeParseStructuredOutput, sanitizeSearchParams, schemaSymbol, stringifyForModel, throttleKy, zodToJsonSchema }; //# sourceMappingURL=index.js.map