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)
|
||||
|
||||
@@ -47,7 +47,9 @@ type Config struct {
|
||||
Dimensions int `json:"dimensions"`
|
||||
ModelID string `json:"model_id"`
|
||||
Provider string `json:"provider"`
|
||||
Extra map[string]any `json:"extra,omitempty"`
|
||||
ExtraConfig map[string]string `json:"extra_config"`
|
||||
AppID string
|
||||
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
|
||||
}
|
||||
|
||||
// NewEmbedder creates an embedder based on the configuration
|
||||
@@ -129,11 +131,9 @@ func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll
|
||||
return embedder, err
|
||||
case provider.ProviderAzureOpenAI:
|
||||
apiVersion := "2024-10-21"
|
||||
if config.Extra != nil {
|
||||
if v, ok := config.Extra["api_version"]; ok {
|
||||
if vs, ok := v.(string); ok && vs != "" {
|
||||
apiVersion = vs
|
||||
}
|
||||
if config.ExtraConfig != nil {
|
||||
if v, ok := config.ExtraConfig["api_version"]; ok {
|
||||
apiVersion = v
|
||||
}
|
||||
}
|
||||
embedder, err = NewAzureOpenAIEmbedder(config.APIKey,
|
||||
@@ -153,6 +153,9 @@ func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll
|
||||
config.ModelID,
|
||||
pooler)
|
||||
return embedder, err
|
||||
case provider.ProviderWeKnoraCloud:
|
||||
embedder, err = NewWeKnoraCloudEmbedder(config)
|
||||
return embedder, err
|
||||
default:
|
||||
// Use OpenAI-compatible embedder for other providers
|
||||
embedder, err = NewOpenAIEmbedder(config.APIKey,
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/utils"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const weKnoraCloudEmbedPath = "/api/v1/embeddings"
|
||||
|
||||
// WeKnoraCloudEmbedder 实现 embedding.Embedder 接口,对接 WeKnoraCloud /api/v1/embeddings
|
||||
type WeKnoraCloudEmbedder struct {
|
||||
modelName string
|
||||
remoteModelName string
|
||||
modelID string
|
||||
appID string
|
||||
apiKey string
|
||||
baseURL string
|
||||
dimensions int
|
||||
client *http.Client
|
||||
EmbedderPooler
|
||||
}
|
||||
|
||||
// NewWeKnoraCloudEmbedder 构造 WeKnoraCloudEmbedder
|
||||
func NewWeKnoraCloudEmbedder(config Config) (*WeKnoraCloudEmbedder, error) {
|
||||
if config.AppID == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud embedder: AppID is required")
|
||||
}
|
||||
if config.AppSecret == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud embedder: AppSecret is required")
|
||||
}
|
||||
remoteModelName := ""
|
||||
if config.ExtraConfig != nil {
|
||||
remoteModelName = strings.TrimSpace(config.ExtraConfig["remote_model_name"])
|
||||
}
|
||||
return &WeKnoraCloudEmbedder{
|
||||
modelName: config.ModelName,
|
||||
remoteModelName: remoteModelName,
|
||||
modelID: config.ModelID,
|
||||
appID: config.AppID,
|
||||
apiKey: config.AppSecret,
|
||||
baseURL: strings.TrimRight(config.BaseURL, "/"),
|
||||
dimensions: config.Dimensions,
|
||||
client: &http.Client{Timeout: 60 * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type weKnoraCloudEmbedRequest struct {
|
||||
Model string `json:"model"`
|
||||
Input []string `json:"input"`
|
||||
}
|
||||
|
||||
type weKnoraCloudEmbedResponse struct {
|
||||
Data []struct {
|
||||
Index int `json:"index"`
|
||||
Embedding []float32 `json:"embedding"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (e *WeKnoraCloudEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
|
||||
results, err := e.BatchEmbed(ctx, []string{text})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(results) == 0 {
|
||||
return nil, fmt.Errorf("weknoracloud embedder: empty response")
|
||||
}
|
||||
return results[0], nil
|
||||
}
|
||||
|
||||
func (e *WeKnoraCloudEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
|
||||
reqBody := weKnoraCloudEmbedRequest{Model: e.effectiveModelName(), Input: texts}
|
||||
bodyBytes, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud embedder: marshal: %w", err)
|
||||
}
|
||||
|
||||
requestID := uuid.New().String()
|
||||
headers := utils.Sign(e.appID, e.apiKey, requestID, string(bodyBytes))
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.baseURL+weKnoraCloudEmbedPath, bytes.NewReader(bodyBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud embedder: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
resp, err := e.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud embedder: do request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud embedder: read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("weknoracloud embedder: status %d: %s", resp.StatusCode, string(respBytes))
|
||||
}
|
||||
|
||||
var embedResp weKnoraCloudEmbedResponse
|
||||
if err := json.Unmarshal(respBytes, &embedResp); err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud embedder: unmarshal: %w", err)
|
||||
}
|
||||
|
||||
result := make([][]float32, len(texts))
|
||||
for _, item := range embedResp.Data {
|
||||
if item.Index < len(result) {
|
||||
result[item.Index] = item.Embedding
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (e *WeKnoraCloudEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) {
|
||||
return e.BatchEmbed(ctx, texts)
|
||||
}
|
||||
|
||||
func (e *WeKnoraCloudEmbedder) effectiveModelName() string {
|
||||
if e.remoteModelName != "" {
|
||||
return e.remoteModelName
|
||||
}
|
||||
return e.modelName
|
||||
}
|
||||
|
||||
func (e *WeKnoraCloudEmbedder) GetModelName() string { return e.modelName }
|
||||
func (e *WeKnoraCloudEmbedder) GetModelID() string { return e.modelID }
|
||||
func (e *WeKnoraCloudEmbedder) GetDimensions() int { return e.dimensions }
|
||||
@@ -87,6 +87,7 @@ func AllProviders() []ProviderName {
|
||||
ProviderNvidia,
|
||||
ProviderNovita,
|
||||
ProviderAzureOpenAI,
|
||||
ProviderWeKnoraCloud,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package provider
|
||||
|
||||
import "github.com/Tencent/WeKnora/internal/types"
|
||||
|
||||
const (
|
||||
ProviderWeKnoraCloud ProviderName = "weknoracloud"
|
||||
|
||||
// WeKnoraCloudBaseURL WeKnoraCloud 服务硬编码 Base URL(统一入口,路径由各实现拼接)
|
||||
WeKnoraCloudBaseURL = "https://weknora.weixin.qq.com"
|
||||
)
|
||||
|
||||
type WeKnoraCloudProvider struct{}
|
||||
|
||||
func init() {
|
||||
Register(&WeKnoraCloudProvider{})
|
||||
}
|
||||
|
||||
func (p *WeKnoraCloudProvider) Info() ProviderInfo {
|
||||
return ProviderInfo{
|
||||
Name: ProviderWeKnoraCloud,
|
||||
DisplayName: "WeKnoraCloud",
|
||||
Description: "WeKnoraCloud 平台,提供 Chat / Embedding / Rerank 模型,使用 APPID + API Key 签名认证",
|
||||
DefaultURLs: map[types.ModelType]string{
|
||||
types.ModelTypeKnowledgeQA: WeKnoraCloudBaseURL,
|
||||
types.ModelTypeEmbedding: WeKnoraCloudBaseURL,
|
||||
types.ModelTypeRerank: WeKnoraCloudBaseURL,
|
||||
},
|
||||
ModelTypes: []types.ModelType{
|
||||
types.ModelTypeKnowledgeQA,
|
||||
types.ModelTypeEmbedding,
|
||||
types.ModelTypeRerank,
|
||||
},
|
||||
RequiresAuth: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *WeKnoraCloudProvider) ValidateConfig(config *Config) error {
|
||||
// AppID/AppSecret 通过专用初始化接口写入,此处仅做结构校验。
|
||||
// 其中 AppSecret 字段当前实际承载上游 API Key。
|
||||
return nil
|
||||
}
|
||||
@@ -78,12 +78,15 @@ func (d *DocumentInfo) UnmarshalJSON(data []byte) error {
|
||||
}
|
||||
|
||||
type RerankerConfig struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
ModelName string
|
||||
Source types.ModelSource
|
||||
ModelID string
|
||||
Provider string // Provider identifier: openai, aliyun, zhipu, siliconflow, jina, generic
|
||||
APIKey string
|
||||
BaseURL string
|
||||
ModelName string
|
||||
Source types.ModelSource
|
||||
ModelID string
|
||||
Provider string // Provider identifier: openai, aliyun, zhipu, siliconflow, jina, generic
|
||||
ExtraConfig map[string]string
|
||||
AppID string
|
||||
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
|
||||
}
|
||||
|
||||
// NewReranker creates a reranker based on the configuration
|
||||
@@ -103,6 +106,8 @@ func NewReranker(config *RerankerConfig) (Reranker, error) {
|
||||
return NewJinaReranker(config)
|
||||
case provider.ProviderNvidia:
|
||||
return NewNvidiaReranker(config)
|
||||
case provider.ProviderWeKnoraCloud:
|
||||
return NewWeKnoraCloudReranker(config)
|
||||
default:
|
||||
return NewOpenAIReranker(config)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package rerank
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/utils"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const weKnoraCloudRerankPath = "/api/v1/rerank"
|
||||
|
||||
// WeKnoraCloudReranker 实现 rerank.Reranker 接口,对接 WeKnoraCloud /api/v1/rerank
|
||||
type WeKnoraCloudReranker struct {
|
||||
modelName string
|
||||
remoteModelName string
|
||||
modelID string
|
||||
appID string
|
||||
apiKey string
|
||||
baseURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewWeKnoraCloudReranker 构造 WeKnoraCloudReranker
|
||||
func NewWeKnoraCloudReranker(config *RerankerConfig) (*WeKnoraCloudReranker, error) {
|
||||
if config.AppID == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud reranker: AppID is required")
|
||||
}
|
||||
if config.AppSecret == "" {
|
||||
return nil, fmt.Errorf("WeKnoraCloud reranker: AppSecret is required")
|
||||
}
|
||||
remoteModelName := ""
|
||||
if config.ExtraConfig != nil {
|
||||
remoteModelName = strings.TrimSpace(config.ExtraConfig["remote_model_name"])
|
||||
}
|
||||
return &WeKnoraCloudReranker{
|
||||
modelName: config.ModelName,
|
||||
remoteModelName: remoteModelName,
|
||||
modelID: config.ModelID,
|
||||
appID: config.AppID,
|
||||
apiKey: config.AppSecret,
|
||||
baseURL: strings.TrimRight(config.BaseURL, "/"),
|
||||
client: &http.Client{Timeout: 60 * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type weKnoraCloudRerankRequest struct {
|
||||
Model string `json:"model"`
|
||||
Query string `json:"query"`
|
||||
Documents []string `json:"documents"`
|
||||
}
|
||||
|
||||
type weKnoraCloudRerankResponse struct {
|
||||
Results []struct {
|
||||
Index int `json:"index"`
|
||||
RelevanceScore float64 `json:"relevance_score"`
|
||||
Document struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"document"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
func (r *WeKnoraCloudReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) {
|
||||
reqBody := weKnoraCloudRerankRequest{
|
||||
Model: r.effectiveModelName(),
|
||||
Query: query,
|
||||
Documents: documents,
|
||||
}
|
||||
bodyBytes, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud reranker: marshal: %w", err)
|
||||
}
|
||||
|
||||
requestID := uuid.New().String()
|
||||
headers := utils.Sign(r.appID, r.apiKey, requestID, string(bodyBytes))
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.baseURL+weKnoraCloudRerankPath, bytes.NewReader(bodyBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud reranker: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud reranker: do request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud reranker: read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("weknoracloud reranker: status %d: %s", resp.StatusCode, string(respBytes))
|
||||
}
|
||||
|
||||
var rerankResp weKnoraCloudRerankResponse
|
||||
if err := json.Unmarshal(respBytes, &rerankResp); err != nil {
|
||||
return nil, fmt.Errorf("weknoracloud reranker: unmarshal: %w", err)
|
||||
}
|
||||
|
||||
results := make([]RankResult, 0, len(rerankResp.Results))
|
||||
for _, item := range rerankResp.Results {
|
||||
results = append(results, RankResult{
|
||||
Index: item.Index,
|
||||
RelevanceScore: item.RelevanceScore,
|
||||
Document: DocumentInfo{Text: item.Document.Text},
|
||||
})
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (r *WeKnoraCloudReranker) effectiveModelName() string {
|
||||
if r.remoteModelName != "" {
|
||||
return r.remoteModelName
|
||||
}
|
||||
return r.modelName
|
||||
}
|
||||
|
||||
func (r *WeKnoraCloudReranker) GetModelName() string { return r.modelName }
|
||||
func (r *WeKnoraCloudReranker) GetModelID() string { return r.modelID }
|
||||
@@ -0,0 +1,93 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
nonceChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
nonceLength = 16
|
||||
)
|
||||
|
||||
// Sign 按 WeKnoraCloud 参考实现生成请求头。
|
||||
// appID: 上游 APPID
|
||||
// apiKey: 上游 API Key(当前沿用 AppSecret 字段承载)
|
||||
// requestID: 每次请求唯一的 UUID 字符串
|
||||
// bodyJSON: 请求体 JSON 字符串,空请求体传 "{}"
|
||||
func Sign(appID, apiKey, requestID, bodyJSON string) map[string]string {
|
||||
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
nonce := generateNonce(nonceLength)
|
||||
|
||||
bodyForHash := bodyJSON
|
||||
if bodyForHash == "" {
|
||||
bodyForHash = "{}"
|
||||
}
|
||||
bodyMD5 := md5Hex(bodyForHash)
|
||||
|
||||
params := map[string]string{
|
||||
"x-appid": appID,
|
||||
"x-api-key": apiKey,
|
||||
"x-request-id": requestID,
|
||||
"x-timestamp": timestamp,
|
||||
"x-nonce": nonce,
|
||||
"body": bodyMD5,
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(params))
|
||||
for k := range params {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
parts := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
parts = append(parts, rfc3986Encode(k)+"="+rfc3986Encode(params[k]))
|
||||
}
|
||||
signature := md5Hex(strings.Join(parts, "&"))
|
||||
|
||||
return map[string]string{
|
||||
"X-APPID": appID,
|
||||
"X-API-Key": apiKey,
|
||||
"X-Request-ID": requestID,
|
||||
"X-Timestamp": timestamp,
|
||||
"X-Nonce": nonce,
|
||||
"X-Signature": signature,
|
||||
}
|
||||
}
|
||||
|
||||
func md5Hex(s string) string {
|
||||
h := md5.New()
|
||||
h.Write([]byte(s))
|
||||
return fmt.Sprintf("%x", h.Sum(nil))
|
||||
}
|
||||
|
||||
func generateNonce(length int) string {
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = nonceChars[rand.Intn(len(nonceChars))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// rfc3986Encode 对字符串做 RFC3986 编码
|
||||
// 保留字符:A-Z a-z 0-9 - _ . ~
|
||||
func rfc3986Encode(s string) string {
|
||||
var buf bytes.Buffer
|
||||
for _, r := range s {
|
||||
if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') ||
|
||||
(r >= '0' && r <= '9') || r == '-' || r == '_' ||
|
||||
r == '.' || r == '~' {
|
||||
buf.WriteRune(r)
|
||||
} else {
|
||||
fmt.Fprintf(&buf, "%%%02X", r)
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
Reference in New Issue
Block a user