Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
3 changes: 3 additions & 0 deletions docs/api_reference/api_reference/llms/helicone.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
::: llama_index.llms.helicone
options:
members: - Helicone
153 changes: 153 additions & 0 deletions llama-index-integrations/llms/llama-index-llms-helicone/.gitignore
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
21 changes: 21 additions & 0 deletions llama-index-integrations/llms/llama-index-llms-helicone/LICENSE
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.
17 changes: 17 additions & 0 deletions llama-index-integrations/llms/llama-index-llms-helicone/Makefile
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/
83 changes: 83 additions & 0 deletions llama-index-integrations/llms/llama-index-llms-helicone/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# LlamaIndex LLMs Integration: Helicone

## Installation

To install the required packages, run:

```bash
pip install llama-index-llms-helicone
pip install llama-index
```

## Setup

### Initialize Helicone

Set your Helicone API key via `HELICONE_API_KEY` (or pass directly). No provider API keys are needed when using the Helicone AI Gateway.

```python
from llama_index.llms.helicone import Helicone
from llama_index.core.llms import ChatMessage

llm = Helicone(
api_key="<helicone-api-key>", # or set HELICONE_API_KEY env var
model="gpt-4o-mini", # works across providers via gateway
)
```

## Generate Chat Responses

You can generate a chat response by sending a list of `ChatMessage` instances:

```python
message = ChatMessage(role="user", content="Tell me a joke")
resp = llm.chat([message])
print(resp)
```

### Streaming Responses

To stream responses, use the `stream_chat` method:

```python
message = ChatMessage(role="user", content="Tell me a story in 250 words")
resp = llm.stream_chat([message])
for r in resp:
print(r.delta, end="")
```

### Complete with Prompt

You can also generate completions with a prompt using the `complete` method:

```python
resp = llm.complete("Tell me a joke")
print(resp)
```

### Streaming Completion

To stream completions, use the `stream_complete` method:

```python
resp = llm.stream_complete("Tell me a story in 250 words")
for r in resp:
print(r.delta, end="")
```

## Model Configuration

To use a specific model, you can specify it during initialization. For example, to use Mistral's Mixtral model, you can set it like this:

```python
from llama_index.llms.helicone import Helicone

llm = Helicone(model="gpt-4o-mini")
resp = llm.complete("Write a story about a dragon who can code in Rust")
print(resp)
```

### Notes

- Default Helicone base URL is `https://ai-gateway.helicone.ai/v1`. Override with `api_base` or `HELICONE_API_BASE` if needed.
- Only `HELICONE_API_KEY` is required. The gateway routes to the correct provider based on the `model` string.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from llama_index.llms.helicone.base import Helicone

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

from llama_index.core.bridge.pydantic import Field
from llama_index.core.constants import (
DEFAULT_NUM_OUTPUTS,
DEFAULT_TEMPERATURE,
)
from llama_index.core.base.llms.generic_utils import get_from_param_or_env
from llama_index.llms.openai_like import OpenAILike

# Default Helicone AI Gateway base. Override with HELICONE_API_BASE if needed.
DEFAULT_API_BASE = "https://ai-gateway.helicone.ai/v1"
# Default model routed via gateway; users may override to any supported provider.
DEFAULT_MODEL = "gpt-4o-mini"


class Helicone(OpenAILike):
"""
Helicone (OpenAI-compatible) LLM.

Route OpenAI-compatible requests through Helicone for observability and control.

Authentication:
- Set your Helicone API key via the `api_key` parameter or `HELICONE_API_KEY`.
No OpenAI/third-party provider keys are required when using the AI Gateway.

Examples:
`pip install llama-index-llms-helicone`

```python
from llama_index.llms.helicone import Helicone

llm = Helicone(
api_key="<helicone-api-key>",
model="gpt-4o-mini", # works across providers
)

response = llm.complete("Hello World!")
print(str(response))
```

"""

model: str = Field(
description=(
"OpenAI-compatible model name routed via the Helicone AI Gateway. "
"Learn more about [provider routing](https://docs.helicone.ai/gateway/provider-routing). "
"All models are visible [here](https://www.helicone.ai/models)."
)
)
api_base: Optional[str] = Field(
default=DEFAULT_API_BASE,
description=(
"Base URL for the Helicone AI Gateway. Can also be set via the "
"HELICONE_API_BASE environment variable. See the "
"[Gateway overview](https://docs.helicone.ai/gateway/overview)."
),
)
api_key: Optional[str] = Field(
description=(
"Helicone API key used to authorize requests (Authorization: Bearer). "
"Provide directly or set via HELICONE_API_KEY. Generate your API key "
"in the [dashboard settings](https://us.helicone.ai/settings/api-keys). "
),
)
default_headers: Optional[Dict[str, str]] = Field(
default=None,
description=(
"Additional HTTP headers to include with requests. The Helicone "
"Authorization header is added automatically from api_key. See "
"[custom properties](https://docs.helicone.ai/features/advanced-usage/custom-properties)/[headers](https://docs.helicone.ai/helicone-headers/header-directory)."
),
)

def __init__(
self,
model: str = DEFAULT_MODEL,
temperature: float = DEFAULT_TEMPERATURE,
max_tokens: int = DEFAULT_NUM_OUTPUTS,
additional_kwargs: Optional[Dict[str, Any]] = None,
max_retries: int = 5,
api_base: Optional[str] = DEFAULT_API_BASE,
api_key: Optional[str] = None,
default_headers: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> None:
additional_kwargs = additional_kwargs or {}

api_base = get_from_param_or_env("api_base", api_base, "HELICONE_API_BASE")
api_key = get_from_param_or_env("api_key", api_key, "HELICONE_API_KEY")

if default_headers:
default_headers.update({"Authorization": f"Bearer {api_key}"})
else:
default_headers = {"Authorization": f"Bearer {api_key}"}

super().__init__(
model=model,
temperature=temperature,
max_tokens=max_tokens,
api_base=api_base,
default_headers=default_headers,
additional_kwargs=additional_kwargs,
max_retries=max_retries,
**kwargs,
)

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