> ## Documentation Index
> Fetch the complete documentation index at: https://docs.triqai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Confidence Scores

> Understanding and using confidence scores and reason tags for reliable enrichment

Every enrichment result includes confidence scores that indicate how certain Triqai is about each piece of data. In addition to numeric scores, Triqai provides **reason tags** that explain *why* a score is what it is. Understanding these helps you make better decisions about when to trust automated enrichment and when to require manual review.

## What Are Confidence Scores?

Confidence scores are objects with two fields:

```json theme={null}
{
  "value": 92,
  "reasons": ["name_closely_matched", "results_consensus"]
}
```

* **`value`**: An integer from 0 to 100 representing certainty
* **`reasons`**: An array of string tags explaining the score

### Score Ranges

* **0**: No confidence (should not be used)
* **50**: Low confidence (uncertain match)
* **75**: Moderate confidence (likely correct)
* **90**: High confidence (very likely correct)
* **100**: Maximum confidence (definitive match)

## Where Scores Appear

Confidence scores appear at multiple levels in the response:

### Overall Transaction Confidence

```json theme={null}
{
  "data": {
    "transaction": {
      "confidence": { "value": 92, "reasons": [] }
    }
  }
}
```

This represents the overall quality of the enrichment across all modules.

### Category Confidence

```json theme={null}
{
  "category": {
    "primary": { "name": "Shopping" },
    "secondary": { "name": "Online Shopping" },
    "confidence": { "value": 95, "reasons": ["merchant_category_match"] }
  }
}
```

### Per-Entity Confidence

Each entity in the `entities` array has its own confidence:

```json theme={null}
{
  "entities": [
    {
      "type": "merchant",
      "role": "organization",
      "confidence": {
        "value": 98,
        "reasons": ["name_closely_matched", "results_consensus"]
      },
      "data": { "name": "Starbucks" }
    },
    {
      "type": "location",
      "role": "store_location",
      "confidence": {
        "value": 72,
        "reasons": ["city_match", "multiple_plausible_locations"]
      },
      "data": { "name": "Starbucks - Downtown" }
    },
    {
      "type": "intermediary",
      "role": "processor",
      "confidence": { "value": 99, "reasons": ["known_processor_match"] },
      "data": { "name": "Square" }
    }
  ]
}
```

## Confidence Reason Tags

Reason tags explain what contributed to or detracted from the confidence score. They are divided into several categories.

### Global Reasons

These can appear on any entity type (merchant, location, or intermediary):

| Tag                     | Meaning                                                                |
| ----------------------- | ---------------------------------------------------------------------- |
| `results_consensus`     | Multiple independent sources/results point to the same entity          |
| `ambiguous_entity`      | Multiple plausible candidates; evidence does not uniquely identify one |
| `results_contradict`    | Top results disagree on key identity fields, indicating uncertainty    |
| `insufficient_evidence` | Not enough reliable evidence to support a strong match                 |

### Category Reasons

Applied to the category confidence score (deterministic, code-only):

| Tag                       | Meaning                                                                |
| ------------------------- | ---------------------------------------------------------------------- |
| `merchant_category_match` | The identified merchant has a known/linked category mapping            |
| `fallback_classification` | Category came from fallback logic rather than strong merchant evidence |
| `p2p_transfer_detected`   | Transaction detected as P2P transfer by deterministic rules            |

### Merchant Reasons

Applied to merchant entity confidence (global + merchant-specific):

| Tag                                | Meaning                                                                                                      |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `broad_merchant_name`              | Extracted merchant string is a generic category term, not a distinct brand name                              |
| `generic_descriptor`               | "Merchant name" is primarily a descriptor rather than a proper noun                                          |
| `name_closely_matched`             | Chosen merchant name matches the raw transaction tokens strongly                                             |
| `name_inferred`                    | Output name differs from extracted name because AI inferred the likely correct name                          |
| `brand_disambiguated`              | AI resolved a brand ambiguity based on evidence                                                              |
| `category_consistent_with_context` | Merchant type implied by evidence matches transaction context/category                                       |
| `venue_or_attraction`              | Merchant appears to be a venue, attraction, or transport operator and is treated as a valid merchant context |

