gpt4 book ai didi

javascript - 我在这个 openAI API 上做错了什么?

转载 作者:行者123 更新时间:2023-12-02 05:47:47 24 4
gpt4 key购买 nike

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>

当我点击提交按钮时出现了这两个错误:

POST http://localhost:3000/api/completion 500 (Internal Server Error)
TypeError: response.json is not a function
at onSubmit (index.vue:15:1)

最佳答案

解决方法:

服务器/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:`
}

索引.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>

关于javascript - 我在这个 openAI API 上做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74945886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com