Skip to content

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

Go: implement provider: OpenRouter (#14652)

Haruko386a377512110c9
diff --git a/conf/models/openrouter.json b/conf/models/openrouter.json
new file mode 100644
index 0000000000..4d9fca3665
--- /dev/null
+++ b/conf/models/openrouter.json
@@ -0,0 +1,46 @@
+{
+ "name": "OpenRouter",
+ "url": {
+ "default": "https://openrouter.ai/api/v1"
+ },
+ "url_suffix": {
+ "chat": "chat/completions",
+ "models": "models"
+ },
+ "class": "openrouter",
+ "models": [
+ {
+ "name": "google/gemma-4-31b-it",
+ "max_tokens": 262144,
+ "model_types": [
+ "chat"
+ ],
+ "thinking": {
+ "default_value": true,
+ "clear_thinking": true
+ }
+ },
+ {
+ "name": "minimax/minimax-m2.5",
+ "max_tokens": 196608,
+ "model_types": [
+ "chat"
+ ],
+ "thinking": {
+ "default_value": true,
+ "clear_thinking": true
+ }
+ },
+ {
+ "name": "tencent/hy3-preview",
+ "max_tokens": 262144,
+ "model_types": [
+ "chat"
+ ],
+ "thinking": {
+ "default_value": true,
+ "clear_thinking": true
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/internal/entity/models/aliyun.go b/internal/entity/models/aliyun.go
index 2578be56d5..2019f1db4b 100644
--- a/internal/entity/models/aliyun.go
+++ b/internal/entity/models/aliyun.go
@@ -66,7 +66,7 @@ func (z *AliyunModel) ChatWithMessages(modelName string, messages []Message, api
}
var region = "default"
- if apiConfig != nil && apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -202,7 +202,7 @@ func (z *AliyunModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/deepseek.go b/internal/entity/models/deepseek.go
index 8218d0116c..b74ef0db46 100644
--- a/internal/entity/models/deepseek.go
+++ b/internal/entity/models/deepseek.go
@@ -66,7 +66,7 @@ func (z *DeepSeekModel) ChatWithMessages(modelName string, messages []Message, a
}
var region = "default"
- if apiConfig != nil && apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -234,7 +234,7 @@ func (z *DeepSeekModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/factory.go b/internal/entity/models/factory.go
index dfb5854a28..b4c5d25abd 100644
--- a/internal/entity/models/factory.go
+++ b/internal/entity/models/factory.go
@@ -59,6 +59,8 @@ func (f *ModelFactory) CreateModelDriver(providerName string, baseURL map[string
return NewLmStudioModel(baseURL, urlSuffix), nil
case "nvidia":
return NewNvidiaModel(baseURL, urlSuffix), nil
+ case "openrouter":
+ return NewOpenRouterModel(baseURL, urlSuffix), nil
default:
return NewDummyModel(baseURL, urlSuffix), nil
}
diff --git a/internal/entity/models/gitee.go b/internal/entity/models/gitee.go
index 9e5d64090e..7f7050bfb9 100644
--- a/internal/entity/models/gitee.go
+++ b/internal/entity/models/gitee.go
@@ -71,7 +71,7 @@ func (z *GiteeModel) ChatWithMessages(modelName string, messages []Message, apiC
}
region := "default"
- if apiConfig.Region != nil {
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
@@ -218,7 +218,7 @@ func (z *GiteeModel) ChatStreamlyWithSender(modelName string, messages []Message
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/lmstudio.go b/internal/entity/models/lmstudio.go
index ec6a473237..061203837e 100644
--- a/internal/entity/models/lmstudio.go
+++ b/internal/entity/models/lmstudio.go
@@ -180,11 +180,20 @@ func (l *LmStudioModel) ChatWithMessages(modelName string, messages []Message, a
return nil, fmt.Errorf("invalid content format")
}
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelClass, &content)
+ var reasonContent string
+ if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
+ reasonContent, ok = messageMap["reasoning_content"].(string)
+ if !ok {
+ return nil, fmt.Errorf("invalid content format")
+ }
+ if reasonContent != "" && reasonContent[0] == '\n' {
+ reasonContent = reasonContent[1:]
+ }
+ }
chatResponse := &ChatResponse{
- Answer: answer,
- ReasonContent: thinking,
+ Answer: &content,
+ ReasonContent: &reasonContent,
}
return chatResponse, nil
@@ -197,7 +206,7 @@ func (l *LmStudioModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/minimax.go b/internal/entity/models/minimax.go
index 916a407375..04f5b1a02f 100644
--- a/internal/entity/models/minimax.go
+++ b/internal/entity/models/minimax.go
@@ -60,124 +60,6 @@ func (z *MinimaxModel) Name() string {
return "minimax"
}
-// Chat sends a message and returns response
-func (z *MinimaxModel) Chat(modelName, message *string, apiConfig *APIConfig, modelConfig *ChatConfig) (*ChatResponse, error) {
- var region = "default"
-
- if *apiConfig.Region != "" {
- region = *apiConfig.Region
- }
-
- url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
-
- // Build request Body
- reqBody := map[string]interface{}{
- "model": modelName,
- "messages": []map[string]interface{}{
- {"role": "user", "content": *message},
- },
- "stream": false,
- "temperature": 1,
- }
-
- if modelConfig.Temperature != nil {
- reqBody["temperature"] = *modelConfig.Temperature
- }
-
- if modelConfig.MaxTokens != nil {
- reqBody["max_tokens"] = *modelConfig.MaxTokens
- }
-
- if modelConfig.Stream != nil {
- reqBody["stream"] = *modelConfig.Stream
- }
-
- if modelConfig.TopP != nil {
- reqBody["top_p"] = *modelConfig.TopP
- }
-
- if modelConfig.DoSample != nil {
- reqBody["do_sample"] = *modelConfig.DoSample
- }
-
- if modelConfig.Thinking != nil {
- reqBody["thinking"] = *modelConfig.Thinking
- }
-
- jsonData, err := json.Marshal(reqBody)
- if err != nil {
- return nil, fmt.Errorf("failed to marshal request: %w", err)
- }
-
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
- if err != nil {
- return nil, fmt.Errorf("failed to create request: %w", err)
- }
-
- req.Header.Add("Content-Type", "application/json")
- req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
-
- resp, err := z.httpClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("failed to send request: %w", err)
- }
- defer resp.Body.Close()
-
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("failed to read response body: %w", err)
- }
-
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("failed to send request: %d %s", resp.StatusCode, string(body))
- }
-
- // Parse response
- var result map[string]interface{}
- if err := json.Unmarshal(body, &result); err != nil {
- return nil, fmt.Errorf("failed to unmarshal response: %w", err)
- }
-
- choices, ok := result["choices"].([]interface{})
- if !ok {
- return nil, fmt.Errorf("no choices in response")
- }
-
- firstChoice, ok := choices[0].(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("no choices in response")
- }
-
- messageMap, ok := firstChoice["message"].(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("no message in response")
- }
-
- content, ok := messageMap["content"].(string)
- if !ok {
- return nil, fmt.Errorf("no message in response")
- }
-
- var reasonContent string
- if modelConfig.Thinking != nil && *modelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
- // if first char of reasonContent is \n remove the \n
- if reasonContent != "" && reasonContent[0] == '\n' {
- reasonContent = reasonContent[1:]
- }
- }
-
- chatResponse := &ChatResponse{
- Answer: &content,
- ReasonContent: &reasonContent,
- }
-
- return chatResponse, nil
-}
-
// ChatWithMessages sends multiple messages with roles and returns response
func (z *MinimaxModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
diff --git a/internal/entity/models/moonshot.go b/internal/entity/models/moonshot.go
index 9138dce31f..9d0de2c051 100644
--- a/internal/entity/models/moonshot.go
+++ b/internal/entity/models/moonshot.go
@@ -66,7 +66,7 @@ func (k *MoonshotModel) ChatWithMessages(modelName string, messages []Message, a
}
var region = "default"
- if apiConfig != nil && apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -206,7 +206,7 @@ func (k *MoonshotModel) ChatStreamlyWithSender(modelName string, messages []Mess
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/nvidia.go b/internal/entity/models/nvidia.go
index 2700ab86b6..7c13b060db 100644
--- a/internal/entity/models/nvidia.go
+++ b/internal/entity/models/nvidia.go
@@ -165,15 +165,20 @@ func (n *NvidiaModel) ChatWithMessages(modelName string, messages []Message, api
return nil, fmt.Errorf("invalid content format")
}
- var modelClass *string
- if chatModelConfig != nil {
- modelClass = chatModelConfig.ModelClass
+ var reasonContent string
+ if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
+ reasonContent, ok = messageMap["reasoning_content"].(string)
+ if !ok {
+ return nil, fmt.Errorf("invalid content format")
+ }
+ if reasonContent != "" && reasonContent[0] == '\n' {
+ reasonContent = reasonContent[1:]
+ }
}
- thinking, answer := GetThinkingAndAnswer(modelClass, &content)
chatResponse := &ChatResponse{
- Answer: answer,
- ReasonContent: thinking,
+ Answer: &content,
+ ReasonContent: &reasonContent,
}
return chatResponse, nil
@@ -185,7 +190,7 @@ func (n *NvidiaModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
var region = "default"
- if apiConfig != nil && apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/ollama.go b/internal/entity/models/ollama.go
index 4f680e0cc0..4e936fd9d7 100644
--- a/internal/entity/models/ollama.go
+++ b/internal/entity/models/ollama.go
@@ -179,11 +179,20 @@ func (o *OllamaModel) ChatWithMessages(modelName string, messages []Message, api
return nil, fmt.Errorf("invalid content format")
}
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelClass, &content)
+ var reasonContent string
+ if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
+ reasonContent, ok = messageMap["reasoning_content"].(string)
+ if !ok {
+ return nil, fmt.Errorf("invalid content format")
+ }
+ if reasonContent != "" && reasonContent[0] == '\n' {
+ reasonContent = reasonContent[1:]
+ }
+ }
chatResponse := &ChatResponse{
- Answer: answer,
- ReasonContent: thinking,
+ Answer: &content,
+ ReasonContent: &reasonContent,
}
return chatResponse, nil
@@ -195,7 +204,7 @@ func (o *OllamaModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/openai.go b/internal/entity/models/openai.go
index 0d3e259ff2..f83d5810d4 100644
--- a/internal/entity/models/openai.go
+++ b/internal/entity/models/openai.go
@@ -235,7 +235,7 @@ func (z *OpenAIModel) ChatStreamlyWithSender(modelName string, messages []Messag
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/openrouter.go b/internal/entity/models/openrouter.go
new file mode 100644
index 0000000000..fbc8e3394e
--- /dev/null
+++ b/internal/entity/models/openrouter.go
@@ -0,0 +1,493 @@
+package models
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "ragflow/internal/common"
+ "strings"
+ "time"
+)
+
+// OpenRouterModel implements ModelDriver for OpenRouter AI
+type OpenRouterModel struct {
+ BaseURL map[string]string
+ URLSuffix URLSuffix
+ httpClient *http.Client
+}
+
+// NewOpenRouterModel creates a new OpenRouter AI model instance
+func NewOpenRouterModel(baseURL map[string]string, urlSuffix URLSuffix) *OpenRouterModel {
+ return &OpenRouterModel{
+ BaseURL: baseURL,
+ URLSuffix: urlSuffix,
+ httpClient: &http.Client{
+ Timeout: 120 * time.Second,
+ Transport: &http.Transport{
+ MaxIdleConns: 10,
+ MaxIdleConnsPerHost: 100,
+ IdleConnTimeout: 90 * time.Second,
+ DisableCompression: false,
+ },
+ },
+ }
+}
+
+func (o *OpenRouterModel) NewInstance(baseURL map[string]string) ModelDriver {
+ return &OpenRouterModel{
+ BaseURL: baseURL,
+ URLSuffix: o.URLSuffix,
+ httpClient: &http.Client{
+ Timeout: 120 * time.Second,
+ Transport: &http.Transport{
+ MaxIdleConns: 10,
+ MaxIdleConnsPerHost: 100,
+ IdleConnTimeout: 90 * time.Second,
+ DisableCompression: false,
+ },
+ },
+ }
+}
+
+func (o *OpenRouterModel) Name() string {
+ return "openrouter"
+}
+
+func (o *OpenRouterModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is nil or empty")
+ }
+ if len(messages) == 0 {
+ return nil, fmt.Errorf("messages is empty")
+ }
+
+ var region = "default"
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
+ region = *apiConfig.Region
+ }
+
+ url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Chat)
+
+ // Convert messages to API format
+ apiMessages := make([]map[string]interface{}, len(messages))
+ for i, msg := range messages {
+ apiMessages[i] = map[string]interface{}{
+ "role": msg.Role,
+ "content": msg.Content,
+ }
+ }
+
+ // Build request body
+ reqBody := map[string]interface{}{
+ "model": modelName,
+ "messages": apiMessages,
+ "stream": false,
+ "temperature": 1,
+ }
+
+ if chatModelConfig != nil {
+ if chatModelConfig.Temperature != nil {
+ reqBody["temperature"] = *chatModelConfig.Temperature
+ }
+
+ if chatModelConfig.MaxTokens != nil {
+ reqBody["max_tokens"] = *chatModelConfig.MaxTokens
+ }
+
+ if chatModelConfig.Stream != nil {
+ reqBody["stream"] = *chatModelConfig.Stream
+ }
+
+ if chatModelConfig.TopP != nil {
+ reqBody["top_p"] = *chatModelConfig.TopP
+ }
+
+ if chatModelConfig.DoSample != nil {
+ reqBody["do_sample"] = *chatModelConfig.DoSample
+ }
+
+ reqBody["reasoning"] = map[string]interface{}{
+ "effort": "low",
+ }
+ }
+
+ jsonData, err := json.Marshal(reqBody)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Add("Content-Type", "application/json")
+ req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+
+ resp, err := o.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to send request: %w", err)
+ }
+ defer resp.Body.Close()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read response body: %w", err)
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("failed to send request: %d %s", resp.StatusCode, string(body))
+ }
+
+ // Parse response
+ var result map[string]interface{}
+ if err := json.Unmarshal(body, &result); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal response: %w", err)
+ }
+
+ choices, ok := result["choices"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("no choices in response")
+ }
+
+ firstChoice, ok := choices[0].(map[string]interface{})
+ if !ok {
+ return nil, fmt.Errorf("no choices in response")
+ }
+
+ messageMap, ok := firstChoice["message"].(map[string]interface{})
+ if !ok {
+ return nil, fmt.Errorf("no message in response")
+ }
+
+ content, ok := messageMap["content"].(string)
+ if !ok {
+ return nil, fmt.Errorf("no message in response")
+ }
+
+ var reasonContent string
+ if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
+ reasonContent, ok = messageMap["reasoning"].(string)
+ if !ok {
+ return nil, fmt.Errorf("invalid content format")
+ }
+ if reasonContent != "" && reasonContent[0] == '\n' {
+ reasonContent = reasonContent[1:]
+ }
+ }
+
+ chatResponse := &ChatResponse{
+ Answer: &content,
+ ReasonContent: &reasonContent,
+ }
+
+ return chatResponse, nil
+}
+
+func (o *OpenRouterModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error {
+ if len(messages) == 0 {
+ return fmt.Errorf("messages is empty")
+ }
+
+ var region = "default"
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
+ region = *apiConfig.Region
+ }
+
+ url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Chat)
+
+ modelType := strings.Split(modelName, "_")[0]
+ if modelType == "qwen" || modelType == "glm" {
+ url = fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.AsyncChat)
+ }
+
+ // Convert messages to API format
+ apiMessages := make([]map[string]interface{}, len(messages))
+ for i, msg := range messages {
+ apiMessages[i] = map[string]interface{}{
+ "role": msg.Role,
+ "content": msg.Content,
+ }
+ }
+
+ reqBody := map[string]interface{}{
+ "model": modelName,
+ "messages": apiMessages,
+ "stream": true,
+ "temperature": 1,
+ }
+
+ if modelConfig != nil {
+ if modelConfig.Stream != nil {
+ reqBody["stream"] = *modelConfig.Stream
+ }
+
+ if modelConfig.MaxTokens != nil {
+ reqBody["max_tokens"] = *modelConfig.MaxTokens
+ }
+
+ if modelConfig.Temperature != nil {
+ reqBody["temperature"] = *modelConfig.Temperature
+ }
+
+ if modelConfig.DoSample != nil {
+ reqBody["do_sample"] = *modelConfig.DoSample
+ }
+
+ if modelConfig.TopP != nil {
+ reqBody["top_p"] = *modelConfig.TopP
+ }
+
+ if modelConfig.Stop != nil {
+ reqBody["stop"] = *modelConfig.Stop
+ }
+
+ if modelConfig.Thinking != nil {
+ if *modelConfig.Thinking {
+ reqBody["thinking"] = map[string]interface{}{
+ "type": "enabled",
+ }
+ } else {
+ reqBody["thinking"] = map[string]interface{}{
+ "type": "disabled",
+ }
+ }
+ }
+ }
+
+ jsonData, err := json.Marshal(reqBody)
+ if err != nil {
+ return fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+
+ resp, err := o.httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to send request: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("invalid status code: %d, body: %s", resp.StatusCode, string(body))
+ }
+
+ // SSE parsing: read line by line
+ scanner := bufio.NewScanner(resp.Body)
+ 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
+ }
+
+ choices, ok := event["choices"].([]interface{})
+ if !ok || len(choices) == 0 {
+ continue
+ }
+
+ firstChoice, ok := choices[0].(map[string]interface{})
+ if !ok {
+ continue
+ }
+
+ delta, ok := firstChoice["delta"].(map[string]interface{})
+ if !ok {
+ continue
+ }
+
+ reasoningContent, ok := delta["reasoning"].(string)
+ if ok && reasoningContent != "" {
+ if err := sender(nil, &reasoningContent); err != nil {
+ return err
+ }
+ }
+
+ content, ok := delta["content"].(string)
+ if ok && content != "" {
+ if err := sender(&content, nil); err != nil {
+ return err
+ }
+ }
+
+ finishReason, ok := firstChoice["finish_reason"].(string)
+ if ok && finishReason != "" {
+ break
+ }
+ }
+
+ // Send [DONE] marker for OpenAI compatibility
+ endOfStream := "[DONE]"
+ if err = sender(&endOfStream, nil); err != nil {
+ return err
+ }
+
+ return scanner.Err()
+}
+
+func (o *OpenRouterModel) Encode(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
+ //TODO implement me
+ panic("implement me")
+}
+
+func (o *OpenRouterModel) Rerank(modelName *string, query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
+ if len(texts) == 0 {
+ return []float64{}, nil
+ }
+
+ var region = "default"
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
+ region = *apiConfig.Region
+ }
+
+ apiKey := ""
+ if apiConfig != nil && apiConfig.ApiKey != nil {
+ apiKey = *apiConfig.ApiKey
+ }
+
+ reqBody := SiliconflowRerankRequest{
+ Model: *modelName,
+ Query: query,
+ Documents: texts,
+ TopN: len(texts),
+ ReturnDocuments: false,
+ MaxChunksPerDoc: 1024,
+ OverlapTokens: 80,
+ }
+
+ jsonData, err := json.Marshal(reqBody)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ url := fmt.Sprintf("%s/%s", strings.TrimSuffix(o.BaseURL[region], "/"), o.URLSuffix.Rerank)
+
+ req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonData)))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ if apiKey != "" {
+ req.Header.Set("Authorization", "Bearer "+apiKey)
+ }
+
+ resp, err := o.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to send request: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("SiliconFlow Rerank API error: %s, body: %s", resp.Status, string(body))
+ }
+
+ body, _ := io.ReadAll(resp.Body)
+
+ var rerankResp SiliconflowRerankResponse
+ if err := json.Unmarshal(body, &rerankResp); err != nil {
+ return nil, fmt.Errorf("failed to decode response: %w", err)
+ }
+
+ scores := make([]float64, len(texts))
+ for _, result := range rerankResp.Results {
+ if result.Index >= 0 && result.Index < len(texts) {
+ scores[result.Index] = result.RelevanceScore
+ }
+ }
+
+ return scores, nil
+}
+
+func (o *OpenRouterModel) ListModels(apiConfig *APIConfig) ([]string, error) {
+ var region = "default"
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
+ region = *apiConfig.Region
+ }
+
+ url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Models)
+
+ // Build request body
+ reqBody := map[string]interface{}{}
+
+ jsonData, err := json.Marshal(reqBody)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+
+ resp, err := o.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to send request: %w", err)
+ }
+ defer resp.Body.Close()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read response: %w", err)
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("API requestssss failed with status %d: %s : %s", resp.StatusCode, string(body), url)
+ }
+
+ // Parse response
+ var result map[string]interface{}
+ if err = json.Unmarshal(body, &result); err != nil {
+ return nil, fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ // convert result["data"] to []map[string]interface{}
+ models := make([]string, 0)
+ for _, model := range result["data"].([]interface{}) {
+ modelMap := model.(map[string]interface{})
+ modelName := modelMap["id"].(string)
+ models = append(models, modelName)
+ }
+
+ return models, nil
+}
+
+func (o *OpenRouterModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
+ //TODO implement me
+ panic("implement me")
+}
+
+func (o *OpenRouterModel) CheckConnection(apiConfig *APIConfig) error {
+ //TODO implement me
+ panic("implement me")
+}
diff --git a/internal/entity/models/siliconflow.go b/internal/entity/models/siliconflow.go
index 6c9e9ce4af..6c85d96abf 100644
--- a/internal/entity/models/siliconflow.go
+++ b/internal/entity/models/siliconflow.go
@@ -91,7 +91,7 @@ func (z *SiliconflowModel) ChatWithMessages(modelName string, messages []Message
}
region := "default"
- if apiConfig.Region != nil {
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
@@ -222,7 +222,7 @@ func (z *SiliconflowModel) ChatStreamlyWithSender(modelName string, messages []M
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -383,7 +383,7 @@ func (s *SiliconflowModel) Encode(modelName *string, texts []string, apiConfig *
}
var region = "default"
- if apiConfig != nil && apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -630,7 +630,7 @@ func (s *SiliconflowModel) Rerank(modelName *string, query string, texts []strin
}
var region = "default"
- if apiConfig != nil && apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/vllm.go b/internal/entity/models/vllm.go
index 1497012a74..8f6d1e19be 100644
--- a/internal/entity/models/vllm.go
+++ b/internal/entity/models/vllm.go
@@ -79,7 +79,7 @@ func (z *VllmModel) ChatWithMessages(modelName string, messages []Message, apiCo
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -196,11 +196,20 @@ func (z *VllmModel) ChatWithMessages(modelName string, messages []Message, apiCo
return nil, fmt.Errorf("invalid content format")
}
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelClass, &content)
+ var reasonContent string
+ if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
+ reasonContent, ok = messageMap["reasoning_content"].(string)
+ if !ok {
+ return nil, fmt.Errorf("invalid content format")
+ }
+ if reasonContent != "" && reasonContent[0] == '\n' {
+ reasonContent = reasonContent[1:]
+ }
+ }
chatResponse := &ChatResponse{
- Answer: answer,
- ReasonContent: thinking,
+ Answer: &content,
+ ReasonContent: &reasonContent,
}
return chatResponse, nil
@@ -213,7 +222,7 @@ func (z *VllmModel) ChatStreamlyWithSender(modelName string, messages []Message,
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/volcengine.go b/internal/entity/models/volcengine.go
index d500a5ad36..2364502762 100644
--- a/internal/entity/models/volcengine.go
+++ b/internal/entity/models/volcengine.go
@@ -217,7 +217,7 @@ func (z *VolcEngine) ChatWithMessages(modelName string, messages []Message, apiC
}
var region = "default"
- if apiConfig != nil && apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -378,7 +378,7 @@ func (z *VolcEngine) ChatStreamlyWithSender(modelName string, messages []Message
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -576,7 +576,7 @@ func (z *VolcEngine) Balance(apiConfig *APIConfig) (map[string]interface{}, erro
func (z *VolcEngine) CheckConnection(apiConfig *APIConfig) error {
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/xai.go b/internal/entity/models/xai.go
index 85fe49815b..afc6cc3dd3 100644
--- a/internal/entity/models/xai.go
+++ b/internal/entity/models/xai.go
@@ -234,7 +234,7 @@ func (z *XAIModel) ChatStreamlyWithSender(modelName string, messages []Message,
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -410,7 +410,7 @@ func (z *XAIModel) ListModels(apiConfig *APIConfig) ([]string, error) {
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
diff --git a/internal/entity/models/zhipu-ai.go b/internal/entity/models/zhipu-ai.go
index 8da7b0f5e0..e0de7d8263 100644
--- a/internal/entity/models/zhipu-ai.go
+++ b/internal/entity/models/zhipu-ai.go
@@ -71,7 +71,7 @@ func (z *ZhipuAIModel) ChatWithMessages(modelName string, messages []Message, ap
}
region := "default"
- if apiConfig.Region != nil {
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
@@ -208,7 +208,7 @@ func (z *ZhipuAIModel) ChatStreamlyWithSender(modelName string, messages []Messa
}
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
@@ -457,7 +457,7 @@ func (z *ZhipuAIModel) Balance(apiConfig *APIConfig) (map[string]interface{}, er
func (z *ZhipuAIModel) CheckConnection(apiConfig *APIConfig) error {
var region = "default"
- if apiConfig.Region != nil {
+ if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}