Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError An error occurred. --- fetch failed #17

Closed
VincentHan888 opened this issue Mar 7, 2023 · 1 comment
Closed

TypeError An error occurred. --- fetch failed #17

VincentHan888 opened this issue Mar 7, 2023 · 1 comment

Comments

@VincentHan888
Copy link

WeChatba6eb839fe006f7924577891e6d85fe9


输入问题后,一直提示这个问题

env中加入这个:HTTPS_PROXY=http://127.0.0.1:15235
一样也是连接不成功,求解谢谢


import type { APIRoute } from "astro"
import {
createParser,
ParsedEvent,
ReconnectInterval
} from "eventsource-parser"

const apiKeys = (
import.meta.env.OPENAI_API_KEY?.split(/\s*|\s*/) ?? []
).filter(Boolean)

export const post: APIRoute = async context => {
const body = await context.request.json()
const apiKey = apiKeys.length
? apiKeys[Math.floor(Math.random() * apiKeys.length)]
: ""
let { messages, key = apiKey, temperature = 0.6 } = body

const encoder = new TextEncoder()
const decoder = new TextDecoder()
^

if (!key.startsWith("sk-")) key = apiKey
if (!key) {
return new Response("没有填写 OpenAI API key")
}
if (!messages) {
return new Response("没有输入任何文字")
}

const completion = await fetch("https://api.openai.com/v1/chat/completions", {
headers: {
"Content-Type": "application/json",
Authorization: Bearer ${key}
},
method: "POST",
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages,
temperature,
stream: true
})
})

const stream = new ReadableStream({
async start(controller) {
const streamParser = (event: ParsedEvent | ReconnectInterval) => {
if (event.type === "event") {
const data = event.data
if (data === "[DONE]") {
controller.close()
return
}
try {
// response = {
// id: 'chatcmpl-6pULPSegWhFgi0XQ1DtgA3zTa1WR6',
// object: 'chat.completion.chunk',
// created: 1677729391,
// model: 'gpt-3.5-turbo-0301',
// choices: [
// { delta: { content: '你' }, index: 0, finish_reason: null }
// ],
// }
const json = JSON.parse(data)
const text = json.choices[0].delta?.content
const queue = encoder.encode(text)
controller.enqueue(queue)
} catch (e) {
controller.error(e)
}
}
}

  const parser = createParser(streamParser)
  for await (const chunk of completion.body as any) {
    parser.feed(decoder.decode(chunk))
  }
}

})

return new Response(stream)
}

@HoneyPig
Copy link

HoneyPig commented Mar 7, 2023

我也这样,有办法解决吗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants