linebot_pydantic_fastapi / OPENROUTER_INTEGRATION.md
mickeywu520's picture
first commit
cd9bca9
|
raw
history blame
6.4 kB
# 🚀 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 是付費服務,請根據您的使用量選擇適合的模型和方案。