Files
yara724-api/docs/ai-market-price-estimation.md
T

14 KiB
Raw Blame History

AI market price estimation (backend MVP)

This opt-in module gives an expert an advisory estimate for an existing claim: replacement parts, labor, painting, current vehicle market value, and accident-related market depreciation. It uses OpenAI image inputs, live web search, and Structured Outputs. It is separate from the existing AI damage detector and does not submit prices, alter damage selections, change compensation decisions, or write to claim/blame documents. Normal claim-detail access checks and stale-lock reconciliation still apply.

Enable and test in Swagger

Set these variables in the API environment and restart the API:

OPENAI_PRICE_ESTIMATION_ENABLED=true
OPENAI_PRICE_ESTIMATION_API_KEY=your-separate-openai-project-key
OPENAI_PRICE_ESTIMATION_MODEL=gpt-5.4
OPENAI_PRICE_ESTIMATION_TIMEOUT_MS=240000

The default is disabled, including in production. Keep the key on the backend. It is independent of AI_DAMAGE_ENABLED and AI_DAMAGE_URL; the damage pipeline does not need to be running. The existing SOCKS_PROXY_HOST / SOCKS_PROXY_PORT configuration also applies to this module's HTTP client. Requests go to https://api.openai.com/v1/responses, with redirects disabled. Use a model available to your project that supports image inputs, web search, structured outputs and medium reasoning effort; the default model is configurable rather than an account availability guarantee.

Open /docs in development and find AI market price estimation (MVP). Authenticate with the usual expert bearer token. Supported roles are damage_expert, field_expert, file_reviewer, and file_maker, subject to the same tenant, branch, assignment, ownership and phase rules as the existing claim-detail endpoint. An insurer/company token is not an expert token.

  1. Select an existing claim ID, not the blame ID or public file number. The claim must contain selected damaged parts.

  2. Call POST /v2/price-estimation/claims/{claimRequestId} with {} to use stored data, or provide known market information:

    {
      "currentMarketValueRial": 8000000000,
      "modelYear": 1402,
      "mileageKm": 45000,
      "city": "تهران",
      "partQuality": "oem",
      "vehicleCondition": "بدون رنگ و تصادف قبلی"
    }
    

    All fields are optional. currentMarketValueRial is rials, not tomans. Year accepts Jalali or Gregorian, inferred from its range; zero mileage is supported. city is the market location, not an accident address. Quality accepts oem, aftermarket, or any; default oem. Unknown fields, invalid units/types, negative amounts and invalid identifiers are rejected.

  3. The response is HTTP 202 with estimateId, claimRequestId, status, model, input, and timestamps. Research runs asynchronously; the initial request does not wait for OpenAI. The first run may take several minutes.

  4. Poll GET /v2/price-estimation/claims/{claimRequestId}/{estimateId} every five seconds until completed or failed. GET /v2/price-estimation/claims/{claimRequestId} retrieves the latest job; 404 means no estimate exists yet.

  5. If failed, inspect the sanitized error.code and error.message. After correcting connectivity/key/model configuration, call POST /v2/price-estimation/claims/{claimRequestId}/{estimateId}/retry. If case data or a photo changed, submit a new estimate request instead. Retry preserves the original snapshot and checks photo hashes again.

Every request, including cached reads and retries, rechecks current claim access. A job from another claim cannot be retrieved by changing its ID. Disabling estimation prevents new requests/retries/workers; authorized reads of saved results remain available.

Result contract

result exists only for completed jobs. Every monetary range has the form { "low": ..., "likely": ..., "high": ... }, all integer IRR amounts. A null range means unknown, not free.

