Vue 3 串接 ChatGPT 進階方法

Vue 3 串接 ChatGPT 進階方法
  1. 前言
  2. 進階技巧
    1. 1. 安裝 OpenAI SDK
    2. 2. 配置 OpenAI API
    3. 3. 創建 ChatGPT 組件
    4. 4. 在主應用中使用 ChatGPT 組件
  3. 總結
  4. 參考資料

前言

在本文中,我們將深入探討如何在 Vue 3 中高效地串接 ChatGPT,幫助開發者利用這些技術來構建更智能、更高效的應用。

進階技巧

1. 安裝 OpenAI SDK

首先,我們需要安裝 OpenAI 的 SDK 來與 ChatGPT 進行通信:

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,構建更智能的應用:

  1. 安裝 OpenAI SDK。

  2. 配置 OpenAI API。

  3. 創建 ChatGPT 組件。
  4. 在主應用中使用 ChatGPT 組件。

參考資料


© 2021. All rights reserved.