@mastra/core
Version:
334 lines (333 loc) • 15.9 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_base = require("../base-BIzR1D3_.cjs");
const require_storage = require("../storage-CfG0I2aF.cjs");
const require_utils = require("../utils-D-eNsgDM.cjs");
let _ai_sdk_provider_utils_v7 = require("@ai-sdk/provider-utils-v7");
let _ai_sdk_provider_v7 = require("@ai-sdk/provider-v7");
// src/classifier/index.ts
var MastraDecisionModel = class extends require_base.MastraBase {
specificationVersion = "v4";
provider;
modelId;
supportedQuestionTypes;
#model;
constructor(model) {
super({ name: "decision-model" });
this.#model = model;
this.provider = model.provider;
this.modelId = model.modelId;
this.supportedQuestionTypes = model.supportedQuestionTypes;
}
async doDecide(options) {
const model = this.#model;
const result = "doDecide" in model ? await model.doDecide(options) : await model.doEvaluate(options);
return this.transformResult(result);
}
/** @deprecated Use `doDecide` instead. */
doEvaluate(options) {
return this.doDecide(options);
}
transformResult(result) {
return result;
}
};
/** @deprecated Use `MastraDecisionModel` instead. `MastraEvaluationModel` will be removed in a future release. */
var MastraEvaluationModel = class extends MastraDecisionModel {};
var Classifier = class extends require_base.MastraBase {
id;
model;
questions;
#mastra;
constructor(options) {
super({ name: options.id });
if (typeof options.id !== "string" || options.id.trim().length === 0) throw new TypeError("Classifier id must be a non-empty string.");
this.id = options.id;
this.model = options.model instanceof MastraDecisionModel ? options.model : new MastraDecisionModel(options.model);
this.questions = options.questions;
if (this.questions !== void 0) validateQuestions(this.questions, this.model);
}
/**
* Internal: called by `Mastra.addClassifier()` so evaluations can start root spans
* through the registered observability instance when no span is active.
*/
__registerMastra(mastra) {
this.#mastra = mastra;
}
async evaluate(options) {
return this.decide(options);
}
async decide(options) {
const questions = this.questions ?? ("questions" in options ? options.questions : void 0);
if (questions === void 0) throw new TypeError("Questions are required when the classifier is constructed without questions.");
validateState(options.state);
validateQuestions(questions, this.model);
validateMaxRetries(options.maxRetries);
options.abortSignal?.throwIfAborted();
const providerQuestions = toProviderQuestions(questions);
const questionTypes = [...new Set(Object.values(questions).map((question) => question.type))];
const span = require_utils.getOrCreateSpan({
type: "classifier_evaluation",
name: `classifier evaluate: '${this.id}'`,
entityType: require_storage.EntityType.CLASSIFIER,
entityId: this.id,
entityName: this.name ?? this.id,
tracingContext: { currentSpan: require_utils.resolveCurrentSpan() },
mastra: this.#mastra,
input: {
state: options.state,
questions
},
attributes: {
classifierId: this.id,
modelId: this.model.modelId,
provider: this.model.provider,
questionCount: Object.keys(questions).length,
questionTypes,
maxRetries: options.maxRetries ?? 2
}
});
const startedAt = Date.now();
let attemptCount = 0;
try {
const retry = (0, _ai_sdk_provider_utils_v7.retryWithExponentialBackoff)({
maxRetries: options.maxRetries ?? 2,
abortSignal: options.abortSignal,
shouldRetry: (error) => _ai_sdk_provider_v7.APICallError.isInstance(error) && error.isRetryable
});
let lastProviderError;
let providerResult;
try {
providerResult = await retry(async () => {
options.abortSignal?.throwIfAborted();
attemptCount += 1;
try {
const callOptions = {
state: toProviderState(options.state),
questions: providerQuestions,
abortSignal: options.abortSignal,
providerOptions: options.providerOptions
};
return this.model.doEvaluate !== MastraDecisionModel.prototype.doEvaluate ? await this.model.doEvaluate(callOptions) : await this.model.doDecide(callOptions);
} catch (error) {
lastProviderError = error;
throw error;
}
});
} catch (error) {
if (options.abortSignal?.aborted) throw options.abortSignal.reason;
if (lastProviderError !== void 0 && !_ai_sdk_provider_v7.APICallError.isInstance(error)) throw lastProviderError;
throw error;
}
options.abortSignal?.throwIfAborted();
validateProviderResult(questions, providerResult.answers, providerResult.rounding);
validateProviderEnvelope(providerResult);
const inputTokens = providerResult.usage?.inputTokens;
const outputTokens = providerResult.usage?.outputTokens;
const result = {
answers: providerResult.answers,
usage: {
inputTokens,
outputTokens,
totalTokens: (inputTokens ?? 0) + (outputTokens ?? 0)
},
warnings: providerResult.warnings,
rounding: providerResult.rounding,
providerMetadata: providerResult.providerMetadata,
response: {
...providerResult.response,
timestamp: providerResult.response?.timestamp ?? /* @__PURE__ */ new Date(),
modelId: providerResult.response?.modelId ?? this.model.modelId
}
};
span?.update({ attributes: {
attemptCount,
retryCount: attemptCount - 1,
durationMs: Date.now() - startedAt,
usage: {
inputTokens: result.usage.inputTokens,
outputTokens: result.usage.outputTokens
}
} });
span?.end({ output: { answers: result.answers } });
return result;
} catch (error) {
span?.update({ attributes: {
attemptCount,
retryCount: Math.max(0, attemptCount - 1),
durationMs: Date.now() - startedAt,
errorType: error instanceof Error ? error.name : typeof error
} });
span?.error({
error: error instanceof Error ? error : new Error(String(error)),
endSpan: true
});
throw error;
}
}
};
function toProviderState(state) {
if (typeof state === "string") return [{
type: "text",
text: state
}];
if (Array.isArray(state) && state.every(isStatePart)) return state;
return [{
type: "json",
value: state
}];
}
function isStatePart(value) {
return isPlainObject(value) && (value.type === "text" || value.type === "file" || value.type === "json");
}
function toProviderQuestions(questions) {
return Object.fromEntries(Object.entries(questions).map(([questionId, question]) => [questionId, {
...question,
instructions: question.instructions ?? questionId
}]));
}
function validateMaxRetries(maxRetries) {
if (maxRetries !== void 0 && (!Number.isInteger(maxRetries) || maxRetries < 0)) throw new TypeError("maxRetries must be a non-negative integer.");
}
function validateState(state) {
validateJsonValue(state, "state");
}
function validateQuestions(questions, model) {
if (!isPlainObject(questions) || Object.keys(questions).length === 0) throw new TypeError("Questions must be a non-empty object.");
for (const [questionId, question] of Object.entries(questions)) {
if (questionId.length === 0) throw new TypeError("Question ids must be non-empty strings.");
if (!isPlainObject(question) || ![
"choice",
"score",
"boolean"
].includes(question.type)) throw new TypeError(`Question '${questionId}' has an invalid type.`);
if (!model.supportedQuestionTypes.includes(question.type)) throw new _ai_sdk_provider_v7.Experimental_DecisionUnsupportedQuestionTypeError({
questionId,
questionType: question.type,
provider: model.provider,
modelId: model.modelId
});
if (question.instructions !== void 0) validateJsonValue(question.instructions, `Question '${questionId}' instructions`);
if (question.type === "choice") {
if (!isPlainObject(question.criteria) || Object.keys(question.criteria).length === 0) throw new TypeError(`Choice question '${questionId}' criteria must be a non-empty object.`);
for (const [choice, description] of Object.entries(question.criteria)) {
if (choice.length === 0) throw new TypeError(`Choice question '${questionId}' option names must be non-empty.`);
if (description !== null) validateJsonValue(description, `Choice question '${questionId}' criterion '${choice}'`);
}
} else if (question.type === "score") {
if (!Array.isArray(question.criteria) || question.criteria.length < 2) throw new TypeError(`Score question '${questionId}' criteria must contain at least two levels.`);
for (let index = 0; index < question.criteria.length; index++) {
const description = question.criteria[index];
if (!(index in question.criteria) || description === void 0) throw new TypeError(`Score question '${questionId}' criterion ${index} is missing.`);
if (description !== null) validateJsonValue(description, `Score question '${questionId}' criterion ${index}`);
}
} else if (question.criteria !== void 0) {
if (!isPlainObject(question.criteria)) throw new TypeError(`Boolean question '${questionId}' criteria must be an object.`);
for (const key of Object.keys(question.criteria)) if (key !== "true" && key !== "false") throw new TypeError(`Boolean question '${questionId}' criteria may only contain true and false.`);
for (const [key, description] of Object.entries(question.criteria)) if (description !== null && description !== void 0) validateJsonValue(description, `Boolean question '${questionId}' criterion '${key}'`);
}
}
}
/**
* Check the parts of the provider result that surround the answers.
*
* These fields are declared by the provider interface but not guaranteed by it.
* A non-numeric token count would otherwise turn `totalTokens` into a string or
* `NaN`, and a non-`Date` timestamp would reach callers typed as a `Date`.
*/
function validateProviderEnvelope(result) {
for (const field of ["inputTokens", "outputTokens"]) {
const value = result.usage?.[field];
if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value))) throw new TypeError(`The evaluation model returned a non-numeric '${field}' token count.`);
}
if (result.warnings !== void 0 && !Array.isArray(result.warnings)) throw new TypeError("The evaluation model returned warnings that are not an array.");
const timestamp = result.response?.timestamp;
if (timestamp !== void 0 && !(timestamp instanceof Date)) throw new TypeError("The evaluation model returned a response timestamp that is not a Date.");
}
function validateProviderResult(questions, answers, rounding) {
if (!isPlainObject(answers)) throw new TypeError("The evaluation model returned invalid answers.");
const questionIds = Object.keys(questions);
const answerIds = Object.keys(answers);
if (answerIds.length !== questionIds.length || answerIds.some((id) => !(id in questions))) throw new TypeError("The evaluation model must return exactly one answer per question.");
validateRounding(rounding);
const probabilityTolerance = rounding?.probabilityDecimals === void 0 ? 1e-6 : .5 * 10 ** -rounding.probabilityDecimals;
const scoreTolerance = rounding?.scoreDecimals === void 0 ? 1e-6 : .5 * 10 ** -rounding.scoreDecimals;
for (const questionId of questionIds) {
const question = questions[questionId];
const answer = answers[questionId];
if (!isPlainObject(answer)) throw new TypeError(`Answer '${questionId}' does not match its question type.`);
if (answer.type === "refusal") {
if ([
"choice",
"score",
"probability",
"probabilities"
].some((field) => field in answer)) throw new TypeError(`Refusal answer '${questionId}' must not include answer fields.`);
continue;
}
if (answer.type !== question.type) throw new TypeError(`Answer '${questionId}' does not match its question type.`);
if (answer.type === "boolean") {
validateProbability(answer.probability, `Boolean answer '${questionId}' probability`);
continue;
}
if (answer.type === "choice") {
const choices = Object.keys(question.criteria);
if (!choices.includes(answer.choice)) throw new TypeError(`Choice answer '${questionId}' selected an unknown option.`);
if (answer.probabilities !== void 0) {
validateDistribution(answer.probabilities, choices, probabilityTolerance, questionId);
const maximum = Math.max(...Object.values(answer.probabilities));
if (answer.probabilities[answer.choice] < maximum - probabilityTolerance) throw new TypeError(`Choice answer '${questionId}' is not a highest-probability option.`);
}
continue;
}
const levelCount = question.criteria.length;
if (!Number.isFinite(answer.score) || answer.score < 0 || answer.score > levelCount - 1) throw new TypeError(`Score answer '${questionId}' is outside the question range.`);
if (answer.probabilities !== void 0) {
const levels = Array.from({ length: levelCount }, (_, index) => String(index));
validateDistribution(answer.probabilities, levels, probabilityTolerance, questionId);
const mean = levels.reduce((sum, level) => sum + Number(level) * answer.probabilities[level], 0);
if (Math.abs(mean - answer.score) > scoreTolerance + levelCount * probabilityTolerance) throw new TypeError(`Score answer '${questionId}' does not match its probability-weighted mean.`);
}
}
}
function validateRounding(rounding) {
if (rounding === void 0) return;
if (!isPlainObject(rounding)) throw new TypeError("Evaluation rounding metadata must be an object.");
for (const [name, value] of Object.entries(rounding)) if (name !== "probabilityDecimals" && name !== "scoreDecimals" || !Number.isInteger(value) || value < 0) throw new TypeError("Evaluation rounding precision must use non-negative integer decimal counts.");
}
function validateDistribution(probabilities, expectedKeys, tolerance, questionId) {
if (!isPlainObject(probabilities)) throw new TypeError(`Answer '${questionId}' probabilities must be an object.`);
const keys = Object.keys(probabilities);
if (keys.length !== expectedKeys.length || keys.some((key) => !expectedKeys.includes(key))) throw new TypeError(`Answer '${questionId}' probabilities must contain the complete distribution.`);
let sum = 0;
for (const value of Object.values(probabilities)) {
validateProbability(value, `Answer '${questionId}' probability`);
sum += value;
}
if (Math.abs(sum - 1) > 1e-6 + expectedKeys.length * tolerance) throw new TypeError(`Answer '${questionId}' probabilities must sum to 1.`);
}
function validateProbability(value, label) {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) throw new TypeError(`${label} must be a finite number between 0 and 1.`);
}
function validateJsonValue(value, label, seen = /* @__PURE__ */ new Set()) {
if (value === null || typeof value === "string" || typeof value === "boolean") return;
if (typeof value === "number") {
if (Number.isFinite(value)) return;
throw new TypeError(`${label} must contain only JSON-compatible values.`);
}
if (typeof value !== "object") throw new TypeError(`${label} must contain only JSON-compatible values.`);
if (seen.has(value)) throw new TypeError(`${label} must not contain circular references.`);
seen.add(value);
if (Array.isArray(value)) for (const item of value) validateJsonValue(item, label, seen);
else if (isPlainObject(value)) for (const item of Object.values(value)) validateJsonValue(item, label, seen);
else throw new TypeError(`${label} must contain only JSON-compatible values.`);
seen.delete(value);
}
function isPlainObject(value) {
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
exports.Classifier = Classifier;
exports.MastraDecisionModel = MastraDecisionModel;
exports.MastraEvaluationModel = MastraEvaluationModel;
//# sourceMappingURL=index.cjs.map