Field Meaning
currency Always IRR
advisoryOnly, requiresExpertReview Always true
asOfDate Research day in Asia/Tehran
summary Persian overview of the model's assessment
vehicleValue.rangeRial, basis Known expert/request value or researched market range; policy insured value is not substituted for today's value
parts[] One row per selected part, with stable snapshot partKey, original catalogId/name/side/label, severity, recommendation, confidence, explanation, source URLs and cost ranges
replacementPriceRial Purchase price of a replacement part; excludes labor and paint
laborPriceRial Repair labor or replacement installation, according to recommendation
paintPriceRial Painting; zero only if not required, null if unknown
recommendedCostRial Server sum of required components for repair/replacement; null for inspection or missing components
totals.knownRepairCostRial Subtotal of completely priced recommendations; may be partial or null
totals.complete, missingPartKeys Whether all recommendations are priced; never present a partial subtotal as the full damage bill
depreciation.percent Market depreciation percentage range (0–100), or null
depreciation.amountRial Server calculation from vehicle-value and percentage ranges; null if either is unknown
depreciation.method ai_market_estimate; separate from existing statutory/insurer calculations
sources[] URLs found in OpenAI search metadata, short evidence paraphrases, original quoted prices/currency, computed listedPriceRial, associated part keys and research day
assumptions, warnings Missing photos/history/fitment, ambiguous sources/units, heuristic labor/depreciation and other limitations

Iranian shop prices often use tomans (IRT). Source quotes retain their original unit; the server converts a quoted toman amount to rials by multiplying by ten. An unknown quote unit does not support a purchase or market-value estimate. Source URLs not present in OpenAI's search/citation metadata are dropped. Purchase estimates require a positive quote with a known currency associated with the specific part; researched vehicle values require a vehicle quote. URL membership proves source provenance, not correct fitment, accurate extraction, current stock, or a certified offer. The expert must check the linked evidence.

Unsupported purchase/vehicle figures become null. Unsourced labor/paint and depreciation heuristics may remain as provisional estimates with low confidence/warnings. Missing model rows become unknown/inspection rows, preserving the case's complete selected-parts list. Unknown/duplicated part keys, malformed output, negative/overflowing prices, reversed ranges and percentages outside 0–100 are rejected. The server computes totals and depreciation amounts instead of trusting model arithmetic.

Future frontend integration must keep these estimates visually separate from entered expert prices. Existing price-entry APIs may use tomans: convert IRR explicitly if an expert chooses to copy an estimate. Nothing is copied or approved automatically by this module.

Input selection and storage

  • Vehicle identity comes from the damaged party, including historical third-party claims whose owner still points at the culprit. Approved Fanavaran vehicle classifications take precedence. The module never uses the third-party FIRST policy inquiry as a fallback for the damaged SECOND vehicle. Unresolved identity stays unknown.
  • Each request explicitly scopes the assessment to one damaged-party vehicle. Other cars visible in photos, reflections, descriptions or detector hints are excluded from research, pricing and narrative. Ambiguous target photos require expert inspection rather than an estimate for another car. Missing blame records do not authorize using an unverified historical owner's vehicle; a persisted beneficiary's party snapshot or verified owner vehicle can still supply the target.
  • Expert claim lists/detail responses and price estimation share vehicle identity resolution. Body classes such as sedan are never names or variants, and manufacturing years stay separate from variants. Each inquiry is scoped to its party; no unconditional FIRST fallback is used. Conflicting legacy aliases (for example FAW versus Saipa/111SE) retain the primary inquiry name, omit the unverified variant and add an estimation warning until an expert approves consistent system/kind values. The disabled-inquiry fixture now uses coherent FAW aliases with an unknown variant; this does not rewrite existing cases or fabricate missing real vehicle details.
  • Claim detail responses expose vehiclePartyRole (FIRST/SECOND) when the damaged party can be resolved. The expert panel uses it to apply approved system/kind corrections to that party only; the other vehicle keeps its own inquiry identity.
  • Current market value precedence is request value → expert fanavaranFieldReview.values.VehicleCurrentValue → live market research. Insured vehicle value, where known, is labeled historical policy context.
  • Current outer parts and other damaged parts are included. Removed-part history and its photos are excluded. Newly added parts without photos remain present with warnings. Car-angle images supplement damage photos.
  • At most 40 parts, 12 images, 10 MiB per image and 24 MiB total raw image bytes. Only JPEG/PNG/WebP are supported; missing/unsupported/over-limit images are skipped with warnings. The source content hash is frozen at request time and rechecked during processing; replacement images never receive an old snapshot's result.
  • Identity documents, signatures, invoices, names, phone numbers, national codes, VIN, plates, policy identifiers, account numbers and raw inquiries are excluded from text context. Damage/car photos are sent as originally captured and may themselves contain identifying details. No arbitrary URL downloads or supplied filesystem paths are accepted.
  • Existing completed detector hints may be included without starting new detector jobs. They remain fallible context and never add parts to the expert's selection.
  • OpenAI receives inline image bytes and projected vehicle/parts data with store:false. This flag does not promise zero retention under all OpenAI account policies. Local jobs store the input snapshot and compact normalized result, not image base64, raw upstream responses or credentials.

