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

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

  •  
  •   helloword001 · 204 天前 · 777 次点击
    这是一个创建于 204 天前的主题,其中的信息可能已经有所发展或是发生改变。
    用的库是 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)
    }
    }
    8 条回复    2023-10-07 15:54:04 +08:00
    guonaihong
        1
    guonaihong  
       204 天前
    你启个 websocket 或者 grpc stream 服务端。客户端不停读就行。
    helloword001
        2
    helloword001  
    OP
       204 天前
    w.Write([]byte(response.Choices[0].Delta.Content + "\n"))
    这种形式可以吗
    guonaihong
        3
    guonaihong  
       204 天前
    websocket 库可以玩下我写的,https://github.com/antlabs/quickws ,有使用上的问题帮你看看。
    guonaihong
        4
    guonaihong  
       204 天前
    @helloword001 你想用 http chunked 模拟?具体代码网上找找例子,这个也看客户端的开发能力,搞得定也行,缺点只能模拟单向流,s->c 侧的。websocket 和 grpc stream 是全双工的,c->s ,s->c 都行。
    dddd1919
        5
    dddd1919  
       204 天前
    sse
    helloword001
        6
    helloword001  
    OP
       204 天前
    @guonaihong openai "github.com/sashabaranov/go-openai"
    这个是 http 的,可以转 websocket 吗
    guonaihong
        7
    guonaihong  
       204 天前
    @helloword001 不能无缝转,要自己写代码。无论是 http chunked 模拟(也叫 sse),还是 websocket 或者 grpc 都要写点代码。
    helloword001
        8
    helloword001  
    OP
       204 天前
    @guonaihong 好的,谢谢大佬
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5672 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 03:17 · PVG 11:17 · LAX 20:17 · JFK 23:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.