LangChain ``Embeddings`` backed by an OpenAI-compatible HTTP API. The service must expose a ``POST /embeddings`` endpoint that accepts ``{"model": "…", "input": ["…"]}`` and returns the standard OpenAI response shape. Args: url: Base URL of the embedding service (e.g. ``"ht
| 12 | |
| 13 | |
| 14 | class ModalEmbeddings(Embeddings): |
| 15 | """LangChain ``Embeddings`` backed by an OpenAI-compatible HTTP API. |
| 16 | |
| 17 | The service must expose a ``POST /embeddings`` endpoint that accepts |
| 18 | ``{"model": "…", "input": ["…"]}`` and returns the standard OpenAI |
| 19 | response shape. |
| 20 | |
| 21 | Args: |
| 22 | url: Base URL of the embedding service (e.g. ``"http://localhost:1234/v1"``). |
| 23 | model_name: Model identifier(e.g. ``"intfloat/multilingual-e5-large-instruct"``). |
| 24 | api_key: Optional bearer token for authenticated endpoints. |
| 25 | """ |
| 26 | |
| 27 | def __init__(self, url: str, model_name: str, api_key: str = None): |
| 28 | self.url = url |
| 29 | self.model_name = model_name |
| 30 | self.api_key = api_key |
| 31 | |
| 32 | def embed(self, text: List[str]) -> List[List[float]]: |
| 33 | """Embed a list of texts via the configured API. |
| 34 | |
| 35 | Newlines are replaced with spaces before sending, since most |
| 36 | embedding models treat them as noise. |
| 37 | |
| 38 | Args: |
| 39 | text: Strings to embed. |
| 40 | |
| 41 | Returns: |
| 42 | list[list[float]]: One embedding vector per input string. |
| 43 | |
| 44 | Raises: |
| 45 | requests.HTTPError: If the API returns a non-2xx status. |
| 46 | """ |
| 47 | # Newlines degrade embedding quality for most models |
| 48 | cleaned_text = [t.replace("\n", " ") for t in text] |
| 49 | |
| 50 | payload = {"text": "\n".join(cleaned_text)} |
| 51 | |
| 52 | headers = {} |
| 53 | if self.api_key: |
| 54 | headers = {"x-api-key": self.api_key} |
| 55 | |
| 56 | response = requests.post(self.url, data=payload, files=[], headers=headers) |
| 57 | response.raise_for_status() |
| 58 | |
| 59 | # print(response.text) |
| 60 | return response.json() |
| 61 | |
| 62 | def embed_documents(self, text: List[str]) -> List[List[str]]: |
| 63 | """Embed multiple documents (LangChain interface). |
| 64 | |
| 65 | Args: |
| 66 | text: Document strings to embed. |
| 67 | |
| 68 | Returns: |
| 69 | list[list[float]]: One embedding vector per document. |
| 70 | """ |
| 71 | return self.embed(text) |
no outgoing calls
no test coverage detected