GetResponseContent 获取响应内容
(c *gin.Context, isStream bool, resp *http.Response)
| 13 | |
| 14 | // GetResponseContent 获取响应内容 |
| 15 | func GetResponseContent(c *gin.Context, isStream bool, resp *http.Response) (string, string) { |
| 16 | if resp == nil { |
| 17 | return "", "" |
| 18 | } |
| 19 | |
| 20 | if !isStream { |
| 21 | respBody, err := io.ReadAll(resp.Body) |
| 22 | if err != nil { |
| 23 | logger.Errorf(c.Request.Context(), "read response body failed: %s", err.Error()) |
| 24 | return "", "" |
| 25 | } |
| 26 | // 重置响应体,以便后续处理 |
| 27 | resp.Body = io.NopCloser(bytes.NewBuffer(respBody)) |
| 28 | |
| 29 | // 尝试解析不同格式的响应内容 |
| 30 | var openaiResp struct { |
| 31 | Choices []struct { |
| 32 | Message struct { |
| 33 | Content string `json:"content"` |
| 34 | } `json:"message"` |
| 35 | Text string `json:"text"` |
| 36 | ReasoningContent string `json:"reasoning_content"` |
| 37 | } `json:"choices"` |
| 38 | Text string `json:"text"` |
| 39 | ReasoningContent string `json:"reasoning_content"` |
| 40 | } |
| 41 | |
| 42 | if err := json.Unmarshal(respBody, &openaiResp); err != nil { |
| 43 | logger.Errorf(c.Request.Context(), "unmarshal response failed: %s", err.Error()) |
| 44 | return string(respBody), "" |
| 45 | } |
| 46 | |
| 47 | // 优先检查 message.content (chat completions) |
| 48 | if len(openaiResp.Choices) > 0 { |
| 49 | if openaiResp.Choices[0].Message.Content != "" { |
| 50 | return openaiResp.Choices[0].Message.Content, openaiResp.Choices[0].ReasoningContent |
| 51 | } |
| 52 | if openaiResp.Choices[0].Text != "" { |
| 53 | return openaiResp.Choices[0].Text, openaiResp.Choices[0].ReasoningContent |
| 54 | } |
| 55 | if openaiResp.Choices[0].ReasoningContent != "" { |
| 56 | return "", openaiResp.Choices[0].ReasoningContent |
| 57 | } |
| 58 | } |
| 59 | if openaiResp.Text != "" { |
| 60 | return openaiResp.Text, openaiResp.ReasoningContent |
| 61 | } |
| 62 | if openaiResp.ReasoningContent != "" { |
| 63 | return "", openaiResp.ReasoningContent |
| 64 | } |
| 65 | return string(respBody), "" |
| 66 | } |
| 67 | |
| 68 | // 对于流式响应,从上下文中获取收集器 |
| 69 | collector, exists := c.Get("stream_response_collector") |
| 70 | if exists { |
| 71 | if streamCollector, ok := collector.(*StreamResponseCollector); ok { |
| 72 | return streamCollector.GetContent() |
nothing calls this directly
no test coverage detected