diff --git a/README.md b/README.md index 1090089..37a613f 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,61 @@ for result in search.results: print(f"{result.title}: {result.url}") ``` +## Embeddings + +Use the pplx-embed-v2 models. Start with `pplx-embed-v2-context-0.6b` for higher +throughput and lower latency, and choose `pplx-embed-v2-context-9b` for retrieval +quality. Their 1024-dimension outputs share one embedding space, so you can index +with one model and query with the other. The `pplx-embed-v1-*` and +`pplx-embed-context-v1-*` models still work but will be phased out during 2027. +See the [Embeddings guide](https://docs.perplexity.ai/docs/embeddings/contextualized-embeddings) +for parameters and limits. + +v2 models require `input_type`: `"query"` for the text a user types to search, and +`"document"` for everything you index, including short titles or summaries. The +shape of `input` sets the shape of the response: + +| `input` | `input_type` | Response | +| --------------------------------------------- | ------------ | ----------------------------------------- | +| String or list of strings | `"query"` | One embedding per query, `data[i].embedding` | +| String or list of strings | `"document"` | One embedding per document, `data[i].embedding` | +| List of chunk lists, one per document | `"document"` | One embedding per chunk, `data[i].data[j].embedding` | +| List of image objects | `"document"` | One embedding per image, `data[i].embedding` | +| List of image objects with `num_chunks` > 1 | `"document"` | One embedding per image region, `data[i].data[j].embedding` | + +```python +from perplexity import Perplexity + +client = Perplexity() + +query = client.embeddings.create( + model="pplx-embed-v2-context-0.6b", + input_type="query", + input=["What drives scientific breakthroughs?"], +) +print(query.data[0].embedding) + +# Each chunk is embedded in the context of its whole document. Send +# non-overlapping chunks in source order. +documents = client.embeddings.create( + model="pplx-embed-v2-context-0.6b", + input_type="document", + input=[ + ["Curiosity sparks questions.", "They drive breakthroughs."], + ["The Curiosity rover explores Mars."], + ], +) +for document in documents.data or []: + for chunk in document.data or []: + print(document.index, chunk.index, chunk.embedding) +``` + +Images are base64 data URIs such as +`{"type": "image", "image": "data:image/png;base64,..."}`. A request holds either +text or images, not both. Embeddings are base64-encoded signed int8 values by +default; decode one with `numpy.frombuffer(base64.b64decode(embedding), dtype=numpy.int8)` +and compare with cosine similarity. + ## Chat Completions The full API of this library can be found in [api.md](api.md). diff --git a/e2e/live/test_embeddings.py b/e2e/live/test_embeddings.py index 341f760..a87422e 100644 --- a/e2e/live/test_embeddings.py +++ b/e2e/live/test_embeddings.py @@ -1,8 +1,30 @@ from __future__ import annotations +import zlib +import base64 +import struct + from e2e.live.helpers import create_client +def png_data_uri(size: int = 64) -> str: + """Build a small RGB gradient PNG so the test needs no fixture file.""" + + def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + rows = b"".join( + b"\x00" + b"".join(bytes([x * 255 // size, y * 255 // size, 128]) for x in range(size)) for y in range(size) + ) + png = ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows)) + + chunk(b"IEND", b"") + ) + return "data:image/png;base64," + base64.b64encode(png).decode() + + def test_embeddings() -> None: with create_client() as client: embeddings = client.embeddings.create( @@ -15,3 +37,63 @@ def test_embeddings() -> None: assert embeddings.data assert embeddings.data[0].index == 0 assert embeddings.data[0].embedding + + +def test_embeddings_v2_query() -> None: + with create_client() as client: + embeddings = client.embeddings.create( + input=["What does Perplexity do?"], + input_type="query", + model="pplx-embed-v2-context-0.6b", + ) + + assert embeddings.model + assert embeddings.data + assert embeddings.data[0].index == 0 + assert embeddings.data[0].embedding + + +def test_embeddings_v2_document() -> None: + with create_client() as client: + embeddings = client.embeddings.create( + input=[["Perplexity answers questions.", "Its answers include citations."]], + input_type="document", + model="pplx-embed-v2-context-0.6b", + ) + + assert embeddings.model + assert embeddings.data + chunks = embeddings.data[0].data + assert chunks + assert [chunk.index for chunk in chunks] == [0, 1] + assert all(chunk.embedding for chunk in chunks) + + +def test_embeddings_v2_image() -> None: + with create_client() as client: + embeddings = client.embeddings.create( + input=[{"type": "image", "image": png_data_uri()}], + input_type="document", + model="pplx-embed-v2-context-0.6b", + ) + + assert embeddings.data + assert embeddings.data[0].index == 0 + assert embeddings.data[0].embedding + + +def test_embeddings_v2_image_regions() -> None: + with create_client() as client: + embeddings = client.embeddings.create( + input=[{"type": "image", "image": png_data_uri(256)}], + input_type="document", + model="pplx-embed-v2-context-0.6b", + num_chunks=2, + ) + + assert embeddings.data + regions = embeddings.data[0].data + assert regions + # Small images can return fewer regions than requested. + assert 1 <= len(regions) <= 2 + assert all(region.embedding for region in regions) diff --git a/src/perplexity/types/embedding_create_params.py b/src/perplexity/types/embedding_create_params.py index d661ac7..0d00c88 100644 --- a/src/perplexity/types/embedding_create_params.py +++ b/src/perplexity/types/embedding_create_params.py @@ -2,31 +2,65 @@ from __future__ import annotations -from typing import Union +from typing import Union, Iterable from typing_extensions import Literal, Required, TypedDict from .._types import SequenceNotStr -__all__ = ["EmbeddingCreateParams"] +__all__ = ["EmbeddingCreateParams", "ImageInput"] + + +class ImageInput(TypedDict, total=False): + type: Required[Literal["image"]] + + image: Required[str] + """Base64 data URI, for example `data:image/png;base64,...`.""" class EmbeddingCreateParams(TypedDict, total=False): - input: Required[Union[str, SequenceNotStr[str]]] - """Input text to embed, encoded as a string or array of strings. + input: Required[Union[str, SequenceNotStr[str], Iterable[SequenceNotStr[str]], Iterable[ImageInput]]] + """Input to embed. The shape of `input` sets the shape of the response. - Maximum 512 texts per request. Each input must not exceed 32K tokens. All inputs - in a single request must not exceed 120,000 tokens combined. Empty strings are - not allowed. + - A string or array of strings: one embedding per string in + `data[i].embedding`. With pplx-embed-v2 models, set `input_type` to + `"query"` for search queries or `"document"` for whole documents. + - An array of string arrays (pplx-embed-v2, `input_type="document"`): each + inner array holds one document's non-overlapping chunks in source order. + Each chunk is embedded in the context of its whole document, and the + response returns one embedding per chunk in `data[i].data[j].embedding`. + - An array of `{"type": "image", "image": }` objects (pplx-embed-v2, + `input_type="document"`): JPEG, PNG, or WebP. One embedding per image in + `data[i].embedding`, or one per region in `data[i].data[j].embedding` when + `num_chunks` is above 1. A request holds either text or images, not both. + + Maximum 512 texts or documents, 16,000 chunks, or 96 images (20 MB of base64 + data) per request. Each text or document must not exceed 32K tokens, and all + text in a request must not exceed 120,000 tokens. Empty strings are not + allowed. """ - model: Required[Literal["pplx-embed-v1-0.6b", "pplx-embed-v1-4b"]] - """The embedding model to use""" + model: Required[ + Literal[ + "pplx-embed-v2-context-0.6b", + "pplx-embed-v2-context-9b", + "pplx-embed-v1-0.6b", + "pplx-embed-v1-4b", + ] + ] + """The embedding model to use. + + Start with `pplx-embed-v2-context-0.6b` for higher throughput and lower + latency; choose `pplx-embed-v2-context-9b` for retrieval quality. Their + 1024-dimension outputs share one embedding space. pplx-embed-v2 models + require `input_type`. pplx-embed-v1 models will be phased out during 2027. + """ dimensions: int """Number of dimensions for output embeddings (Matryoshka). - Range: 128-1024 for pplx-embed-v1-0.6b, 128-2560 for pplx-embed-v1-4b. Defaults - to full dimensions (1024 or 2560). + Range: 128-1024 for pplx-embed-v1-0.6b, 128-2560 for pplx-embed-v1-4b, 1024 for + pplx-embed-v2-context-0.6b, 1024 or 2048 for pplx-embed-v2-context-9b. + Defaults to full dimensions (1024, 2560, 1024, or 2048 respectively). """ encoding_format: Literal["base64_int8", "base64_binary"] @@ -35,3 +69,19 @@ class EmbeddingCreateParams(TypedDict, total=False): base64_int8 returns base64-encoded signed int8 values. base64_binary returns base64-encoded packed binary (1 bit per dimension). """ + + input_type: Literal["query", "document"] + """Required for pplx-embed-v2 models. + + Use `"query"` only for the text a user types to search, and `"document"` for + everything you index, including chunked documents and images. Omit for + pplx-embed-v1 models. + """ + + num_chunks: Literal[1, 2, 4, 8, 16, 32] + """Regions per image (pplx-embed-v2 image inputs only). Defaults to 1. + + Values above 1 split each image into horizontal regions, top to bottom, and + return one embedding per region. This can improve retrieval for text-rich + document screenshots. Small images can return fewer regions. + """ diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index 953d51f..bf91bf3 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -38,6 +38,17 @@ pytest_test( ], ) +pytest_test( + name = "test_embeddings_test", + srcs = ["test_embeddings.py"], + deps = [ + ":conftest", + "//src:perplexity", + "@pip//httpx", + "@pip//pydantic", + ], +) + pytest_test( name = "test_extract_files_test", srcs = ["test_extract_files.py"], diff --git a/tests/test_embeddings.py b/tests/test_embeddings.py new file mode 100644 index 0000000..e710b9b --- /dev/null +++ b/tests/test_embeddings.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import json +from typing import Any, Callable + +import httpx +import pytest +from pydantic import ValidationError + +from perplexity import Perplexity, AsyncPerplexity +from perplexity.types import EmbeddingObject, EmbeddingCreateResponse + +USAGE = {"prompt_tokens": 5, "total_tokens": 5} +IMAGE = {"type": "image", "image": "data:image/png;base64,AAAA"} + + +def dense_response(model: str, count: int = 1) -> dict[str, Any]: + return { + "object": "list", + "model": model, + "data": [{"object": "embedding", "index": index, "embedding": "AAE="} for index in range(count)], + "usage": USAGE, + } + + +def chunked_response(model: str, chunks: list[int]) -> dict[str, Any]: + return { + "object": "list", + "model": model, + "data": [ + { + "object": "list", + "index": document, + "data": [{"object": "embedding", "index": chunk, "embedding": "AgM="} for chunk in range(count)], + } + for document, count in enumerate(chunks) + ], + "usage": USAGE, + } + + +def mock_client(body: dict[str, Any], requests: list[httpx.Request]) -> Perplexity: + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, json=body, request=request) + + return Perplexity( + api_key="test", + base_url="https://example.test", + max_retries=0, + http_client=httpx.Client(transport=httpx.MockTransport(handler)), + ) + + +def sent(requests: list[httpx.Request]) -> Any: + assert len(requests) == 1 + assert requests[0].method == "POST" + assert requests[0].url == "https://example.test/v1/embeddings" + return json.loads(requests[0].content) + + +@pytest.mark.parametrize("model", ["pplx-embed-v1-0.6b", "pplx-embed-v1-4b"]) +def test_v1_request_is_unchanged(model: Any) -> None: + requests: list[httpx.Request] = [] + with mock_client(dense_response(model, 2), requests) as client: + response = client.embeddings.create( + model=model, + input=["first", "second"], + dimensions=128, + encoding_format="base64_binary", + ) + + assert sent(requests) == { + "model": model, + "input": ["first", "second"], + "dimensions": 128, + "encoding_format": "base64_binary", + } + assert isinstance(response, EmbeddingCreateResponse) + assert response.data is not None + assert [item.index for item in response.data] == [0, 1] + assert all(item.embedding == "AAE=" for item in response.data) + + +def test_v1_single_string_input() -> None: + requests: list[httpx.Request] = [] + with mock_client(dense_response("pplx-embed-v1-0.6b"), requests) as client: + client.embeddings.create(model="pplx-embed-v1-0.6b", input="Perplexity answers questions.") + + assert sent(requests) == {"model": "pplx-embed-v1-0.6b", "input": "Perplexity answers questions."} + + +@pytest.mark.parametrize("model", ["pplx-embed-v2-context-9b", "pplx-embed-v2-context-0.6b"]) +def test_v2_query(model: Any) -> None: + requests: list[httpx.Request] = [] + with mock_client(dense_response(model), requests) as client: + response = client.embeddings.create( + model=model, + input_type="query", + input=["What is late interaction retrieval?"], + dimensions=1024, + ) + + assert sent(requests) == { + "model": model, + "input_type": "query", + "input": ["What is late interaction retrieval?"], + "dimensions": 1024, + } + assert response.model == model + assert response.data is not None + assert response.data[0].embedding == "AAE=" + assert response.data[0].data is None + + +@pytest.mark.parametrize("model", ["pplx-embed-v2-context-9b", "pplx-embed-v2-context-0.6b"]) +def test_v2_whole_documents_return_one_embedding_per_document(model: Any) -> None: + requests: list[httpx.Request] = [] + with mock_client(dense_response(model, 2), requests) as client: + response = client.embeddings.create( + model=model, + input_type="document", + input=["First document.", "Second document."], + ) + + assert sent(requests) == { + "model": model, + "input_type": "document", + "input": ["First document.", "Second document."], + } + assert response.data is not None + assert [(item.index, item.embedding, item.data) for item in response.data] == [(0, "AAE=", None), (1, "AAE=", None)] + + +def test_v2_image_without_num_chunks_returns_one_embedding_per_image() -> None: + requests: list[httpx.Request] = [] + with mock_client(dense_response("pplx-embed-v2-context-0.6b"), requests) as client: + response = client.embeddings.create( + model="pplx-embed-v2-context-0.6b", + input_type="document", + input=[IMAGE], + ) + + assert sent(requests) == {"model": "pplx-embed-v2-context-0.6b", "input_type": "document", "input": [IMAGE]} + assert response.data is not None + assert response.data[0].embedding == "AAE=" + + +@pytest.mark.parametrize("model", ["pplx-embed-v2-context-9b", "pplx-embed-v2-context-0.6b"]) +def test_v2_chunked_documents_return_one_embedding_per_chunk(model: Any) -> None: + requests: list[httpx.Request] = [] + with mock_client(chunked_response(model, [2, 1]), requests) as client: + response = client.embeddings.create( + model=model, + input_type="document", + input=[["First chunk.", "Second chunk."], ["Another document."]], + ) + + assert sent(requests) == { + "model": model, + "input_type": "document", + "input": [["First chunk.", "Second chunk."], ["Another document."]], + } + assert response.data is not None + assert [document.index for document in response.data] == [0, 1] + assert [len(document.data or []) for document in response.data] == [2, 1] + first = response.data[0].data + assert first is not None + assert isinstance(first[1], EmbeddingObject) + assert (first[1].index, first[1].embedding) == (1, "AgM=") + + +def test_v2_image_documents_with_num_chunks() -> None: + requests: list[httpx.Request] = [] + with mock_client(chunked_response("pplx-embed-v2-context-9b", [4]), requests) as client: + response = client.embeddings.create( + model="pplx-embed-v2-context-9b", + input_type="document", + input=[IMAGE], + num_chunks=4, + encoding_format="base64_binary", + ) + + assert sent(requests) == { + "model": "pplx-embed-v2-context-9b", + "input_type": "document", + "input": [IMAGE], + "num_chunks": 4, + "encoding_format": "base64_binary", + } + assert response.data is not None + assert len(response.data[0].data or []) == 4 + + +@pytest.mark.parametrize( + "create", + [ + lambda client: client.embeddings.create(model="pplx-embed-v3", input="x"), + lambda client: client.embeddings.create(model="pplx-embed-v2-context-9b", input="x", input_type="passage"), + lambda client: client.embeddings.create(model="pplx-embed-v2-context-9b", input="x", num_chunks=3), + ], + ids=["unknown-model", "unknown-input-type", "unsupported-num-chunks"], +) +def test_invalid_parameters_fail_before_sending(create: Callable[[Any], object]) -> None: + requests: list[httpx.Request] = [] + with mock_client(dense_response("unused"), requests) as client, pytest.raises(ValidationError): + create(client) + + assert requests == [] + + +async def test_async_v2_chunked_documents() -> None: + requests: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, json=chunked_response("pplx-embed-v2-context-0.6b", [2]), request=request) + + async with AsyncPerplexity( + api_key="test", + base_url="https://example.test", + max_retries=0, + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) as client: + response = await client.embeddings.create( + model="pplx-embed-v2-context-0.6b", + input_type="document", + input=[["First chunk.", "Second chunk."]], + ) + + assert sent(requests)["input"] == [["First chunk.", "Second chunk."]] + assert response.data is not None + assert len(response.data[0].data or []) == 2 + + +def test_contextualized_embeddings_v1_is_unchanged() -> None: + requests: list[httpx.Request] = [] + body = { + "object": "list", + "model": "pplx-embed-context-v1-0.6b", + "data": [{"object": "list", "index": 0, "data": [{"object": "embedding", "index": 0, "embedding": "AAE="}]}], + "usage": USAGE, + } + with mock_client(body, requests) as client: + response = client.contextualized_embeddings.create( + model="pplx-embed-context-v1-0.6b", + input=[["Perplexity answers questions."]], + ) + + assert requests[0].url == "https://example.test/v1/contextualizedembeddings" + assert json.loads(requests[0].content) == { + "model": "pplx-embed-context-v1-0.6b", + "input": [["Perplexity answers questions."]], + } + assert response.data is not None + assert response.data[0].data is not None + assert response.data[0].data[0].embedding == "AAE="