### Location Reasons

Applied to location entity confidence (global + location-specific):

| Tag                                      | Meaning                                                                               |
| ---------------------------------------- | ------------------------------------------------------------------------------------- |
| `country_match`                          | Location country aligns with expected country hints                                   |
| `wrong_country`                          | Location country does not align with expected country hints                           |
| `city_match`                             | City token is present in raw or strong context and matches chosen location city       |
| `store_id_match`                         | Store number/branch ID appears in raw and matches a specific store                    |
| `single_result_match`                    | Only one strong relevant place result exists and it matches clearly                   |
| `identifier_match`                       | Specific identifier matches (street, phone, postal code, store code)                  |
| `address_closely_matched`                | Address text in results aligns closely with chosen location fields                    |
| `multiple_plausible_locations`           | Several plausible places exist and evidence doesn't uniquely select one               |
| `chain_location_disambiguated`           | For chains, AI selected a specific branch based on evidence                           |
| `merchant_location_crosscheck_corrected` | Merchant-location cross-check detected a mismatch and corrected the selected location |
| `merchant_location_crosscheck_recovered` | Location was recovered from alternate search results using merchant-aligned evidence  |
| `merchant_location_mismatch`             | Merchant identity and selected location evidence conflict, reducing confidence        |
| `geo_mismatch`                           | Geographic signals (city/country/address/coordinates) conflict with expected context  |

### Intermediary Reasons

Applied to intermediary entity confidence (global + intermediary-specific):

| Tag                                  | Meaning                                                                 |
| ------------------------------------ | ----------------------------------------------------------------------- |
| `name_closely_matched`               | Intermediary name matches raw tokens strongly                           |
| `processor_role_disambiguated`       | AI resolved whether entity acts as processor/gateway vs actual merchant |
| `platform_vs_merchant_disambiguated` | AI resolved platform vs underlying merchant                             |
| `known_processor_match`              | Deterministic match to internal processor dictionary (prefix/pattern)   |

## Score Interpretation

<Tabs>
  <Tab title="90-100: Very High">
    **Interpretation**: Highly reliable for automated decisions **When you see
    this**: - Transaction string closely matches known patterns - Multiple data
    points confirm the identification - Entity is well-known with clear
    signatures **Common reasons**: `results_consensus`, `name_closely_matched`,
    `known_processor_match` **Recommended action**: Use directly in your
    application without review
  </Tab>

  <Tab title="70-89: High">
    **Interpretation**: Suitable for most use cases **When you see this**: - Good
    pattern match but some ambiguity - Entity identified with reasonable certainty

    * Minor uncertainty in specific fields **Common reasons**: `city_match`,
      `brand_disambiguated`, `category_consistent_with_context` **Recommended
      action**: Use for display and analytics; consider review for financial
      decisions
  </Tab>

  <Tab title="50-69: Moderate">
    **Interpretation**: May benefit from manual review **When you see this**: -
    Partial pattern match - Multiple possible interpretations - Limited data
    points available **Common reasons**: `ambiguous_entity`,
    `multiple_plausible_locations`, `broad_merchant_name` **Recommended action**:
    Display with caveat or queue for review
  </Tab>

  <Tab title="0-49: Low">
    **Interpretation**: Requires verification **When you see this**: - Weak or
    ambiguous pattern match - Unknown or unusual merchant - Conflicting signals
    in transaction **Common reasons**: `results_contradict`,
    `insufficient_evidence`, `generic_descriptor` **Recommended action**:
    Request user confirmation or manual review
  </Tab>
</Tabs>

## Confidence by Entity Type

Different entity types typically have different confidence distributions:

