feat: integrate ChatBot provider and docreader
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/provider"
|
||||
@@ -93,13 +94,15 @@ type Chat interface {
|
||||
}
|
||||
|
||||
type ChatConfig struct {
|
||||
Source types.ModelSource
|
||||
BaseURL string
|
||||
ModelName string
|
||||
APIKey string
|
||||
ModelID string
|
||||
Provider string
|
||||
Extra map[string]any
|
||||
Source types.ModelSource
|
||||
BaseURL string
|
||||
ModelName string
|
||||
APIKey string
|
||||
ModelID string
|
||||
Provider string
|
||||
ExtraConfig map[string]string
|
||||
AppID string
|
||||
AppSecret string // 加密值,由工厂函数调用方传入,在 NewWeKnoraCloudChat 中使用前已解密
|
||||
}
|
||||
|
||||
// NewChat 创建聊天实例
|
||||
@@ -134,6 +137,11 @@ func NewRemoteChat(config *ChatConfig) (Chat, error) {
|
||||
if spec.EndpointCustomizer != nil {
|
||||
remoteChat.SetEndpointCustomizer(spec.EndpointCustomizer)
|
||||
}
|
||||
if spec.HeaderCustomizer != nil {
|
||||
remoteChat.SetHeaderCustomizer(func(req *http.Request, body []byte) error {
|
||||
return spec.HeaderCustomizer(remoteChat, req, body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return remoteChat, nil
|
||||
|
||||
@@ -2,10 +2,13 @@ package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/provider"
|
||||
modelutils "github.com/Tencent/WeKnora/internal/models/utils"
|
||||
"github.com/google/uuid"
|
||||
"github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
@@ -20,11 +23,22 @@ type ProviderSpec struct {
|
||||
RequestCustomizer func(req *openai.ChatCompletionRequest, opts *ChatOptions, isStream bool) (any, bool)
|
||||
// EndpointCustomizer: provider-specific endpoint URL override.
|
||||
EndpointCustomizer func(baseURL string, modelID string, isStream bool) string
|
||||
// HeaderCustomizer: provider-specific raw HTTP header customization.
|
||||
HeaderCustomizer func(chat *RemoteAPIChat, req *http.Request, body []byte) error
|
||||
}
|
||||
|
||||
// chatProviderSpecs is the ordered list of provider specs.
|
||||
// Order matters: more specific specs (with ModelMatcher) should come before generic ones.
|
||||
var chatProviderSpecs = []ProviderSpec{
|
||||
// WeKnoraCloud
|
||||
{
|
||||
Provider: provider.ProviderWeKnoraCloud,
|
||||
RequestCustomizer: weKnoraCloudRequestCustomizer,
|
||||
EndpointCustomizer: func(baseURL string, _ string, _ bool) string {
|
||||
return strings.TrimRight(baseURL, "/") + "/api/v1/chat/completions"
|
||||
},
|
||||
HeaderCustomizer: weKnoraCloudHeaderCustomizer,
|
||||
},
|
||||
// Aliyun Qwen Thinking Models (must be before generic Aliyun)
|
||||
{
|
||||
Provider: provider.ProviderAliyun,
|
||||
@@ -95,6 +109,61 @@ type ThinkingChatCompletionRequest struct {
|
||||
|
||||
// --- Customizer functions ---
|
||||
|
||||
type weKnoraCloudChatRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []weKnoraCloudMessage `json:"messages"`
|
||||
Stream bool `json:"stream"`
|
||||
MaxTokens int `json:"max_tokens,omitempty"`
|
||||
Temperature float64 `json:"temperature,omitempty"`
|
||||
TopP float64 `json:"top_p,omitempty"`
|
||||
}
|
||||
|
||||
type weKnoraCloudMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
func weKnoraCloudRequestCustomizer(req *openai.ChatCompletionRequest, opts *ChatOptions, isStream bool) (any, bool) {
|
||||
weKnoraCloudReq := weKnoraCloudChatRequest{
|
||||
Model: req.Model,
|
||||
Messages: convertToWeKnoraCloudMessagesFromOpenAI(req.Messages),
|
||||
Stream: isStream,
|
||||
}
|
||||
if opts != nil {
|
||||
weKnoraCloudReq.Temperature = opts.Temperature
|
||||
weKnoraCloudReq.TopP = opts.TopP
|
||||
weKnoraCloudReq.MaxTokens = opts.MaxTokens
|
||||
}
|
||||
return weKnoraCloudReq, true
|
||||
}
|
||||
|
||||
func weKnoraCloudHeaderCustomizer(chat *RemoteAPIChat, req *http.Request, body []byte) error {
|
||||
requestID := uuid.NewString()
|
||||
headers := modelutils.Sign(chat.appID, chat.appSecret, requestID, string(body))
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func convertToWeKnoraCloudMessagesFromOpenAI(messages []openai.ChatCompletionMessage) []weKnoraCloudMessage {
|
||||
result := make([]weKnoraCloudMessage, 0, len(messages))
|
||||
for _, m := range messages {
|
||||
content := m.Content
|
||||
if content == "" && len(m.MultiContent) > 0 {
|
||||
var textParts []string
|
||||
for _, part := range m.MultiContent {
|
||||
if part.Type == openai.ChatMessagePartTypeText && part.Text != "" {
|
||||
textParts = append(textParts, part.Text)
|
||||
}
|
||||
}
|
||||
content = strings.Join(textParts, "\n")
|
||||
}
|
||||
result = append(result, weKnoraCloudMessage{Role: m.Role, Content: content})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// qwenThinkingRequestCustomizer 自定义 Qwen 系列(阿里云)模型的思考请求
|
||||
func qwenThinkingRequestCustomizer(
|
||||
req *openai.ChatCompletionRequest, opts *ChatOptions, isStream bool,
|
||||
|
||||
@@ -39,6 +39,8 @@ type RemoteAPIChat struct {
|
||||
baseURL string
|
||||
apiKey string
|
||||
provider provider.ProviderName
|
||||
appID string
|
||||
appSecret string
|
||||
|
||||
// requestCustomizer 允许子类自定义请求
|
||||
// 返回自定义请求体(如果为 nil 则使用标准请求)和是否需要使用原始 HTTP 请求
|
||||
@@ -47,6 +49,9 @@ type RemoteAPIChat struct {
|
||||
// endpointCustomizer 允许子类自定义请求的 endpoint
|
||||
// 返回是否使用自定义请求地址, 返回空则使用默认OpenAI格式地址
|
||||
endpointCustomizer func(baseURL string, modelID string, isStream bool) (endpoint string)
|
||||
|
||||
// headerCustomizer 允许子类自定义原始 HTTP 请求头(例如签名认证)
|
||||
headerCustomizer func(req *http.Request, body []byte) error
|
||||
}
|
||||
|
||||
// NewRemoteAPIChat 创建远程 API 聊天实例
|
||||
@@ -69,11 +74,9 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
|
||||
config.AzureModelMapperFunc = func(model string) string {
|
||||
return model
|
||||
}
|
||||
if chatConfig.Extra != nil {
|
||||
if v, ok := chatConfig.Extra["api_version"]; ok {
|
||||
if vs, ok := v.(string); ok && vs != "" {
|
||||
config.APIVersion = vs
|
||||
}
|
||||
if chatConfig.ExtraConfig != nil {
|
||||
if v, ok := chatConfig.ExtraConfig["api_version"]; ok {
|
||||
config.APIVersion = v
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -83,13 +86,30 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
|
||||
}
|
||||
}
|
||||
|
||||
modelName := chatConfig.ModelName
|
||||
if chatConfig.ExtraConfig != nil {
|
||||
if override := strings.TrimSpace(chatConfig.ExtraConfig["remote_model_name"]); override != "" {
|
||||
modelName = override
|
||||
}
|
||||
}
|
||||
if providerName == provider.ProviderWeKnoraCloud {
|
||||
if chatConfig.AppID == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud provider: AppID is required")
|
||||
}
|
||||
if chatConfig.AppSecret == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud provider: AppSecret is required")
|
||||
}
|
||||
}
|
||||
|
||||
return &RemoteAPIChat{
|
||||
modelName: chatConfig.ModelName,
|
||||
modelName: modelName,
|
||||
client: openai.NewClientWithConfig(config),
|
||||
modelID: chatConfig.ModelID,
|
||||
baseURL: chatConfig.BaseURL,
|
||||
apiKey: apiKey,
|
||||
provider: providerName,
|
||||
appID: chatConfig.AppID,
|
||||
appSecret: chatConfig.AppSecret,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -103,6 +123,11 @@ func (c *RemoteAPIChat) SetEndpointCustomizer(customizer func(baseURL string, mo
|
||||
c.endpointCustomizer = customizer
|
||||
}
|
||||
|
||||
// SetHeaderCustomizer 设置原始 HTTP 请求头自定义器
|
||||
func (c *RemoteAPIChat) SetHeaderCustomizer(customizer func(req *http.Request, body []byte) error) {
|
||||
c.headerCustomizer = customizer
|
||||
}
|
||||
|
||||
// ConvertMessages 转换消息格式为 OpenAI 格式(导出供子类使用)
|
||||
func (c *RemoteAPIChat) ConvertMessages(messages []Message) []openai.ChatCompletionMessage {
|
||||
openaiMessages := make([]openai.ChatCompletionMessage, 0, len(messages))
|
||||
@@ -330,7 +355,12 @@ func (c *RemoteAPIChat) chatWithRawHTTP(ctx context.Context, endpoint string, cu
|
||||
}
|
||||
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
if c.provider == provider.ProviderAzureOpenAI {
|
||||
|
||||
if c.headerCustomizer != nil {
|
||||
if err := c.headerCustomizer(httpReq, jsonData); err != nil {
|
||||
return nil, fmt.Errorf("customize headers: %w", err)
|
||||
}
|
||||
} else if c.provider == provider.ProviderAzureOpenAI {
|
||||
httpReq.Header.Set("api-key", c.apiKey)
|
||||
} else {
|
||||
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
|
||||
@@ -486,7 +516,12 @@ func (c *RemoteAPIChat) chatStreamWithRawHTTP(ctx context.Context, endpoint stri
|
||||
}
|
||||
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
if c.provider == provider.ProviderAzureOpenAI {
|
||||
|
||||
if c.headerCustomizer != nil {
|
||||
if err := c.headerCustomizer(httpReq, jsonData); err != nil {
|
||||
return nil, fmt.Errorf("customize headers: %w", err)
|
||||
}
|
||||
} else if c.provider == provider.ProviderAzureOpenAI {
|
||||
httpReq.Header.Set("api-key", c.apiKey)
|
||||
} else {
|
||||
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
|
||||
|
||||
Reference in New Issue
Block a user