前端引入chatGpt
1. 訪問 chatGpt 官網
2. 獲得 API Key

3. 生成 API Key

4. 邀請團隊成員(可暫時忽略)

5. 輸入API key name,Project name (可申請多個api key)

6. API key 生成啦~~,可以去使用啦~~

7. 前端代碼
<template>
<div class="border p-4 rounded-lg">
<input placeholder="輸入chatGpt搜索內容" v-model="searchVal" />
<button
@click="getAISuggestion"
:disabled="loading"
class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
{{ loading ? 'AI分析中...' : '獲取優化建議' }}
</button>
<div v-if="advice" class="mt-4 p-3 bg-gray-50 rounded">
<h3 class="font-bold mb-2">?? AI建議:</h3>
<pre class="whitespace-pre-wrap">{{ advice }}</pre>
</div>
</div>
</template>
<script setup>
import OpenAI from "openai";
import { computed, onMounted, ref } from "vue";
let loading = ref(false)
const openai = new OpenAI({
apiKey:
"****",
dangerouslyAllowBrowser: true, // 允許在瀏覽器環境中運行
});
let searchVal = ref(null);
let advice = ref(null)
const getAISuggestion = async () => {
// ChatGPT
try {
loading.value = true
const completion = await openai.chat.completions.create({
messages: [{ role: "user", content: searchVal.value }],
model: "gpt-4o-mini",
store: true,
});
loading.value = false
advice.value = completion.choices[0].message.content
} catch {
console.error("OpenAI API Error:", error);
res.status(500).json({ error: "AI分析失敗" });
}
};
</script>
<style scoped>
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>

浙公網安備 33010602011771號