(c *gin.Context, resp *http.Response)
| 121 | } |
| 122 | |
| 123 | func aliStreamHandler(c *gin.Context, resp *http.Response) (*types.NewAPIError, *dto.Usage) { |
| 124 | var usage dto.Usage |
| 125 | scanner := bufio.NewScanner(resp.Body) |
| 126 | scanner.Split(bufio.ScanLines) |
| 127 | dataChan := make(chan string) |
| 128 | stopChan := make(chan bool) |
| 129 | go func() { |
| 130 | for scanner.Scan() { |
| 131 | data := scanner.Text() |
| 132 | if len(data) < 5 { // ignore blank line or wrong format |
| 133 | continue |
| 134 | } |
| 135 | if data[:5] != "data:" { |
| 136 | continue |
| 137 | } |
| 138 | data = data[5:] |
| 139 | dataChan <- data |
| 140 | } |
| 141 | stopChan <- true |
| 142 | }() |
| 143 | helper.SetEventStreamHeaders(c) |
| 144 | lastResponseText := "" |
| 145 | c.Stream(func(w io.Writer) bool { |
| 146 | select { |
| 147 | case data := <-dataChan: |
| 148 | var aliResponse AliResponse |
| 149 | err := json.Unmarshal([]byte(data), &aliResponse) |
| 150 | if err != nil { |
| 151 | common.SysError("error unmarshalling stream response: " + err.Error()) |
| 152 | return true |
| 153 | } |
| 154 | if aliResponse.Usage.OutputTokens != 0 { |
| 155 | usage.PromptTokens = aliResponse.Usage.InputTokens |
| 156 | usage.CompletionTokens = aliResponse.Usage.OutputTokens |
| 157 | usage.TotalTokens = aliResponse.Usage.InputTokens + aliResponse.Usage.OutputTokens |
| 158 | } |
| 159 | response := streamResponseAli2OpenAI(&aliResponse) |
| 160 | response.Choices[0].Delta.SetContentString(strings.TrimPrefix(response.Choices[0].Delta.GetContentString(), lastResponseText)) |
| 161 | lastResponseText = aliResponse.Output.Text |
| 162 | jsonResponse, err := json.Marshal(response) |
| 163 | if err != nil { |
| 164 | common.SysError("error marshalling stream response: " + err.Error()) |
| 165 | return true |
| 166 | } |
| 167 | c.Render(-1, common.CustomEvent{Data: "data: " + string(jsonResponse)}) |
| 168 | return true |
| 169 | case <-stopChan: |
| 170 | c.Render(-1, common.CustomEvent{Data: "data: [DONE]"}) |
| 171 | return false |
| 172 | } |
| 173 | }) |
| 174 | common.CloseResponseBodyGracefully(resp) |
| 175 | return nil, &usage |
| 176 | } |
| 177 | |
| 178 | func aliHandler(c *gin.Context, resp *http.Response) (*types.NewAPIError, *dto.Usage) { |
| 179 | var aliResponse AliResponse |
nothing calls this directly
no test coverage detected