Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

feat(models): add shared HTTP client, SSE parser, and stub helpers for Go model drivers (#15821)

JPette1783daa381116534
diff --git a/internal/entity/models/302ai.go b/internal/entity/models/302ai.go
index 98c1140a80..641100470e 100644
--- a/internal/entity/models/302ai.go
+++ b/internal/entity/models/302ai.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -31,7 +30,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "time"
)
type AI302Model struct {
@@ -41,17 +39,9 @@ type AI302Model struct {
func NewAI302Model(baseURL map[string]string, urlSuffix URLSuffix) *AI302Model {
return &AI302Model{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: time.Second * 90,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -334,44 +324,20 @@ func (a *AI302Model) ChatStreamlyWithSender(modelName string, messages []Message
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- // SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -388,19 +354,14 @@ func (a *AI302Model) ChatStreamlyWithSender(modelName string, messages []Message
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
func (a *AI302Model) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/aliyun.go b/internal/entity/models/aliyun.go
index 29990326d5..a9c22e5e3f 100644
--- a/internal/entity/models/aliyun.go
+++ b/internal/entity/models/aliyun.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -26,7 +25,6 @@ import (
"net/http"
"ragflow/internal/common"
"strings"
- "time"
)
// AliyunModel implements ModelDriver for Aliyun
@@ -38,16 +36,9 @@ type AliyunModel struct {
func NewAliyunModel(baseURL map[string]string, urlSuffix URLSuffix) *AliyunModel {
return &AliyunModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -296,44 +287,22 @@ func (a *AliyunModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -350,19 +319,14 @@ func (a *AliyunModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
type aliyunEmbeddingResponse struct {
diff --git a/internal/entity/models/anthropic.go b/internal/entity/models/anthropic.go
index 2dc1112869..96a45a1b64 100644
--- a/internal/entity/models/anthropic.go
+++ b/internal/entity/models/anthropic.go
@@ -25,7 +25,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
const anthropicVersion = "2023-06-01"
@@ -37,19 +36,11 @@ type AnthropicModel struct {
}
func NewAnthropicModel(baseURL map[string]string, urlSuffix URLSuffix) *AnthropicModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &AnthropicModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/astraflow.go b/internal/entity/models/astraflow.go
index ffe2f909ad..cbc8a9793d 100644
--- a/internal/entity/models/astraflow.go
+++ b/internal/entity/models/astraflow.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// AstraflowModel implements ModelDriver for Astraflow (UCloud
@@ -51,20 +49,11 @@ type AstraflowModel struct {
// NewAstraflowModel creates a new Astraflow model instance.
func NewAstraflowModel(baseURL map[string]string, urlSuffix URLSuffix) *AstraflowModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &AstraflowModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -264,35 +253,19 @@ func (a *AstraflowModel) ChatStreamlyWithSender(modelName string, messages []Mes
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("astraflow: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
if apiErr, ok := event["error"]; ok {
return fmt.Errorf("astraflow: upstream stream error: %v", apiErr)
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if delta, ok := firstChoice["delta"].(map[string]interface{}); ok {
if r, ok := delta["reasoning_content"].(string); ok && r != "" {
@@ -310,14 +283,13 @@ func (a *AstraflowModel) ChatStreamlyWithSender(modelName string, messages []Mes
}
if finish, ok := firstChoice["finish_reason"].(string); ok && finish != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("astraflow: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/avian.go b/internal/entity/models/avian.go
index 35afd3063b..a85b1e3d81 100644
--- a/internal/entity/models/avian.go
+++ b/internal/entity/models/avian.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// AvianModel implements ModelDriver for Avian (https://api.avian.io/docs/).
@@ -34,21 +32,14 @@ type AvianModel struct {
}
// NewAvianModel creates a new Avian model instance.
+// NewDriverHTTPClient applies the same transport settings that were previously
+// set inline (MaxIdleConns, IdleConnTimeout, ResponseHeaderTimeout, etc.).
func NewAvianModel(baseURL map[string]string, urlSuffix URLSuffix) *AvianModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &AvianModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -238,32 +229,14 @@ func (a *AvianModel) ChatStreamlyWithSender(modelName string, messages []Message
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event avianChatResponse
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("avian: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[avianChatResponse](resp.Body, func(event avianChatResponse) error {
if event.Error != nil {
return fmt.Errorf("avian: upstream stream error: %v", event.Error)
}
if len(event.Choices) == 0 {
- continue
+ return nil
}
-
choice := event.Choices[0]
if reasoning := choice.Delta.ReasoningContent; reasoning != "" {
if err := sender(nil, &reasoning); err != nil {
@@ -281,13 +254,13 @@ func (a *AvianModel) ChatStreamlyWithSender(modelName string, messages []Message
}
if choice.FinishReason != "" || event.FinishReason != "" {
sawTerminal = true
- break
}
- }
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("avian: stream ended before [DONE] or finish_reason")
}
@@ -391,3 +364,4 @@ func (a *AvianModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) {
func (a *AvianModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) {
return nil, fmt.Errorf("%s, no such method", a.Name())
}
+
diff --git a/internal/entity/models/azure_openai.go b/internal/entity/models/azure_openai.go
index 4ff4234b0d..b6fd2dbb17 100644
--- a/internal/entity/models/azure_openai.go
+++ b/internal/entity/models/azure_openai.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// azureAPIVersion is the Azure OpenAI REST API version sent as the
@@ -38,20 +36,11 @@ type AzureOpenAIModel struct {
// NewAzureOpenAIModel creates a new Azure OpenAI model instance.
func NewAzureOpenAIModel(baseURL map[string]string, urlSuffix URLSuffix) *AzureOpenAIModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &AzureOpenAIModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -270,43 +259,21 @@ func (a *AzureOpenAIModel) ChatStreamlyWithSender(modelName string, messages []M
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- // SSE parsing: bump the scanner buffer to 1MB so a long data: line is
- // never silently truncated by the default 64KB cap.
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if reasoningContent, ok := delta["reasoning_content"].(string); ok && reasoningContent != "" {
@@ -323,14 +290,13 @@ func (a *AzureOpenAIModel) ChatStreamlyWithSender(modelName string, messages []M
if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("azure-openai: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/baichuan.go b/internal/entity/models/baichuan.go
index d8903d5375..d659eb82be 100644
--- a/internal/entity/models/baichuan.go
+++ b/internal/entity/models/baichuan.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -26,7 +25,6 @@ import (
"net/http"
"ragflow/internal/common"
"strings"
- "time"
)
type BaichuanModel struct {
@@ -36,16 +34,9 @@ type BaichuanModel struct {
func NewBaichuanModel(baseURL map[string]string, urlSuffix URLSuffix) *BaichuanModel {
return &BaichuanModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -255,44 +246,23 @@ func (b *BaichuanModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -304,17 +274,20 @@ func (b *BaichuanModel) ChatStreamlyWithSender(modelName string, messages []Mess
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("baichuan: stream ended before [DONE] or finish_reason")
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
func (b *BaichuanModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/baidu.go b/internal/entity/models/baidu.go
index 09d142b647..49ecf22636 100644
--- a/internal/entity/models/baidu.go
+++ b/internal/entity/models/baidu.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -27,7 +26,6 @@ import (
"net/http"
"ragflow/internal/common"
"strings"
- "time"
)
type BaiduModel struct {
@@ -41,16 +39,9 @@ func (b *BaiduModel) NewInstance(baseURL map[string]string) ModelDriver {
func NewBaiduModel(baseURL map[string]string, urlSuffix URLSuffix) *BaiduModel {
return &BaiduModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxConnsPerHost: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -357,44 +348,23 @@ func (b *BaiduModel) ChatStreamlyWithSender(modelName string, messages []Message
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -413,8 +383,16 @@ func (b *BaiduModel) ChatStreamlyWithSender(modelName string, messages []Message
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("baidu: stream ended before [DONE] or finish_reason")
}
// Send [DONE] marker for OpenAI compatibility
@@ -423,7 +401,7 @@ func (b *BaiduModel) ChatStreamlyWithSender(modelName string, messages []Message
return err
}
- return scanner.Err()
+ return nil
}
type baiduEmbeddingResponse struct {
diff --git a/internal/entity/models/base_model.go b/internal/entity/models/base_model.go
index 1e43849f08..24f202626f 100644
--- a/internal/entity/models/base_model.go
+++ b/internal/entity/models/base_model.go
@@ -17,9 +17,15 @@
package models
import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
"fmt"
+ "io"
"net/http"
"strings"
+ "time"
)
type BaseModel struct {
@@ -79,6 +85,31 @@ func (b *BaseModel) GetBaseURL(apiConfig *APIConfig) (string, error) {
return baseURL, nil
}
+// ParseSSEStream reads the body of an OpenAI-compatible Server-Sent Events
+// response and calls onEvent for each successfully-parsed JSON payload.
+func ParseSSEStream[T any](r io.Reader, onEvent func(event T) error) (done bool, err error) {
+ scanner := bufio.NewScanner(r)
+ scanner.Buffer(make([]byte, 64*1024), 1024*1024)
+ for scanner.Scan() {
+ line := scanner.Text()
+ if !strings.HasPrefix(line, "data:") {
+ continue
+ }
+ data := strings.TrimSpace(line[5:])
+ if data == "[DONE]" {
+ return true, nil
+ }
+ var event T
+ if err := json.Unmarshal([]byte(data), &event); err != nil {
+ continue
+ }
+ if err := onEvent(event); err != nil {
+ return false, err
+ }
+ }
+ return false, scanner.Err()
+}
+
// ParseListModel Parse model list
func ParseListModel(modelList ModelList) []ListModelResponse {
var models []ListModelResponse
@@ -107,3 +138,42 @@ func ParseListModel(modelList ModelList) []ListModelResponse {
}
return models
}
+
+// NewDriverHTTPClient returns an *http.Client with the standard connection-pool
+func NewDriverHTTPClient() *http.Client {
+ var t *http.Transport
+ if dt, ok := http.DefaultTransport.(*http.Transport); ok {
+ t = dt.Clone()
+ } else {
+ t = &http.Transport{Proxy: http.ProxyFromEnvironment}
+ }
+ t.MaxIdleConns = 100
+ t.MaxIdleConnsPerHost = 10
+ t.IdleConnTimeout = 90 * time.Second
+ t.DisableCompression = false
+ t.ResponseHeaderTimeout = 60 * time.Second
+ return &http.Client{Transport: t}
+}
+
+// PostJSONRequest marshals body to JSON, creates a POST request to url
+func PostJSONRequest(ctx context.Context, client *http.Client, url, auth string, body map[string]interface{}) (*http.Response, error) {
+ data, err := json.Marshal(body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(data))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ if auth != "" {
+ req.Header.Set("Authorization", auth)
+ }
+ return client.Do(req)
+}
+
+// ReadErrorBody reads all bytes from r and returns them as a string suitable
+func ReadErrorBody(r io.Reader) string {
+ b, _ := io.ReadAll(r)
+ return string(b)
+}
diff --git a/internal/entity/models/bedrock.go b/internal/entity/models/bedrock.go
index e4d8debbda..760e801fe0 100644
--- a/internal/entity/models/bedrock.go
+++ b/internal/entity/models/bedrock.go
@@ -98,32 +98,12 @@ type BedrockModel struct {
}
// NewBedrockModel creates a new Bedrock model instance.
-//
-// We clone http.DefaultTransport to keep Go's defaults for
-// ProxyFromEnvironment, DialContext (with KeepAlive), HTTP/2,
-// TLSHandshakeTimeout, and ExpectContinueTimeout, and only override
-// the connection-pool fields we care about.
-//
-// The Client itself has no overall Timeout because Bedrock
-// Converse-Stream is long-lived. http.Client.Timeout would also cap
-// time spent reading the response body, cutting off mid-stream.
-// Non-streaming callers wrap each request in context.WithTimeout
-// instead, and ResponseHeaderTimeout still caps connection setup.
func NewBedrockModel(baseURL map[string]string, urlSuffix URLSuffix) *BedrockModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &BedrockModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/cohere.go b/internal/entity/models/cohere.go
index 8c27b12571..985a17b03c 100644
--- a/internal/entity/models/cohere.go
+++ b/internal/entity/models/cohere.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -44,7 +43,7 @@ func NewCoHereModel(baseURL map[string]string, urlSuffix URLSuffix) *CoHereModel
baseModel: BaseModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
- httpClient: &http.Client{},
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -286,45 +285,30 @@ func (c *CoHereModel) ChatStreamlyWithSender(modelName string, messages []Messag
return fmt.Errorf("Cohere stream API error %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- data := strings.TrimSpace(line)
-
- if strings.HasPrefix(data, "data:") {
- data = strings.TrimSpace(data[5:])
- }
-
- if data == "" || data == "[DONE]" {
- continue
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
eventType, ok := event["type"].(string)
if !ok {
- continue
+ return nil
}
if eventType == "message-end" {
- break
+ sawTerminal = true
+ return nil
}
if eventType == "content-delta" {
delta, ok := event["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
msg, ok := delta["message"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := msg["content"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if thinking, ok := content["thinking"].(string); ok && thinking != "" {
@@ -339,14 +323,17 @@ func (c *CoHereModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
}
}
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
-
- endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
+ if !done && !sawTerminal {
+ return fmt.Errorf("Cohere: stream ended before [DONE] or finish_reason")
}
- return scanner.Err()
+ endOfStream := "[DONE]"
+ return sender(&endOfStream, nil)
}
func (c *CoHereModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/cometapi.go b/internal/entity/models/cometapi.go
index e538d1f73d..6af140e969 100644
--- a/internal/entity/models/cometapi.go
+++ b/internal/entity/models/cometapi.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -30,7 +29,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "time"
)
// CometAPIModel implements ModelDriver for CometAPI AI.
@@ -40,20 +38,11 @@ type CometAPIModel struct {
// NewCometAPIModel creates a new CometAPI model instance.
func NewCometAPIModel(baseURL map[string]string, urlSuffix URLSuffix) *CometAPIModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &CometAPIModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -334,27 +323,14 @@ func (c *CometAPIModel) ChatStreamlyWithSender(modelName string, messages []Mess
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- content, reasoningContent, terminal, ok := parseCometAPIStreamEvent(data)
- if !ok {
- continue
+ done, err := ParseSSEStream[cometapiChatResponsePayload](resp.Body, func(event cometapiChatResponsePayload) error {
+ if len(event.Choices) == 0 {
+ return nil
}
+ choice := event.Choices[0]
+ reasoningContent := choice.Delta.ReasoningContent
+ content := choice.Delta.Content
if reasoningContent != "" {
if err := sender(nil, &reasoningContent); err != nil {
@@ -368,16 +344,15 @@ func (c *CometAPIModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
}
- if terminal {
+ if choice.FinishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("cometapi: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/deepinfra.go b/internal/entity/models/deepinfra.go
index fe8f75c9ee..39c44283c5 100644
--- a/internal/entity/models/deepinfra.go
+++ b/internal/entity/models/deepinfra.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -32,7 +31,6 @@ import (
"slices"
"strconv"
"strings"
- "time"
)
type DeepInfraModel struct {
@@ -42,16 +40,9 @@ type DeepInfraModel struct {
func NewDeepInfraModel(baseURL map[string]string, urlSuffix URLSuffix) *DeepInfraModel {
return &DeepInfraModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: time.Second * 90,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -296,45 +287,23 @@ func (d *DeepInfraModel) ChatStreamlyWithSender(modelName string, messages []Mes
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- // SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -353,17 +322,20 @@ func (d *DeepInfraModel) ChatStreamlyWithSender(modelName string, messages []Mes
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("deepinfra: stream ended before [DONE] or finish_reason")
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
func (d *DeepInfraModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/deepseek.go b/internal/entity/models/deepseek.go
index da17298aaa..47be9d9e41 100644
--- a/internal/entity/models/deepseek.go
+++ b/internal/entity/models/deepseek.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -27,7 +26,6 @@ import (
"ragflow/internal/common"
"strconv"
"strings"
- "time"
)
// DeepSeekModel implements ModelDriver for DeepSeek
@@ -39,16 +37,9 @@ type DeepSeekModel struct {
func NewDeepSeekModel(baseURL map[string]string, urlSuffix URLSuffix) *DeepSeekModel {
return &DeepSeekModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -361,44 +352,23 @@ func (d *DeepSeekModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -417,17 +387,20 @@ func (d *DeepSeekModel) ChatStreamlyWithSender(modelName string, messages []Mess
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("deepseek: stream ended before [DONE] or finish_reason")
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
// Embed embeds a list of texts into embeddings
diff --git a/internal/entity/models/fishaudio.go b/internal/entity/models/fishaudio.go
index d19ed81fac..631f3b291a 100644
--- a/internal/entity/models/fishaudio.go
+++ b/internal/entity/models/fishaudio.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -41,7 +40,7 @@ func NewFishAudioModel(baseURL map[string]string, urlSuffix URLSuffix) *FishAudi
baseModel: BaseModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
- httpClient: &http.Client{},
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -301,29 +300,11 @@ func (f *FishAudioModel) AudioSpeechWithSender(modelName *string, audioContent *
return fmt.Errorf("FishAudio stream API error: %d - %s", resp.StatusCode, string(buf[:n]))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
-
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data: ") {
- continue
- }
-
- dataStr := strings.TrimSpace(line[6:])
- if dataStr == "" {
- continue
- }
-
- var event struct {
- AudioBase64 string `json:"audio_base64"`
- }
-
- if err := json.Unmarshal([]byte(dataStr), &event); err != nil {
- continue
- }
-
+ if _, err := ParseSSEStream[struct {
+ AudioBase64 string `json:"audio_base64"`
+ }](resp.Body, func(event struct {
+ AudioBase64 string `json:"audio_base64"`
+ }) error {
if event.AudioBase64 != "" {
audioBytes, err := base64.StdEncoding.DecodeString(event.AudioBase64)
if err == nil && len(audioBytes) > 0 {
@@ -333,10 +314,9 @@ func (f *FishAudioModel) AudioSpeechWithSender(modelName *string, audioContent *
}
}
}
- }
-
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("error reading FishAudio stream: %w", err)
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
return nil
diff --git a/internal/entity/models/futurmix.go b/internal/entity/models/futurmix.go
index 280a91baa6..f0fef4b2a0 100644
--- a/internal/entity/models/futurmix.go
+++ b/internal/entity/models/futurmix.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// FuturMixModel implements ModelDriver for FuturMix
@@ -35,20 +33,11 @@ type FuturMixModel struct {
// NewFuturMixModel creates a new FuturMix model instance.
func NewFuturMixModel(baseURL map[string]string, urlSuffix URLSuffix) *FuturMixModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &FuturMixModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -261,90 +250,38 @@ func (f *FuturMixModel) ChatStreamlyWithSender(modelName string, messages []Mess
return fmt.Errorf("futurmix chat stream API error: %s, body: %s", resp.Status, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
-
- var dataLines []string
- dispatchEvent := func() (bool, error) {
- if len(dataLines) == 0 {
- return false, nil
- }
- payload := strings.Join(dataLines, "\n")
- dataLines = dataLines[:0]
- if payload == "[DONE]" {
- sawTerminal = true
- return true, nil
- }
-
- var event futurmixChatResponse
- if err := json.Unmarshal([]byte(payload), &event); err != nil {
- return false, fmt.Errorf("futurmix: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[futurmixChatResponse](resp.Body, func(event futurmixChatResponse) error {
if len(event.Choices) == 0 {
- return false, nil
+ return nil
}
choice := event.Choices[0]
if choice.Delta.ReasoningContent != "" {
r := choice.Delta.ReasoningContent
if err := sender(nil, &r); err != nil {
- return false, err
+ return err
}
}
if choice.Delta.Content != "" {
c := choice.Delta.Content
if err := sender(&c, nil); err != nil {
- return false, err
+ return err
}
}
if choice.FinishReason != "" {
sawTerminal = true
- return true, nil
}
- return false, nil
- }
-
- for scanner.Scan() {
- line := scanner.Text()
- if line == "" {
- // Blank line == event terminator. Flush accumulated `data:`
- // lines as a single JSON payload.
- stop, err := dispatchEvent()
- if err != nil {
- return err
- }
- if stop {
- break
- }
- continue
- }
- if strings.HasPrefix(line, "data:") {
-
- value := line[5:]
- if strings.HasPrefix(value, " ") {
- value = value[1:]
- }
- dataLines = append(dataLines, value)
- }
- }
- if !sawTerminal {
- if _, err := dispatchEvent(); err != nil {
- return err
- }
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("futurmix: stream ended before [DONE] or finish_reason")
}
endOfStream := "[DONE]"
- if err := sender(&endOfStream, nil); err != nil {
- return err
- }
- return nil
+ return sender(&endOfStream, nil)
}
// Embed is not exposed by the FuturMix API per the public docs.
diff --git a/internal/entity/models/gitee.go b/internal/entity/models/gitee.go
index cc49990148..130a625614 100644
--- a/internal/entity/models/gitee.go
+++ b/internal/entity/models/gitee.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -39,16 +38,9 @@ type GiteeModel struct {
func NewGiteeModel(baseURL map[string]string, urlSuffix URLSuffix) *GiteeModel {
return &GiteeModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -314,58 +306,35 @@ func (g *GiteeModel) ChatStreamlyWithSender(modelName string, messages []Message
reserveText := ""
thinkingPhase := false
answerPhase := false
+ sawTerminal := false
- // SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
if ok && content != "" {
+ common.Info(content)
if content == "<think>" {
thinkingPhase = true
- continue
+ return nil
} else if content == "</think>" {
thinkingPhase = false
answerPhase = true
- continue
+ return nil
}
if thinkingPhase {
@@ -389,8 +358,15 @@ func (g *GiteeModel) ChatStreamlyWithSender(modelName string, messages []Message
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("gitee: stream ended before [DONE] or finish_reason")
}
if reserveText != "" {
@@ -405,7 +381,7 @@ func (g *GiteeModel) ChatStreamlyWithSender(modelName string, messages []Message
return err
}
- return scanner.Err()
+ return nil
}
type giteeEmbeddingResponse struct {
diff --git a/internal/entity/models/gitee_test.go b/internal/entity/models/gitee_test.go
index c83ca947fa..33839891ac 100644
--- a/internal/entity/models/gitee_test.go
+++ b/internal/entity/models/gitee_test.go
@@ -94,7 +94,7 @@ func TestGiteeListModelsMapsAllDeepSeekAliasesToModelMetadata(t *testing.T) {
t.Errorf("Content-Type=%q, want application/json", got)
}
- resp := DSModelList{
+ resp := ModelList{
Object: "list",
Models: make([]DSModel, 0, len(aliases)+1),
}
diff --git a/internal/entity/models/gpustack.go b/internal/entity/models/gpustack.go
index f369ff5ae6..e6d5361fe7 100644
--- a/internal/entity/models/gpustack.go
+++ b/internal/entity/models/gpustack.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// GPUStackModel implements ModelDriver for GPUStack
@@ -34,21 +32,12 @@ type GPUStackModel struct {
}
func NewGPUStackModel(baseURL map[string]string, urlSuffix URLSuffix) *GPUStackModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &GPUStackModel{
baseModel: BaseModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: transport,
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -254,43 +243,23 @@ func (g *GPUStackModel) ChatStreamlyWithSender(modelName string, messages []Mess
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("gpustack: invalid SSE event: %w", err)
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
if apiErr, ok := event["error"]; ok {
return fmt.Errorf("gpustack: upstream stream error: %v", apiErr)
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if r, ok := delta["reasoning_content"].(string); ok && r != "" {
@@ -309,14 +278,13 @@ func (g *GPUStackModel) ChatStreamlyWithSender(modelName string, messages []Mess
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("gpustack: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/groq.go b/internal/entity/models/groq.go
index 33e6978989..9e8618aa68 100644
--- a/internal/entity/models/groq.go
+++ b/internal/entity/models/groq.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -29,7 +28,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "time"
)
// GroqModel implements ModelDriver for Groq.
@@ -38,28 +36,11 @@ type GroqModel struct {
}
func NewGroqModel(baseURL map[string]string, urlSuffix URLSuffix) *GroqModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &GroqModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -261,30 +242,13 @@ func (g *GroqModel) ChatStreamlyWithSender(modelName string, messages []Message,
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event groqChatResponse
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("groq: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[groqChatResponse](resp.Body, func(event groqChatResponse) error {
if event.Error != nil {
return fmt.Errorf("groq: upstream stream error: %v", event.Error)
}
if len(event.Choices) == 0 {
- continue
+ return nil
}
choice := event.Choices[0]
@@ -304,13 +268,13 @@ func (g *GroqModel) ChatStreamlyWithSender(modelName string, messages []Message,
}
if choice.FinishReason != "" || event.FinishReason != "" {
sawTerminal = true
- break
}
- }
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("groq: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/huaweicloud.go b/internal/entity/models/huaweicloud.go
index b9c50342d5..ff15ba0957 100644
--- a/internal/entity/models/huaweicloud.go
+++ b/internal/entity/models/huaweicloud.go
@@ -17,14 +17,12 @@
package models
import (
- "bufio"
"bytes"
"context"
"fmt"
"io"
"net/http"
"strings"
- "time"
"github.com/goccy/go-json"
)
@@ -36,16 +34,9 @@ type HuaweiCloudModel struct {
func NewHuaweiCloudModel(baseURL map[string]string, urlSuffix URLSuffix) *HuaweiCloudModel {
return &HuaweiCloudModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -343,40 +334,23 @@ func (h *HuaweiCloudModel) ChatStreamlyWithSender(modelName string, messages []M
return fmt.Errorf("Huawei Cloud stream API error: status %d, body: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("huaweicloud: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
if apiErr, ok := event["error"]; ok {
return fmt.Errorf("huaweicloud: upstream stream error: %v", apiErr)
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if r, ok := delta["reasoning_content"].(string); ok && r != "" {
@@ -391,14 +365,13 @@ func (h *HuaweiCloudModel) ChatStreamlyWithSender(modelName string, messages []M
}
if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("huaweicloud: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/huggingface.go b/internal/entity/models/huggingface.go
index 4744a44164..f8b0f95717 100644
--- a/internal/entity/models/huggingface.go
+++ b/internal/entity/models/huggingface.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"ragflow/internal/common"
- "strings"
)
// HuggingFaceModel implements ModelDriver for HuggingFace
@@ -39,7 +37,7 @@ func NewHuggingFaceModel(baseURL map[string]string, urlSuffix URLSuffix) *Huggin
baseModel: BaseModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
- httpClient: &http.Client{},
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -288,45 +286,22 @@ func (h *HuggingFaceModel) ChatStreamlyWithSender(modelName string, messages []M
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- // SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -343,19 +318,14 @@ func (h *HuggingFaceModel) ChatStreamlyWithSender(modelName string, messages []M
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
func (h *HuggingFaceModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/hunyuan.go b/internal/entity/models/hunyuan.go
index 0799ac28f0..096892fc86 100644
--- a/internal/entity/models/hunyuan.go
+++ b/internal/entity/models/hunyuan.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// HunyuanModel implements ModelDriver for Tencent Hunyuan
@@ -35,20 +33,11 @@ type HunyuanModel struct {
// NewHunyuanModel creates a new Hunyuan model instance.
func NewHunyuanModel(baseURL map[string]string, urlSuffix URLSuffix) *HunyuanModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &HunyuanModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -245,36 +234,19 @@ func (h *HunyuanModel) ChatStreamlyWithSender(modelName string, messages []Messa
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("hunyuan: invalid SSE event: %w", err)
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
if apiErr, ok := event["error"]; ok {
return fmt.Errorf("hunyuan: upstream stream error: %v", apiErr)
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if delta, ok := firstChoice["delta"].(map[string]interface{}); ok {
if r, ok := delta["reasoning_content"].(string); ok && r != "" {
@@ -292,14 +264,13 @@ func (h *HunyuanModel) ChatStreamlyWithSender(modelName string, messages []Messa
}
if finish, ok := firstChoice["finish_reason"].(string); ok && finish != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("hunyuan: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/jiekouai.go b/internal/entity/models/jiekouai.go
index c4d3a9e585..8c7f8a4876 100644
--- a/internal/entity/models/jiekouai.go
+++ b/internal/entity/models/jiekouai.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"encoding/json"
"fmt"
@@ -32,19 +31,16 @@ type JieKouAIModel struct {
}
func NewJieKouAIModel(baseURL map[string]string, urlSuffix URLSuffix) *JieKouAIModel {
+ // JieKouAI's methods issue requests without a per-call context deadline, so
+ // keep an explicit 120s client-level timeout to bound them. Built on the
+ // shared transport via NewDriverHTTPClient.
+ client := NewDriverHTTPClient()
+ client.Timeout = 120 * time.Second
return &JieKouAIModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Timeout: time.Second * 120,
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxConnsPerHost: 100,
- IdleConnTimeout: time.Second * 90,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: client,
},
}
}
@@ -291,43 +287,20 @@ func (j *JieKouAIModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -344,10 +317,9 @@ func (j *JieKouAIModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -356,7 +328,7 @@ func (j *JieKouAIModel) ChatStreamlyWithSender(modelName string, messages []Mess
return err
}
- return scanner.Err()
+ return nil
}
func (j *JieKouAIModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/jina.go b/internal/entity/models/jina.go
index f83e92246d..7eaf3b8cb3 100644
--- a/internal/entity/models/jina.go
+++ b/internal/entity/models/jina.go
@@ -32,13 +32,16 @@ type JinaModel struct {
}
func NewJinaModel(baseURL map[string]string, urlSuffix URLSuffix) *JinaModel {
+ // Embed/Rerank/ListModels issue requests without a per-call context
+ // deadline, so keep an explicit 90s client-level timeout to bound them.
+ // Built on the shared transport via NewDriverHTTPClient.
+ client := NewDriverHTTPClient()
+ client.Timeout = 90 * time.Second
return &JinaModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Timeout: time.Second * 90,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: client,
},
}
}
diff --git a/internal/entity/models/lmstudio.go b/internal/entity/models/lmstudio.go
index f7f6a6959e..f3e3ac7818 100644
--- a/internal/entity/models/lmstudio.go
+++ b/internal/entity/models/lmstudio.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -26,7 +25,6 @@ import (
"net/http"
"ragflow/internal/common"
"strings"
- "time"
)
// LmStudioModel implements ModelDriver for lm-studio
@@ -41,14 +39,7 @@ func NewLmStudioModel(baseURL map[string]string, urlSuffix URLSuffix) *LmStudioM
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -314,44 +305,22 @@ func (l *LmStudioModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -368,10 +337,9 @@ func (l *LmStudioModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -380,7 +348,7 @@ func (l *LmStudioModel) ChatStreamlyWithSender(modelName string, messages []Mess
return err
}
- return scanner.Err()
+ return nil
}
func (l *LmStudioModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/localai.go b/internal/entity/models/localai.go
index 286d9d07d6..8112c2d1d1 100644
--- a/internal/entity/models/localai.go
+++ b/internal/entity/models/localai.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -39,21 +38,12 @@ type LocalAIModel struct {
// NewLocalAIModel creates a new LocalAI model instance
func NewLocalAIModel(baseURL map[string]string, urlSuffix URLSuffix) *LocalAIModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &LocalAIModel{
baseModel: BaseModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: transport,
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -309,45 +299,25 @@ func (l *LocalAIModel) ChatStreamlyWithSender(modelName string, messages []Messa
}
}()
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
+ streamDone, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
lastActiveMu.Lock()
lastActive = time.Now()
lastActiveMu.Unlock()
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if reasoning := extractLocalAIReasoning(delta); reasoning != "" {
@@ -366,17 +336,16 @@ func (l *LocalAIModel) ChatStreamlyWithSender(modelName string, messages []Messa
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
if ctx.Err() != nil {
return fmt.Errorf("localai: stream idle for more than %s, aborted", localAIStreamIdleTimeout)
}
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !streamDone && !sawTerminal {
return fmt.Errorf("localai: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/longcat.go b/internal/entity/models/longcat.go
index 9a8ad6bb01..71612b9288 100644
--- a/internal/entity/models/longcat.go
+++ b/internal/entity/models/longcat.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// LongCatModel implements ModelDriver for LongCat (Meituan).
@@ -35,28 +33,11 @@ type LongCatModel struct {
// NewLongCatModel creates a new LongCat model instance.
func NewLongCatModel(baseURL map[string]string, urlSuffix URLSuffix) *LongCatModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &LongCatModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -261,45 +242,25 @@ func (l *LongCatModel) ChatStreamlyWithSender(modelName string, messages []Messa
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("longcat: invalid SSE event: %w", err)
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
if apiErr, ok := event["error"]; ok {
return fmt.Errorf("longcat: upstream stream error: %v", apiErr)
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if r, ok := delta["reasoning_content"].(string); ok && r != "" {
@@ -318,14 +279,13 @@ func (l *LongCatModel) ChatStreamlyWithSender(modelName string, messages []Messa
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("longcat: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/mineru.go b/internal/entity/models/mineru.go
index 7a7e0da624..60604e67b1 100644
--- a/internal/entity/models/mineru.go
+++ b/internal/entity/models/mineru.go
@@ -23,7 +23,6 @@ import (
"fmt"
"io"
"net/http"
- "time"
)
type MinerUModel struct {
@@ -33,16 +32,9 @@ type MinerUModel struct {
func NewMinerUModel(baseURL map[string]string, urlSuffix URLSuffix) *MinerUModel {
return &MinerUModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: time.Second * 90,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/mineru_local.go b/internal/entity/models/mineru_local.go
index 5fdd61b2e2..b88a7f7fc7 100644
--- a/internal/entity/models/mineru_local.go
+++ b/internal/entity/models/mineru_local.go
@@ -24,7 +24,6 @@ import (
"io"
"mime/multipart"
"net/http"
- "time"
)
type MinerULocalModel struct {
@@ -37,14 +36,7 @@ func NewMinerLocalUModel(baseURL map[string]string, urlSuffix URLSuffix) *MinerU
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: time.Second * 90,
- DisableCompression: false,
- },
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/minimax.go b/internal/entity/models/minimax.go
index b59ec2051b..8e0b5337b7 100644
--- a/internal/entity/models/minimax.go
+++ b/internal/entity/models/minimax.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/hex"
@@ -26,7 +25,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// MinimaxModel implements ModelDriver for Minimax
@@ -38,16 +36,9 @@ type MinimaxModel struct {
func NewMinimaxModel(baseURL map[string]string, urlSuffix URLSuffix) *MinimaxModel {
return &MinimaxModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -315,43 +306,21 @@ func (m *MinimaxModel) ChatStreamlyWithSender(modelName string, messages []Messa
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
-
- // SSE data line start with data:
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after data:
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err := json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -370,17 +339,21 @@ func (m *MinimaxModel) ChatStreamlyWithSender(modelName string, messages []Messa
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("minimax: stream ended before [DONE] or finish_reason")
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
// Embed embeds a list of texts into embeddings
@@ -617,32 +590,14 @@ func (m *MinimaxModel) AudioSpeechWithSender(modelName *string, audioContent *st
return fmt.Errorf("MiniMax stream TTS API error: %d, body: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 2*1024*1024)
-
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- dataStr := strings.TrimSpace(line[5:])
- if dataStr == "" {
- continue
- }
-
- var event struct {
- Data struct {
- Audio string `json:"audio"`
- Status int `json:"status"`
- } `json:"data"`
- }
-
- if err := json.Unmarshal([]byte(dataStr), &event); err != nil {
- continue
- }
+ type minimaxTTSEvent struct {
+ Data struct {
+ Audio string `json:"audio"`
+ Status int `json:"status"`
+ } `json:"data"`
+ }
+ if _, err := ParseSSEStream[minimaxTTSEvent](resp.Body, func(event minimaxTTSEvent) error {
if event.Data.Audio != "" {
audioBytes, err := hex.DecodeString(event.Data.Audio)
if err == nil && len(audioBytes) > 0 {
@@ -653,13 +608,9 @@ func (m *MinimaxModel) AudioSpeechWithSender(modelName *string, audioContent *st
}
}
- if event.Data.Status == 2 {
- break
- }
- }
-
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("error reading minimax stream: %w", err)
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
return nil
diff --git a/internal/entity/models/mistral.go b/internal/entity/models/mistral.go
index 0daaee0313..bc674a671d 100644
--- a/internal/entity/models/mistral.go
+++ b/internal/entity/models/mistral.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -37,20 +36,11 @@ type MistralModel struct {
// NewMistralModel creates a new Mistral model instance.
func NewMistralModel(baseURL map[string]string, urlSuffix URLSuffix) *MistralModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &MistralModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -294,43 +284,21 @@ func (m *MistralModel) ChatStreamlyWithSender(modelName string, messages []Messa
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- // SSE parsing: bump the scanner buffer from the 64KB default to 1MB
- // so we never silently truncate a long data: line.
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -343,14 +311,13 @@ func (m *MistralModel) ChatStreamlyWithSender(modelName string, messages []Messa
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("mistral: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/modelscope.go b/internal/entity/models/modelscope.go
index 2d2ff85467..97d1d55515 100644
--- a/internal/entity/models/modelscope.go
+++ b/internal/entity/models/modelscope.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -56,29 +55,12 @@ type modelscopeModelListResponse struct {
// NewModelScopeModel creates a new ModelScope model instance.
func NewModelScopeModel(baseURL map[string]string, urlSuffix URLSuffix) *ModelScopeModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &ModelScopeModel{
baseModel: BaseModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: transport,
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -301,36 +283,19 @@ func (m *ModelScopeModel) ChatStreamlyWithSender(modelName string, messages []Me
}
}()
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
+ streamDone, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
lastActiveMu.Lock()
lastActive = time.Now()
lastActiveMu.Unlock()
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if delta, ok := firstChoice["delta"].(map[string]interface{}); ok {
@@ -348,17 +313,16 @@ func (m *ModelScopeModel) ChatStreamlyWithSender(modelName string, messages []Me
if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
if ctx.Err() != nil {
return fmt.Errorf("modelscope: stream idle for more than %s, aborted", modelscopeStreamIdleTimeout)
}
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !streamDone && !sawTerminal {
return fmt.Errorf("modelscope: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/moonshot.go b/internal/entity/models/moonshot.go
index 4763c3118e..b551e8c529 100644
--- a/internal/entity/models/moonshot.go
+++ b/internal/entity/models/moonshot.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// MoonshotModel implements ModelDriver for Moonshot
@@ -37,16 +35,9 @@ type MoonshotModel struct {
func NewMoonshotModel(baseURL map[string]string, urlSuffix URLSuffix) *MoonshotModel {
return &MoonshotModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -308,43 +299,21 @@ func (m *MoonshotModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -363,12 +332,16 @@ func (m *MoonshotModel) ChatStreamlyWithSender(modelName string, messages []Mess
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
- }
- if err = scanner.Err(); err != nil {
- return err
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("moonshot: stream ended before [DONE] or finish_reason")
}
// Send [DONE] marker for OpenAI compatibility
diff --git a/internal/entity/models/n1n.go b/internal/entity/models/n1n.go
index b66e24ea8c..9ea47eb3df 100644
--- a/internal/entity/models/n1n.go
+++ b/internal/entity/models/n1n.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// N1NModel implements ModelDriver for n1n.ai
@@ -35,28 +33,11 @@ type N1NModel struct {
// NewN1NModel creates a new n1n.ai model instance.
func NewN1NModel(baseURL map[string]string, urlSuffix URLSuffix) *N1NModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &N1NModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -285,26 +266,10 @@ func (n *N1NModel) ChatStreamlyWithSender(modelName string, messages []Message,
return fmt.Errorf("n1n chat stream API error: %s, body: %s", resp.Status, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event n1nChatResponse
- if err := json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("n1n: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[n1nChatResponse](resp.Body, func(event n1nChatResponse) error {
if len(event.Choices) == 0 {
- continue
+ return nil
}
choice := event.Choices[0]
if choice.Delta.ReasoningContent != "" {
@@ -321,14 +286,13 @@ func (n *N1NModel) ChatStreamlyWithSender(modelName string, messages []Message,
}
if choice.FinishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("n1n: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/novita.go b/internal/entity/models/novita.go
index 2b86005afb..15581ab40e 100644
--- a/internal/entity/models/novita.go
+++ b/internal/entity/models/novita.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -26,7 +25,6 @@ import (
"net/http"
"strconv"
"strings"
- "time"
)
// NovitaModel implements ModelDriver for Novita.ai
@@ -36,28 +34,11 @@ type NovitaModel struct {
// NewNovitaModel creates a new Novita model instance.
func NewNovitaModel(baseURL map[string]string, urlSuffix URLSuffix) *NovitaModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &NovitaModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -428,35 +409,20 @@ func (n *NovitaModel) ChatStreamlyWithSender(modelName string, messages []Messag
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
extractor := &novitaThinkExtractor{}
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
// deepseek-v3.1 / glm-4.5 (and other models that emit reasoning
// separately) put chain-of-thought in delta.reasoning_content
@@ -488,8 +454,11 @@ func (n *NovitaModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
if finish, ok := firstChoice["finish_reason"].(string); ok && finish != "" {
sawTerminal = true
- break
}
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Flush any buffered tail (rare, but covers the case where the
@@ -510,10 +479,7 @@ func (n *NovitaModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
}
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("failed to scan response body: %w", err)
- }
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("novita: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/nvidia.go b/internal/entity/models/nvidia.go
index f560d07245..90752fd781 100644
--- a/internal/entity/models/nvidia.go
+++ b/internal/entity/models/nvidia.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// NvidiaModel implements ModelDriver for Nvidia
@@ -37,16 +35,9 @@ type NvidiaModel struct {
func NewNvidiaModel(baseURL map[string]string, urlSuffix URLSuffix) *NvidiaModel {
return &NvidiaModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -282,38 +273,20 @@ func (n *NvidiaModel) ChatStreamlyWithSender(modelName string, messages []Messag
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -330,10 +303,9 @@ func (n *NvidiaModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
endOfStream := "[DONE]"
@@ -341,7 +313,7 @@ func (n *NvidiaModel) ChatStreamlyWithSender(modelName string, messages []Messag
return err
}
- return scanner.Err()
+ return nil
}
type nvidiaEmbeddingResponse struct {
diff --git a/internal/entity/models/ollama.go b/internal/entity/models/ollama.go
index a189aa6146..86bc80b91a 100644
--- a/internal/entity/models/ollama.go
+++ b/internal/entity/models/ollama.go
@@ -25,7 +25,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// OllamaModel implements ModelDriver for Ollama AI
@@ -60,14 +59,7 @@ func NewOllamaModel(baseURL map[string]string, urlSuffix URLSuffix) *OllamaModel
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/openai.go b/internal/entity/models/openai.go
index 7159edbaac..f5010da859 100644
--- a/internal/entity/models/openai.go
+++ b/internal/entity/models/openai.go
@@ -30,7 +30,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "time"
)
// OpenAIModel implements ModelDriver for OpenAI (GPT models).
@@ -40,20 +39,11 @@ type OpenAIModel struct {
// NewOpenAIModel creates a new OpenAI model instance.
func NewOpenAIModel(baseURL map[string]string, urlSuffix URLSuffix) *OpenAIModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &OpenAIModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -272,45 +262,21 @@ func (o *OpenAIModel) ChatStreamlyWithSender(modelName string, messages []Messag
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of the stream
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -330,14 +296,13 @@ func (o *OpenAIModel) ChatStreamlyWithSender(modelName string, messages []Messag
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("openai: stream ended before [DONE] or finish_reason")
}
@@ -585,31 +550,15 @@ func (o *OpenAIModel) TranscribeAudioWithSender(modelName *string, file *string,
}
sentDelta := false
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data: ") {
- continue
- }
-
- dataStr := strings.TrimSpace(line[6:])
- if dataStr == "" {
- continue
- }
- if dataStr == "[DONE]" {
- break
- }
-
- var event struct {
- Type string `json:"type"`
- Delta string `json:"delta"`
- Text string `json:"text"`
- }
- if err = json.Unmarshal([]byte(dataStr), &event); err != nil {
- continue
- }
-
+ if _, err = ParseSSEStream[struct {
+ Type string `json:"type"`
+ Delta string `json:"delta"`
+ Text string `json:"text"`
+ }](resp.Body, func(event struct {
+ Type string `json:"type"`
+ Delta string `json:"delta"`
+ Text string `json:"text"`
+ }) error {
switch {
case event.Delta != "":
if err = sender(&event.Delta, nil); err != nil {
@@ -626,8 +575,8 @@ func (o *OpenAIModel) TranscribeAudioWithSender(modelName *string, file *string,
return err
}
}
- }
- if err = scanner.Err(); err != nil {
+ return nil
+ }); err != nil {
return fmt.Errorf("error reading OpenAI ASR stream: %w", err)
}
diff --git a/internal/entity/models/openrouter.go b/internal/entity/models/openrouter.go
index 0122c5d0e8..adbf0a4a4f 100644
--- a/internal/entity/models/openrouter.go
+++ b/internal/entity/models/openrouter.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -29,7 +28,6 @@ import (
"path/filepath"
"ragflow/internal/common"
"strings"
- "time"
)
// OpenRouterModel implements ModelDriver for OpenRouter AI
@@ -41,16 +39,9 @@ type OpenRouterModel struct {
func NewOpenRouterModel(baseURL map[string]string, urlSuffix URLSuffix) *OpenRouterModel {
return &OpenRouterModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -299,45 +290,22 @@ func (o *OpenRouterModel) ChatStreamlyWithSender(modelName string, messages []Me
return fmt.Errorf("invalid status code: %d, body: %s", resp.StatusCode, string(body))
}
- // SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning"].(string)
@@ -354,10 +322,9 @@ func (o *OpenRouterModel) ChatStreamlyWithSender(modelName string, messages []Me
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -366,7 +333,7 @@ func (o *OpenRouterModel) ChatStreamlyWithSender(modelName string, messages []Me
return err
}
- return scanner.Err()
+ return nil
}
type openrouterEmbeddingResponse struct {
diff --git a/internal/entity/models/orcarouter.go b/internal/entity/models/orcarouter.go
index baa96b3cec..84e68aaf6a 100644
--- a/internal/entity/models/orcarouter.go
+++ b/internal/entity/models/orcarouter.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,8 +24,6 @@ import (
"io"
"net/http"
"ragflow/internal/common"
- "strings"
- "time"
)
type OrcaRouterModel struct {
@@ -36,16 +33,9 @@ type OrcaRouterModel struct {
func NewOrcaRouterModel(baseURL map[string]string, urlSuffix URLSuffix) *OrcaRouterModel {
return &OrcaRouterModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -259,44 +249,23 @@ func (o *OrcaRouterModel) ChatStreamlyWithSender(modelName string, messages []Me
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -308,9 +277,15 @@ func (o *OrcaRouterModel) ChatStreamlyWithSender(modelName string, messages []Me
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
+ _ = done
+ _ = sawTerminal
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
@@ -318,7 +293,7 @@ func (o *OrcaRouterModel) ChatStreamlyWithSender(modelName string, messages []Me
return err
}
- return scanner.Err()
+ return nil
}
func (o *OrcaRouterModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/paddleocr.go b/internal/entity/models/paddleocr.go
index 26685590c2..4b250924d4 100644
--- a/internal/entity/models/paddleocr.go
+++ b/internal/entity/models/paddleocr.go
@@ -39,14 +39,7 @@ func NewPaddleOCRModel(baseURL map[string]string, urlSuffix URLSuffix) *PaddleOC
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/paddleocr_local.go b/internal/entity/models/paddleocr_local.go
index 847eb9b057..4a392c85b6 100644
--- a/internal/entity/models/paddleocr_local.go
+++ b/internal/entity/models/paddleocr_local.go
@@ -25,7 +25,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
type PaddleOCRLocalModel struct {
@@ -35,16 +34,9 @@ type PaddleOCRLocalModel struct {
func NewPaddleOCRLocalModel(baseURL map[string]string, urlSuffix URLSuffix) *PaddleOCRLocalModel {
return &PaddleOCRLocalModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: time.Second * 90,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/perplexity.go b/internal/entity/models/perplexity.go
index 2c73d96d80..03205e2cf9 100644
--- a/internal/entity/models/perplexity.go
+++ b/internal/entity/models/perplexity.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
type PerplexityModel struct {
@@ -33,20 +31,11 @@ type PerplexityModel struct {
}
func NewPerplexityModel(baseURL map[string]string, urlSuffix URLSuffix) *PerplexityModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &PerplexityModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -245,30 +234,13 @@ func (p *PerplexityModel) ChatStreamlyWithSender(modelName string, messages []Me
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event perplexityChatResponse
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("perplexity: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[perplexityChatResponse](resp.Body, func(event perplexityChatResponse) error {
if event.Error != nil {
return fmt.Errorf("perplexity: upstream stream error: %v", event.Error)
}
if len(event.Choices) == 0 {
- continue
+ return nil
}
choice := event.Choices[0]
@@ -289,13 +261,13 @@ func (p *PerplexityModel) ChatStreamlyWithSender(modelName string, messages []Me
}
if choice.FinishReason != "" || event.FinishReason != "" {
sawTerminal = true
- break
}
- }
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("perplexity: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/ppio.go b/internal/entity/models/ppio.go
index 094a0cccde..a1f09dbd6a 100644
--- a/internal/entity/models/ppio.go
+++ b/internal/entity/models/ppio.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// PPIOModel implements ModelDriver for PPIO.
@@ -36,28 +34,11 @@ type PPIOModel struct {
}
func NewPPIOModel(baseURL map[string]string, urlSuffix URLSuffix) *PPIOModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &PPIOModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -248,30 +229,13 @@ func (p *PPIOModel) ChatStreamlyWithSender(modelName string, messages []Message,
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event ppioChatResponse
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("ppio: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[ppioChatResponse](resp.Body, func(event ppioChatResponse) error {
if event.Error != nil {
return fmt.Errorf("ppio: upstream stream error: %v", event.Error)
}
if len(event.Choices) == 0 {
- continue
+ return nil
}
choice := event.Choices[0]
@@ -291,13 +255,13 @@ func (p *PPIOModel) ChatStreamlyWithSender(modelName string, messages []Message,
}
if choice.FinishReason != "" || event.FinishReason != "" {
sawTerminal = true
- break
}
- }
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("ppio: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/qiniu.go b/internal/entity/models/qiniu.go
index 0513e8dab4..79ce00c5ef 100644
--- a/internal/entity/models/qiniu.go
+++ b/internal/entity/models/qiniu.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"fmt"
@@ -25,7 +24,6 @@ import (
"net/http"
"ragflow/internal/common"
"strings"
- "time"
"github.com/goccy/go-json"
)
@@ -37,16 +35,9 @@ type QiniuModel struct {
func NewQiniuModel(baseURL map[string]string, urlSuffix URLSuffix) *QiniuModel {
return &QiniuModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxConnsPerHost: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -348,42 +339,20 @@ func (q *QiniuModel) ChatStreamlyWithSender(modelName string, messages []Message
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -399,10 +368,9 @@ func (q *QiniuModel) ChatStreamlyWithSender(modelName string, messages []Message
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
@@ -410,7 +378,7 @@ func (q *QiniuModel) ChatStreamlyWithSender(modelName string, messages []Message
return err
}
- return scanner.Err()
+ return nil
}
func (q *QiniuModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/replicate.go b/internal/entity/models/replicate.go
index 0f3396e287..3f543b2548 100644
--- a/internal/entity/models/replicate.go
+++ b/internal/entity/models/replicate.go
@@ -37,20 +37,11 @@ type ReplicateModel struct {
}
func NewReplicateModel(baseURL map[string]string, urlSuffix URLSuffix) *ReplicateModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &ReplicateModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/siliconflow.go b/internal/entity/models/siliconflow.go
index 95c7922c91..238834b841 100644
--- a/internal/entity/models/siliconflow.go
+++ b/internal/entity/models/siliconflow.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -30,7 +29,6 @@ import (
"ragflow/internal/common"
"strconv"
"strings"
- "time"
)
// SiliconflowModel implements ModelDriver for Siliconflow
@@ -42,16 +40,9 @@ type SiliconflowModel struct {
func NewSiliconflowModel(baseURL map[string]string, urlSuffix URLSuffix) *SiliconflowModel {
return &SiliconflowModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -324,44 +315,23 @@ func (s *SiliconflowModel) ChatStreamlyWithSender(modelName string, messages []M
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ sawTerminal := false
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -380,8 +350,16 @@ func (s *SiliconflowModel) ChatStreamlyWithSender(modelName string, messages []M
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
- break
+ sawTerminal = true
}
+
+ return nil
+ })
+ if err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
+ }
+ if !done && !sawTerminal {
+ return fmt.Errorf("siliconflow: stream ended before [DONE] or finish_reason")
}
// Send [DONE] marker for OpenAI compatibility
@@ -390,7 +368,7 @@ func (s *SiliconflowModel) ChatStreamlyWithSender(modelName string, messages []M
return err
}
- return scanner.Err()
+ return nil
}
type siliconflowEmbeddingResponse struct {
diff --git a/internal/entity/models/stepfun.go b/internal/entity/models/stepfun.go
index 8723e181fa..f8ef70535d 100644
--- a/internal/entity/models/stepfun.go
+++ b/internal/entity/models/stepfun.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -26,7 +25,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// StepFunModel implements ModelDriver for StepFun (阶跃星辰).
@@ -36,20 +34,11 @@ type StepFunModel struct {
// NewStepFunModel creates a new StepFun model instance.
func NewStepFunModel(baseURL map[string]string, urlSuffix URLSuffix) *StepFunModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &StepFunModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -249,41 +238,21 @@ func (s *StepFunModel) ChatStreamlyWithSender(modelName string, messages []Messa
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -296,14 +265,13 @@ func (s *StepFunModel) ChatStreamlyWithSender(modelName string, messages []Messa
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("stepfun: stream ended before [DONE] or finish_reason")
}
@@ -516,32 +484,11 @@ func (s *StepFunModel) AudioSpeechWithSender(modelName *string, audioContent *st
return fmt.Errorf("StepFun stream TTS API error: %d - %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
-
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data: ") {
- continue
- }
-
- dataStr := strings.TrimSpace(line[6:])
- // [DONE]
- if dataStr == "" || dataStr == "[DONE]" {
- continue
- }
-
- // Parse
- var event struct {
- Type string `json:"type"`
- Audio string `json:"audio"`
- }
-
- if err := json.Unmarshal([]byte(dataStr), &event); err != nil {
- continue
- }
-
+ type ttsEvent struct {
+ Type string `json:"type"`
+ Audio string `json:"audio"`
+ }
+ if _, err := ParseSSEStream[ttsEvent](resp.Body, func(event ttsEvent) error {
if event.Type == "speech.audio.error" {
return fmt.Errorf("StepFun stream encountered an error during generation")
}
@@ -556,10 +503,9 @@ func (s *StepFunModel) AudioSpeechWithSender(modelName *string, audioContent *st
}
}
}
- }
-
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("error reading StepFun stream: %w", err)
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
return nil
diff --git a/internal/entity/models/togetherai.go b/internal/entity/models/togetherai.go
index bf598cc063..440a19deae 100644
--- a/internal/entity/models/togetherai.go
+++ b/internal/entity/models/togetherai.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -30,7 +29,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "time"
)
type TogetherAIModel struct {
@@ -38,20 +36,11 @@ type TogetherAIModel struct {
}
func NewTogetherAIModel(baseURL map[string]string, urlSuffix URLSuffix) *TogetherAIModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &TogetherAIModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -254,30 +243,13 @@ func (t *TogetherAIModel) ChatStreamlyWithSender(modelName string, messages []Me
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event togetherAIChatResponse
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("togetherai: invalid SSE event: %w", err)
- }
+ done, err := ParseSSEStream[togetherAIChatResponse](resp.Body, func(event togetherAIChatResponse) error {
if event.Error != nil {
return fmt.Errorf("togetherai: upstream stream error: %v", event.Error)
}
if len(event.Choices) == 0 {
- continue
+ return nil
}
choice := event.Choices[0]
@@ -298,13 +270,13 @@ func (t *TogetherAIModel) ChatStreamlyWithSender(modelName string, messages []Me
}
if choice.FinishReason != "" || event.FinishReason != "" {
sawTerminal = true
- break
}
- }
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("togetherai: stream ended before [DONE] or finish_reason")
}
@@ -773,35 +745,13 @@ func (t *TogetherAIModel) AudioSpeechWithSender(modelName *string, audioContent
return fmt.Errorf("TogetherAI stream API error: %d - %s", resp.StatusCode, string(buf[:n]))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
-
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data: ") {
- continue
- }
-
- dataStr := strings.TrimSpace(line[6:])
- if dataStr == "" {
- continue
- }
-
- // End
- if dataStr == "[DONE]" {
- break
- }
-
- var event struct {
- Type string `json:"type"`
- Delta string `json:"delta"`
- }
-
- if err := json.Unmarshal([]byte(dataStr), &event); err != nil {
- continue
- }
-
+ if _, err := ParseSSEStream[struct {
+ Type string `json:"type"`
+ Delta string `json:"delta"`
+ }](resp.Body, func(event struct {
+ Type string `json:"type"`
+ Delta string `json:"delta"`
+ }) error {
// Parse delta audio
if event.Type == "conversation.item.audio_output.delta" && event.Delta != "" {
audioBytes, err := base64.StdEncoding.DecodeString(event.Delta)
@@ -812,10 +762,9 @@ func (t *TogetherAIModel) AudioSpeechWithSender(modelName *string, audioContent
}
}
}
- }
-
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("error reading TogetherAI stream: %w", err)
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
return nil
diff --git a/internal/entity/models/tokenhub.go b/internal/entity/models/tokenhub.go
index dac152f4a9..c17df6cc17 100644
--- a/internal/entity/models/tokenhub.go
+++ b/internal/entity/models/tokenhub.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
type TokenHubModel struct {
@@ -35,16 +33,9 @@ type TokenHubModel struct {
func NewTokenHubModel(baseURL map[string]string, urlSuffix URLSuffix) *TokenHubModel {
return &TokenHubModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: time.Second * 60,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -279,44 +270,20 @@ func (t *TokenHubModel) ChatStreamlyWithSender(modelName string, messages []Mess
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- // SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -337,19 +304,14 @@ func (t *TokenHubModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ return sender(&endOfStream, nil)
}
func (t *TokenHubModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/tokenpony.go b/internal/entity/models/tokenpony.go
index 7474308603..1f2407236a 100644
--- a/internal/entity/models/tokenpony.go
+++ b/internal/entity/models/tokenpony.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// TokenPonyModel implements ModelDriver for TokenPony. TokenPony is a
@@ -35,20 +33,11 @@ type TokenPonyModel struct {
// NewTokenPonyModel creates a new TokenPony model instance.
func NewTokenPonyModel(baseURL map[string]string, urlSuffix URLSuffix) *TokenPonyModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &TokenPonyModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -246,36 +235,19 @@ func (t *TokenPonyModel) ChatStreamlyWithSender(modelName string, messages []Mes
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- return fmt.Errorf("tokenpony: invalid SSE event: %w", err)
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
if apiErr, ok := event["error"]; ok {
return fmt.Errorf("tokenpony: upstream stream error: %v", apiErr)
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if delta, ok := firstChoice["delta"].(map[string]interface{}); ok {
@@ -294,14 +266,13 @@ func (t *TokenPonyModel) ChatStreamlyWithSender(modelName string, messages []Mes
}
if finish, ok := firstChoice["finish_reason"].(string); ok && finish != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("tokenpony: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/upstage.go b/internal/entity/models/upstage.go
index a8762f50f4..b03d72d9db 100644
--- a/internal/entity/models/upstage.go
+++ b/internal/entity/models/upstage.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// UpstageModel implements ModelDriver for Upstage (Solar models).
@@ -35,20 +33,11 @@ type UpstageModel struct {
// NewUpstageModel creates a new Upstage model instance.
func NewUpstageModel(baseURL map[string]string, urlSuffix URLSuffix) *UpstageModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &UpstageModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -258,41 +247,21 @@ func (u *UpstageModel) ChatStreamlyWithSender(modelName string, messages []Messa
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(line[5:])
-
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if r, ok := delta["reasoning"].(string); ok && r != "" {
@@ -311,14 +280,13 @@ func (u *UpstageModel) ChatStreamlyWithSender(modelName string, messages []Messa
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("upstage: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/vllm.go b/internal/entity/models/vllm.go
index de12d25187..3b78be34e4 100644
--- a/internal/entity/models/vllm.go
+++ b/internal/entity/models/vllm.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -26,7 +25,6 @@ import (
"net/http"
"ragflow/internal/common"
"strings"
- "time"
)
// VllmModel implements ModelDriver for Vllm AI
@@ -41,14 +39,7 @@ func NewVllmModel(baseURL map[string]string, urlSuffix URLSuffix) *VllmModel {
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -314,44 +305,22 @@ func (v *VllmModel) ChatStreamlyWithSender(modelName string, messages []Message,
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -368,10 +337,9 @@ func (v *VllmModel) ChatStreamlyWithSender(modelName string, messages []Message,
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -380,7 +348,7 @@ func (v *VllmModel) ChatStreamlyWithSender(modelName string, messages []Message,
return err
}
- return scanner.Err()
+ return nil
}
// Encode encodes a list of texts into embeddings
diff --git a/internal/entity/models/volcengine.go b/internal/entity/models/volcengine.go
index 7abd7e8061..c4d9481690 100644
--- a/internal/entity/models/volcengine.go
+++ b/internal/entity/models/volcengine.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -26,7 +25,6 @@ import (
"net/http"
"ragflow/internal/common"
"strings"
- "time"
)
// VolcEngine implements ModelDriver for VolcEngine
@@ -38,16 +36,9 @@ type VolcEngine struct {
func NewVolcEngine(baseURL map[string]string, urlSuffix URLSuffix) *VolcEngine {
return &VolcEngine{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -354,45 +345,22 @@ func (v *VolcEngine) ChatStreamlyWithSender(modelName string, messages []Message
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- // SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line start with data:
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after data:
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err := json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
content, ok := delta["content"].(string)
@@ -409,10 +377,9 @@ func (v *VolcEngine) ChatStreamlyWithSender(modelName string, messages []Message
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -421,7 +388,7 @@ func (v *VolcEngine) ChatStreamlyWithSender(modelName string, messages []Message
return err
}
- return scanner.Err()
+ return nil
}
type volcengineEmbeddingResponse struct {
diff --git a/internal/entity/models/voyage.go b/internal/entity/models/voyage.go
index 548ec73324..3a14428cf6 100644
--- a/internal/entity/models/voyage.go
+++ b/internal/entity/models/voyage.go
@@ -24,7 +24,6 @@ import (
"io"
"net/http"
"strings"
- "time"
)
// VoyageModel implements ModelDriver for Voyage AI.
@@ -34,28 +33,11 @@ type VoyageModel struct {
// NewVoyageModel creates a new Voyage AI model instance.
func NewVoyageModel(baseURL map[string]string, urlSuffix URLSuffix) *VoyageModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &VoyageModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
diff --git a/internal/entity/models/xai.go b/internal/entity/models/xai.go
index 052f2fcea4..76191c349c 100644
--- a/internal/entity/models/xai.go
+++ b/internal/entity/models/xai.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -45,19 +44,11 @@ type XAIModel struct {
// NewXAIModel creates a new xAI model instance.
func NewXAIModel(baseURL map[string]string, urlSuffix URLSuffix) *XAIModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
-
return &XAIModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -279,45 +270,21 @@ func (x *XAIModel) ChatStreamlyWithSender(modelName string, messages []Message,
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
- line := scanner.Text()
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of the stream
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -337,14 +304,13 @@ func (x *XAIModel) ChatStreamlyWithSender(modelName string, messages []Message,
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
- if !sawTerminal {
+ if !done && !sawTerminal {
return fmt.Errorf("xai: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/xiaomi.go b/internal/entity/models/xiaomi.go
index 59b74e6e0a..8584e73a13 100644
--- a/internal/entity/models/xiaomi.go
+++ b/internal/entity/models/xiaomi.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -28,9 +27,7 @@ import (
"net/http"
"os"
"path/filepath"
- "ragflow/internal/common"
"strings"
- "time"
)
type XiaomiModel struct {
@@ -38,28 +35,11 @@ type XiaomiModel struct {
}
func NewXiaomiModel(baseURL map[string]string, urlSuffix URLSuffix) *XiaomiModel {
- defaultTransport, ok := http.DefaultTransport.(*http.Transport)
- var transport *http.Transport
- if ok {
- transport = defaultTransport.Clone()
- } else {
- transport = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &XiaomiModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: transport,
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -317,44 +297,20 @@ func (x *XiaomiModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -371,10 +327,9 @@ func (x *XiaomiModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -383,7 +338,7 @@ func (x *XiaomiModel) ChatStreamlyWithSender(modelName string, messages []Messag
return err
}
- return scanner.Err()
+ return nil
}
func (x *XiaomiModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
@@ -619,28 +574,9 @@ func decodeXiaomiASRResponse(body []byte) (*ASRResponse, error) {
}
func readXiaomiASRStream(body io.Reader, sender func(*string, *string) error) error {
- scanner := bufio.NewScanner(body)
- scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
- if data == "" {
- continue
- }
- if data == "[DONE]" {
- break
- }
-
- var chunk xiaomiChatCompletionChunk
- if err := json.Unmarshal([]byte(data), &chunk); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[xiaomiChatCompletionChunk](body, func(chunk xiaomiChatCompletionChunk) error {
if len(chunk.Choices) == 0 {
- continue
+ return nil
}
content := chunk.Choices[0].Delta.Content
@@ -649,8 +585,8 @@ func readXiaomiASRStream(body io.Reader, sender func(*string, *string) error) er
return err
}
}
- }
- if err := scanner.Err(); err != nil {
+ return nil
+ }); err != nil {
return fmt.Errorf("error reading Xiaomi ASR stream: %w", err)
}
@@ -835,35 +771,16 @@ func decodeXiaomiTTSResponse(body []byte) (*TTSResponse, error) {
}
func readXiaomiTTSStream(body io.Reader, sender func(*string, *string) error) error {
- scanner := bufio.NewScanner(body)
- scanner.Buffer(make([]byte, 64*1024), 8*1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
- if data == "" {
- continue
- }
- if data == "[DONE]" {
- break
- }
-
- var chunk xiaomiChatCompletionChunk
- if err := json.Unmarshal([]byte(data), &chunk); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[xiaomiChatCompletionChunk](body, func(chunk xiaomiChatCompletionChunk) error {
if len(chunk.Choices) == 0 || chunk.Choices[0].Delta.Audio == nil || chunk.Choices[0].Delta.Audio.Data == "" {
- continue
+ return nil
}
audioData := chunk.Choices[0].Delta.Audio.Data
if err := sender(&audioData, nil); err != nil {
return err
}
- }
- if err := scanner.Err(); err != nil {
+ return nil
+ }); err != nil {
return fmt.Errorf("error reading Xiaomi TTS stream: %w", err)
}
return nil
diff --git a/internal/entity/models/xinference.go b/internal/entity/models/xinference.go
index 5a446885e4..864bbe62ab 100644
--- a/internal/entity/models/xinference.go
+++ b/internal/entity/models/xinference.go
@@ -16,7 +16,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -58,21 +57,12 @@ type xinferenceModelListResponse struct {
// NewXinferenceModel creates a new Xinference model instance.
func NewXinferenceModel(baseURL map[string]string, urlSuffix URLSuffix) *XinferenceModel {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.MaxIdleConns = 100
- transport.MaxIdleConnsPerHost = 10
- transport.IdleConnTimeout = 90 * time.Second
- transport.DisableCompression = false
- transport.ResponseHeaderTimeout = 60 * time.Second
-
return &XinferenceModel{
baseModel: BaseModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
AllowEmptyAPIKey: true,
- httpClient: &http.Client{
- Transport: transport,
- },
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -295,36 +285,19 @@ func (x *XinferenceModel) ChatStreamlyWithSender(modelName string, messages []Me
}
}()
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
sawTerminal := false
- for scanner.Scan() {
+ sseDone, parseErr := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
lastActiveMu.Lock()
lastActive = time.Now()
lastActiveMu.Unlock()
- line := scanner.Text()
- if !strings.HasPrefix(line, "data:") {
- continue
- }
- data := strings.TrimSpace(line[5:])
- if data == "[DONE]" {
- sawTerminal = true
- break
- }
-
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
-
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
if delta, ok := firstChoice["delta"].(map[string]interface{}); ok {
@@ -342,17 +315,16 @@ func (x *XinferenceModel) ChatStreamlyWithSender(modelName string, messages []Me
if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" {
sawTerminal = true
- break
}
- }
-
- if err := scanner.Err(); err != nil {
+ return nil
+ })
+ if parseErr != nil {
if ctx.Err() != nil {
return fmt.Errorf("xinference: stream idle for more than %s, aborted", xinferenceStreamIdleTimeout)
}
- return fmt.Errorf("failed to scan response body: %w", err)
+ return fmt.Errorf("failed to scan response body: %w", parseErr)
}
- if !sawTerminal {
+ if !sseDone && !sawTerminal {
return fmt.Errorf("xinference: stream ended before [DONE] or finish_reason")
}
diff --git a/internal/entity/models/xunfei.go b/internal/entity/models/xunfei.go
index 5eaf90d8b4..a4229ef859 100644
--- a/internal/entity/models/xunfei.go
+++ b/internal/entity/models/xunfei.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/json"
@@ -25,8 +24,6 @@ import (
"io"
"net/http"
"ragflow/internal/common"
- "strings"
- "time"
)
type XunFeiModel struct {
@@ -36,16 +33,9 @@ type XunFeiModel struct {
func NewXunFeiModel(baseURL map[string]string, urlSuffix URLSuffix) *XunFeiModel {
return &XunFeiModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: time.Second * 90,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -283,44 +273,24 @@ func (x *XunFeiModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ if data, marshalErr := json.Marshal(event); marshalErr == nil {
+ common.Info(string(data))
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -337,10 +307,9 @@ func (x *XunFeiModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -349,7 +318,7 @@ func (x *XunFeiModel) ChatStreamlyWithSender(modelName string, messages []Messag
return err
}
- return scanner.Err()
+ return nil
}
func (x *XunFeiModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
diff --git a/internal/entity/models/zhipu-ai.go b/internal/entity/models/zhipu-ai.go
index e63e3ba2a5..728c284d1b 100644
--- a/internal/entity/models/zhipu-ai.go
+++ b/internal/entity/models/zhipu-ai.go
@@ -17,7 +17,6 @@
package models
import (
- "bufio"
"bytes"
"context"
"encoding/base64"
@@ -30,7 +29,6 @@ import (
"path/filepath"
"ragflow/internal/common"
"strings"
- "time"
)
// ZhipuAIModel implements ModelDriver for Zhipu AI
@@ -42,16 +40,9 @@ type ZhipuAIModel struct {
func NewZhipuAIModel(baseURL map[string]string, urlSuffix URLSuffix) *ZhipuAIModel {
return &ZhipuAIModel{
baseModel: BaseModel{
- BaseURL: baseURL,
- URLSuffix: urlSuffix,
- httpClient: &http.Client{
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 10,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: false,
- },
- },
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: NewDriverHTTPClient(),
},
}
}
@@ -309,44 +300,22 @@ func (z *ZhipuAIModel) ChatStreamlyWithSender(modelName string, messages []Messa
}
// SSE parsing: read line by line
- scanner := bufio.NewScanner(resp.Body)
- scanner.Buffer(make([]byte, 64*1024), 1024*1024)
- for scanner.Scan() {
- line := scanner.Text()
- common.Info(line)
-
- // SSE data line starts with "data:"
- if !strings.HasPrefix(line, "data:") {
- continue
- }
-
- // Extract JSON after "data:"
- data := strings.TrimSpace(line[5:])
-
- // [DONE] marks the end of stream
- if data == "[DONE]" {
- break
- }
-
- // Parse the JSON event
- var event map[string]interface{}
- if err = json.Unmarshal([]byte(data), &event); err != nil {
- continue
- }
+ if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error {
+ common.Info(fmt.Sprintf("%v", event))
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
- continue
+ return nil
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
- continue
+ return nil
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
- continue
+ return nil
}
reasoningContent, ok := delta["reasoning_content"].(string)
@@ -363,10 +332,9 @@ func (z *ZhipuAIModel) ChatStreamlyWithSender(modelName string, messages []Messa
}
}
- finishReason, ok := firstChoice["finish_reason"].(string)
- if ok && finishReason != "" {
- break
- }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("failed to scan response body: %w", err)
}
// Send [DONE] marker for OpenAI compatibility
@@ -375,7 +343,7 @@ func (z *ZhipuAIModel) ChatStreamlyWithSender(modelName string, messages []Messa
return err
}
- return scanner.Err()
+ return nil
}
type zhipuEmbeddingResponse struct {