(c *gin.Context, resp *http.Response)
| 300 | } |
| 301 | |
| 302 | func StreamHandler(c *gin.Context, resp *http.Response) (*model.ErrorWithStatusCode, string) { |
| 303 | responseText := "" |
| 304 | scanner := bufio.NewScanner(resp.Body) |
| 305 | scanner.Split(bufio.ScanLines) |
| 306 | |
| 307 | common.SetEventStreamHeaders(c) |
| 308 | |
| 309 | for scanner.Scan() { |
| 310 | data := scanner.Text() |
| 311 | data = strings.TrimSpace(data) |
| 312 | if !strings.HasPrefix(data, "data: ") { |
| 313 | continue |
| 314 | } |
| 315 | data = strings.TrimPrefix(data, "data: ") |
| 316 | data = strings.TrimSuffix(data, "\"") |
| 317 | |
| 318 | var geminiResponse ChatResponse |
| 319 | err := json.Unmarshal([]byte(data), &geminiResponse) |
| 320 | if err != nil { |
| 321 | logger.SysError("error unmarshalling stream response: " + err.Error()) |
| 322 | continue |
| 323 | } |
| 324 | |
| 325 | response := streamResponseGeminiChat2OpenAI(&geminiResponse) |
| 326 | if response == nil { |
| 327 | continue |
| 328 | } |
| 329 | |
| 330 | responseText += response.Choices[0].Delta.StringContent() |
| 331 | |
| 332 | err = render.ObjectData(c, response) |
| 333 | if err != nil { |
| 334 | logger.SysError(err.Error()) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | if err := scanner.Err(); err != nil { |
| 339 | logger.SysError("error reading stream: " + err.Error()) |
| 340 | } |
| 341 | |
| 342 | render.Done(c) |
| 343 | |
| 344 | err := resp.Body.Close() |
| 345 | if err != nil { |
| 346 | return openai.ErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), "" |
| 347 | } |
| 348 | |
| 349 | return nil, responseText |
| 350 | } |
| 351 | |
| 352 | func Handler(c *gin.Context, resp *http.Response, promptTokens int, modelName string) (*model.ErrorWithStatusCode, *model.Usage) { |
| 353 | responseBody, err := io.ReadAll(resp.Body) |
no test coverage detected