AI 串接指南 - 以 Perplexity 為例
AIPerplexityChatBot
為什麼我選擇 Perplexity?
最近 AI 工具真的很火,就試試了幾個當下最熱門的,其中 Perplexity 在官網上就有 JavaScript 的串接範例,尤其我當時有個需求是希望回答的資料來源以我指定得網站為主。
什麼是 Perplexity?
簡單說,Perplexity 就是一個會搜尋網路的 AI 助手。它於 2022 年推出,主要特色是:
- 即時搜尋:會從網路上找最新資訊
- 自動引用:回答會附上來源連結
- 對話式:可以連續對話,有上下文理解
- 多語言:支援中文等多種語言
對開發者來說,最吸引我的是它的 API 設定很好用跟方便。
開始前的準備工作
1. 註冊帳號
去 Perplexity 註冊一個帳號。
2. 綁定信用卡
這步驟不會馬上扣款,只是為了之後使用 API。我試用了一陣子,花費其實不多。
3. 生成 API Key
在設定頁面生成 API Key,這個 Key 可以長期使用,記得好好保存。
API 基本使用
基本呼叫方式
javascript
const response = await fetch('https://api.perplexity.ai/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'sonar',
messages: [
{ role: 'system', content: '請用繁體中文回答,並保持簡潔' },
{ role: 'user', content: '最新的 JavaScript 框架趨勢是什麼?' },
],
temperature: 0.2,
max_tokens: 500,
}),
});
const data = await response.json();
console.log(data.choices[0].message.content);
實際整合到專案
React 元件範例
我做了一個簡單的搜尋元件:
jsx
import { useState } from 'react';
const PerplexitySearch = () => {
const [query, setQuery] = useState('');
const [result, setResult] = useState('');
const [loading, setLoading] = useState(false);
const searchWithPerplexity = async () => {
if (!query.trim()) return;
setLoading(true);
try {
const response = await fetch('/api/perplexity', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question: query }),
});
const data = await response.json();
setResult(data.answer);
} catch (error) {
console.error('搜尋失敗:', error);
} finally {
setLoading(false);
}
};
return (
<div>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="問我任何問題..."
onKeyPress={(e) => e.key === 'Enter' && searchWithPerplexity()}
/>
<button onClick={searchWithPerplexity} disabled={loading}>
{loading ? '搜尋中...' : '搜尋'}
</button>
{result && (
<div style={{ marginTop: '20px', padding: '15px', border: '1px solid #ccc' }}>
<div dangerouslySetInnerHTML={{ __html: result }} />
</div>
)}
</div>
);
};
Next.js API Route
javascript
// pages/api/perplexity.js (或 app/api/perplexity/route.js)
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { question } = req.body;
try {
const response = await fetch('https://api.perplexity.ai/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.PERPLEXITY_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'sonar',
messages: [
{
role: 'system',
content: '請用繁體中文回答,並在回答中包含相關的來源連結',
},
{ role: 'user', content: question },
],
temperature: 0.3,
max_tokens: 1000,
}),
});
const data = await response.json();
const answer = data.choices[0].message.content;
res.status(200).json({ answer });
} catch (error) {
console.error('Perplexity API 錯誤:', error);
res.status(500).json({ error: '搜尋服務暫時無法使用' });
}
}
參數調整技巧
我花了不少時間調整這些參數,分享一下心得:
temperature (創造性)
- 0.1-0.3: 回答比較精準,適合資訊查詢
- 0.5-0.7: 回答比較有創意,適合創作類任務
- 0.8+: 回答很有創意但可能不太準確
max_tokens (回應長度)
- 100-300: 簡短回答
- 500-1000: 一般詳細度
- 1000+: 很詳細的回答
search_recency_filter (時效性)
- hour: 只搜尋一小時內的資訊
- day: 一天內
- week: 一週內
- month: 一個月內
我做的測試工具
為了方便測試不同參數,我做了一個簡單的測試工具: Perplexity API 參數測試工具
可以即時調整參數看效果,對新手很有幫助。