forked from Yara724/api
Added AI damage estimation
This commit is contained in:
@@ -0,0 +1,307 @@
|
||||
import {
|
||||
EstimateContext,
|
||||
ModelEstimate,
|
||||
PriceRange,
|
||||
} from "./price-estimation.types";
|
||||
|
||||
const obj = (properties: Record<string, unknown>) => ({
|
||||
type: "object",
|
||||
properties,
|
||||
required: Object.keys(properties),
|
||||
additionalProperties: false,
|
||||
});
|
||||
const str = (maxLength = 1500) => ({ type: "string", maxLength });
|
||||
const list = (items: unknown, maxItems = 100) => ({
|
||||
type: "array",
|
||||
items,
|
||||
maxItems,
|
||||
});
|
||||
const nullable = (schema: unknown) => ({ anyOf: [schema, { type: "null" }] });
|
||||
const choice = (...values: string[]) => ({ type: "string", enum: values });
|
||||
const confidence = choice("low", "medium", "high");
|
||||
const money = { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER };
|
||||
const range = (type: unknown) => obj({ low: type, likely: type, high: type });
|
||||
export const ESTIMATE_OUTPUT_SCHEMA = obj({
|
||||
summary: str(3000),
|
||||
vehicleValue: obj({
|
||||
rangeRial: nullable(range(money)),
|
||||
confidence,
|
||||
sourceUrls: list(str(2000)),
|
||||
explanation: str(),
|
||||
}),
|
||||
parts: list(
|
||||
obj({
|
||||
partKey: str(100),
|
||||
severity: choice("minor", "moderate", "severe", "unknown"),
|
||||
recommendation: choice("repair", "replace", "inspect"),
|
||||
replacementPriceRial: nullable(range(money)),
|
||||
laborPriceRial: nullable(range(money)),
|
||||
paintPriceRial: nullable(range(money)),
|
||||
confidence,
|
||||
sourceUrls: list(str(2000)),
|
||||
explanation: str(),
|
||||
}),
|
||||
40,
|
||||
),
|
||||
depreciation: obj({
|
||||
percent: nullable(range({ type: "number", minimum: 0, maximum: 100 })),
|
||||
confidence,
|
||||
sourceUrls: list(str(2000)),
|
||||
explanation: str(3000),
|
||||
}),
|
||||
sources: list(
|
||||
obj({
|
||||
url: str(2000),
|
||||
title: str(300),
|
||||
evidence: str(500),
|
||||
originalPrice: nullable(money),
|
||||
originalCurrency: choice("IRR", "IRT", "unknown"),
|
||||
partKeys: list(str(100), 40),
|
||||
}),
|
||||
),
|
||||
assumptions: list(str(), 40),
|
||||
warnings: list(str(), 40),
|
||||
});
|
||||
|
||||
/** A separate runtime check is required even with provider-side Structured Outputs. */
|
||||
function validateShape(value: any, schema: any): void {
|
||||
if (schema.anyOf) {
|
||||
if (value === null) return;
|
||||
return validateShape(value, schema.anyOf[0]);
|
||||
}
|
||||
if (schema.enum && !schema.enum.includes(value))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
switch (schema.type) {
|
||||
case "object":
|
||||
if (!value || typeof value !== "object" || Array.isArray(value))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
if (Object.keys(value).some((key) => !(key in schema.properties)))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
for (const key of schema.required)
|
||||
validateShape(value[key], schema.properties[key]);
|
||||
return;
|
||||
case "array":
|
||||
if (!Array.isArray(value) || value.length > schema.maxItems)
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
value.forEach((item) => validateShape(item, schema.items));
|
||||
return;
|
||||
case "string":
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
value.length > (schema.maxLength ?? Infinity)
|
||||
)
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
return;
|
||||
case "integer":
|
||||
case "number":
|
||||
if (
|
||||
typeof value !== "number" ||
|
||||
!Number.isFinite(value) ||
|
||||
(schema.type === "integer" && !Number.isSafeInteger(value)) ||
|
||||
value < schema.minimum ||
|
||||
value > schema.maximum
|
||||
)
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
return;
|
||||
default:
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
}
|
||||
}
|
||||
|
||||
function checkRange(value: PriceRange | null): void {
|
||||
if (value && !(value.low <= value.likely && value.likely <= value.high))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
}
|
||||
export function canonicalSourceUrl(raw: string): string | null {
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (
|
||||
!["http:", "https:"].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password
|
||||
)
|
||||
return null;
|
||||
url.hash = "";
|
||||
return url.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const sumRanges = (ranges: PriceRange[]): PriceRange | null => {
|
||||
if (!ranges.length) return null;
|
||||
const total = ranges.reduce(
|
||||
(a, b) => ({
|
||||
low: a.low + b.low,
|
||||
likely: a.likely + b.likely,
|
||||
high: a.high + b.high,
|
||||
}),
|
||||
{ low: 0, likely: 0, high: 0 },
|
||||
);
|
||||
if (!Object.values(total).every(Number.isSafeInteger))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
return total;
|
||||
};
|
||||
|
||||
export function normalizeEstimate(
|
||||
value: unknown,
|
||||
context: EstimateContext,
|
||||
visitedUrls: string[],
|
||||
) {
|
||||
validateShape(value, ESTIMATE_OUTPUT_SCHEMA);
|
||||
const raw = value as ModelEstimate;
|
||||
const warnings = [...context.warnings, ...raw.warnings];
|
||||
const visited = new Set(visitedUrls.map(canonicalSourceUrl).filter(Boolean));
|
||||
const expectedKeys = new Set(context.parts.map((part) => part.partKey));
|
||||
const seen = new Set<string>();
|
||||
for (const part of raw.parts) {
|
||||
if (!expectedKeys.has(part.partKey) || seen.has(part.partKey))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
seen.add(part.partKey);
|
||||
[
|
||||
part.replacementPriceRial,
|
||||
part.laborPriceRial,
|
||||
part.paintPriceRial,
|
||||
].forEach(checkRange);
|
||||
}
|
||||
const sourceMap = new Map<string, any>();
|
||||
for (const source of raw.sources) {
|
||||
if (source.partKeys.some((key) => !expectedKeys.has(key)))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
const url = canonicalSourceUrl(source.url);
|
||||
if (!url || !visited.has(url)) {
|
||||
warnings.push(
|
||||
"یک منبع پیشنهادی مدل در نتایج جستوجو وجود نداشت و حذف شد.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const listedPriceRial =
|
||||
source.originalPrice == null || source.originalCurrency === "unknown"
|
||||
? null
|
||||
: source.originalPrice * (source.originalCurrency === "IRT" ? 10 : 1);
|
||||
if (listedPriceRial != null && !Number.isSafeInteger(listedPriceRial))
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
sourceMap.set(url, {
|
||||
...source,
|
||||
url,
|
||||
listedPriceRial,
|
||||
checkedOn: context.asOfDate,
|
||||
partKeys: source.partKeys.filter((key) => expectedKeys.has(key)),
|
||||
});
|
||||
}
|
||||
const links = (urls: string[]) => [
|
||||
...new Set(
|
||||
urls.map(canonicalSourceUrl).filter((url) => sourceMap.has(url)),
|
||||
),
|
||||
];
|
||||
const hasPrice = (url: string) => sourceMap.get(url)?.listedPriceRial > 0;
|
||||
checkRange(raw.vehicleValue.rangeRial);
|
||||
checkRange(raw.depreciation.percent);
|
||||
const vehicleValue = {
|
||||
...raw.vehicleValue,
|
||||
sourceUrls: links(raw.vehicleValue.sourceUrls),
|
||||
basis: context.vehicle.valueSource ?? "market_research",
|
||||
};
|
||||
if (context.vehicle.currentMarketValueRial != null) {
|
||||
const n = context.vehicle.currentMarketValueRial;
|
||||
vehicleValue.rangeRial = { low: n, likely: n, high: n };
|
||||
vehicleValue.explanation = `ارزش روز خودرو از ${context.vehicle.valueSource === "request" ? "ورودی درخواست" : "اطلاعات تأییدشده کارشناس"} استفاده شده است؛ صحت آن مستقلاً بررسی نشده است.`;
|
||||
} else if (
|
||||
vehicleValue.rangeRial &&
|
||||
!vehicleValue.sourceUrls.some(
|
||||
(url) => hasPrice(url) && !sourceMap.get(url).partKeys.length,
|
||||
)
|
||||
) {
|
||||
vehicleValue.rangeRial = null;
|
||||
vehicleValue.confidence = "low";
|
||||
vehicleValue.basis = "insufficient_evidence";
|
||||
warnings.push("ارزش روز خودرو بدون منبع قابل ارجاع پذیرفته نشد.");
|
||||
}
|
||||
if (vehicleValue.rangeRial && vehicleValue.rangeRial.low <= 0)
|
||||
throw new Error("INVALID_OUTPUT");
|
||||
const parts = context.parts.map((part) => {
|
||||
const estimate = raw.parts.find((row) => row.partKey === part.partKey) ?? {
|
||||
partKey: part.partKey,
|
||||
severity: "unknown",
|
||||
recommendation: "inspect",
|
||||
replacementPriceRial: null,
|
||||
laborPriceRial: null,
|
||||
paintPriceRial: null,
|
||||
confidence: "low",
|
||||
sourceUrls: [],
|
||||
explanation:
|
||||
"مدل برای این قطعه برآورد قابل استفاده ارائه نکرد؛ بررسی کارشناس لازم است.",
|
||||
};
|
||||
const sourceUrls = links(estimate.sourceUrls);
|
||||
const safe = { ...estimate, sourceUrls };
|
||||
if (
|
||||
!sourceUrls.some(
|
||||
(url) =>
|
||||
hasPrice(url) && sourceMap.get(url).partKeys.includes(part.partKey),
|
||||
)
|
||||
) {
|
||||
if (safe.replacementPriceRial)
|
||||
warnings.push(
|
||||
`قیمت خرید ${part.label} به علت نبود منبع قابل ارجاع حذف شد.`,
|
||||
);
|
||||
safe.replacementPriceRial = null;
|
||||
safe.confidence = "low";
|
||||
}
|
||||
if (!sourceUrls.length && (safe.laborPriceRial || safe.paintPriceRial))
|
||||
warnings.push(
|
||||
`اجرت و رنگ ${part.label} تخمین مدل است و منبع بازار ندارد.`,
|
||||
);
|
||||
const components =
|
||||
safe.recommendation === "replace"
|
||||
? [safe.replacementPriceRial, safe.laborPriceRial, safe.paintPriceRial]
|
||||
: [safe.laborPriceRial, safe.paintPriceRial];
|
||||
const recommendedCostRial =
|
||||
safe.recommendation !== "inspect" && components.every((c) => c != null)
|
||||
? sumRanges(components)
|
||||
: null;
|
||||
return { ...part, ...safe, recommendedCostRial };
|
||||
});
|
||||
const depreciation = {
|
||||
...raw.depreciation,
|
||||
sourceUrls: links(raw.depreciation.sourceUrls),
|
||||
amountRial: null as PriceRange | null,
|
||||
method: "ai_market_estimate",
|
||||
};
|
||||
if (!depreciation.sourceUrls.length && depreciation.percent) {
|
||||
depreciation.confidence = "low";
|
||||
warnings.push(
|
||||
"درصد افت قیمت تخمین مدل است؛ فرمول قانونی یا تصمیم بیمه محسوب نمیشود.",
|
||||
);
|
||||
}
|
||||
if (depreciation.percent && vehicleValue.rangeRial) {
|
||||
const p = depreciation.percent,
|
||||
v = vehicleValue.rangeRial;
|
||||
depreciation.amountRial = {
|
||||
low: Math.round((v.low * p.low) / 100),
|
||||
likely: Math.round((v.likely * p.likely) / 100),
|
||||
high: Math.round((v.high * p.high) / 100),
|
||||
};
|
||||
}
|
||||
const missingPartKeys = parts
|
||||
.filter((part) => !part.recommendedCostRial)
|
||||
.map((part) => part.partKey);
|
||||
return {
|
||||
currency: "IRR",
|
||||
advisoryOnly: true,
|
||||
requiresExpertReview: true,
|
||||
asOfDate: context.asOfDate,
|
||||
summary: raw.summary,
|
||||
vehicleValue,
|
||||
parts,
|
||||
depreciation,
|
||||
totals: {
|
||||
knownRepairCostRial: sumRanges(
|
||||
parts.map((part) => part.recommendedCostRial).filter(Boolean),
|
||||
),
|
||||
complete: !missingPartKeys.length,
|
||||
missingPartKeys,
|
||||
},
|
||||
sources: [...sourceMap.values()],
|
||||
assumptions: raw.assumptions,
|
||||
warnings: [...new Set(warnings)],
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user