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个错误:
一个二个一个一个
1条答案
按热度按时间hi3rlvi21#
解决方案:
server/api/completion.js
index.vue