logoAnt Design X

设计研发组件演示
  • Ant Design X of React
  • 更新日志
    v1.2.0
  • 模型接入
    • OpenAI
      Updated
    • 通义千问
      Updated
    • 其他
  • 其他
    • 贡献指南
    • dangerouslyApiKey 说明
      New
    • FAQ
  • 如何使用
    • 在 create-react-app 中使用
    • 在 Vite 中使用
    • 在 Next.js 中使用
    • 在 Umi 中使用
    • 在 Rsbuild 中使用

OpenAI

相关资源

Ant Design
Ant Design Charts
Ant Design Pro
Pro Components
Ant Design Mobile
Ant Design Mini
Ant Design Web3
Ant Design Landing-首页模板集
Scaffolds-脚手架市场
Umi-React 应用开发框架
dumi-组件/文档研发工具
qiankun-微前端框架
Ant Motion-设计动效
国内镜像站点 🇨🇳

社区

Awesome Ant Design
Medium
Twitter
yuque logoAnt Design 语雀专栏
Ant Design 知乎专栏
体验科技专栏
seeconf logoSEE Conf-蚂蚁体验科技大会
加入我们

帮助

GitHub
更新日志
常见问题
报告 Bug
议题
讨论区
StackOverflow
SegmentFault

Ant XTech logo更多产品

yuque logo语雀-构建你的数字花园
AntV logoAntV-数据可视化解决方案
Egg logoEgg-企业级 Node.js 框架
Kitchen logoKitchen-Sketch 工具集
Galacean logoGalacean-互动图形解决方案
xtech logo蚂蚁体验科技
主题编辑器
Made with ❤ by
蚂蚁集团和 Ant Design 开源社区
loading

这篇指南将介绍如何在使用 Ant Design X 搭建的应用中接入 OpenAI 提供的模型服务。

使用 OpenAI API

等同于接入兼容 OpenAI 的模型推理服务,参考 模型接入-通义千问

使用 openai-node

通常情况 openai-node 用于 node 环境,如果在浏览器环境使用,需要开启 dangerouslyAllowBrowser。

注意: dangerouslyAllowBrowser 存在安全风险,对此 openai-node 的官方文档有详细的说明。

tsx
import { useXAgent, useXChat, Sender, Bubble } from '@ant-design/x';
import OpenAI from 'openai';
import React from 'react';
const client = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'],
dangerouslyAllowBrowser: true,
});
const Demo: React.FC = () => {
const [agent] = useXAgent({
request: async (info, callbacks) => {
const { messages, message } = info;
const { onSuccess, onUpdate, onError } = callbacks;
// current message
console.log('message', message);
// history messages
console.log('messages', messages);
let content: string = '';
try {
const stream = await client.chat.completions.create({
model: 'gpt-4o',
// if chat context is needed, modify the array
messages: [{ role: 'user', content: message }],
// stream mode
stream: true,
});
for await (const chunk of stream) {
content += chunk.choices[0]?.delta?.content || '';
onUpdate(content);
}
onSuccess(content);
} catch (error) {
// handle error
// onError();
}
},
});
const {
// use to send message
onRequest,
// use to render messages
messages,
} = useXChat({ agent });
const items = messages.map(({ message, id }) => ({
// key is required, used to identify the message
key: id,
content: message,
}));
return (
<div>
<Bubble.List items={items} />
<Sender onSubmit={onRequest} />
</div>
);
};
export default Demo;