前端引入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号