File size: 3,159 Bytes
3536fc0
 
c9b82b3
 
60532a1
c9b82b3
 
3536fc0
 
 
 
c9b82b3
 
 
 
 
 
3536fc0
 
eede10d
 
3536fc0
 
 
 
 
 
 
 
 
c9b82b3
 
 
 
 
 
3536fc0
3a5efa8
3536fc0
 
3a5efa8
3536fc0
 
 
c9b82b3
 
3536fc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212ff4c
3536fc0
212ff4c
3536fc0
c9b82b3
 
3536fc0
212ff4c
3536fc0
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import ollama
import openai
import voyageai
import voyageai.client
from knowlang.configs.config import EmbeddingConfig, ModelProvider
from typing import Union, List, overload, Optional
from enum import Enum

# Type definitions
EmbeddingVector = List[float]


class EmbeddingInputType(Enum):
    DOCUMENT = "document"
    QUERY = "query"


def _process_ollama_batch(inputs: List[str], model_name: str) -> List[EmbeddingVector]:
    """Helper function to process Ollama embeddings in batch."""
    return ollama.embed(model=model_name, input=inputs)['embeddings']
    

def _process_openai_batch(inputs: List[str], model_name: str) -> List[EmbeddingVector]:
    """Helper function to process OpenAI embeddings in batch."""
    response = openai.embeddings.create(
        input=inputs,
        model=model_name
    )
    return [item.embedding for item in response.data]

def _process_voiage_batch(inputs: List[str], model_name: str, input_type:EmbeddingInputType) -> List[EmbeddingVector]:
    """Helper function to process VoyageAI embeddings in batch."""
    vo = voyageai.Client()
    embeddings_obj = vo.embed(model=model_name, texts=inputs, input_type=input_type.value)
    return embeddings_obj.embeddings

@overload
def generate_embedding(input: str, config: EmbeddingConfig, input_type: Optional[EmbeddingInputType]) -> EmbeddingVector: ...

@overload
def generate_embedding(input: List[str], config: EmbeddingConfig, input_type: Optional[EmbeddingInputType]) -> List[EmbeddingVector]: ...

def generate_embedding(
    input: Union[str, List[str]], 
    config: EmbeddingConfig,
    input_type: Optional[EmbeddingInputType] = EmbeddingInputType.DOCUMENT
) -> Union[EmbeddingVector, List[EmbeddingVector]]:
    """
    Generate embeddings for single text input or batch of texts.
    
    Args:
        input: Single string or list of strings to embed
        config: Configuration object containing provider and model information
    
    Returns:
        Single embedding vector for single input, or list of embedding vectors for batch input
    
    Raises:
        ValueError: If input type is invalid or provider is not supported
        RuntimeError: If embedding generation fails
    """
    if not input:
        raise ValueError("Input cannot be empty")

    # Convert single string to list for batch processing
    is_single_input = isinstance(input, str)
    inputs = [input] if is_single_input else input

    try:
        if config.model_provider == ModelProvider.OLLAMA:
            embeddings = _process_ollama_batch(inputs, config.model_name)
        elif config.model_provider == ModelProvider.OPENAI:
            embeddings = _process_openai_batch(inputs, config.model_name)
        elif config.model_provider == ModelProvider.VOYAGE:
            embeddings = _process_voiage_batch(inputs, config.model_name, input_type)
        else:
            raise ValueError(f"Unsupported provider: {config.model_provider}")

        # Return single embedding for single input
        return embeddings[0] if is_single_input else embeddings

    except Exception as e:
        raise RuntimeError(f"Failed to generate embeddings: {str(e)}") from e