| Entity           | Typical Range | Notes                                      |
| ---------------- | ------------- | ------------------------------------------ |
| **Merchant**     | 70-99         | Well-known merchants score higher          |
| **Location**     | 50-95         | Store-level matching is harder             |
| **Category**     | 75-99         | Based on merchant + context                |
| **Intermediary** | 90-99         | Distinct patterns, high accuracy           |
| **Person**       | 85-99         | Extracted directly from transaction string |

## Using Confidence in Your Application

### Threshold-Based Logic

```typescript theme={null}
import Triqai from "triqai";

const triqai = new Triqai(process.env.TRIQAI_API_KEY!);

const result = await triqai.transactions.enrich({
  title: "STARBUCKS NYC",
  country: "US",
  type: "expense",
});

const threshold = 85;

const autoApprove =
  result.data.transaction.confidence.value >= threshold &&
  result.data.entities.every((e) => e.confidence.value >= threshold);

const needsReview = result.data.transaction.confidence.value < 70;
```

### Using Reason Tags

```typescript theme={null}
function analyzeConfidence(entity: { confidence: { value: number; reasons: string[] } }) {
  const { value, reasons } = entity.confidence;

  if (value >= 90 && reasons.includes("results_consensus")) {
    return { reliable: true, action: "auto_approve" };
  }

  if (reasons.includes("ambiguous_entity") || reasons.includes("results_contradict")) {
    return { reliable: false, action: "manual_review" };
  }

  if (reasons.includes("known_processor_match")) {
    return { reliable: true, action: "auto_approve" };
  }

  return {
    reliable: value >= 75,
    action: value >= 75 ? "auto_approve" : "manual_review",
  };
}

const result = await triqai.transactions.enrich({
  title: "STRIPE* ACME CORP",
  country: "US",
  type: "expense",
});

for (const entity of result.data.entities) {
  const analysis = analyzeConfidence(entity);
  console.log(`${entity.type}: ${analysis.action}`);
}
```

### Displaying Confidence to Users

```typescript theme={null}
function getConfidenceLabel(confidence: { value: number; reasons: string[] }) {
  if (confidence.value >= 90) return { text: "Verified", color: "green" };
  if (confidence.value >= 70) return { text: "Likely", color: "blue" };
  if (confidence.value >= 50) return { text: "Uncertain", color: "yellow" };
  return { text: "Unverified", color: "red" };
}
```

### Filtering by Confidence

```typescript theme={null}
const result = await triqai.transactions.enrich({
  title: "AMAZON MKTPLACE PMTS",
  country: "US",
  type: "expense",
});

const reliableMerchants = result.data.entities.filter(
  (e) => e.type === "merchant" && e.confidence.value >= 80,
);

const flaggedForReview = result.data.entities.filter(
  (e) => e.confidence.value < 60 || e.confidence.reasons.includes("ambiguous_entity"),
);
```

## Best Practices

<AccordionGroup>
  <Accordion title="Set appropriate thresholds for your use case" icon="sliders">
    Different applications have different tolerance for errors. A personal
    finance app might accept lower confidence than a compliance system.
  </Accordion>

  <Accordion title="Consider the cost of errors" icon="scale-balanced">
    If incorrect categorization has serious consequences, require higher
    confidence thresholds or manual review.
  </Accordion>

  <Accordion title="Use reason tags for smarter decisions" icon="tags">
    Don't just check the numeric score reason tags like `known_processor_match` or
    `results_contradict` give you richer context for decision-making.
  </Accordion>

  <Accordion title="Track confidence distributions" icon="chart-line">
    Monitor the confidence scores you're seeing. Consistently low scores for
    certain transaction types might indicate a need for different handling.
  </Accordion>

  <Accordion title="Report issues for low-confidence matches" icon="flag">
    Use the Issue Report API to flag incorrect enrichments. This helps improve
    accuracy over time.
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Error Handling" icon="triangle-exclamation" href="/guides/error-handling">
    Handle errors and partial results gracefully
  </Card>

  <Card title="Report Issues" icon="flag" href="/api-reference/create-issue-report">
    Report enrichment issues to improve accuracy
  </Card>
</CardGroup>
