Vue 3 串接 ChatGPT 入門
in Blog Last modified at:

前言
在本文中,我們將探討如何在 Vue 3 中串接 ChatGPT,幫助開發者利用這些技術來構建智能應用。
進階技巧
1. 安裝 OpenAI SDK
首先,我們需要安裝 OpenAI 的 SDK 來與 ChatGPT 進行通信:
bash
npm install openai
2. 配置 OpenAI API
接下來,我們需要在 Vue 3 應用中配置 OpenAI API:
// src/api/openai.js
import { Configuration, OpenAIApi } from 'openai';
const configuration = new Configuration({
apiKey: process.env.VUE_APP_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default openai;
3. 創建 ChatGPT 組件
我們將創建一個 ChatGPT 組件來處理用戶輸入並顯示 ChatGPT 的回應:
<!-- src/components/ChatGPT.vue -->
<template>
<div>
<h1>ChatGPT 聊天</h1>
<input
v-model="userInput"
@keyup.enter="sendMessage"
placeholder="輸入訊息"
/>
<button @click="sendMessage">發送</button>
<div v-if="response">
<h2>回應:</h2>
<p></p>
</div>
</div>
</template>
<script>
import openai from '../api/openai';
export default {
data() {
return {
userInput: '',
response: null,
};
},
methods: {
async sendMessage() {
if (this.userInput.trim() === '') return;
try {
const result = await openai.createCompletion({
model: 'text-davinci-003',
prompt: this.userInput,
max_tokens: 150,
});
this.response = result.data.choices[0].text.trim();
} catch (error) {
console.error('與OpenAI通信時出錯:', error);
}
},
},
};
</script>
<style scoped>
input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
}
button {
padding: 10px 20px;
}
</style>
4. 在主應用中使用 ChatGPT 組件
最後,我們需要在主應用中引入並使用 ChatGPT 組件:
<!-- src/App.vue -->
<template>
<div id="app">
<ChatGPT />
</div>
</template>
<script>
import ChatGPT from './components/ChatGPT.vue';
export default {
components: {
ChatGPT,
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
總結
通過掌握這些技巧和最佳實踐,開發者可以在 Vue 3 中輕鬆串接 ChatGPT,構建智能應用:
- 安裝 OpenAI SDK。
- 配置 OpenAI API。
- 創建 ChatGPT 組件。
- 在主應用中使用 ChatGPT 組件。