File size: 6,402 Bytes
cd9bca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# 🚀 OpenRouter 整合文件

## 📋 概述

本專案已整合 OpenRouter API 來提供進階的自然語言處理功能,包括:
- 更精確的意圖識別
- 智能實體提取
- 自然的回應生成

## 🔧 設定方式

### 1. 取得 OpenRouter API Key

1. 前往 [OpenRouter 官網](https://openrouter.ai/)
2. 註冊帳號並登入
3. 前往 [API Keys 頁面](https://openrouter.ai/keys)
4. 建立新的 API Key
5. 複製 API Key 備用

### 2. 環境變數設定

在 Hugging Face Spaces 的 Settings 中新增以下環境變數:

```bash
# 必要設定
OPENROUTER_API_KEY=your_openrouter_api_key_here

# 可選設定 (預設值已設定)
OPENROUTER_MODEL=anthropic/claude-3-haiku
```

### 3. 支援的模型

OpenRouter 支援多種 AI 模型,您可以根據需求選擇:

#### 推薦模型 (成本效益佳)
- `anthropic/claude-3-haiku` (預設) - 快速、便宜
- `openai/gpt-3.5-turbo` - 平衡性能與成本
- `meta-llama/llama-2-70b-chat` - 開源選項

#### 高性能模型
- `anthropic/claude-3-sonnet` - 更好的理解能力
- `openai/gpt-4` - 最佳性能
- `anthropic/claude-3-opus` - 最高品質

#### 設定範例
```bash
# 使用 GPT-3.5 Turbo
OPENROUTER_MODEL=openai/gpt-3.5-turbo

# 使用 Claude 3 Sonnet
OPENROUTER_MODEL=anthropic/claude-3-sonnet
```

## 🎯 功能特色

### 1. 進階意圖識別

OpenRouter 整合後,系統能更準確地識別用戶意圖:

```python
# 範例輸入
"幫我找一下價格在一千到五千之間的手機"

# 基礎 NLP (規則引擎)
{
    "intent": "search_product",
    "confidence": 0.6,
    "entities": {"min_price": 1000, "max_price": 5000}
}

# 進階 NLP (OpenRouter)
{
    "intent": "search_product",
    "confidence": 0.9,
    "entities": {
        "min_price": 1000,
        "max_price": 5000,
        "category": "手機",
        "product_type": "電子產品"
    }
}
```

### 2. 智能回應生成

系統會根據查詢結果生成更自然的回應:

```python
# 基礎回應
"找到 3 筆商品資料。"

# 進階回應 (OpenRouter)
"我為您找到了 3 款符合條件的手機:
1. iPhone 15 Pro - NT$ 35,900
2. Samsung Galaxy S24 - NT$ 28,900  
3. Google Pixel 8 - NT$ 24,900

這些都在您的預算範圍內,您想了解哪一款的詳細資訊呢?"
```

## 🔄 降級機制

系統具有完整的降級機制:

1. **優先使用 OpenRouter**: 如果 API Key 可用且正常運作
2. **自動降級**: 如果 OpenRouter 失敗,自動使用基礎規則引擎
3. **錯誤處理**: 完整的錯誤日誌和異常處理

```python
# 在程式碼中的實作
def analyze_message(self, message: str, use_advanced: bool = True):
    if use_advanced and self.openrouter_service.api_key:
        try:
            # 嘗試使用 OpenRouter
            return advanced_analysis
        except Exception as e:
            logger.warning(f"進階 NLP 分析失敗,使用基礎分析: {str(e)}")
    
    # 降級到基礎規則引擎
    return basic_analysis
```

## 💰 成本考量

### 模型成本比較 (每 1M tokens)

| 模型 | 輸入成本 | 輸出成本 | 適用場景 |
|------|----------|----------|----------|
| claude-3-haiku | $0.25 | $1.25 | 日常查詢 |
| gpt-3.5-turbo | $0.50 | $1.50 | 平衡使用 |
| claude-3-sonnet | $3.00 | $15.00 | 複雜查詢 |
| gpt-4 | $10.00 | $30.00 | 高精度需求 |

### 成本優化建議

1. **使用 claude-3-haiku** 作為預設模型 (成本最低)
2. **設定合理的 token 限制** (max_tokens: 300-500)
3. **監控使用量** 透過 OpenRouter Dashboard
4. **考慮快取機制** 對常見查詢進行快取

## 🛠️ 開發與測試

### 本地測試

```bash
# 設定環境變數
export OPENROUTER_API_KEY="your_key_here"
export OPENROUTER_MODEL="anthropic/claude-3-haiku"

# 執行測試
python test_api.py
```

### API 測試範例

```python
# 測試進階 NLP
from backend.services.openrouter_service import OpenRouterService

service = OpenRouterService()
result = await service.analyze_intent_advanced("查詢用戶張三的訂單")
print(result)
```

## 🔍 監控與除錯

### 日誌監控

系統會記錄以下資訊:

```python
# 成功使用 OpenRouter
logger.info("使用 OpenRouter 進行進階分析")

# 降級到基礎引擎
logger.warning("進階 NLP 分析失敗,使用基礎分析")

# API 錯誤
logger.error("OpenRouter API 錯誤: 401 Unauthorized")
```

### 常見問題

1. **API Key 無效**
   - 檢查 API Key 是否正確
   - 確認 OpenRouter 帳戶餘額

2. **模型不存在**
   - 檢查模型名稱是否正確
   - 參考 OpenRouter 模型列表

3. **請求超時**
   - 檢查網路連線
   - 考慮增加 timeout 設定

## 📈 效能優化

### 1. 異步處理

```python
# 使用 asyncio 避免阻塞
async def analyze_intent_advanced(self, message: str):
    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.post(...)
```

### 2. 錯誤重試

```python
# 實作重試機制
for attempt in range(3):
    try:
        result = await openrouter_request()
        break
    except Exception as e:
        if attempt == 2:
            raise e
        await asyncio.sleep(1)
```

### 3. 快取策略

```python
# 快取常見查詢結果
@lru_cache(maxsize=100)
def cached_analysis(message_hash: str):
    return analysis_result
```

## 🚀 進階功能

### 1. 自訂提示詞

您可以修改 `openrouter_service.py` 中的提示詞來優化特定領域的表現:

```python
def _build_analysis_prompt(self, message: str):
    # 自訂您的提示詞
    prompt = f"""
    您是一個專業的電商客服助手...
    """
```

### 2. 多語言支援

```python
# 支援多語言分析
def analyze_message_multilingual(self, message: str, language: str = "zh"):
    prompt = self._build_multilingual_prompt(message, language)
```

### 3. 上下文記憶

```python
# 維護對話上下文
def analyze_with_context(self, message: str, conversation_history: List[str]):
    context = {"history": conversation_history}
    return await self.analyze_intent_advanced(message, context)
```

## 📞 技術支援

如果您在整合 OpenRouter 時遇到問題:

1. 檢查 [OpenRouter 文件](https://openrouter.ai/docs)
2. 查看系統日誌檔案
3. 參考本專案的 `test_api.py` 進行測試
4. 確認環境變數設定正確

---

**注意**: OpenRouter 是付費服務,請根據您的使用量選擇適合的模型和方案。