vue.js 我在这个openAI API上做错了什么?

1u4esq0p  于 2022-12-30  发布在  Vue.js
关注(0)|答案(1)|浏览(888)

openAI API在React/Next中给出了这个示例,我尝试在Nuxt中重现它
https://github.com/openai/openai-quickstart-node.git
https://beta.openai.com/docs/quickstart/build-your-application
我创建了文件夹server/api/completion.js

import { Configuration, OpenAIApi } from 'openai'

const configuration = new Configuration({
    apiKey: import.meta.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(configuration)

export default async function (req, res) {
    if (!configuration.apiKey) {
        res.status(500).json({
            error: {
                message: 'OpenAI API key not configured, please follow instructions in README.md'
            }
        })
        return
    }

    const animal = req.body.animal || ''
    if (animal.trim().length === 0) {
        res.status(400).json({
            error: {
                message: 'Please enter a valid animal'
            }
        })
        return
    }

    try {
        const completion = await openai.createCompletion({
            model: 'text-davinci-003',
            prompt: generatePrompt(animal),
            temperature: 0.6
        })
        res.status(200).json({ result: completion.data.choices[0].text })
    } catch (error) {
        // Consider adjusting the error handling logic for your use case
        if (error.response) {
            console.error(error.response.status, error.response.data)
            res.status(error.response.status).json(error.response.data)
        } else {
            console.error(`Error with OpenAI API request: ${error.message}`)
            res.status(500).json({
                error: {
                    message: 'An error occurred during your request.'
                }
            })
        }
    }
}

function generatePrompt(animal) {
    const capitalizedAnimal = animal[0].toUpperCase() + animal.slice(1).toLowerCase()
    return `Suggest three names for an animal that is a superhero.
  
  Animal: Cat
  Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
  Animal: Dog
  Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
  Animal: ${capitalizedAnimal}
  Names:`
}

并在index.vue中

<script setup>
const animal = ref('')
const result = ref('')

const onSubmit = async () => {
    try {
        const response = await useFetch('/api/completion', {
            method: 'POST',
            body: JSON.stringify({ animal: animal.value }),
            headers: {
                'Content-Type': 'application/json'
            }
        })

        const data = await response.json()
        result.value = data.result
    } catch (error) {
        console.error(error)
    }
}
</script>

<template>
    <div>
        <form @submit.prevent="onSubmit">
            <label for="animal">Animal:</label>
            <input id="animal" v-model="animal" />
            <button type="submit">Submit</button>
        </form>
        <p v-if="result">Result: {{ result }}</p>
    </div>
</template>

当我点击提交按钮时,我收到这2个错误:
一个二个一个一个

hi3rlvi2

hi3rlvi21#

解决方案:
server/api/completion.js

import { Configuration, OpenAIApi } from 'openai'

const configuration = new Configuration({
    apiKey: import.meta.env.OPENAI_API_KEY
})

const openai = new OpenAIApi(configuration)

export default defineEventHandler(async (event) => {
    if (!configuration.apiKey) {
        return {
            status: 500,
            body: {
                error: {
                    message: 'OpenAI API key not configured, please follow instructions in README.md'
                }
            }
        }
    }

    const body = await readBody(event)
    const animal = body.animal || ''
    if (animal.trim().length === 0) {
        return {
            status: 400,
            body: {
                error: {
                    message: 'Please enter a valid animal'
                }
            }
        }
    }

    try {
        const completion = await openai.createCompletion({
            model: 'text-davinci-003',
            prompt: generatePrompt(animal),
            temperature: 0.6
        })
        return {
            status: 200,
            body: { result: completion.data.choices[0].text }
        }
    } catch (error) {
        // Consider adjusting the error handling logic for your use case
        if (error.response) {
            console.error(error.response.status, error.response.data)
            return {
                status: error.response.status,
                body: error.response.data
            }
        } else {
            console.error(`Error with OpenAI API request: ${error.message}`)
            return {
                status: 500,
                body: {
                    error: {
                        message: 'An error occurred during your request.'
                    }
                }
            }
        }
    }
})

function generatePrompt(animal) {
    const capitalizedAnimal = animal[0].toUpperCase() + animal.slice(1).toLowerCase()
    return `Suggest three names for an animal that is a superhero.
  
  Animal: Cat
  Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
  Animal: Dog
  Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
  Animal: ${capitalizedAnimal}
  Names:`
}

index.vue

<script setup>
const animal = ref('')
const result = ref('')

const onSubmit = async () => {
    fetch('/api/completion', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ animal: animal.value })
    })
        .then((response) => response.json())
        .then((data) => {
            if (data.body) {
                result.value = data.body.result
            } else {
                console.error('Response from server does not contain a body property')
            }
        })

        .catch((error) => {
            console.error(error)
        })
}
</script>

<template>
    <div>
        <form @submit.prevent="onSubmit">
            <label for="animal">Animal:</label>
            <input id="animal" v-model="animal" />
            <button type="submit">Submit</button>
        </form>
        <p v-if="result">Result: {{ result }}</p>
    </div>
</template>

相关问题