Jobs, cache and operations

Jobs live in a new claim-price-estimates collection. An atomic upsert with a unique claim/fingerprint index deduplicates identical inputs/model/prompt/photo hashes/detector hints on the same research day. Successful results are reused. A new day, changed inputs or changed photos create a new snapshot. Failed snapshots require explicit retry. Completed snapshots are not automatically refreshed repeatedly on the same day.

The damaged-vehicle-only prompt is versioned iran-parts-v2-damaged-vehicle-only. Request a fresh estimate to use it; earlier completed reports remain available and are not rewritten or automatically rerun.

Each API instance processes one job at a time. Atomic leases allow multiple replicas and recover expired work after restart. A lease token protects completion/failure writes. HTTP timeout is configurable from 1,000 to 600,000 ms; default four minutes. Search/output caps are ten tool calls and 20,000 output tokens per attempt. Transient network/429/5xx failures retry once after 30 seconds; invalid/refused/incomplete responses and image changes require manual action. Retry-exhausted crash recovery is terminal. Processing is at least once: a crash/network ambiguity can cause another chargeable attempt. Manual retry also initiates a new chargeable attempt; returned provider metadata includes response ID, model, web-search count and token usage for successful work.

Replicas must share the existing files storage and MongoDB. Development creates indexes automatically. If enabling where autoIndex=false, create these indexes first:

db.getCollection('claim-price-estimates').createIndex({ claimId: 1, fingerprint: 1 }, { unique: true });
db.getCollection('claim-price-estimates').createIndex({ claimId: 1, createdAt: -1 });
db.getCollection('claim-price-estimates').createIndex({ status: 1, nextAttemptAt: 1, leaseUntil: 1 });

No existing collection is migrated. The module adds four authenticated routes to the retained API contract; all previous route/guard/role records remain unchanged.

Verification and next step

Automated checks cover Swagger generation/examples, DTO/identifier/config validation, damaged-party vehicle selection, privacy projection, current/removed media, safe image bytes/paths/hash checks, Responses payloads, evidence filtering, unit conversion/arithmetic, malformed/refused/incomplete responses, job deduplication, authorization before reads/queue/retries, scoped job IDs, leases/recovery/shutdown, bounded retries and secret-free failures. Run npm test -- --runInBand and npm run build in api.

The implementation tests use mocked OpenAI responses; no key was configured during implementation, so there is no live model-quality acceptance result yet. QA should enable the key, compare a few real claims against expert assessments and retail quotes, check source units/fitment/dates, and verify changed-photo and missing-photo behavior.

For a stronger next iteration, retain confirmed expert estimates and verified supplier quotes keyed by canonical vehicle/part IDs, side and quality. Use that reference set first and web research to fill gaps. Keep model/expert corrections measurable; prompts alone cannot solve poor source naming or guarantee reliable Iranian listing access.

Official API contracts used: Responses API, image inputs, web search and source metadata, Structured Outputs, and GPT-5.4 capabilities.