# 證件辨識

企業在處理身分驗證、開戶、報到等流程時，經常需要人工逐一輸入證件上的姓名、身分證字號、地址等資訊，不僅耗時且容易出錯。透過 MaiAgent 的多模態 AI 助理，使用者只需上傳證件照片，系統即可自動辨識並輸出結構化 JSON 資料，可直接串接至後續業務系統。

與傳統 OCR 方案相比，MaiAgent 結合大型語言模型的多模態能力，具備以下優勢：

|       | 傳統 OCR 引擎      | MaiAgent 多模態 AI   |
| ----- | -------------- | ----------------- |
| 版面適應性 | 需針對每種證件設計模板    | 自動理解不同證件版面        |
| 正反面處理 | 需分開處理並手動對應     | 單張圖片即可同時辨識正反面     |
| 欄位擴充  | 需修改程式碼         | 修改 JSON Schema 即可 |
| 部署成本  | 自建 OCR 服務或購買授權 | 平台設定，無需撰寫程式碼      |
| 錯誤處理  | 回傳原始文字，需後處理    | AI 理解語意，自動修正格式    |

## 應用場景 <a href="#use-cases" id="use-cases"></a>

* **金融業開戶**：客戶上傳身分證，自動擷取姓名、證號等資訊填入開戶表單
* **人資報到流程**：新進員工上傳證件，系統自動建檔
* **醫療掛號**：患者上傳健保卡或身分證，自動填入基本資料
* **政府機關臨櫃**：民眾出示證件，即時辨識並帶入申辦表單

## 解決方案架構 <a href="#solution-architecture" id="solution-architecture"></a>

```mermaid
graph LR
  使用者 -->|上傳證件圖片| AI助理["證件 OCR 辨識助理<br/>（多模態 LLM）"]
  AI助理 -->|辨識 + 結構化| JSON輸出["JSON Schema 輸出"]

  JSON輸出 --> WebChat["Web Chat 即時顯示"]
  JSON輸出 --> API["API 串接業務系統"]

  AI助理 -.->|角色指令| 辨識規則["辨識規則<br/>正反面欄位對應"]
  AI助理 -.->|輸出格式| Schema["JSON Schema<br/>9 個標準欄位"]
```

## 建置步驟 <a href="#setup-steps" id="setup-steps"></a>

### Step 1：建立 AI 助理 <a href="#step1-create-ai-agent" id="step1-create-ai-agent"></a>

1. 左側選單 → <mark style="color:blue;">**AI 功能**</mark> → <mark style="color:blue;">**AI 助理**</mark>
2. 點擊右上角 <mark style="color:blue;">**建立 AI 助理**</mark>
3. 填寫基本設定：

| 欄位        | 填寫內容                          |
| --------- | ----------------------------- |
| **助理名稱**  | 證件 OCR 辨識助理                   |
| **大語言模型** | Gemini 3.1 Flash-Lite（需支援多模態） |

<figure><img src="/files/JCu9hzHnVHir8OjYJArL" alt=""><figcaption><p>建立 AI 助理基本設定</p></figcaption></figure>

{% hint style="info" %}
選擇大語言模型時，請確認該模型支援**多模態**（圖片輸入），例如 Gemini 系列。若選用純文字模型，將無法辨識圖片內容。
{% endhint %}

### Step 2：設定回覆模式與 JSON Schema <a href="#step2-configure-reply-mode-and-json-schema" id="step2-configure-reply-mode-and-json-schema"></a>

切換至 <mark style="color:blue;">**回答模式設定**</mark> 頁籤：

| 欄位       | 填寫內容       |
| -------- | ---------- |
| **回答模式** | RAG 問答     |
| **輸出格式** | 輸出 JSON 格式 |

選擇 <mark style="color:blue;">**輸出 JSON 格式**</mark> 後，在下方的 JSON Schema 欄位中填入以下內容：

```json
{
  "type": "object",
  "properties": {
    "document_type": {
      "type": "string",
      "description": "證件類型，如中華民國國民身分證、駕照、護照、健保卡、居留證等"
    },
    "name": {
      "type": "string",
      "description": "持證人完整姓名，從正面姓名欄位讀取"
    },
    "gender": {
      "type": "string",
      "enum": ["男", "女"],
      "description": "性別"
    },
    "date_of_birth": {
      "type": "string",
      "description": "出生年月日，民國年格式"
    },
    "military_service": {
      "type": ["string", "null"],
      "description": "役別，如免役、已服、未服、替代役。女性或無此欄位則為 null"
    },
    "place_of_birth": {
      "type": ["string", "null"],
      "description": "出生地，從背面讀取"
    },
    "id_number": {
      "type": "string",
      "description": "身分證統一編號，1 英文字母 + 9 數字"
    },
    "expiry_or_issue_date": {
      "type": ["string", "null"],
      "description": "截切日期（發證日期或有效期限），民國年格式"
    },
    "address": {
      "type": ["string", "null"],
      "description": "完整住址，從背面住址欄位讀取，包含縣市區里鄰路段巷弄號樓"
    }
  },
  "required": [
    "document_type", "name", "gender", "date_of_birth",
    "military_service", "place_of_birth", "id_number",
    "expiry_or_issue_date", "address"
  ]
}
```

<figure><img src="/files/DY8tA6DKVnu3gPBDHlX7" alt=""><figcaption><p>JSON Schema 輸出格式設定</p></figcaption></figure>

### Step 3：撰寫角色指令 <a href="#step3-write-system-prompt" id="step3-write-system-prompt"></a>

在同一頁籤的 <mark style="color:blue;">**角色指令**</mark> 區塊中，填入以下內容：

```
你是一個專業的證件 OCR 辨識助理。使用者會上傳證件圖片，你必須仔細辨識圖片中的所有文字並擷取關鍵資訊。

## 最重要：仔細掃描整張圖片的所有區域

⚠️ 使用者經常在同一張圖片中同時拍攝證件的正面和背面（左右並排或上下排列）。你必須：
1. 先掃描整張圖片，辨識圖中有幾個證件面（可能是 1 面或 2 面）
2. 分別辨識每個區域的文字
3. 將正面和背面的資訊合併填入結果

絕對不可以說「背面未提供」或「資訊不在圖片中」，除非你確實在整張圖片的所有區域都找不到該資訊。

## 中華民國國民身分證欄位位置

### 正面（有國旗、照片）
- 「姓名」：照片旁邊，這是持證人本人的名字
- 「出生年月日」：民國 XX 年 XX 月 XX 日
- 「性別」：標示「男」或「女」
- 「統一編號」：底部，1 個英文大寫字母 + 9 個數字
- 「發證日期」：底部左側

### 背面（有父母配偶欄位，背景通常較暗）
- 「父」「母」：父母姓名（不是持證人）
- 「配偶」：配偶姓名
- 「役別」：兵役狀態
- 「出生地」：如「臺北市」「新北市」
- 「住址」：完整戶籍地址

## 辨識規則
1. 證件類型：根據外觀判斷
2. 名字：必須從正面的「姓名」欄位讀取，不可讀成背面的父/母/配偶
3. 性別：從正面讀取
4. 出生年月日：從正面讀取，民國年格式
5. 役別：從背面讀取。女性通常無役別填 null
6. 出生地：從背面讀取
7. 身分證字號：從正面底部讀取，逐字仔細辨識
8. 截切：從正面的「發證日期」欄位讀取
9. 住址：從背面的「住址」欄位讀取，完整包含縣市區里鄰路段巷弄號樓

## 輸出注意事項
- 無法辨識的欄位填入 null
- 所有辨識結果必須忠實於圖片內容，不可推測或編造
```

<figure><img src="/files/5BdnMSB3RHM78E8TDR6d" alt=""><figcaption><p>角色指令設定</p></figcaption></figure>

點擊 <mark style="color:blue;">**儲存**</mark> 完成助理建立。

### Step 4：測試辨識效果 <a href="#step4-test-recognition" id="step4-test-recognition"></a>

1. 進入助理的 <mark style="color:blue;">**測試對話**</mark>
2. 上傳一張證件圖片（可同時包含正反面）
3. 輸入「請辨識這張證件圖片」
4. 確認回傳的 JSON 結構與欄位內容正確

<figure><img src="/files/DSIHVAd9dkPSnZkhxAL1" alt=""><figcaption><p>證件辨識測試結果</p></figcaption></figure>

## 使用範例 <a href="#usage-examples" id="usage-examples"></a>

上傳一張包含身分證正反面的圖片，AI 助理會自動辨識並輸出結構化 JSON：

