请教各位大佬,go-openai 返回的数据,怎么流式返回给 iOS 客户端使用

220 天前
 helloword001
用的库是 github.com/sashabaranov/go-openai,请问怎么流式的返给 iOS 客户端

package main

import (
"context"
"errors"
"fmt"
"io"
openai "github.com/sashabaranov/go-openai"
)

func main() {
c := openai.NewClient("your token")
ctx := context.Background()

req := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
MaxTokens: 20,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "Lorem ipsum",
},
},
Stream: true,
}
stream, err := c.CreateChatCompletionStream(ctx, req)
if err != nil {
fmt.Printf("ChatCompletionStream error: %v\n", err)
return
}
defer stream.Close()

fmt.Printf("Stream response: ")
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
fmt.Println("\nStream finished")
return
}

if err != nil {
fmt.Printf("\nStream error: %v\n", err)
return
}

fmt.Printf(response.Choices[0].Delta.Content)
}
}
790 次点击
所在节点    程序员
8 条回复
guonaihong
220 天前
你启个 websocket 或者 grpc stream 服务端。客户端不停读就行。
helloword001
220 天前
w.Write([]byte(response.Choices[0].Delta.Content + "\n"))
这种形式可以吗
guonaihong
220 天前
websocket 库可以玩下我写的,https://github.com/antlabs/quickws ,有使用上的问题帮你看看。
guonaihong
220 天前
@helloword001 你想用 http chunked 模拟?具体代码网上找找例子,这个也看客户端的开发能力,搞得定也行,缺点只能模拟单向流,s->c 侧的。websocket 和 grpc stream 是全双工的,c->s ,s->c 都行。
dddd1919
220 天前
sse
helloword001
220 天前
@guonaihong openai "github.com/sashabaranov/go-openai"
这个是 http 的,可以转 websocket 吗
guonaihong
220 天前
@helloword001 不能无缝转,要自己写代码。无论是 http chunked 模拟(也叫 sse),还是 websocket 或者 grpc 都要写点代码。
helloword001
220 天前
@guonaihong 好的,谢谢大佬

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/979463

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX