V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
oyp
V2EX  ›  程序员

Node.js 调用 ChatGPT 并实现流式传输

  •  
  •   oyp · 2023-07-27 17:17:04 +08:00 · 581 次点击
    这是一个创建于 442 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import {
        OpenAIApi,
        Configuration,
        CreateChatCompletionResponse
    } from 'openai'
    import process from 'process'
    
    const configuration = new Configuration({
        apiKey: 'sk-xxxxxxxxxxxx'
    })
    const openai = new OpenAIApi(configuration)
    openai.createChatCompletion({
        model: 'gpt-3.5-turbo',
        messages: [
            { role: 'user', content: '请模仿李白写一首诗' }
        ],
        stream: true
    }, { responseType: 'stream' }).then(value => {
        const data = value.data as ChatData
        data.on('data', chunk => {
            const match = chunk.toString().match(/^data: (.*)/)
            if (!match || match[1] == '[DONE]') return
            const res = JSON.parse(match[1])
            const { content } = res.choices[0].delta
            if (!content) return
            process.stdout.write(content)
        })
    })
    
    interface ChatData extends CreateChatCompletionResponse {
        /** 绑定事件 */
        on<K extends keyof EventType>(
            eventType: K,
            handle: (event: EventType[K]) => void
        ): void
    }
    
    interface EventType {
        'data': Buffer
    }
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5739 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 02:20 · PVG 10:20 · LAX 19:20 · JFK 22:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.