# 企業整合模式

## 企業整合模式

本指南為尋求將 Rememberizer 的知識管理和語義搜索功能整合到企業環境中的組織提供全面的信息。它涵蓋了架構模式、安全考量、可擴展性和最佳實踐。

### 企業整合概述

Rememberizer 提供強大的企業整合能力，超越基本的 API 使用，讓組織能夠建立複雜的知識管理系統，具備以下功能：

* **滿足組織需求的擴展性**，涵蓋各部門和團隊
* **維持安全性和合規性**，符合企業要求
* **與現有系統**和工作流程工具**整合**
* **啟用基於團隊的訪問控制**和知識共享
* **支持高容量批次操作**以進行文件處理

### 企業整合的架構模式

#### 1. 多租戶知識管理

組織可以實施多租戶架構，以按團隊、部門或功能組織知識：

```
                  ┌───────────────┐
                  │   Rememberizer│
                  │     平台      │
                  └───────┬───────┘
                          │
        ┌─────────────────┼─────────────────┐
        │                 │                 │
┌───────▼────────┐ ┌──────▼───────┐ ┌───────▼────────┐
│  工程          │ │    銷售      │ │     法律       │
│  知識庫        │ │ 知識庫      │ │ 知識庫        │
└───────┬────────┘ └──────┬───────┘ └───────┬────────┘
        │                 │                 │
        │                 │                 │
┌───────▼────────┐ ┌──────▼───────┐ ┌───────▼────────┐
│  團隊專屬      │ │ 團隊專屬    │ │  團隊專屬      │
│    記憶        │ │   記憶      │ │     記憶       │
└────────────────┘ └──────────────┘ └─────────────────┘
```

**實施步驟：**

1. 為每個部門或主要知識領域創建單獨的向量存儲
2. 使用 Rememberizer 的團隊功能配置基於團隊的訪問控制
3. 定義記憶以控制對特定知識子集的訪問
4. 實施基於角色的權限，供知識管理員和消費者使用

#### 2. 整合中心架構

對於擁有現有系統的企業，中心-輻射模式允許 Rememberizer 作為中央知識庫：

```
       ┌─────────────┐               ┌─────────────┐
       │ CRM 系統    │               │  ERP 系統   │
       └──────┬──────┘               └──────┬──────┘
              │                             │
              │                             │
              ▼                             ▼
       ┌──────────────────────────────────────────┐
       │                                          │
       │           企業服務總線                  │
       │                                          │
       └────────────────────┬─────────────────────┘
                            │
                            ▼
                  ┌───────────────────┐
                  │   Rememberizer    │
                  │ 知識平台          │
                  └─────────┬─────────┘
                            │
          ┌─────────────────┴────────────────┐
          │                                  │
┌─────────▼──────────┐            ┌──────────▼────────┐
│ 內部知識庫        │            │ 客戶知識庫       │
│                  │            │                  │
└────────────────────┘            └─────────────────────┘
```

**實施步驟：**

1. 創建並配置系統對系統整合的 API 金鑰
2. 實施 OAuth2 以便基於用戶的訪問知識庫
3. 設置 ETL 流程以進行定期的知識同步
4. 使用網絡鉤子通知外部系統知識更新

#### 3. 微服務架構

對於採用微服務的組織，將 Rememberizer 整合為專門的知識服務：

```
┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
│ 用戶服務    │  │ 認證服務    │  │ 數據服務    │  │ 搜索 UI     │
└──────┬──────┘  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘
       │                │                │                │
       └────────────────┼────────────────┼────────────────┘
                        │                │                  
                        ▼                ▼                  
               ┌─────────────────────────────────┐         
               │       API 閘道                │         
               └─────────────────┬─────────────┘         
                                 │                        
                                 ▼                        
                       ┌───────────────────┐              
                       │   Rememberizer    │              
                       │   知識 API        │              
                       └───────────────────┘              
```

**實施步驟：**

1. 為微服務整合創建專用服務帳戶
2. 實施基於 JWT 令牌的服務間通信認證
3. 設計冪等 API 交互以提高韌性
4. 實施斷路器以實現容錯

### 企業安全模式

#### 認證與授權

Rememberizer 支援多種適合企業環境的認證方法：

**1. OAuth2 整合**

對於基於用戶的訪問，實現 OAuth2 授權流程：

