langchain/libs/community/langchain_community/embeddings/cloudflare_workersai.py
Eugene Yurtsev bf5193bb99
community[patch]: Upgrade pydantic extra (#25185)
Upgrade to using a literal for specifying the extra which is the
recommended approach in pydantic 2.

This works correctly also in pydantic v1.

```python
from pydantic.v1 import BaseModel

class Foo(BaseModel, extra="forbid"):
    x: int

Foo(x=5, y=1)
```

And 


```python
from pydantic.v1 import BaseModel

class Foo(BaseModel):
    x: int

    class Config:
      extra = "forbid"

Foo(x=5, y=1)
```


## Enum -> literal using grit pattern:

```
engine marzano(0.1)
language python
or {
    `extra=Extra.allow` => `extra="allow"`,
    `extra=Extra.forbid` => `extra="forbid"`,
    `extra=Extra.ignore` => `extra="ignore"`
}
```

Resorted attributes in config and removed doc-string in case we will
need to deal with going back and forth between pydantic v1 and v2 during
the 0.3 release. (This will reduce merge conflicts.)


## Sort attributes in Config:

```
engine marzano(0.1)
language python


function sort($values) js {
    return $values.text.split(',').sort().join("\n");
}


class_definition($name, $body) as $C where {
    $name <: `Config`,
    $body <: block($statements),
    $values = [],
    $statements <: some bubble($values) assignment() as $A where {
        $values += $A
    },
    $body => sort($values),
}

```
2024-08-08 17:20:39 +00:00

93 lines
2.7 KiB
Python

from typing import Any, Dict, List
import requests
from langchain_core.embeddings import Embeddings
from langchain_core.pydantic_v1 import BaseModel
DEFAULT_MODEL_NAME = "@cf/baai/bge-base-en-v1.5"
class CloudflareWorkersAIEmbeddings(BaseModel, Embeddings):
"""Cloudflare Workers AI embedding model.
To use, you need to provide an API token and
account ID to access Cloudflare Workers AI.
Example:
.. code-block:: python
from langchain_community.embeddings import CloudflareWorkersAIEmbeddings
account_id = "my_account_id"
api_token = "my_secret_api_token"
model_name = "@cf/baai/bge-small-en-v1.5"
cf = CloudflareWorkersAIEmbeddings(
account_id=account_id,
api_token=api_token,
model_name=model_name
)
"""
api_base_url: str = "https://api.cloudflare.com/client/v4/accounts"
account_id: str
api_token: str
model_name: str = DEFAULT_MODEL_NAME
batch_size: int = 50
strip_new_lines: bool = True
headers: Dict[str, str] = {"Authorization": "Bearer "}
def __init__(self, **kwargs: Any):
"""Initialize the Cloudflare Workers AI client."""
super().__init__(**kwargs)
self.headers = {"Authorization": f"Bearer {self.api_token}"}
class Config:
extra = "forbid"
def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Compute doc embeddings using Cloudflare Workers AI.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
if self.strip_new_lines:
texts = [text.replace("\n", " ") for text in texts]
batches = [
texts[i : i + self.batch_size]
for i in range(0, len(texts), self.batch_size)
]
embeddings = []
for batch in batches:
response = requests.post(
f"{self.api_base_url}/{self.account_id}/ai/run/{self.model_name}",
headers=self.headers,
json={"text": batch},
)
embeddings.extend(response.json()["result"]["data"])
return embeddings
def embed_query(self, text: str) -> List[float]:
"""Compute query embeddings using Cloudflare Workers AI.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
text = text.replace("\n", " ") if self.strip_new_lines else text
response = requests.post(
f"{self.api_base_url}/{self.account_id}/ai/run/{self.model_name}",
headers=self.headers,
json={"text": [text]},
)
return response.json()["result"]["data"][0]