-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Draft implementation of support for embeddings APIs #3252
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
dmontagu
wants to merge
6
commits into
main
Choose a base branch
from
embeddings-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+5,535
−79
Draft
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3dbad0d
Draft implementation of support for embeddings APIs
dmontagu 467bb8e
Merge branch 'main' into embeddings-api
DouweM 00d8e26
Progress is made
DouweM a133796
Merge branch 'main' into embeddings-api
DouweM 6d9e2a5
fix typing
DouweM 9ffddf8
fix tests
DouweM File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| from collections.abc import Iterator, Sequence | ||
| from contextlib import contextmanager | ||
| from contextvars import ContextVar | ||
| from dataclasses import dataclass | ||
| from typing import Literal, overload | ||
|
|
||
| from typing_extensions import TypeAliasType | ||
|
|
||
| from pydantic_ai import _utils | ||
| from pydantic_ai.embeddings.embedding_model import EmbeddingModel | ||
| from pydantic_ai.embeddings.settings import EmbeddingSettings, merge_embedding_settings | ||
| from pydantic_ai.exceptions import UserError | ||
| from pydantic_ai.models.instrumented import InstrumentationSettings | ||
| from pydantic_ai.providers import infer_provider | ||
|
|
||
| KnownEmbeddingModelName = TypeAliasType( | ||
| 'KnownEmbeddingModelName', | ||
| Literal[ | ||
| 'openai:text-embedding-ada-002', | ||
| 'openai:text-embedding-3-small', | ||
| 'openai:text-embedding-3-largecohere:embed-v4.0', | ||
| ], | ||
| ) | ||
| """Known model names that can be used with the `model` parameter of [`Agent`][pydantic_ai.Agent]. | ||
|
|
||
| `KnownModelName` is provided as a concise way to specify a model. | ||
| """ | ||
|
|
||
|
|
||
| def infer_model(model: EmbeddingModel | KnownEmbeddingModelName | str) -> EmbeddingModel: | ||
| """Infer the model from the name.""" | ||
| if isinstance(model, EmbeddingModel): | ||
| return model | ||
|
|
||
| try: | ||
| provider_name, model_name = model.split(':', maxsplit=1) | ||
| except ValueError as e: | ||
| raise ValueError('You must provide a provider prefix when specifying an embedding model name') from e | ||
|
|
||
| provider = infer_provider(provider_name) | ||
|
|
||
| model_kind = provider_name | ||
| if model_kind.startswith('gateway/'): | ||
| model_kind = provider_name.removeprefix('gateway/') | ||
|
|
||
| # TODO: extend the following list for other providers as appropriate | ||
DouweM marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if model_kind in ('openai',): | ||
| model_kind = 'openai' | ||
|
|
||
| if model_kind == 'openai': | ||
| from .openai import OpenAIEmbeddingModel | ||
|
|
||
| return OpenAIEmbeddingModel(model_name, provider=provider) | ||
| elif model_kind == 'cohere': | ||
| from .cohere import CohereEmbeddingModel | ||
|
|
||
| return CohereEmbeddingModel(model_name, provider=provider) | ||
| else: | ||
| raise UserError(f'Unknown embeddings model: {model}') # pragma: no cover | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. https://github.com/ggozad/haiku.rag/tree/main/src/haiku/rag/embeddings has Ollama, vLLM and VoyageAI, which would be worth adding as well |
||
|
|
||
|
|
||
| @dataclass | ||
DouweM marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| class Embedder: | ||
| instrument: InstrumentationSettings | bool | None | ||
| """Options to automatically instrument with OpenTelemetry.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| model: EmbeddingModel | KnownEmbeddingModelName | str, | ||
| *, | ||
| settings: EmbeddingSettings | None = None, | ||
| defer_model_check: bool = True, | ||
| # TODO: Figure out instrumentation later.. | ||
| instrument: InstrumentationSettings | bool | None = None, | ||
| ) -> None: | ||
| self._model = model if defer_model_check else infer_model(model) | ||
| self._settings = settings | ||
| self._instrument = instrument | ||
|
|
||
| self._override_model: ContextVar[EmbeddingModel | None] = ContextVar('_override_model', default=None) | ||
|
|
||
| @property | ||
| def model(self) -> EmbeddingModel | KnownEmbeddingModelName | str: | ||
| return self._model | ||
|
|
||
| @contextmanager | ||
| def override( | ||
| self, | ||
| *, | ||
| model: EmbeddingModel | KnownEmbeddingModelName | str | _utils.Unset = _utils.UNSET, | ||
| ) -> Iterator[None]: | ||
| if _utils.is_set(model): | ||
| model_token = self._override_model.set(infer_model(model)) | ||
| else: | ||
| model_token = None | ||
|
|
||
| try: | ||
| yield | ||
| finally: | ||
| if model_token is not None: | ||
| self._override_model.reset(model_token) | ||
|
|
||
| @overload | ||
| async def embed(self, documents: str, *, settings: EmbeddingSettings | None = None) -> list[float]: | ||
| pass | ||
|
|
||
| @overload | ||
| async def embed(self, documents: Sequence[str], *, settings: EmbeddingSettings | None = None) -> list[list[float]]: | ||
| pass | ||
|
|
||
| async def embed( | ||
| self, documents: str | Sequence[str], *, settings: EmbeddingSettings | None = None | ||
| ) -> list[float] | list[list[float]]: | ||
| model = self._get_model() | ||
| settings = merge_embedding_settings(self._settings, settings) | ||
| return await model.embed(documents, settings=settings) | ||
|
|
||
| def _get_model(self) -> EmbeddingModel: | ||
| """Create a model configured for this agent. | ||
|
|
||
| Returns: | ||
| The embedding model to use | ||
| """ | ||
| model_: EmbeddingModel | ||
| if some_model := self._override_model.get(): | ||
| model_ = some_model | ||
| else: | ||
| model_ = self._model = infer_model(self.model) | ||
|
|
||
| # TODO: Port the instrumentation logic from Model once we settle on an embeddings API | ||
| # instrument = self.instrument | ||
| # if instrument is None: | ||
| # instrument = Agent._instrument_default | ||
| # | ||
| # return instrument_model(model_, instrument) | ||
|
|
||
| return model_ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| from collections.abc import Sequence | ||
| from dataclasses import dataclass, field | ||
| from typing import Literal, cast, overload | ||
|
|
||
| from pydantic_ai.embeddings.embedding_model import EmbeddingModel | ||
| from pydantic_ai.embeddings.settings import EmbeddingSettings | ||
| from pydantic_ai.providers import Provider, infer_provider | ||
|
|
||
| from .settings import merge_embedding_settings | ||
|
|
||
| try: | ||
| from cohere import AsyncClientV2 | ||
| except ImportError as _import_error: | ||
| raise ImportError( | ||
| 'Please install `cohere` to use the Cohere embeddings model, ' | ||
| 'you can use the `cohere` optional group — `pip install "pydantic-ai-slim[cohere]"`' | ||
| ) from _import_error | ||
|
|
||
| LatestCohereEmbeddingModelNames = Literal[ | ||
| 'cohere:embed-v4.0', | ||
| # TODO: Add the others | ||
| ] | ||
| """Latest Cohere embeddings models.""" | ||
|
|
||
| CohereEmbeddingModelName = str | LatestCohereEmbeddingModelNames | ||
| """Possible Cohere embeddings model names.""" | ||
|
|
||
|
|
||
| @dataclass(init=False) | ||
| class CohereEmbeddingModel(EmbeddingModel): | ||
| _model_name: CohereEmbeddingModelName = field(repr=False) | ||
| _provider: Provider[AsyncClientV2] = field(repr=False) | ||
|
|
||
| def __init__( | ||
| self, | ||
| model_name: CohereEmbeddingModelName, | ||
| *, | ||
| provider: Literal['cohere'] | Provider[AsyncClientV2] = 'cohere', | ||
| settings: EmbeddingSettings | None = None, | ||
| ): | ||
| """Initialize an Cohere model. | ||
| Args: | ||
| model_name: The name of the Cohere model to use. List of model names | ||
| available [here](https://docs.cohere.com/docs/models#command). | ||
DouweM marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| provider: The provider to use for authentication and API access. Can be either the string | ||
| 'cohere' or an instance of `Provider[AsyncClientV2]`. If not provided, a new provider will be | ||
| created using the other parameters. | ||
| profile: The model profile to use. Defaults to a profile picked by the provider based on the model name. | ||
DouweM marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| settings: Model-specific settings that will be used as defaults for this model. | ||
| """ | ||
| self._model_name = model_name | ||
|
|
||
| if isinstance(provider, str): | ||
| provider = infer_provider(provider) | ||
| self._provider = provider | ||
| self._client = provider.client | ||
|
|
||
| super().__init__(settings=settings) | ||
|
|
||
| @property | ||
| def base_url(self) -> str: | ||
| """The base URL for the provider API, if available.""" | ||
| return self._provider.base_url | ||
|
|
||
| @property | ||
| def model_name(self) -> CohereEmbeddingModelName: | ||
| """The embedding model name.""" | ||
| return self._model_name | ||
|
|
||
| @property | ||
| def system(self) -> str: | ||
| """The embedding model provider.""" | ||
| return self._provider.name | ||
|
|
||
| @overload | ||
| async def embed(self, documents: str, *, settings: EmbeddingSettings | None = None) -> list[float]: | ||
| pass | ||
|
|
||
| @overload | ||
| async def embed(self, documents: Sequence[str], *, settings: EmbeddingSettings | None = None) -> list[list[float]]: | ||
| pass | ||
|
|
||
| async def embed( | ||
| self, documents: Sequence[str], *, settings: EmbeddingSettings | None = None | ||
| ) -> list[float] | list[list[float]]: | ||
| input_is_string = isinstance(documents, str) | ||
| if input_is_string: | ||
| documents = [documents] | ||
|
|
||
| settings = merge_embedding_settings(self._settings, settings) or {} | ||
| response = await self._client.embed( | ||
| model=self.model_name, | ||
| input_type=settings.get('input_type', 'search_document'), | ||
| texts=cast(Sequence[str], documents), | ||
| output_dimension=settings.get('output_dimension'), | ||
| ) | ||
| embeddings = response.embeddings.float_ | ||
| assert embeddings is not None, 'This is a bug in cohere?' | ||
|
|
||
| if input_is_string: | ||
| return embeddings[0] | ||
|
|
||
| return embeddings | ||
55 changes: 55 additions & 0 deletions
55
pydantic_ai_slim/pydantic_ai/embeddings/embedding_model.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| from abc import ABC, abstractmethod | ||
| from collections.abc import Sequence | ||
| from typing import overload | ||
|
|
||
| from pydantic_ai.embeddings.settings import EmbeddingSettings | ||
|
|
||
|
|
||
| class EmbeddingModel(ABC): | ||
| """Abstract class for a model.""" | ||
|
|
||
| _settings: EmbeddingSettings | None = None | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| settings: EmbeddingSettings | None = None, | ||
| ) -> None: | ||
| """Initialize the model with optional settings and profile. | ||
|
|
||
| Args: | ||
| settings: Model-specific settings that will be used as defaults for this model. | ||
| profile: The model profile to use. | ||
| """ | ||
| self._settings = settings | ||
|
|
||
| @property | ||
| def settings(self) -> EmbeddingSettings | None: | ||
| """Get the model settings.""" | ||
| return self._settings | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def model_name(self) -> str: | ||
| """The model name.""" | ||
| raise NotImplementedError() | ||
|
|
||
| # TODO: Add system? | ||
|
|
||
| @property | ||
| def base_url(self) -> str | None: | ||
| """The base URL for the provider API, if available.""" | ||
| return None | ||
|
|
||
| @overload | ||
| async def embed(self, documents: str, *, settings: EmbeddingSettings | None = None) -> list[float]: | ||
| pass | ||
|
|
||
| @overload | ||
| async def embed(self, documents: Sequence[str], *, settings: EmbeddingSettings | None = None) -> list[list[float]]: | ||
| pass | ||
|
|
||
| async def embed( | ||
| self, documents: str | Sequence[str], *, settings: EmbeddingSettings | None = None | ||
| ) -> list[float] | list[list[float]]: | ||
| raise NotImplementedError |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add a test like this one to verify this is up to date:
pydantic-ai/tests/models/test_model_names.py
Line 52 in efa1e26