```javascript
// 步驟 1：將用戶重定向到 Rememberizer 授權端點
function redirectToAuth() {
  const authUrl = 'https://api.rememberizer.ai/oauth/authorize/';
  const params = new URLSearchParams({
    client_id: 'YOUR_CLIENT_ID',
    redirect_uri: 'YOUR_REDIRECT_URI',
    response_type: 'code',
    scope: 'read write'
  });
  
  window.location.href = `${authUrl}?${params.toString()}`;
}

// 步驟 2：用授權碼交換令牌
async function exchangeCodeForTokens(code) {
  const tokenUrl = 'https://api.rememberizer.ai/oauth/token/';
  const response = await fetch(tokenUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      client_id: 'YOUR_CLIENT_ID',
      client_secret: 'YOUR_CLIENT_SECRET',
      grant_type: 'authorization_code',
      code: code,
      redirect_uri: 'YOUR_REDIRECT_URI'
    })
  });
  
  return response.json();
}
```

**2. 服務帳戶認證**

對於系統到系統的整合，使用 API 金鑰認證：

```python
import requests

def search_knowledge_base(query, api_key):
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }
    
    payload = {
        'query': query,
        'num_results': 10
    }
    
    response = requests.post(
        'https://api.rememberizer.ai/api/v1/search/',
        headers=headers,
        json=payload
    )
    
    return response.json()
```

**3. SAML 與企業單一登入**

對於企業單一登入整合：

1. 配置您的身份提供者（Okta、Azure AD 等）以識別 Rememberizer 為服務提供者
2. 設定 SAML 屬性映射以匹配 Rememberizer 使用者屬性
3. 配置 Rememberizer 將身份驗證委派給您的身份提供者

#### 零信任安全模型

透過 Rememberizer 實施零信任方法：

1. **微分段**：創建具有不同訪問控制的獨立知識庫
2. **持續驗證**：實施短期令牌和定期重新身份驗證
3. **最小特權**：定義細粒度的回憶物，以限制對特定知識子集的訪問
4. **事件日誌**：監控和審計對敏感知識的所有訪問

### 可擴展性模式

#### 批次處理文件攝取

對於大規模的文件攝取，實現批次上傳模式：

```python
import requests
import time
from concurrent.futures import ThreadPoolExecutor

def batch_upload_documents(files, api_key, batch_size=5):
    """
    批次上傳文件以避免速率限制
    
    參數：
        files: 要上傳的文件路徑列表
        api_key: Rememberizer API 金鑰
        batch_size: 同時上傳的數量
    """
    headers = {
        'X-API-Key': api_key
    }
    
    results = []
    
    # 批次處理文件
    with ThreadPoolExecutor(max_workers=batch_size) as executor:
        for i in range(0, len(files), batch_size):
            batch = files[i:i+batch_size]
            futures = []
            
            # 提交批次上傳
            for file_path in batch:
                with open(file_path, 'rb') as f:
                    files = {'file': f}
                    future = executor.submit(
                        requests.post,
                        'https://api.rememberizer.ai/api/v1/documents/upload/',
                        headers=headers,
                        files=files
                    )
                    futures.append(future)
            
            # 收集結果
            for future in futures:
                response = future.result()
                results.append(response.json())
            
            # 速率限制 - 批次之間暫停
            if i + batch_size < len(files):
                time.sleep(1)
    
    return results
```

#### 高容量搜尋操作

對於需要高容量搜尋的應用程式：

```javascript
async function batchSearchWithRateLimit(queries, apiKey, options = {}) {
  const {
    batchSize = 5,
    delayBetweenBatches = 1000,
    maxRetries = 3,
    retryDelay = 2000
  } = options;
  
  const results = [];
  
  // 以批次處理查詢
  for (let i = 0; i < queries.length; i += batchSize) {
    const batch = queries.slice(i, i + batchSize);
    const batchPromises = batch.map(query => searchWithRetry(query, apiKey, maxRetries, retryDelay));
    
    // 執行批次
    const batchResults = await Promise.all(batchPromises);
    results.push(...batchResults);
    
    // 在批次之間應用速率限制
    if (i + batchSize < queries.length) {
      await new Promise(resolve => setTimeout(resolve, delayBetweenBatches));
    }
  }
  
  return results;
}

async function searchWithRetry(query, apiKey, maxRetries, retryDelay) {
  let retries = 0;
  
  while (retries < maxRetries) {
    try {
      const response = await fetch('https://api.rememberizer.ai/api/v1/search/', {
        method: 'POST',
        headers: {
          'X-API-Key': apiKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ query })
      });
      
      if (response.ok) {
        return response.json();
      }
      
      // 特別處理速率限制
      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After') || retryDelay / 1000;
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        retries++;
        continue;
      }
      
      // 其他錯誤
      throw new Error(`搜尋失敗，狀態碼：${response.status}`);
    } catch (error) {
      retries++;
      if (retries >= maxRetries) {
        throw error;
      }
      await new Promise(resolve => setTimeout(resolve, retryDelay));
    }
  }
}
```

