|
| 1 | +import os |
| 2 | +from typing import List, Union |
| 3 | + |
| 4 | +import requests |
| 5 | + |
| 6 | +from deepsearcher.embedding.base import BaseEmbedding |
| 7 | + |
| 8 | +# TODO: Update with actual JiekouAI model dimensions when available |
| 9 | +JIEKOUAI_MODEL_DIM_MAP = { |
| 10 | + "qwen/qwen3-embedding-0.6b": 1024, |
| 11 | + "qwen/qwen3-embedding-8b": 1024, |
| 12 | + "baai/bge-m3": 1024, |
| 13 | +} |
| 14 | + |
| 15 | +JIEKOUAI_EMBEDDING_API = "https://api.jiekou.ai/openai/v1/embeddings" |
| 16 | + |
| 17 | + |
| 18 | +class JiekouAIEmbedding(BaseEmbedding): |
| 19 | + """ |
| 20 | + JiekouAI embedding model implementation. |
| 21 | +
|
| 22 | + This class provides an interface to the JiekouAI embedding API, which offers |
| 23 | + various embedding models for text processing. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__(self, model="qwen/qwen3-embedding-8b", batch_size=32, **kwargs): |
| 27 | + """ |
| 28 | + Initialize the JiekouAI embedding model. |
| 29 | +
|
| 30 | + Args: |
| 31 | + model (str): The model identifier to use for embeddings. Default is "baai/bge-m3". |
| 32 | + batch_size (int): Maximum number of texts to process in a single batch. Default is 32. |
| 33 | + **kwargs: Additional keyword arguments. |
| 34 | + - api_key (str, optional): The JiekouAI API key. If not provided, |
| 35 | + it will be read from the JIEKOU_API_KEY environment variable. |
| 36 | + - model_name (str, optional): Alternative way to specify the model. |
| 37 | +
|
| 38 | + Raises: |
| 39 | + RuntimeError: If no API key is provided or found in environment variables. |
| 40 | + """ |
| 41 | + if "model_name" in kwargs and (not model or model == "qwen/qwen3-embedding-8b"): |
| 42 | + model = kwargs.pop("model_name") |
| 43 | + self.model = model |
| 44 | + |
| 45 | + if "api_key" in kwargs: |
| 46 | + api_key = kwargs.pop("api_key") |
| 47 | + else: |
| 48 | + api_key = os.getenv("JIEKOU_API_KEY") |
| 49 | + |
| 50 | + if not api_key or len(api_key) == 0: |
| 51 | + raise RuntimeError("api_key is required for JiekouAIEmbedding") |
| 52 | + self.api_key = api_key |
| 53 | + self.batch_size = batch_size |
| 54 | + |
| 55 | + def embed_query(self, text: str) -> List[float]: |
| 56 | + """ |
| 57 | + Embed a single query text. |
| 58 | +
|
| 59 | + Args: |
| 60 | + text (str): The query text to embed. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + List[float]: A list of floats representing the embedding vector. |
| 64 | + """ |
| 65 | + return self._embed_input(text)[0] |
| 66 | + |
| 67 | + def embed_documents(self, texts: List[str]) -> List[List[float]]: |
| 68 | + """ |
| 69 | + Embed a list of document texts. |
| 70 | +
|
| 71 | + This method handles batching of document embeddings based on the configured |
| 72 | + batch size to optimize API calls. |
| 73 | +
|
| 74 | + Args: |
| 75 | + texts (List[str]): A list of document texts to embed. |
| 76 | +
|
| 77 | + Returns: |
| 78 | + List[List[float]]: A list of embedding vectors, one for each input text. |
| 79 | + """ |
| 80 | + # batch embedding |
| 81 | + if self.batch_size > 0: |
| 82 | + if len(texts) > self.batch_size: |
| 83 | + batch_texts = [ |
| 84 | + texts[i : i + self.batch_size] for i in range(0, len(texts), self.batch_size) |
| 85 | + ] |
| 86 | + embeddings = [] |
| 87 | + for batch_text in batch_texts: |
| 88 | + batch_embeddings = self._embed_input(batch_text) |
| 89 | + embeddings.extend(batch_embeddings) |
| 90 | + return embeddings |
| 91 | + return self._embed_input(texts) |
| 92 | + return [self.embed_query(text) for text in texts] |
| 93 | + |
| 94 | + def _embed_input(self, input: Union[str, List[str]]) -> List[List[float]]: |
| 95 | + """ |
| 96 | + Internal method to handle the API call for embedding inputs. |
| 97 | +
|
| 98 | + Args: |
| 99 | + input (Union[str, List[str]]): Either a single text string or a list of text strings to embed. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + List[List[float]]: A list of embedding vectors for the input(s). |
| 103 | +
|
| 104 | + Raises: |
| 105 | + HTTPError: If the API request fails. |
| 106 | + """ |
| 107 | + headers = { |
| 108 | + "Authorization": f"Bearer {self.api_key}", |
| 109 | + "Content-Type": "application/json", |
| 110 | + } |
| 111 | + |
| 112 | + # Handle both single string and list of strings |
| 113 | + input_list = input if isinstance(input, list) else [input] |
| 114 | + |
| 115 | + payload = {"model": self.model, "input": input_list} |
| 116 | + |
| 117 | + response = requests.request("POST", JIEKOUAI_EMBEDDING_API, json=payload, headers=headers) |
| 118 | + response.raise_for_status() |
| 119 | + result = response.json()["data"] |
| 120 | + sorted_results = sorted(result, key=lambda x: x["index"]) |
| 121 | + return [res["embedding"] for res in sorted_results] |
| 122 | + |
| 123 | + @property |
| 124 | + def dimension(self) -> int: |
| 125 | + """ |
| 126 | + Get the dimensionality of the embeddings for the current model. |
| 127 | +
|
| 128 | + Returns: |
| 129 | + int: The number of dimensions in the embedding vectors. |
| 130 | + """ |
| 131 | + return JIEKOUAI_MODEL_DIM_MAP[self.model] |
0 commit comments