uniapp开发中如何实现uni.request流式请求大模型api接口?
网友回复
uniapp进行流式请求chatgpt的api接口的代码需要分平台
1、如果最终导出微信小程序的话,那么就可以直接使用uni.request,其他小程序、app、h5都不支持uni.request进行流式请求数据了。


示例代码
var requestTaskw = uni.request({
url: 'https://api.openai.com/v1/chat/completions', // 请求地址
method: "POST", // 你的请求方法
timeout: 15000,
data: JSON.stringify({
model: 'gpt4O',
messages: [{
role: 'user',
content: 'hello'
}],
temperature: 0.9,
max_tokens: 100,
stream: true
}),
header: {
"Content-Type": "application/json",
'Authorization': `Bearer APIKEY`,
},
responseType: "text",
enableChunked: true, // 开启流传输
success: response => {
console.log(response)
},
fail: error => {}
});
requestTaskw.onHeadersReceived(function(res) {
console.log(res.header);
});
// 这里监听消息
requestTaskw.onChunkReceived(function(res) {
let decoder = new TextDecoder('utf-8');
let text = decoder.decode(new Uint8Array(res.data));
console.log(text)
})2、如果最终导出h5页面的话,可以使用fetch参考代码:点击打开链接
3、如果是andriod或app及其他小程序,有两种办法
3.1 内嵌h5网页,h5网页中使用fetch方式
3.2 服务端统一采用websocket进行中转,这个适合所有的客户端
服务端示例代码如下:
点击查看全文
增加一个enableChunked: true, // 开启流传输,代码如下:
const response = uni.request({
url: 'Your requested address', // 请求地址
method: "Request method", // 你的请求方法
data: data,
header: {
"Accept": 'tex...点击查看剩余70%
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?
linux上如何运行任意windows程序?
ai能写出比黑客还厉害的零日漏洞等攻击工具攻击任意软件系统工程?
js如何获取浏览器的音频上下文指纹、Canvas指纹、WebGL渲染特征?
为啥ai开始抛弃markdown文本,重新偏好html文本了?
网站有没有办法鉴别访问请求是由ai操控chrome-devtools-mcp发出的?
有没有python自动操作浏览器让网站无法鉴别是机器行为?
为啥最新由Meta / 斯坦福 / 哈佛出的ProgramBench基准GPT-5.4、Claude Opus 4.7、Gemini 3.1 Pro 等全部 0% 通过率?