```json
{
  "document_type": "中華民國國民身分證",
  "name": "陳筱玲",
  "gender": "女",
  "date_of_birth": "民國57年6月5日",
  "military_service": null,
  "place_of_birth": "臺北市",
  "id_number": "A234567890",
  "expiry_or_issue_date": "民國94年7月1日",
  "address": "臺北市內湖區葫洲里1鄰民權東路六段283巷165弄218號"
}
```

{% hint style="warning" %}
辨識準確度取決於圖片品質。建議拍攝時確保光線充足、避免反光，並將證件平放拍攝。若同時拍攝正反面，建議左右並排或上下排列。
{% endhint %}

## JSON 輸出欄位說明 <a href="#json-output-field-reference" id="json-output-field-reference"></a>

| 欄位                     | 型別          | 來源 | 說明         |
| ---------------------- | ----------- | -- | ---------- |
| `document_type`        | string      | 正面 | 證件類型       |
| `name`                 | string      | 正面 | 持證人姓名      |
| `gender`               | string      | 正面 | 性別（男/女）    |
| `date_of_birth`        | string      | 正面 | 出生年月日（民國年） |
| `military_service`     | string/null | 背面 | 役別         |
| `place_of_birth`       | string/null | 背面 | 出生地        |
| `id_number`            | string      | 正面 | 身分證統一編號    |
| `expiry_or_issue_date` | string/null | 正面 | 發證日期       |
| `address`              | string/null | 背面 | 完整住址       |

## API 串接 <a href="#api-integration" id="api-integration"></a>

此助理可透過 MaiAgent API 串接至業務系統，實現自動化證件辨識流程。

### 呼叫流程 <a href="#call-flow" id="call-flow"></a>

```mermaid
sequenceDiagram
    participant Client as 業務系統
    participant API as MaiAgent API
    participant Bot as OCR 辨識助理

    Client->>API: POST /attachments-upload/<br/>上傳證件圖片
    API-->>Client: 回傳附件 ID
    Client->>API: POST /chatbots/{id}/completions/<br/>帶入附件 ID
    API->>Bot: 圖片辨識
    Bot-->>API: JSON 結構化結果
    API-->>Client: 回傳 OCR JSON
```

### Step 1：上傳圖片取得附件 ID <a href="#api-step1-upload-image-get-attachment-id" id="api-step1-upload-image-get-attachment-id"></a>

```bash
curl -X POST \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -F "file=@/path/to/id_card.jpeg" \
  "https://api.maiagent.ai/api/v1/attachments-upload/"
```

回傳結果中記下 `id`、`type`、`file`、`filename` 欄位，下一步會用到。

### Step 2：呼叫助理進行辨識 <a href="#api-step2-call-assistant-for-recognition" id="api-step2-call-assistant-for-recognition"></a>

```bash
curl -X POST \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": {
      "content": "請辨識這張證件圖片",
      "attachments": [{
        "id": "{Step 1 回傳的 id}",
        "type": "image",
        "file": "{Step 1 回傳的 file URL}",
        "filename": "id_card.jpeg"
      }]
    },
    "isStreaming": false
  }' \
  "https://api.maiagent.ai/api/v1/chatbots/{助理ID}/completions/"
```

### Step 3：解析回傳結果 <a href="#api-step3-parse-response" id="api-step3-parse-response"></a>

回傳的 `content` 欄位即為 JSON 格式的辨識結果：

**Python**

```python
import json
ocr_result = json.loads(response["content"])
print(ocr_result["name"])             # 陳筱玲
print(ocr_result["id_number"])        # A234567890
print(ocr_result["address"])          # 臺北市內湖區葫洲里1鄰民權東路六段283巷165弄218號
```

**JavaScript**

```javascript
const ocrResult = JSON.parse(response.content);
console.log(ocrResult.name);             // 陳筱玲
console.log(ocrResult.id_number);        // A234567890
console.log(ocrResult.address);          // 臺北市內湖區葫洲里1鄰民權東路六段283巷165弄218號
```

{% hint style="info" %}
完整範例程式碼請參考 [Playma-Co-Ltd/maiagent-api-examples](https://github.com/Playma-Co-Ltd/maiagent-api-examples)。
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.maiagent.ai/application/image-vision/id-card-recognition.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
