vue调用openai的代码

openai 文章 2023-03-19 17:27 2281 0 全屏看文

AI助手支持GPT4.0

以下是一个简单的 Vue 应用示例,用于对接 ChatGPT 接口。该示例包含一个输入框、一个发送按钮、一个显示对话的区域以及一个保存聊天记录的功能。请注意,你需要在这个示例中替换你自己的 ChatGPT API 密钥。


首先确保已经安装了 Vue 和 Axios:

npm install -g vue
npm install axios

创建一个名为 app.vue 的文件,并将以下内容复制到该文件中:

<template>
  <div id="app">
    <div class="chat-container">
      <div class="messages">
        <div v-for="(message, index) in messages" :key="index" :class="message.type">
          {{ message.content }}
        </div>
      </div>
      <div class="input-container">
        <input type="text" v-model="userInput" @keyup.enter="sendMessage" placeholder="Type your message" />
        <button @click="sendMessage">发送</button>
        <button @click="saveChat">保存聊天记录</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      userInput: '',
      messages: []
    };
  },
  methods: {
    async sendMessage() {
      if (!this.userInput) return;

      this.messages.push({ type: 'user', content: this.userInput });

      const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
        prompt: `User: ${this.userInput}\nChatGPT: `,
        max_tokens: 150,
        n: 1,
        stop: null,
        temperature: 0.7,
      }, {
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        }
      });

      const chatGPTResponse = response.data.choices[0].text.trim();
      this.messages.push({ type: 'chatgpt', content: chatGPTResponse });

      this.userInput = '';
    },
    saveChat() {
      const chatLog = this.messages.map(message => `${message.type === 'user' ? 'User' : 'ChatGPT'}: ${message.content}`).join('\n');
      const blob = new Blob([chatLog], { type: 'text/plain;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'chat_log.txt';
      link.click();
    }
  }
};
</script>

<style scoped>
.chat-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 1rem;
  font-family: Arial, sans-serif;
}

.messages {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 1rem;
}

.input-container {
  display: flex;
  justify-content: space-between;
}

input {
  flex-grow: 1;
  margin-right: 1rem;
}

.user {
  text-align: right;
  color: blue;
}

.chatgpt {
  text-align: left;
  color: green;
}
</style>

请将 YOUR_API_KEY 替换为您的 ChatGPT API 密钥。这个示例中,我们使用了 DaVinci

-EOF-

AI助手支持GPT4.0