### 團隊基礎的知識管理

Rememberizer 支援團隊基礎的知識管理，使企業能夠：

1. **創建團隊工作區**：按部門或功能組織知識
2. **分配基於角色的權限**：控制誰可以查看、編輯或管理知識
3. **跨團隊分享知識**：配置跨團隊訪問特定知識庫

#### 團隊角色和權限

Rememberizer 支援以下團隊角色：

| 角色      | 能力                      |
| ------- | ----------------------- |
| **擁有者** | 完全的管理訪問權限，可以管理團隊成員和所有知識 |
| **管理員** | 可以管理知識和配置備忘錄，但不能管理團隊本身  |
| **成員**  | 可以根據備忘錄權限查看和搜索知識        |

#### 實施基於團隊的知識共享

```python
import requests

def create_team_knowledge_base(team_id, name, description, api_key):
    """
    為特定團隊創建知識庫
    """
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }
    
    payload = {
        'team_id': team_id,
        'name': name,
        'description': description
    }
    
    response = requests.post(
        'https://api.rememberizer.ai/api/v1/teams/knowledge/',
        headers=headers,
        json=payload
    )
    
    return response.json()

def grant_team_access(knowledge_id, team_id, permission_level, api_key):
    """
    授予團隊訪問知識庫的權限
    
    Args:
        knowledge_id: 知識庫的ID
        team_id: 要授予訪問權限的團隊ID
        permission_level: 'read', 'write', 或 'admin'
        api_key: Rememberizer API密鑰
    """
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }
    
    payload = {
        'team_id': team_id,
        'knowledge_id': knowledge_id,
        'permission': permission_level
    }
    
    response = requests.post(
        'https://api.rememberizer.ai/api/v1/knowledge/permissions/',
        headers=headers,
        json=payload
    )
    
    return response.json()
```

### 企業整合最佳實踐

#### 1. 實現穩健的錯誤處理

設計您的整合以優雅地處理各種錯誤場景：

```javascript
async function robustApiCall(endpoint, method, payload, apiKey) {
  try {
    const response = await fetch(`https://api.rememberizer.ai/api/v1/${endpoint}`, {
      method,
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      },
      body: method !== 'GET' ? JSON.stringify(payload) : undefined
    });
    
    // 處理不同的響應類型
    if (response.status === 204) {
      return { success: true };
    }
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || `API 呼叫失敗，狀態碼: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    // 記錄錯誤詳情以便故障排除
    console.error(`對 ${endpoint} 的 API 呼叫失敗:`, error);
    
    // 向調用代碼提供有意義的錯誤
    throw new Error(`無法 ${method} ${endpoint}: ${error.message}`);
  }
}
```

#### 2. 為經常訪問的知識實現快取

減少 API 負載並通過適當的快取提高性能：

```python
import requests
import time
from functools import lru_cache
```

## 快取經常訪問的文件 10 分鐘

@lru\_cache(maxsize=100) def get\_document\_with\_cache(document\_id, api\_key, timestamp=None): """ 獲取帶有快取的文件

```
參數:
    document_id: 要檢索的文件 ID
    api_key: Rememberizer API 金鑰
    timestamp: 快取失效時間戳（默認：10 分鐘塊）
"""
# 生成每 10 分鐘變化一次的時間戳以進行快取失效
if timestamp is None:
    timestamp = int(time.time() / 600)

headers = {
    'X-API-Key': api_key
}

response = requests.get(
    f'https://api.rememberizer.ai/api/v1/documents/{document_id}/',
    headers=headers
)

return response.json()
```

````

### 3. 實現文件上傳的非同步處理

對於大型文件集，實現非同步處理：

```javascript
async function uploadLargeDocument(file, apiKey) {
  // 步驟 1：啟動上傳
  const initResponse = await fetch('https://api.rememberizer.ai/api/v1/documents/upload-async/', {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      filename: file.name,
      filesize: file.size,
      content_type: file.type
    })
  });
  
  const { upload_id, upload_url } = await initResponse.json();
  
  // 步驟 2：將文件上傳到提供的 URL
  await fetch(upload_url, {
    method: 'PUT',
    body: file
  });
  
  // 步驟 3：監控處理狀態
  const processingId = await initiateProcessing(upload_id, apiKey);
  return monitorProcessingStatus(processingId, apiKey);
}

