forked from Yara724/api
feat: replace OpenAI pricing with AI assessment estimates
Extend durable image assessments with explicit Persian vehicle names, deployment severity settings and advisory market prices normalized to rials. Preserve case access and retry boundaries, and remove the retired OpenAI pricing module and routes.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# AI damage companion
|
||||
|
||||
This opt-in integration supplements the expert's claim review. It never changes workflow status, damage selection/history, prices, severity entered by experts, or compensation decisions. The pipeline currently returns no price estimates and no image. The expert UI draws boxes on the captured photo.
|
||||
This opt-in integration supplements the expert's claim review. It never changes workflow status, damage selection/history, prices, severity entered by experts, or compensation decisions. The pipeline returns structured detections and optional advisory market prices, but no rendered image. The expert UI draws boxes on the captured photo.
|
||||
|
||||
## Enable in development
|
||||
|
||||
@@ -9,7 +9,8 @@ Set these **API environment variables** and restart the API:
|
||||
```dotenv
|
||||
AI_DAMAGE_ENABLED=true
|
||||
AI_DAMAGE_URL=http://79.132.207.77:30531
|
||||
AI_DAMAGE_TIMEOUT_MS=180000
|
||||
AI_DAMAGE_TIMEOUT_MS=600000
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY=severe
|
||||
```
|
||||
|
||||
The integration is off when `AI_DAMAGE_ENABLED` is missing or false. Enabling it requires a valid URL. Keep it off in production during this development rollout. No frontend environment variable or credential is needed. The supplied pipeline has no authentication header.
|
||||
@@ -30,7 +31,7 @@ No existing claim documents are migrated or rewritten. The old login/profile/dow
|
||||
- Enqueueing waits only for a Mongo upsert, never for inference; a persistence error is logged without failing upload. Viewing the tab re-schedules a missed current photo.
|
||||
- One worker per instance polls every five seconds and claims one job atomically. A lease token guards completion writes across replicas. Expired leases recover after restart; leases last the configured HTTP timeout plus 60 seconds. Storage must be shared across replicas.
|
||||
- Each claim/photo has one job. Repeated reads/uploads do not reset successful or failed analysis. Transient network/server/invalid-response failures retry up to three claims, with 30/60-second delays. Terminal 4xx image errors require explicit retry. A retry exhausted by process crashes is also marked failed.
|
||||
- The worker sends one multipart `images` file to `POST /api/v1/assessments`, without the retired pipeline query flags. The provider also accepts batches of up to 12 images; this adapter intentionally keeps one photo per durable job, using the supported single-image request so results and retries stay tied to their source capture. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 15 MiB (enforced before upload), multipart body 16 MiB and response size 2 MiB.
|
||||
- The worker sends one multipart `images` file to `POST /api/v1/assessments`, with `include_polygons=false` and `include_prices=false` for automatic capture analysis. Explicit expert pricing requests use `include_prices=true`, the configured `price_min_severity`, and a multipart `car` field. The provider also accepts batches of up to 12 images; this adapter intentionally keeps one photo per durable job, using the supported single-image request so results and retries stay tied to their source capture. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 15 MiB (enforced before upload), multipart body 16 MiB and response size 2 MiB.
|
||||
- The provider's OpenAPI describes JPEG inputs. Current camera/compression flows emit JPEG; a rejected older format stays visible with a recoverable analysis error.
|
||||
- Current media determines the displayed photos. Replaced and removed photos' job results are retained separately, but never attached to a newer photo or inserted into the live carousel. Existing parts revision history is untouched.
|
||||
|
||||
@@ -77,3 +78,70 @@ The historical live probe below used the retired pipeline. The assessment API mi
|
||||
On 2026-10-03 the real multipart adapter successfully called the development pipeline with [Front bumper broken.jpg](https://commons.wikimedia.org/wiki/File:Front_bumper_broken.jpg), a public photograph by Tiia Monto (CC BY-SA 3.0). It returned HTTP 200 and six detections, with Persian reports, severity, confidence and bounding boxes. Rendering was checked against the source JPEG's actual 2121×1188 dimensions. No customer photo was used for this probe. A separate synthetic blank JPEG returned HTTP 500; that failure is handled by the existing bounded retry/error path.
|
||||
|
||||
Backend checks cover upload-to-queue integration, immutable per-photo association, atomic job leases/recovery, retry limits, real multipart bytes/options, response validation, and expert/insurer/admin file-access gates. Frontend checks cover clipping/scaling, readable 24px number badges, report toggles, pending polling, retry, disabled cached results, empty images, fetch recovery and desktop/mobile overflow.
|
||||
|
||||
|
||||
## Unified advisory pricing
|
||||
|
||||
The OpenAI prompt/module, its routes under `/v2/price-estimation`, and the separate
|
||||
expert price tab have been removed. No OpenAI key is needed in this API. Remove
|
||||
`OPENAI_PRICE_ESTIMATION_*` from deployment settings. Existing price-estimate
|
||||
collections are left intact; there is no database deletion or migration.
|
||||
|
||||
The existing AI tab now shows detection and market evidence together. Automatic
|
||||
uploads continue to request detection only. An authorized reviewing expert confirms
|
||||
or enters the damaged vehicle's Persian make/model, selects a current photo, then
|
||||
requests **تحلیل و برآورد قیمت همین تصویر**. The input is prefilled from the panel's
|
||||
resolved damaged-car identity when that name is Persian; missing or English-only
|
||||
names require manual entry. The expert can correct an inquiry name before sending.
|
||||
|
||||
`POST /v2/expert-claim/request/:claimRequestId/ai-analysis/estimate` accepts:
|
||||
|
||||
```json
|
||||
{"imageKey":"<64-character imageKey from the GET response>","carName":"پژو ۲۰۶ تیپ ۲"}
|
||||
```
|
||||
|
||||
It uses the existing claim-detail authorization gate and accepts only a photo from
|
||||
the current case's damage media. It queues work immediately rather than waiting on
|
||||
the upstream model. Failed pricing can use the existing retry endpoint. A running
|
||||
analysis or an already-queued pricing request returns 409 instead of queuing another
|
||||
chargeable request. An explicit request after completion starts a fresh estimate.
|
||||
The submitted car name and severity are stored with that image's job; polling
|
||||
exposes these values while work is pending. Company/super-admin viewers may read
|
||||
saved results and retry detection-only jobs but cannot submit or retry priced analyses.
|
||||
|
||||
The existing backend remains the authorized image transport, durable queue and
|
||||
response adapter. Detection and pricing both come from the same assessment service;
|
||||
there is no separate price-model prompt or market-research orchestration here.
|
||||
|
||||
### Deployment threshold
|
||||
|
||||
`AI_DAMAGE_PRICE_MIN_SEVERITY` accepts `minor`, `moderate`, `severe` (default) or
|
||||
literal `null`. `minor` prices all damaged parts; `moderate` includes moderate and
|
||||
severe parts; `severe` includes only severe parts. The provider's live OpenAPI
|
||||
accepts only the three non-null enum strings, so the `null` setting is adapted to
|
||||
`minor`, meaning all severities. Restart the API after changing configuration.
|
||||
The threshold is recorded per requested job, including on retries.
|
||||
|
||||
### Units, completeness and interpretation
|
||||
|
||||
Provider monetary fields in tomans are converted to rials **once** by the response
|
||||
normalizer: overall/genuine/aftermarket totals, component min/median/max, repair
|
||||
estimates and individual listing prices. Missing/invalid/unsafe numbers remain null,
|
||||
not zero. Unsupported currencies do not acquire a guessed conversion. Provider
|
||||
processing cost remains in USD and duration remains milliseconds. The UI explicitly
|
||||
labels monetary values as rials and identifies an LLM repair guess separately.
|
||||
|
||||
Each job uses one photo, so the provider's `pricing` summary is **that photo's**
|
||||
summary, never a whole-claim total. The UI warns against summing photos: the same
|
||||
physical part may appear in multiple photos. Incomplete results keep their partial
|
||||
warning, priced/unpriced counts and available evidence. No algorithm maps the AI's
|
||||
names to Fanavaran parts or writes prices/repair choices/price drop into the claim.
|
||||
The expert selects the matching catalogue part and enters the final valuation.
|
||||
|
||||
Sources show used/unused status; only absolute HTTP(S) links without credentials
|
||||
are clickable. Price ranges, sample count, spread warning, original/aftermarket
|
||||
alternatives, notes, cache status, model, date, cost and duration remain available.
|
||||
Legacy detection-only results still render normally. Opening the AI tab does not
|
||||
start paid pricing. No real claim images were sent during implementation tests;
|
||||
transport and UI tests use local fixtures. Validate actual market quality with the
|
||||
AI team before relying on the estimates.
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
# 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:
|
||||
|
||||
```dotenv
|
||||
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:
|
||||
|
||||
```json
|
||||
{
|
||||
"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:
|
||||
|
||||
```javascript
|
||||
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](https://developers.openai.com/api/reference/responses/overview), [image inputs](https://developers.openai.com/api/docs/guides/images-vision), [web search and source metadata](https://developers.openai.com/api/docs/guides/tools-web-search), [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs), and [GPT-5.4 capabilities](https://developers.openai.com/api/docs/models/gpt-5.4).
|
||||
Reference in New Issue
Block a user