init commit
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/runtime"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ChatOptions 聊天选项
|
||||
type ChatOptions struct {
|
||||
Temperature float64 `json:"temperature"` // 温度参数
|
||||
TopP float64 `json:"top_p"` // Top P 参数
|
||||
Seed int `json:"seed"` // 随机种子
|
||||
MaxTokens int `json:"max_tokens"` // 最大 token 数
|
||||
MaxCompletionTokens int `json:"max_completion_tokens"` // 最大完成 token 数
|
||||
FrequencyPenalty float64 `json:"frequency_penalty"` // 频率惩罚
|
||||
PresencePenalty float64 `json:"presence_penalty"` // 存在惩罚
|
||||
Thinking *bool `json:"thinking"` // 是否启用思考
|
||||
}
|
||||
|
||||
// Message 表示聊天消息
|
||||
type Message struct {
|
||||
Role string `json:"role"` // 角色:system, user, assistant
|
||||
Content string `json:"content"` // 消息内容
|
||||
}
|
||||
|
||||
// Chat 定义了聊天接口
|
||||
type Chat interface {
|
||||
// Chat 进行非流式聊天
|
||||
Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error)
|
||||
|
||||
// ChatStream 进行流式聊天
|
||||
ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error)
|
||||
|
||||
// GetModelName 获取模型名称
|
||||
GetModelName() string
|
||||
|
||||
// GetModelID 获取模型ID
|
||||
GetModelID() string
|
||||
}
|
||||
|
||||
type ChatConfig struct {
|
||||
Source types.ModelSource
|
||||
BaseURL string
|
||||
ModelName string
|
||||
APIKey string
|
||||
ModelID string
|
||||
}
|
||||
|
||||
// NewChat 创建聊天实例
|
||||
func NewChat(config *ChatConfig) (Chat, error) {
|
||||
var chat Chat
|
||||
var err error
|
||||
switch strings.ToLower(string(config.Source)) {
|
||||
case string(types.ModelSourceLocal):
|
||||
runtime.GetContainer().Invoke(func(ollamaService *ollama.OllamaService) {
|
||||
chat, err = NewOllamaChat(config, ollamaService)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chat, nil
|
||||
case string(types.ModelSourceRemote):
|
||||
return NewRemoteAPIChat(config)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported chat model source: %s", config.Source)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
ollamaapi "github.com/ollama/ollama/api"
|
||||
)
|
||||
|
||||
// OllamaChat 实现了基于 Ollama 的聊天
|
||||
type OllamaChat struct {
|
||||
modelName string
|
||||
modelID string
|
||||
ollamaService *ollama.OllamaService
|
||||
}
|
||||
|
||||
// NewOllamaChat 创建 Ollama 聊天实例
|
||||
func NewOllamaChat(config *ChatConfig, ollamaService *ollama.OllamaService) (*OllamaChat, error) {
|
||||
return &OllamaChat{
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
ollamaService: ollamaService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// convertMessages 转换消息格式为Ollama API格式
|
||||
func (c *OllamaChat) convertMessages(messages []Message) []ollamaapi.Message {
|
||||
ollamaMessages := make([]ollamaapi.Message, len(messages))
|
||||
for i, msg := range messages {
|
||||
ollamaMessages[i] = ollamaapi.Message{
|
||||
Role: msg.Role,
|
||||
Content: msg.Content,
|
||||
}
|
||||
}
|
||||
return ollamaMessages
|
||||
}
|
||||
|
||||
// buildChatRequest 构建聊天请求参数
|
||||
func (c *OllamaChat) buildChatRequest(messages []Message, opts *ChatOptions, isStream bool) *ollamaapi.ChatRequest {
|
||||
// 设置流式标志
|
||||
streamFlag := isStream
|
||||
|
||||
// 构建请求参数
|
||||
chatReq := &ollamaapi.ChatRequest{
|
||||
Model: c.modelName,
|
||||
Messages: c.convertMessages(messages),
|
||||
Stream: &streamFlag,
|
||||
Options: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// 添加可选参数
|
||||
if opts != nil {
|
||||
if opts.Temperature > 0 {
|
||||
chatReq.Options["temperature"] = opts.Temperature
|
||||
}
|
||||
if opts.TopP > 0 {
|
||||
chatReq.Options["top_p"] = opts.TopP
|
||||
}
|
||||
if opts.MaxTokens > 0 {
|
||||
chatReq.Options["num_predict"] = opts.MaxTokens
|
||||
}
|
||||
if opts.Thinking != nil {
|
||||
chatReq.Options["think"] = *opts.Thinking
|
||||
}
|
||||
}
|
||||
|
||||
return chatReq
|
||||
}
|
||||
|
||||
// Chat 进行非流式聊天
|
||||
func (c *OllamaChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
|
||||
// 确保模型可用
|
||||
if err := c.ensureModelAvailable(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 构建请求参数
|
||||
chatReq := c.buildChatRequest(messages, opts, false)
|
||||
|
||||
// 记录请求日志
|
||||
logger.GetLogger(ctx).Infof("发送聊天请求到模型 %s", c.modelName)
|
||||
|
||||
var responseContent string
|
||||
var promptTokens, completionTokens int
|
||||
|
||||
// 使用 Ollama 客户端发送请求
|
||||
err := c.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
|
||||
responseContent = resp.Message.Content
|
||||
|
||||
// 获取token计数
|
||||
if resp.EvalCount > 0 {
|
||||
promptTokens = resp.PromptEvalCount
|
||||
completionTokens = resp.EvalCount - promptTokens
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("聊天请求失败: %w", err)
|
||||
}
|
||||
|
||||
// 构建响应
|
||||
return &types.ChatResponse{
|
||||
Content: responseContent,
|
||||
Usage: struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
}{
|
||||
PromptTokens: promptTokens,
|
||||
CompletionTokens: completionTokens,
|
||||
TotalTokens: promptTokens + completionTokens,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ChatStream 进行流式聊天
|
||||
func (c *OllamaChat) ChatStream(
|
||||
ctx context.Context,
|
||||
messages []Message,
|
||||
opts *ChatOptions,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
// 确保模型可用
|
||||
if err := c.ensureModelAvailable(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 构建请求参数
|
||||
chatReq := c.buildChatRequest(messages, opts, true)
|
||||
|
||||
// 记录请求日志
|
||||
logger.GetLogger(ctx).Infof("发送流式聊天请求到模型 %s", c.modelName)
|
||||
|
||||
// 创建流式响应通道
|
||||
streamChan := make(chan types.StreamResponse)
|
||||
|
||||
// 启动goroutine处理流式响应
|
||||
go func() {
|
||||
defer close(streamChan)
|
||||
|
||||
err := c.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
|
||||
if resp.Message.Content != "" {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: resp.Message.Content,
|
||||
Done: false,
|
||||
}
|
||||
}
|
||||
|
||||
if resp.Done {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("流式聊天请求失败: %v", err)
|
||||
// 发送错误响应
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return streamChan, nil
|
||||
}
|
||||
|
||||
// 确保模型可用
|
||||
func (c *OllamaChat) ensureModelAvailable(ctx context.Context) error {
|
||||
logger.GetLogger(ctx).Infof("确保模型 %s 可用", c.modelName)
|
||||
return c.ollamaService.EnsureModelAvailable(ctx, c.modelName)
|
||||
}
|
||||
|
||||
// GetModelName 获取模型名称
|
||||
func (c *OllamaChat) GetModelName() string {
|
||||
return c.modelName
|
||||
}
|
||||
|
||||
// GetModelID 获取模型ID
|
||||
func (c *OllamaChat) GetModelID() string {
|
||||
return c.modelID
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
// RemoteAPIChat 实现了基于的聊天
|
||||
type RemoteAPIChat struct {
|
||||
modelName string
|
||||
client *openai.Client
|
||||
modelID string
|
||||
}
|
||||
|
||||
// NewRemoteAPIChat 调用远程API 聊天实例
|
||||
func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
|
||||
apiKey := chatConfig.APIKey
|
||||
config := openai.DefaultConfig(apiKey)
|
||||
if baseURL := chatConfig.BaseURL; baseURL != "" {
|
||||
config.BaseURL = baseURL
|
||||
}
|
||||
return &RemoteAPIChat{
|
||||
modelName: chatConfig.ModelName,
|
||||
client: openai.NewClientWithConfig(config),
|
||||
modelID: chatConfig.ModelID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// convertMessages 转换消息格式为OpenAI格式
|
||||
func (c *RemoteAPIChat) convertMessages(messages []Message) []openai.ChatCompletionMessage {
|
||||
openaiMessages := make([]openai.ChatCompletionMessage, len(messages))
|
||||
for i, msg := range messages {
|
||||
openaiMessages[i] = openai.ChatCompletionMessage{
|
||||
Role: msg.Role,
|
||||
Content: msg.Content,
|
||||
}
|
||||
}
|
||||
return openaiMessages
|
||||
}
|
||||
|
||||
// buildChatCompletionRequest 构建聊天请求参数
|
||||
func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
|
||||
opts *ChatOptions, isStream bool,
|
||||
) openai.ChatCompletionRequest {
|
||||
req := openai.ChatCompletionRequest{
|
||||
Model: c.modelName,
|
||||
Messages: c.convertMessages(messages),
|
||||
Stream: isStream,
|
||||
}
|
||||
|
||||
// 添加可选参数
|
||||
if opts != nil {
|
||||
if opts.Temperature > 0 {
|
||||
req.Temperature = float32(opts.Temperature)
|
||||
}
|
||||
if opts.TopP > 0 {
|
||||
req.TopP = float32(opts.TopP)
|
||||
}
|
||||
if opts.MaxTokens > 0 {
|
||||
req.MaxTokens = opts.MaxTokens
|
||||
}
|
||||
if opts.MaxCompletionTokens > 0 {
|
||||
req.MaxCompletionTokens = opts.MaxCompletionTokens
|
||||
}
|
||||
if opts.FrequencyPenalty > 0 {
|
||||
req.FrequencyPenalty = float32(opts.FrequencyPenalty)
|
||||
}
|
||||
if opts.PresencePenalty > 0 {
|
||||
req.PresencePenalty = float32(opts.PresencePenalty)
|
||||
}
|
||||
if opts.Thinking != nil {
|
||||
req.ChatTemplateKwargs = map[string]any{
|
||||
"enable_thinking": *opts.Thinking,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
// Chat 进行非流式聊天
|
||||
func (c *RemoteAPIChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
|
||||
// 构建请求参数
|
||||
req := c.buildChatCompletionRequest(messages, opts, false)
|
||||
|
||||
// 发送请求
|
||||
resp, err := c.client.CreateChatCompletion(ctx, req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create chat completion: %w", err)
|
||||
}
|
||||
|
||||
if len(resp.Choices) == 0 {
|
||||
return nil, fmt.Errorf("no response from OpenAI")
|
||||
}
|
||||
|
||||
// 转换响应格式
|
||||
return &types.ChatResponse{
|
||||
Content: resp.Choices[0].Message.Content,
|
||||
Usage: struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
}{
|
||||
PromptTokens: resp.Usage.PromptTokens,
|
||||
CompletionTokens: resp.Usage.CompletionTokens,
|
||||
TotalTokens: resp.Usage.TotalTokens,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ChatStream 进行流式聊天
|
||||
func (c *RemoteAPIChat) ChatStream(ctx context.Context,
|
||||
messages []Message, opts *ChatOptions,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
// 构建请求参数
|
||||
req := c.buildChatCompletionRequest(messages, opts, true)
|
||||
|
||||
// 创建流式响应通道
|
||||
streamChan := make(chan types.StreamResponse)
|
||||
|
||||
// 启动流式请求
|
||||
stream, err := c.client.CreateChatCompletionStream(ctx, req)
|
||||
if err != nil {
|
||||
close(streamChan)
|
||||
return nil, fmt.Errorf("create chat completion stream: %w", err)
|
||||
}
|
||||
|
||||
// 在后台处理流式响应
|
||||
go func() {
|
||||
defer close(streamChan)
|
||||
defer stream.Close()
|
||||
|
||||
for {
|
||||
response, err := stream.Recv()
|
||||
if err != nil {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(response.Choices) > 0 {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: response.Choices[0].Delta.Content,
|
||||
Done: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return streamChan, nil
|
||||
}
|
||||
|
||||
// GetModelName 获取模型名称
|
||||
func (c *RemoteAPIChat) GetModelName() string {
|
||||
return c.modelName
|
||||
}
|
||||
|
||||
// GetModelID 获取模型ID
|
||||
func (c *RemoteAPIChat) GetModelID() string {
|
||||
return c.modelID
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/utils"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
)
|
||||
|
||||
type batchEmbedder struct {
|
||||
pool *ants.Pool
|
||||
}
|
||||
|
||||
func NewBatchEmbedder(pool *ants.Pool) EmbedderPooler {
|
||||
return &batchEmbedder{pool: pool}
|
||||
}
|
||||
|
||||
type textEmbedding struct {
|
||||
text string
|
||||
results []float32
|
||||
}
|
||||
|
||||
func (e *batchEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) {
|
||||
// Create goroutine pool for concurrent processing of document chunks
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex // For synchronizing access to error
|
||||
var firstErr error // Record the first error that occurs
|
||||
batchSize := 5
|
||||
textEmbeddings := utils.MapSlice(texts, func(text string) *textEmbedding {
|
||||
return &textEmbedding{text: text}
|
||||
})
|
||||
|
||||
// Function to process each document chunk
|
||||
processChunk := func(texts []*textEmbedding) func() {
|
||||
return func() {
|
||||
defer wg.Done()
|
||||
// If an error has already occurred, don't continue processing
|
||||
if firstErr != nil {
|
||||
return
|
||||
}
|
||||
// Embed text
|
||||
embedding, err := model.BatchEmbed(ctx, utils.MapSlice(texts, func(text *textEmbedding) string {
|
||||
return text.text
|
||||
}))
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
for i, text := range texts {
|
||||
text.results = embedding[i]
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Submit all tasks to the goroutine pool
|
||||
for _, texts := range utils.ChunkSlice(textEmbeddings, batchSize) {
|
||||
wg.Add(1)
|
||||
err := e.pool.Submit(processChunk(texts))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for all tasks to complete
|
||||
wg.Wait()
|
||||
|
||||
// Check if any errors occurred
|
||||
if firstErr != nil {
|
||||
return nil, firstErr
|
||||
}
|
||||
|
||||
results := utils.MapSlice(textEmbeddings, func(text *textEmbedding) []float32 {
|
||||
return text.results
|
||||
})
|
||||
return results, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/runtime"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Embedder defines the interface for text vectorization
|
||||
type Embedder interface {
|
||||
// Embed converts text to vector
|
||||
Embed(ctx context.Context, text string) ([]float32, error)
|
||||
|
||||
// BatchEmbed converts multiple texts to vectors in batch
|
||||
BatchEmbed(ctx context.Context, texts []string) ([][]float32, error)
|
||||
|
||||
// GetModelName returns the model name
|
||||
GetModelName() string
|
||||
|
||||
// GetDimensions returns the vector dimensions
|
||||
GetDimensions() int
|
||||
|
||||
// GetModelID returns the model ID
|
||||
GetModelID() string
|
||||
|
||||
EmbedderPooler
|
||||
}
|
||||
|
||||
type EmbedderPooler interface {
|
||||
BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error)
|
||||
}
|
||||
|
||||
// EmbedderType represents the embedder type
|
||||
type EmbedderType string
|
||||
|
||||
// Config represents the embedder configuration
|
||||
type Config struct {
|
||||
Source types.ModelSource `json:"source"`
|
||||
BaseURL string `json:"base_url"`
|
||||
ModelName string `json:"model_name"`
|
||||
APIKey string `json:"api_key"`
|
||||
TruncatePromptTokens int `json:"truncate_prompt_tokens"`
|
||||
Dimensions int `json:"dimensions"`
|
||||
ModelID string `json:"model_id"`
|
||||
}
|
||||
|
||||
// NewEmbedder creates an embedder based on the configuration
|
||||
func NewEmbedder(config Config) (Embedder, error) {
|
||||
var embedder Embedder
|
||||
var err error
|
||||
switch strings.ToLower(string(config.Source)) {
|
||||
case string(types.ModelSourceLocal):
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler, ollamaService *ollama.OllamaService) {
|
||||
embedder, err = NewOllamaEmbedder(config.BaseURL,
|
||||
config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler, ollamaService)
|
||||
})
|
||||
return embedder, err
|
||||
case string(types.ModelSourceRemote):
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler) {
|
||||
embedder, err = NewOpenAIEmbedder(config.APIKey,
|
||||
config.BaseURL,
|
||||
config.ModelName,
|
||||
config.TruncatePromptTokens,
|
||||
config.Dimensions,
|
||||
config.ModelID,
|
||||
pooler)
|
||||
})
|
||||
return embedder, err
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported embedder source: %s", config.Source)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
ollamaapi "github.com/ollama/ollama/api"
|
||||
)
|
||||
|
||||
// OllamaEmbedder implements text vectorization functionality using Ollama
|
||||
type OllamaEmbedder struct {
|
||||
modelName string
|
||||
truncatePromptTokens int
|
||||
ollamaService *ollama.OllamaService
|
||||
dimensions int
|
||||
modelID string
|
||||
EmbedderPooler
|
||||
}
|
||||
|
||||
// OllamaEmbedRequest represents an Ollama embedding request
|
||||
type OllamaEmbedRequest struct {
|
||||
Model string `json:"model"`
|
||||
Prompt string `json:"prompt"`
|
||||
TruncatePromptTokens int `json:"truncate_prompt_tokens"`
|
||||
}
|
||||
|
||||
// OllamaEmbedResponse represents an Ollama embedding response
|
||||
type OllamaEmbedResponse struct {
|
||||
Embedding []float32 `json:"embedding"`
|
||||
}
|
||||
|
||||
// NewOllamaEmbedder creates a new Ollama embedder
|
||||
func NewOllamaEmbedder(baseURL,
|
||||
modelName string,
|
||||
truncatePromptTokens int,
|
||||
dimensions int,
|
||||
modelID string,
|
||||
pooler EmbedderPooler,
|
||||
ollamaService *ollama.OllamaService,
|
||||
) (*OllamaEmbedder, error) {
|
||||
if modelName == "" {
|
||||
modelName = "nomic-embed-text"
|
||||
}
|
||||
|
||||
if truncatePromptTokens == 0 {
|
||||
truncatePromptTokens = 511
|
||||
}
|
||||
|
||||
return &OllamaEmbedder{
|
||||
modelName: modelName,
|
||||
truncatePromptTokens: truncatePromptTokens,
|
||||
ollamaService: ollamaService,
|
||||
EmbedderPooler: pooler,
|
||||
dimensions: dimensions,
|
||||
modelID: modelID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ensureModelAvailable ensures that the model is available
|
||||
func (e *OllamaEmbedder) ensureModelAvailable(ctx context.Context) error {
|
||||
logger.GetLogger(ctx).Infof("Ensuring model %s is available", e.modelName)
|
||||
return e.ollamaService.EnsureModelAvailable(ctx, e.modelName)
|
||||
}
|
||||
|
||||
// Embed converts text to vector
|
||||
func (e *OllamaEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
|
||||
embedding, err := e.BatchEmbed(ctx, []string{text})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to embed text: %w", err)
|
||||
}
|
||||
|
||||
if len(embedding) == 0 {
|
||||
return nil, fmt.Errorf("failed to embed text: %w", err)
|
||||
}
|
||||
|
||||
return embedding[0], nil
|
||||
}
|
||||
|
||||
// BatchEmbed converts multiple texts to vectors in batch
|
||||
func (e *OllamaEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
|
||||
// Ensure model is available
|
||||
if err := e.ensureModelAvailable(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create request
|
||||
req := &ollamaapi.EmbedRequest{
|
||||
Model: e.modelName,
|
||||
Input: texts,
|
||||
Options: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// Set truncation parameters
|
||||
if e.truncatePromptTokens > 0 {
|
||||
req.Options["truncate"] = e.truncatePromptTokens
|
||||
}
|
||||
|
||||
// Send request
|
||||
startTime := time.Now()
|
||||
resp, err := e.ollamaService.Embeddings(ctx, req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get embedding vectors: %w", err)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Debugf("Embedding vector retrieval took: %v", time.Since(startTime))
|
||||
return resp.Embeddings, nil
|
||||
}
|
||||
|
||||
// GetModelName returns the model name
|
||||
func (e *OllamaEmbedder) GetModelName() string {
|
||||
return e.modelName
|
||||
}
|
||||
|
||||
// GetDimensions returns the vector dimensions
|
||||
func (e *OllamaEmbedder) GetDimensions() int {
|
||||
return e.dimensions
|
||||
}
|
||||
|
||||
// GetModelID returns the model ID
|
||||
func (e *OllamaEmbedder) GetModelID() string {
|
||||
return e.modelID
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// OpenAIEmbedder implements text vectorization functionality using OpenAI API
|
||||
type OpenAIEmbedder struct {
|
||||
apiKey string
|
||||
baseURL string
|
||||
modelName string
|
||||
truncatePromptTokens int
|
||||
dimensions int
|
||||
modelID string
|
||||
httpClient *http.Client
|
||||
timeout time.Duration
|
||||
maxRetries int
|
||||
EmbedderPooler
|
||||
}
|
||||
|
||||
// OpenAIEmbedRequest represents an OpenAI embedding request
|
||||
type OpenAIEmbedRequest struct {
|
||||
Model string `json:"model"`
|
||||
Input []string `json:"input"`
|
||||
TruncatePromptTokens int `json:"truncate_prompt_tokens"`
|
||||
}
|
||||
|
||||
// OpenAIEmbedResponse represents an OpenAI embedding response
|
||||
type OpenAIEmbedResponse struct {
|
||||
Data []struct {
|
||||
Embedding []float32 `json:"embedding"`
|
||||
Index int `json:"index"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewOpenAIEmbedder creates a new OpenAI embedder
|
||||
func NewOpenAIEmbedder(apiKey, baseURL, modelName string,
|
||||
truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,
|
||||
) (*OpenAIEmbedder, error) {
|
||||
if baseURL == "" {
|
||||
baseURL = "https://api.openai.com/v1"
|
||||
}
|
||||
|
||||
if modelName == "" {
|
||||
return nil, fmt.Errorf("model name is required")
|
||||
}
|
||||
|
||||
if truncatePromptTokens == 0 {
|
||||
truncatePromptTokens = 511
|
||||
}
|
||||
|
||||
timeout := 60 * time.Second
|
||||
|
||||
// Create HTTP client
|
||||
client := &http.Client{
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
return &OpenAIEmbedder{
|
||||
apiKey: apiKey,
|
||||
baseURL: baseURL,
|
||||
modelName: modelName,
|
||||
httpClient: client,
|
||||
truncatePromptTokens: truncatePromptTokens,
|
||||
EmbedderPooler: pooler,
|
||||
dimensions: dimensions,
|
||||
modelID: modelID,
|
||||
timeout: timeout,
|
||||
maxRetries: 3, // Maximum retry count
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Embed converts text to vector
|
||||
func (e *OpenAIEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
|
||||
for range 3 {
|
||||
embeddings, err := e.BatchEmbed(ctx, []string{text})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(embeddings) > 0 {
|
||||
return embeddings[0], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no embedding returned")
|
||||
}
|
||||
|
||||
func (e *OpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {
|
||||
var resp *http.Response
|
||||
var err error
|
||||
url := e.baseURL + "/embeddings"
|
||||
|
||||
for i := 0; i <= e.maxRetries; i++ {
|
||||
if i > 0 {
|
||||
backoffTime := time.Duration(1<<uint(i-1)) * time.Second
|
||||
if backoffTime > 10*time.Second {
|
||||
backoffTime = 10 * time.Second
|
||||
}
|
||||
logger.GetLogger(ctx).Infof("OpenAIEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)
|
||||
|
||||
select {
|
||||
case <-time.After(backoffTime):
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild request each time to ensure Body is valid
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("OpenAIEmbedder failed to create request: %v", err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+e.apiKey)
|
||||
|
||||
resp, err = e.httpClient.Do(req)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Errorf("OpenAIEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (e *OpenAIEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
|
||||
// Create request body
|
||||
reqBody := OpenAIEmbedRequest{
|
||||
Model: e.modelName,
|
||||
Input: texts,
|
||||
TruncatePromptTokens: e.truncatePromptTokens,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch marshal request error: %v", err)
|
||||
return nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
|
||||
// Send request (passing jsonData instead of constructing http.Request)
|
||||
resp, err := e.doRequestWithRetry(ctx, jsonData)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch send request error: %v", err)
|
||||
return nil, fmt.Errorf("send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Read response
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch read response error: %v", err)
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch API error: Http Status %s", resp.Status)
|
||||
return nil, fmt.Errorf("EmbedBatch API error: Http Status %s", resp.Status)
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var response OpenAIEmbedResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch unmarshal response error: %v", err)
|
||||
return nil, fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
// Extract embedding vectors
|
||||
embeddings := make([][]float32, 0, len(response.Data))
|
||||
for _, data := range response.Data {
|
||||
embeddings = append(embeddings, data.Embedding)
|
||||
}
|
||||
|
||||
return embeddings, nil
|
||||
}
|
||||
|
||||
// GetModelName returns the model name
|
||||
func (e *OpenAIEmbedder) GetModelName() string {
|
||||
return e.modelName
|
||||
}
|
||||
|
||||
// GetDimensions returns the vector dimensions
|
||||
func (e *OpenAIEmbedder) GetDimensions() int {
|
||||
return e.dimensions
|
||||
}
|
||||
|
||||
// GetModelID returns the model ID
|
||||
func (e *OpenAIEmbedder) GetModelID() string {
|
||||
return e.modelID
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package rerank
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// OpenAIReranker implements a reranking system based on OpenAI models
|
||||
type OpenAIReranker struct {
|
||||
modelName string // Name of the model used for reranking
|
||||
modelID string // Unique identifier of the model
|
||||
apiKey string // API key for authentication
|
||||
baseURL string // Base URL for API requests
|
||||
client *http.Client // HTTP client for making API requests
|
||||
}
|
||||
|
||||
// RerankRequest represents a request to rerank documents based on relevance to a query
|
||||
type RerankRequest struct {
|
||||
Model string `json:"model"` // Model to use for reranking
|
||||
Query string `json:"query"` // Query text to compare documents against
|
||||
Documents []string `json:"documents"` // List of document texts to rerank
|
||||
AdditionalData map[string]interface{} `json:"additional_data"` // Optional additional data for the model
|
||||
TruncatePromptTokens int `json:"truncate_prompt_tokens"` // Maximum prompt tokens to use
|
||||
}
|
||||
|
||||
// RerankResponse represents the response from a reranking request
|
||||
type RerankResponse struct {
|
||||
ID string `json:"id"` // Request ID
|
||||
Model string `json:"model"` // Model used for reranking
|
||||
Usage UsageInfo `json:"usage"` // Token usage information
|
||||
Results []RankResult `json:"results"` // Ranked results with relevance scores
|
||||
}
|
||||
|
||||
// UsageInfo contains information about token usage in the API request
|
||||
type UsageInfo struct {
|
||||
TotalTokens int `json:"total_tokens"` // Total tokens consumed
|
||||
}
|
||||
|
||||
// NewOpenAIReranker creates a new instance of OpenAI reranker with the provided configuration
|
||||
func NewOpenAIReranker(config *RerankerConfig) (*OpenAIReranker, error) {
|
||||
apiKey := config.APIKey
|
||||
baseURL := "https://api.openai.com/v1"
|
||||
if url := config.BaseURL; url != "" {
|
||||
baseURL = url
|
||||
}
|
||||
|
||||
return &OpenAIReranker{
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
apiKey: apiKey,
|
||||
baseURL: baseURL,
|
||||
client: &http.Client{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Rerank performs document reranking based on relevance to the query
|
||||
func (r *OpenAIReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) {
|
||||
// Build the request body
|
||||
requestBody := &RerankRequest{
|
||||
Model: r.modelName,
|
||||
Query: query,
|
||||
Documents: documents,
|
||||
TruncatePromptTokens: 511,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(requestBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal request body: %w", err)
|
||||
}
|
||||
|
||||
// Send the request
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("%s/rerank", r.baseURL), bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey))
|
||||
|
||||
// Log the curl equivalent for debugging
|
||||
logger.GetLogger(ctx).Infof(
|
||||
"curl -X POST %s/rerank -H \"Content-Type: application/json\" -H \"Authorization: Bearer %s\" -d '%s'",
|
||||
r.baseURL, r.apiKey, string(jsonData),
|
||||
)
|
||||
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("do request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Read the response
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Rerank API error: Http Status: %s", resp.Status)
|
||||
}
|
||||
|
||||
var response RerankResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
return response.Results, nil
|
||||
}
|
||||
|
||||
// GetModelName returns the name of the reranking model
|
||||
func (r *OpenAIReranker) GetModelName() string {
|
||||
return r.modelName
|
||||
}
|
||||
|
||||
// GetModelID returns the unique identifier of the reranking model
|
||||
func (r *OpenAIReranker) GetModelID() string {
|
||||
return r.modelID
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package rerank
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Reranker defines the interface for document reranking
|
||||
type Reranker interface {
|
||||
// Rerank reranks documents based on relevance to the query
|
||||
Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error)
|
||||
|
||||
// GetModelName returns the model name
|
||||
GetModelName() string
|
||||
|
||||
// GetModelID returns the model ID
|
||||
GetModelID() string
|
||||
}
|
||||
|
||||
type RankResult struct {
|
||||
Index int `json:"index"`
|
||||
Document DocumentInfo `json:"document"`
|
||||
RelevanceScore float64 `json:"relevance_score"`
|
||||
}
|
||||
|
||||
type DocumentInfo struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type RerankerConfig struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
ModelName string
|
||||
Source types.ModelSource
|
||||
ModelID string
|
||||
}
|
||||
|
||||
// NewReranker creates a reranker
|
||||
func NewReranker(config *RerankerConfig) (Reranker, error) {
|
||||
switch strings.ToLower(string(config.Source)) {
|
||||
case string(types.ModelSourceRemote):
|
||||
return NewOpenAIReranker(config)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported rerank model source: %s", config.Source)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package ollama
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/ollama/ollama/api"
|
||||
)
|
||||
|
||||
// OllamaService manages Ollama service
|
||||
type OllamaService struct {
|
||||
client *api.Client
|
||||
baseURL string
|
||||
mu sync.Mutex
|
||||
isAvailable bool
|
||||
isOptional bool // Added: marks if Ollama service is optional
|
||||
}
|
||||
|
||||
// GetOllamaService gets Ollama service instance (singleton pattern)
|
||||
func GetOllamaService() (*OllamaService, error) {
|
||||
// Get Ollama base URL from environment variable, if not set use provided baseURL or default value
|
||||
logger.GetLogger(context.Background()).Infof("Ollama base URL: %s", os.Getenv("OLLAMA_BASE_URL"))
|
||||
baseURL := "http://localhost:11434"
|
||||
envURL := os.Getenv("OLLAMA_BASE_URL")
|
||||
if envURL != "" {
|
||||
baseURL = envURL
|
||||
}
|
||||
|
||||
// Create URL object
|
||||
parsedURL, err := url.Parse(baseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid Ollama service URL: %w", err)
|
||||
}
|
||||
|
||||
// Create official client
|
||||
client := api.NewClient(parsedURL, http.DefaultClient)
|
||||
|
||||
// Check if Ollama is set as optional
|
||||
isOptional := false
|
||||
if os.Getenv("OLLAMA_OPTIONAL") == "true" {
|
||||
isOptional = true
|
||||
logger.GetLogger(context.Background()).Info("Ollama service set to optional mode")
|
||||
}
|
||||
|
||||
service := &OllamaService{
|
||||
client: client,
|
||||
baseURL: baseURL,
|
||||
isOptional: isOptional,
|
||||
}
|
||||
|
||||
return service, nil
|
||||
}
|
||||
|
||||
// StartService checks if Ollama service is available
|
||||
func (s *OllamaService) StartService(ctx context.Context) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// Check if service is available
|
||||
err := s.client.Heartbeat(ctx)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("Ollama service unavailable: %v", err)
|
||||
s.isAvailable = false
|
||||
|
||||
// If configured as optional, don't return an error
|
||||
if s.isOptional {
|
||||
logger.GetLogger(ctx).Info("Ollama service set as optional, will continue running the application")
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("Ollama service unavailable: %w", err)
|
||||
}
|
||||
|
||||
s.isAvailable = true
|
||||
logger.GetLogger(ctx).Info("Ollama service ready")
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsAvailable returns whether the service is available
|
||||
func (s *OllamaService) IsAvailable() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.isAvailable
|
||||
}
|
||||
|
||||
// IsModelAvailable checks if a model is available
|
||||
func (s *OllamaService) IsModelAvailable(ctx context.Context, modelName string) (bool, error) {
|
||||
// First check if the service is available
|
||||
if err := s.StartService(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// If service is not available but set as optional, return false but no error
|
||||
if !s.isAvailable && s.isOptional {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Get model list
|
||||
listResp, err := s.client.List(ctx)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to get model list: %w", err)
|
||||
}
|
||||
|
||||
// Check if model is in the list
|
||||
for _, model := range listResp.Models {
|
||||
if model.Name == modelName {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// PullModel pulls a model
|
||||
func (s *OllamaService) PullModel(ctx context.Context, modelName string) error {
|
||||
// First check if the service is available
|
||||
if err := s.StartService(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// If service is not available but set as optional, return nil without further operations
|
||||
if !s.isAvailable && s.isOptional {
|
||||
logger.GetLogger(ctx).Warnf("Ollama service unavailable, unable to pull model %s", modelName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check if model already exists
|
||||
available, err := s.IsModelAvailable(ctx, modelName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if available {
|
||||
logger.GetLogger(ctx).Infof("Model %s already exists", modelName)
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("Pulling model %s...", modelName)
|
||||
|
||||
// Use official client to pull model
|
||||
pullReq := &api.PullRequest{
|
||||
Name: modelName,
|
||||
}
|
||||
|
||||
err = s.client.Pull(ctx, pullReq, func(progress api.ProgressResponse) error {
|
||||
if progress.Status != "" {
|
||||
if progress.Total > 0 && progress.Completed > 0 {
|
||||
percentage := float64(progress.Completed) / float64(progress.Total) * 100
|
||||
logger.GetLogger(ctx).Infof("Pull progress: %s (%.2f%%)",
|
||||
progress.Status, percentage)
|
||||
} else {
|
||||
logger.GetLogger(ctx).Infof("Pull status: %s", progress.Status)
|
||||
}
|
||||
}
|
||||
|
||||
if progress.Total > 0 && progress.Completed == progress.Total {
|
||||
logger.GetLogger(ctx).Infof("Model %s pull completed", modelName)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to pull model: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnsureModelAvailable ensures the model is available, pulls it if not available
|
||||
func (s *OllamaService) EnsureModelAvailable(ctx context.Context, modelName string) error {
|
||||
// If service is not available but set as optional, return nil directly
|
||||
if !s.IsAvailable() && s.isOptional {
|
||||
logger.GetLogger(ctx).Warnf("Ollama service unavailable, skipping ensuring model %s availability", modelName)
|
||||
return nil
|
||||
}
|
||||
|
||||
available, err := s.IsModelAvailable(ctx, modelName)
|
||||
if err != nil {
|
||||
if s.isOptional {
|
||||
logger.GetLogger(ctx).Warnf("Failed to check model %s availability, but Ollama is set as optional", modelName)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !available {
|
||||
return s.PullModel(ctx, modelName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetVersion gets Ollama version
|
||||
func (s *OllamaService) GetVersion(ctx context.Context) (string, error) {
|
||||
// If service is not available but set as optional, return empty version info
|
||||
if !s.IsAvailable() && s.isOptional {
|
||||
return "unavailable", nil
|
||||
}
|
||||
|
||||
version, err := s.client.Version(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get Ollama version: %w", err)
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
// CreateModel creates a custom model
|
||||
func (s *OllamaService) CreateModel(ctx context.Context, name, modelfile string) error {
|
||||
req := &api.CreateRequest{
|
||||
Model: name,
|
||||
Template: modelfile, // Use Template field instead of Modelfile
|
||||
}
|
||||
|
||||
err := s.client.Create(ctx, req, func(progress api.ProgressResponse) error {
|
||||
if progress.Status != "" {
|
||||
logger.GetLogger(ctx).Infof("Model creation status: %s", progress.Status)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create model: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetModelInfo gets model information
|
||||
func (s *OllamaService) GetModelInfo(ctx context.Context, modelName string) (*api.ShowResponse, error) {
|
||||
req := &api.ShowRequest{
|
||||
Name: modelName,
|
||||
}
|
||||
|
||||
resp, err := s.client.Show(ctx, req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get model information: %w", err)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListModels lists all available models
|
||||
func (s *OllamaService) ListModels(ctx context.Context) ([]string, error) {
|
||||
listResp, err := s.client.List(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get model list: %w", err)
|
||||
}
|
||||
|
||||
modelNames := make([]string, len(listResp.Models))
|
||||
for i, model := range listResp.Models {
|
||||
modelNames[i] = model.Name
|
||||
}
|
||||
|
||||
return modelNames, nil
|
||||
}
|
||||
|
||||
// DeleteModel deletes a model
|
||||
func (s *OllamaService) DeleteModel(ctx context.Context, modelName string) error {
|
||||
req := &api.DeleteRequest{
|
||||
Name: modelName,
|
||||
}
|
||||
|
||||
err := s.client.Delete(ctx, req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete model: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsValidModelName checks if model name is valid
|
||||
func IsValidModelName(name string) bool {
|
||||
// Simple check for model name format
|
||||
return name != "" && !strings.Contains(name, " ")
|
||||
}
|
||||
|
||||
// Chat uses Ollama chat
|
||||
func (s *OllamaService) Chat(ctx context.Context, req *api.ChatRequest, fn api.ChatResponseFunc) error {
|
||||
// First check if service is available
|
||||
if err := s.StartService(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Use official client Chat method
|
||||
return s.client.Chat(ctx, req, fn)
|
||||
}
|
||||
|
||||
// Embeddings gets text embedding vectors
|
||||
func (s *OllamaService) Embeddings(ctx context.Context, req *api.EmbedRequest) (*api.EmbedResponse, error) {
|
||||
// First check if service is available
|
||||
if err := s.StartService(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Use official client Embed method
|
||||
return s.client.Embed(ctx, req)
|
||||
}
|
||||
|
||||
// Generate generates text (used for Rerank)
|
||||
func (s *OllamaService) Generate(ctx context.Context, req *api.GenerateRequest, fn api.GenerateResponseFunc) error {
|
||||
// First check if service is available
|
||||
if err := s.StartService(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Use official client Generate method
|
||||
return s.client.Generate(ctx, req, fn)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package utils
|
||||
|
||||
// ChunkSlice splits a slice into multiple sub-slices of the specified size
|
||||
func ChunkSlice[T any](slice []T, chunkSize int) [][]T {
|
||||
// Handle edge cases
|
||||
if len(slice) == 0 {
|
||||
return [][]T{}
|
||||
}
|
||||
|
||||
if chunkSize <= 0 {
|
||||
panic("chunkSize must be greater than 0")
|
||||
}
|
||||
|
||||
// Calculate how many sub-slices are needed
|
||||
chunks := make([][]T, 0, (len(slice)+chunkSize-1)/chunkSize)
|
||||
|
||||
// Split the slice
|
||||
for i := 0; i < len(slice); i += chunkSize {
|
||||
end := i + chunkSize
|
||||
if end > len(slice) {
|
||||
end = len(slice)
|
||||
}
|
||||
chunks = append(chunks, slice[i:end])
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
// MapSlice applies a function to each element of a slice and returns a new slice with the results
|
||||
func MapSlice[A any, B any](in []A, f func(A) B) []B {
|
||||
out := make([]B, 0, len(in))
|
||||
for _, item := range in {
|
||||
out = append(out, f(item))
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user