async function initiateProcessing(uploadId, apiKey) {
  const response = await fetch('https://api.rememberizer.ai/api/v1/documents/process/', {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      upload_id: uploadId
    })
  });
  
  const { processing_id } = await response.json();
  return processing_id;
}

async function monitorProcessingStatus(processingId, apiKey, interval = 2000) {
  while (true) {
    const statusResponse = await fetch(`https://api.rememberizer.ai/api/v1/documents/process-status/${processingId}/`, {
      headers: {
        'X-API-Key': apiKey
      }
    });
    
    const status = await statusResponse.json();
    
    if (status.status === 'completed') {
      return status.document_id;
    } else if (status.status === 'failed') {
      throw new Error(`處理失敗：${status.error}`);
    }
    
    // 等待後再檢查
    await new Promise(resolve => setTimeout(resolve, interval));
  }
}
````

#### 4. 實施適當的速率限制

尊重 API 的速率限制以確保可靠的操作：

```python
import requests
import time
from functools import wraps

class RateLimiter:
    def __init__(self, calls_per_second=5):
        self.calls_per_second = calls_per_second
        self.last_call_time = 0
        self.min_interval = 1.0 / calls_per_second
    
    def __call__(self, func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            current_time = time.time()
            time_since_last_call = current_time - self.last_call_time
            
            if time_since_last_call < self.min_interval:
                sleep_time = self.min_interval - time_since_last_call
                time.sleep(sleep_time)
            
            self.last_call_time = time.time()
            return func(*args, **kwargs)
        
        return wrapper

# 對 API 調用應用速率限制
@RateLimiter(calls_per_second=5)
def search_documents(query, api_key):
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }
    
    payload = {
        'query': query
    }
    
    response = requests.post(
        'https://api.rememberizer.ai/api/v1/search/',
        headers=headers,
        json=payload
    )
    
    return response.json()
```

### 合規考量

#### 數據居留

對於有數據居留要求的組織：

1. **選擇適當的區域**：選擇符合要求的 Rememberizer 部署區域
2. **記錄數據流**：繪製知識存儲和處理的位置
3. **實施過濾**：使用 mementos 限制敏感數據的訪問

#### 審計日誌

實施全面的審計日誌以符合規範：

```python
import requests
import json
import logging
```

## 配置日誌

logging.basicConfig( level=logging.INFO, format='%(asctime)s \[%(levelname)s] %(message)s', handlers=\[ logging.FileHandler('rememberizer\_audit.log'), logging.StreamHandler() ] )

def audit\_log\_api\_call(endpoint, method, user\_id, result\_status): """ 記錄 API 呼叫詳細信息以便審計 """ log\_entry = { 'timestamp': time.time(), 'endpoint': endpoint, 'method': method, 'user\_id': user\_id, 'status': result\_status }

```
logging.info(f"API 呼叫: {json.dumps(log_entry)}")
```

def search\_with\_audit(query, api\_key, user\_id): endpoint = 'search' method = 'POST'

```
try:
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }
    
    payload = {
        'query': query
    }
    
    response = requests.post(
        'https://api.rememberizer.ai/api/v1/search/',
        headers=headers,
        json=payload
    )
    
    status = 'success' if response.ok else 'error'
    audit_log_api_call(endpoint, method, user_id, status)
    
    return response.json()
except Exception as e:
    audit_log_api_call(endpoint, method, user_id, 'exception')
    raise
```

```

## 下一步

要使用 Rememberizer 實現企業整合：

1. **設計您的知識架構**：繪製知識領域和訪問模式
2. **建立基於角色的團隊結構**：創建團隊並分配適當的權限
3. **實施身份驗證流程**：選擇並實施符合您要求的身份驗證方法
4. **設計可擴展的工作流程**：實施文檔攝取的批處理
5. **建立監控和審計政策**：設置日誌記錄和監控以確保合規性和運營

## 相關資源

* [Mementos 過濾器訪問](../personal/mementos-filter-access.md) - 控制可用於整合的數據來源
* [API 文檔](api-docs/README.md) - 所有端點的完整 API 參考
* [LangChain 整合](langchain-integration.md) - 與 LangChain 框架的程式化整合
* [創建 Rememberizer GPT](creating-a-rememberizer-gpt.md) - 與 OpenAI 的 GPT 平台整合
* [向量存儲](vector-stores.md) - Rememberizer 向量數據庫實現的技術細節

如需進一步協助企業整合，請通過支持門戶聯繫 Rememberizer 團隊。
```


---

# 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.rememberizer.ai/zh-hk/kai-fa-zhe-zi-yuan/enterprise-integration/enterprise-integration-patterns.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.
