Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
82 changes: 82 additions & 0 deletions e2e/live/test_embeddings.py
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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)
72 changes: 61 additions & 11 deletions src/perplexity/types/embedding_create_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": <data URI>}` 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"]
Expand All @@ -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.
"""
11 changes: 11 additions & 0 deletions tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
Loading