mirror of
https://github.com/infiniflow/ragflow.git
synced 2026-08-04 23:00:30 +08:00
## Summary Relate to #17284 Migrate 10 OpenAI-compatible drivers (`302ai`, `aliyun`, `astraflow`, `avian`, `azure_openai`, `baichuan`, `baidu`, `cometapi`, `deepinfra`, `futurmix`) to use the unified response handlers (`HandleNonStreamingResponse` / `HandleStreamingResponse`), following the same pattern established by `deepseek` in #17634. - Cut ~150 lines per driver (1507 lines removed, 144 added across 10 files). - No functional changes — pure deduplication of HTTP plumbing. - Each driver now routes through `baseModel.doRequest()` and `HandleNonStreamingResponse()`. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
235 lines
8.1 KiB
Go
235 lines
8.1 KiB
Go
//
|
|
// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
//
|
|
|
|
package models
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"ragflow/internal/common"
|
|
"strings"
|
|
)
|
|
|
|
type BaichuanModel struct {
|
|
baseModel BaseModel
|
|
}
|
|
|
|
func NewBaichuanModel(baseURL map[string]string, urlSuffix URLSuffix) *BaichuanModel {
|
|
return &BaichuanModel{
|
|
baseModel: BaseModel{
|
|
BaseURL: baseURL,
|
|
URLSuffix: urlSuffix,
|
|
httpClient: NewDriverHTTPClient(false),
|
|
},
|
|
}
|
|
}
|
|
|
|
func (b *BaichuanModel) NewInstance(baseURL map[string]string) ModelDriver {
|
|
return NewBaichuanModel(baseURL, b.baseModel.URLSuffix)
|
|
}
|
|
|
|
func (b *BaichuanModel) Name() string {
|
|
return "BaiChuan"
|
|
}
|
|
|
|
func (b *BaichuanModel) ChatWithMessages(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, modelUsage *common.ModelUsage) (*ChatResponse, error) {
|
|
if err := b.baseModel.APIConfigCheck(apiConfig); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(messages) == 0 {
|
|
return nil, fmt.Errorf("messages is empty")
|
|
}
|
|
|
|
resolvedBaseURL, err := b.baseModel.GetBaseURL(apiConfig)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
url := fmt.Sprintf("%s/%s", resolvedBaseURL, b.baseModel.URLSuffix.Chat)
|
|
reqBody := buildRequestBody(chatModelConfig, modelName, messages, false)
|
|
|
|
body, err := b.baseModel.doRequest(ctx, url, apiConfig, reqBody, nonStreamCallTimeout)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return HandleNonStreamingResponse(body, modelUsage, chatModelConfig, OpenAIParserConfig)
|
|
}
|
|
|
|
func (b *BaichuanModel) ChatStreamlyWithSender(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
|
|
if err := b.baseModel.APIConfigCheck(apiConfig); err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(messages) == 0 {
|
|
return fmt.Errorf("messages is empty")
|
|
}
|
|
|
|
resolvedBaseURL, err := b.baseModel.GetBaseURL(apiConfig)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
url := fmt.Sprintf("%s/%s", resolvedBaseURL, b.baseModel.URLSuffix.Chat)
|
|
|
|
reqBody := buildRequestBody(modelConfig, modelName, messages, true)
|
|
reqBody["stream_options"] = map[string]interface{}{"include_usage": true}
|
|
|
|
return b.baseModel.doStreamRequest(ctx, url, apiConfig, reqBody, streamCallTimeout, func(body io.ReadCloser) error {
|
|
return HandleStreamingResponse(body, modelUsage, modelConfig, OpenAIParserConfig, sender)
|
|
})
|
|
}
|
|
|
|
func (b *BaichuanModel) Embed(ctx context.Context, modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig, modelUsage *common.ModelUsage) ([]EmbeddingData, error) {
|
|
if err := b.baseModel.APIConfigCheck(apiConfig); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(texts) == 0 {
|
|
return []EmbeddingData{}, nil
|
|
}
|
|
|
|
resolvedBaseURL, err := b.baseModel.GetBaseURL(apiConfig)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
url := fmt.Sprintf("%s/%s", resolvedBaseURL, b.baseModel.URLSuffix.Embedding)
|
|
|
|
reqBody := map[string]interface{}{
|
|
"model": *modelName,
|
|
"input": texts,
|
|
}
|
|
|
|
jsonData, err := json.Marshal(reqBody)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal request: %w", err)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, nonStreamCallTimeout)
|
|
defer cancel()
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", 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", strings.TrimSpace(*apiConfig.ApiKey)))
|
|
|
|
resp, err := b.baseModel.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("Baichuan embedding API error: status %d, body: %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
var parsedResponse struct {
|
|
ID string `json:"id"`
|
|
Data []struct {
|
|
Embedding []float64 `json:"embedding"`
|
|
Index int `json:"index"`
|
|
} `json:"data"`
|
|
Usage struct {
|
|
PromptTokens int `json:"prompt_tokens"`
|
|
TotalTokens int `json:"total_tokens"`
|
|
}
|
|
}
|
|
|
|
if err = json.Unmarshal(body, &parsedResponse); err != nil {
|
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
|
}
|
|
|
|
if len(parsedResponse.Data) == 0 {
|
|
return nil, fmt.Errorf("Baichuan embedding response contains no data: %s", string(body))
|
|
}
|
|
|
|
var embeddings []EmbeddingData
|
|
for _, dataElem := range parsedResponse.Data {
|
|
embeddings = append(embeddings, EmbeddingData{
|
|
Embedding: dataElem.Embedding,
|
|
Index: dataElem.Index,
|
|
})
|
|
}
|
|
recordResponseUsage(modelUsage, parsedResponse.ID, &TokenUsage{
|
|
PromptTokens: parsedResponse.Usage.PromptTokens,
|
|
TotalTokens: parsedResponse.Usage.TotalTokens,
|
|
}, "embedding")
|
|
|
|
return embeddings, nil
|
|
}
|
|
|
|
func (b *BaichuanModel) Rerank(ctx context.Context, modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig, modelUsage *common.ModelUsage) (*RerankResponse, error) {
|
|
return nil, fmt.Errorf("no such method")
|
|
}
|
|
|
|
// TranscribeAudio transcribe audio
|
|
func (b *BaichuanModel) TranscribeAudio(ctx context.Context, modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, modelUsage *common.ModelUsage) (*ASRResponse, error) {
|
|
return nil, fmt.Errorf("%s, no such method", b.Name())
|
|
}
|
|
|
|
func (b *BaichuanModel) TranscribeAudioWithSender(ctx context.Context, modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
|
|
return fmt.Errorf("%s, no such method", b.Name())
|
|
}
|
|
|
|
// AudioSpeech convert text to audio
|
|
func (b *BaichuanModel) AudioSpeech(ctx context.Context, modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, modelUsage *common.ModelUsage) (*TTSResponse, error) {
|
|
return nil, fmt.Errorf("%s, no such method", b.Name())
|
|
}
|
|
|
|
func (b *BaichuanModel) AudioSpeechWithSender(ctx context.Context, modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
|
|
return fmt.Errorf("%s, no such method", b.Name())
|
|
}
|
|
|
|
// OCRFile OCR file
|
|
func (b *BaichuanModel) OCRFile(ctx context.Context, modelName *string, content []byte, url *string, apiConfig *APIConfig, ocrConfig *OCRConfig, modelUsage *common.ModelUsage) (*OCRFileResponse, error) {
|
|
return nil, fmt.Errorf("%s, no such method", b.Name())
|
|
}
|
|
|
|
// ParseFile parse file
|
|
func (b *BaichuanModel) ParseFile(ctx context.Context, modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig, modelUsage *common.ModelUsage) (*ParseFileResponse, error) {
|
|
return nil, fmt.Errorf("%s, no such method", b.Name())
|
|
}
|
|
|
|
func (b *BaichuanModel) ListModels(ctx context.Context, apiConfig *APIConfig) ([]ListModelResponse, error) {
|
|
return nil, fmt.Errorf("no such method")
|
|
}
|
|
|
|
func (b *BaichuanModel) Balance(ctx context.Context, apiConfig *APIConfig) (map[string]interface{}, error) {
|
|
return nil, fmt.Errorf("no such method")
|
|
}
|
|
|
|
func (b *BaichuanModel) CheckConnection(ctx context.Context, apiConfig *APIConfig) error {
|
|
return fmt.Errorf("no such method")
|
|
}
|
|
|
|
func (b *BaichuanModel) ListTasks(ctx context.Context, apiConfig *APIConfig) ([]ListTaskStatus, error) {
|
|
return nil, fmt.Errorf("%s, no such method", b.Name())
|
|
}
|
|
|
|
func (b *BaichuanModel) ShowTask(ctx context.Context, taskID string, apiConfig *APIConfig) (*TaskResponse, error) {
|
|
return nil, fmt.Errorf("%s, no such method", b.Name())
|
|
}
|