通常情况 openai-node 用于 node 环境,如果在浏览器环境使用,需要开启 dangerouslyAllowBrowser
。
import { useXAgent, useXChat, Sender } from '@ant-design/x';import OpenAI from 'openai';const client = new OpenAI({apiKey: process.env['OPENAI_API_KEY'],dangerouslyAllowBrowser: true,});// react env ...const [agent] = useXAgent({request: async (info, callbacks) => {const stream = await client.chat.completions.create({model: 'gpt-4o',messages: [{ role: 'user', content: 'Say this is a test' }],stream: true,});for await (const chunk of stream) {// 调用回调callbacks.onUpdate(chunk.choices[0]?.delta?.content || '');}},});const {// 用于发起对话请求onRequest,// 用于绑定视图messages,} = useXChat({ agent });const items = messages.map((i) => ({content: message,}));return (<div><Bubble.List items={items} /><Sender onSubmit={onRequest} /></div>);