Skip to content
Open
Show file tree
Hide file tree
Changes from 8 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
4 changes: 4 additions & 0 deletions docs/docs/api_reference/embeddings/nvidia_triton.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
::: llama_index.embeddings.nvidia_triton
options:
members:
- NvidiaTritonEmbedding
2 changes: 2 additions & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,7 @@ nav:
- ./api_reference/embeddings/netmind.md
- ./api_reference/embeddings/nomic.md
- ./api_reference/embeddings/nvidia.md
- ./api_reference/embeddings/nvidia_triton.md
- ./api_reference/embeddings/oci_data_science.md
- ./api_reference/embeddings/oci_genai.md
- ./api_reference/embeddings/octoai.md
Expand Down Expand Up @@ -2488,6 +2489,7 @@ plugins:
- ../llama-index-integrations/protocols/llama-index-protocols-ag-ui
- ../llama-index-integrations/vector_stores/llama-index-vector-stores-openGauss
- ../llama-index-integrations/tools/llama-index-tools-hive
- ../llama-index-integrations/embeddings/llama-index-embeddings-nvidia-triton
- ../llama-index-integrations/vector_stores/llama-index-vector-stores-db2
- ../llama-index-integrations/voice_agents/llama-index-voice-agents-openai
- redirects:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
llama_index/_static
.DS_Store
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
bin/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
etc/
include/
lib/
lib64/
parts/
sdist/
share/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
.ruff_cache

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints
notebooks/

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pyvenv.cfg

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# Jetbrains
.idea
modules/
*.swp

# VsCode
.vscode

# pipenv
Pipfile
Pipfile.lock

# pyright
pyrightconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) Jerry Liu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
GIT_ROOT ?= $(shell git rev-parse --show-toplevel)

help: ## Show all Makefile targets.
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[33m%-30s\033[0m %s\n", $$1, $$2}'

format: ## Run code autoformatters (black).
pre-commit install
git ls-files | xargs pre-commit run black --files

lint: ## Run linters: pre-commit (black, ruff, codespell) and mypy
pre-commit install && git ls-files | xargs pre-commit run --show-diff-on-failure --files

test: ## Run tests via pytest.
pytest tests

watch-docs: ## Build and watch documentation.
sphinx-autobuild docs/ docs/_build/html --open-browser --watch $(GIT_ROOT)/llama_index/
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# LlamaIndex Embeddings Integration: Nvidia Triton

This integration allows LlamaIndex to use embedding models hosted on a [Triton Inference Server](https://github.com/triton-inference-server/server).

## Usage:

```python
from llama_index.embeddings.nvidia_triton import NvidiaTritonEmbedding

embedding = NvidiaTritonEmbedding(
model_name="text_embeddings",
server_url="localhost:8000",
client_kwargs={"ssl": False},
)

print(embedding.get_text_embedding("hello world"))
```

Parameters:

- `model_name`: the name of the embedding model.
- `server_url`: the URL to the Triton Inference Server, normally on the HTTP port.
- `client_kwargs`: additional arguments to be passed to the `tritonclient.http.InferenceServerClient` instance, such us timeouts, ssl, etc.
- `input_tensor_name`: the name of the tensor the embedding model expects the input to be. Default: `INPUT_TEXT`.
- `output_tensor_name`: the name of the tensor the embedding model will serve the output embedding to. Default: `OUTPUT_EMBEDDINGS`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from llama_index.embeddings.nvidia_triton.base import NvidiaTritonEmbedding

__all__ = ["NvidiaTritonEmbedding"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
from typing import Any, Dict, List, Optional

from llama_index.core.base.embeddings.base import BaseEmbedding
from llama_index.core.constants import DEFAULT_EMBED_BATCH_SIZE
from llama_index.core.callbacks.base import CallbackManager
from llama_index.core.bridge.pydantic import PrivateAttr

import random
import numpy as np
from tritonclient.http import (
InferenceServerClient,
InferInput,
InferRequestedOutput,
)

DEFAULT_INPUT_TENSOR_NAME = "INPUT_TEXT"
DEFAULT_OUTPUT_TENSOR_NAME = "OUTPUT_EMBEDDINGS"


class NvidiaTritonEmbedding(BaseEmbedding):
"""
Nvidia Triton Embedding.

This connector allows for llama_index to interact with embedding models hosted on a Triton
inference server over HTTP.

[Triton Inference Server Github](https://github.com/triton-inference-server/server)

Examples:
`pip install llama-index-embeddings-nvidia-triton`

```python
from llama_index.embeddings.nvidia_triton import NvidiaTritonEmbedding

# Ensure a Triton server instance is running and provide the correct HTTP URL for your Triton server instance
triton_url = "localhost:8000"

# Instantiate the NvidiaTritonEmbedding class
emb_client = NvidiaTritonEmbedding(
server_url=triton_url,
model_name="text_embeddings",
)

# Get a text embedding
embedding = emb_client.get_text_embedding("hello world")
print(f"Embedding for 'hello world': {embedding}")
print(f"Embedding length: {len(embedding)}")
```

"""

_client: InferenceServerClient = PrivateAttr()
_input_tensor_name: str = PrivateAttr()
_output_tensor_name: str = PrivateAttr()

def __init__(
self,
model_name: str,
server_url: str = "localhost:8000",
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
input_tensor_name: str = DEFAULT_INPUT_TENSOR_NAME,
output_tensor_name: str = DEFAULT_OUTPUT_TENSOR_NAME,
callback_manager: Optional[CallbackManager] = None,
client_kwargs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
super().__init__(
model_name=model_name,
embed_batch_size=embed_batch_size,
callback_manager=callback_manager, # type: ignore
**kwargs,
)

self._client = InferenceServerClient(
url=server_url,
**client_kwargs or {},
)
self._input_tensor_name = input_tensor_name
self._output_tensor_name = output_tensor_name

@classmethod
def class_name(cls) -> str:
return "NvidiaTritonEmbedding"

def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding."""
return self.get_general_text_embeddings([query])[0]

async def _aget_query_embedding(self, query: str) -> List[float]:
"""The asynchronous version of _get_query_embedding."""
embs = await self.aget_general_text_embeddings([query])
return embs[0]

def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding."""
return self.get_general_text_embeddings([text])[0]

async def _aget_text_embedding(self, text: str) -> List[float]:
"""Asynchronously get text embedding."""
embs = await self.aget_general_text_embeddings([text])
return embs[0]

def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get text embeddings."""
return self.get_general_text_embeddings(texts)

async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Asynchronously get text embeddings."""
return await self.aget_general_text_embeddings(texts)

def get_general_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get Triton embedding."""
input_data = InferInput(self._input_tensor_name, [len(texts)], "BYTES")
input_data.set_data_from_numpy(np.array(texts, dtype=np.object_))
output_data = InferRequestedOutput(self._output_tensor_name)
request_id = str(random.randint(1, 9999999)) # nosec

response = self._client.infer(
model_name=self.model_name,
inputs=[input_data],
outputs=[output_data],
request_id=request_id,
)

embeddings = response.as_numpy(self._output_tensor_name)
if embeddings is None:
raise ValueError("No embeddings returned from Triton server.")
return [e.tolist() for e in embeddings]

async def aget_general_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Asynchronously get Triton embedding."""
return self.get_general_text_embeddings(texts)
Loading