The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Support arize phoenix on litellm proxy (#7756) (#8715)
Krish Dholakia21ea52105a33
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex 83b6535f753..9e24437449c 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -466,6 +466,9 @@ router_settings:| OTEL_SERVICE_NAME | Service name identifier for OpenTelemetry| OTEL_TRACER_NAME | Tracer name for OpenTelemetry tracing| PAGERDUTY_API_KEY | API key for PagerDuty Alerting+| PHOENIX_API_KEY | API key for Arize Phoenix+| PHOENIX_COLLECTOR_ENDPOINT | API endpoint for Arize Phoenix+| PHOENIX_COLLECTOR_HTTP_ENDPOINT | API http endpoint for Arize Phoenix| POD_NAME | Pod name for the server, this will be [emitted to `datadog` logs](https://docs.litellm.ai/docs/proxy/logging#datadog) as `POD_NAME`| PREDIBASE_API_BASE | Base URL for Predibase API| PRESIDIO_ANALYZER_API_BASE | Base URL for Presidio Analyzer servicediff --git a/litellm/__init__.py b/litellm/__init__.pyindex f4459db0326..24d0dbc1a5f 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -95,6 +95,7 @@ _custom_logger_compatible_callbacks_literal = Literal["galileo","braintrust","arize",+ "arize_phoenix","langtrace","gcs_bucket","azure_storage",diff --git a/litellm/integrations/_types/open_inference.py b/litellm/integrations/_types/open_inference.pyindex bcfabe9b7b1..b5076c0e425 100644--- a/litellm/integrations/_types/open_inference.py+++ b/litellm/integrations/_types/open_inference.py@@ -283,4 +283,4 @@ class OpenInferenceSpanKindValues(Enum):class OpenInferenceMimeTypeValues(Enum):TEXT = "text/plain"- JSON = "application/json"+ JSON = "application/json"\ No newline at end of filediff --git a/litellm/integrations/arize/_utils.py b/litellm/integrations/arize/_utils.pynew file mode 100644index 00000000000..9921d47affe--- /dev/null+++ b/litellm/integrations/arize/_utils.py@@ -0,0 +1,121 @@+import json+from typing import TYPE_CHECKING, Any, Optional++from litellm._logging import verbose_logger+from litellm.types.utils import StandardLoggingPayload++if TYPE_CHECKING:+ from opentelemetry.trace import Span as _Span+ Span = _Span+else:+ Span = Any+++def set_attributes(span: Span, kwargs, response_obj):+ from openinference.semconv.trace import (+ MessageAttributes,+ OpenInferenceSpanKindValues,+ SpanAttributes,+ )++ try:+ litellm_params = kwargs.get("litellm_params", {}) or {}++ #############################################+ ############ LLM CALL METADATA ##############+ #############################################+ metadata = litellm_params.get("metadata", {}) or {}+ span.set_attribute(SpanAttributes.METADATA, str(metadata))++ #############################################+ ########## LLM Request Attributes ###########+ #############################################++ # The name of the LLM a request is being made to+ if kwargs.get("model"):+ span.set_attribute(SpanAttributes.LLM_MODEL_NAME, kwargs.get("model"))++ span.set_attribute(+ SpanAttributes.OPENINFERENCE_SPAN_KIND,+ OpenInferenceSpanKindValues.LLM.value,+ )+ messages = kwargs.get("messages")++ # for /chat/completions+ # https://docs.arize.com/arize/large-language-models/tracing/semantic-conventions+ if messages:+ span.set_attribute(+ SpanAttributes.INPUT_VALUE,+ messages[-1].get("content", ""), # get the last message for input+ )++ # LLM_INPUT_MESSAGES shows up under `input_messages` tab on the span page+ for idx, msg in enumerate(messages):+ # Set the role per message+ span.set_attribute(+ f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}.{MessageAttributes.MESSAGE_ROLE}",+ msg["role"],+ )+ # Set the content per message+ span.set_attribute(+ f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}.{MessageAttributes.MESSAGE_CONTENT}",+ msg.get("content", ""),+ )++ standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get(+ "standard_logging_object"+ )+ if standard_logging_payload and (model_params := standard_logging_payload["model_parameters"]):+ # The Generative AI Provider: Azure, OpenAI, etc.+ span.set_attribute(+ SpanAttributes.LLM_INVOCATION_PARAMETERS, json.dumps(model_params)+ )++ if model_params.get("user"):+ user_id = model_params.get("user")+ if user_id is not None:+ span.set_attribute(SpanAttributes.USER_ID, user_id)++ #############################################+ ########## LLM Response Attributes ##########+ # https://docs.arize.com/arize/large-language-models/tracing/semantic-conventions+ #############################################+ if hasattr(response_obj, 'get'):+ for choice in response_obj.get("choices", []):+ response_message = choice.get("message", {})+ span.set_attribute(+ SpanAttributes.OUTPUT_VALUE, response_message.get("content", "")+ )++ # This shows up under `output_messages` tab on the span page+ # This code assumes a single response+ span.set_attribute(+ f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_ROLE}",+ response_message.get("role"),+ )+ span.set_attribute(+ f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_CONTENT}",+ response_message.get("content", ""),+ )++ usage = response_obj.get("usage")+ if usage:+ span.set_attribute(+ SpanAttributes.LLM_TOKEN_COUNT_TOTAL,+ usage.get("total_tokens"),+ )++ # The number of tokens used in the LLM response (completion).+ span.set_attribute(+ SpanAttributes.LLM_TOKEN_COUNT_COMPLETION,+ usage.get("completion_tokens"),+ )++ # The number of tokens used in the LLM prompt.+ span.set_attribute(+ SpanAttributes.LLM_TOKEN_COUNT_PROMPT,+ usage.get("prompt_tokens"),+ )+ pass+ except Exception as e:+ verbose_logger.error(f"Error setting arize attributes: {e}")diff --git a/litellm/integrations/arize/arize.py b/litellm/integrations/arize/arize.pynew file mode 100644index 00000000000..652957e1ee8--- /dev/null+++ b/litellm/integrations/arize/arize.py@@ -0,0 +1,74 @@+"""+arize AI is OTEL compatible++this file has Arize ai specific helper functions+"""+import os++from typing import TYPE_CHECKING, Any+from litellm.integrations.arize import _utils+from litellm.types.integrations.arize import ArizeConfig++if TYPE_CHECKING:+ from litellm.types.integrations.arize import Protocol as _Protocol+ from opentelemetry.trace import Span as _Span++ Protocol = _Protocol+ Span = _Span+else:+ Protocol = Any+ Span = Any++++class ArizeLogger:++ @staticmethod+ def set_arize_attributes(span: Span, kwargs, response_obj):+ _utils.set_attributes(span, kwargs, response_obj)+ return+++ @staticmethod+ def get_arize_config() -> ArizeConfig:+ """+ Helper function to get Arize configuration.++ Returns:+ ArizeConfig: A Pydantic model containing Arize configuration.++ Raises:+ ValueError: If required environment variables are not set.+ """+ space_key = os.environ.get("ARIZE_SPACE_KEY")+ api_key = os.environ.get("ARIZE_API_KEY")++ if not space_key:+ raise ValueError("ARIZE_SPACE_KEY not found in environment variables")+ if not api_key:+ raise ValueError("ARIZE_API_KEY not found in environment variables")++ grpc_endpoint = os.environ.get("ARIZE_ENDPOINT")+ http_endpoint = os.environ.get("ARIZE_HTTP_ENDPOINT")++ endpoint = None+ protocol: Protocol = "otlp_grpc"++ if grpc_endpoint:+ protocol="otlp_grpc"+ endpoint=grpc_endpoint+ elif http_endpoint:+ protocol="otlp_http"+ endpoint=http_endpoint+ else:+ protocol="otlp_grpc"+ endpoint = "https://otlp.arize.com/v1"++ return ArizeConfig(+ space_key=space_key,+ api_key=api_key,+ protocol=protocol,+ endpoint=endpoint,+ )++diff --git a/litellm/integrations/arize/arize_phoenix.py b/litellm/integrations/arize/arize_phoenix.pynew file mode 100644index 00000000000..57c0ba52c0f--- /dev/null+++ b/litellm/integrations/arize/arize_phoenix.py@@ -0,0 +1,73 @@+import os+from typing import TYPE_CHECKING, Any+from litellm.integrations.arize import _utils+from litellm._logging import verbose_logger+from litellm.types.integrations.arize_phoenix import ArizePhoenixConfig++if TYPE_CHECKING:+ from .opentelemetry import OpenTelemetryConfig as _OpenTelemetryConfig+ from litellm.types.integrations.arize import Protocol as _Protocol+ from opentelemetry.trace import Span as _Span++ Protocol = _Protocol+ OpenTelemetryConfig = _OpenTelemetryConfig+ Span = _Span+else:+ Protocol = Any+ OpenTelemetryConfig = Any+ Span = Any+++ARIZE_HOSTED_PHOENIX_ENDPOINT = "https://app.phoenix.arize.com/v1/traces"++class ArizePhoenixLogger:+ @staticmethod+ def set_arize_phoenix_attributes(span: Span, kwargs, response_obj):+ _utils.set_attributes(span, kwargs, response_obj)+ return++ @staticmethod+ def get_arize_phoenix_config() -> ArizePhoenixConfig:+ """+ Retrieves the Arize Phoenix configuration based on environment variables.++ Returns:+ ArizePhoenixConfig: A Pydantic model containing Arize Phoenix configuration.+ """+ api_key = os.environ.get("PHOENIX_API_KEY")+ grpc_endpoint = os.environ.get("PHOENIX_COLLECTOR_ENDPOINT")+ http_endpoint = os.environ.get("PHOENIX_COLLECTOR_HTTP_ENDPOINT")++ endpoint = None+ protocol: Protocol = "otlp_grpc"++ if grpc_endpoint is not None:+ endpoint = grpc_endpoint+ protocol = "otlp_grpc"+ elif http_endpoint is not None:+ endpoint = http_endpoint+ protocol = "otlp_http"+ else:+ endpoint = ARIZE_HOSTED_PHOENIX_ENDPOINT+ protocol = "otlp_grpc"+ verbose_logger.debug(+ f"No PHOENIX_COLLECTOR_ENDPOINT or PHOENIX_COLLECTOR_HTTP_ENDPOINT found, using default endpoint: {ARIZE_HOSTED_PHOENIX_ENDPOINT}"+ )++ otlp_auth_headers = None+ # If the endpoint is the Arize hosted Phoenix endpoint, use the api_key as the auth header as currently it is uses+ # a slightly different auth header format than self hosted phoenix+ if endpoint == ARIZE_HOSTED_PHOENIX_ENDPOINT:+ if api_key is None:+ raise ValueError("PHOENIX_API_KEY must be set when the Arize hosted Phoenix endpoint is used.")+ otlp_auth_headers = f"api_key={api_key}"+ elif api_key is not None:+ # api_key/auth is optional for self hosted phoenix+ otlp_auth_headers = f"Authorization=Bearer {api_key}"++ return ArizePhoenixConfig(+ otlp_auth_headers=otlp_auth_headers,+ protocol=protocol,+ endpoint=endpoint+ )+diff --git a/litellm/integrations/arize_ai.py b/litellm/integrations/arize_ai.pydeleted file mode 100644index 10c6af69b1a..00000000000--- a/litellm/integrations/arize_ai.py+++ /dev/null@@ -1,213 +0,0 @@-"""-arize AI is OTEL compatible--this file has Arize ai specific helper functions-"""--import json-from typing import TYPE_CHECKING, Any, Optional--from litellm._logging import verbose_logger--if TYPE_CHECKING:- from opentelemetry.trace import Span as _Span-- from .opentelemetry import OpenTelemetryConfig as _OpenTelemetryConfig-- Span = _Span- OpenTelemetryConfig = _OpenTelemetryConfig-else:- Span = Any- OpenTelemetryConfig = Any--import os--from litellm.types.integrations.arize import *---class ArizeLogger:- @staticmethod- def set_arize_ai_attributes(span: Span, kwargs, response_obj):- from litellm.integrations._types.open_inference import (- MessageAttributes,- OpenInferenceSpanKindValues,- SpanAttributes,- )-- try:-- optional_params = kwargs.get("optional_params", {})- # litellm_params = kwargs.get("litellm_params", {}) or {}-- #############################################- ############ LLM CALL METADATA ##############- #############################################- # commented out for now - looks like Arize AI could not log this- # metadata = litellm_params.get("metadata", {}) or {}- # span.set_attribute(SpanAttributes.METADATA, str(metadata))-- #############################################- ########## LLM Request Attributes ###########- #############################################-- # The name of the LLM a request is being made to- if kwargs.get("model"):- span.set_attribute(SpanAttributes.LLM_MODEL_NAME, kwargs.get("model"))-- span.set_attribute(- SpanAttributes.OPENINFERENCE_SPAN_KIND,- OpenInferenceSpanKindValues.LLM.value,- )- messages = kwargs.get("messages")-- # for /chat/completions- # https://docs.arize.com/arize/large-language-models/tracing/semantic-conventions- if messages:- span.set_attribute(- SpanAttributes.INPUT_VALUE,- messages[-1].get("content", ""), # get the last message for input- )-- # LLM_INPUT_MESSAGES shows up under `input_messages` tab on the span page- for idx, msg in enumerate(messages):- # Set the role per message- span.set_attribute(- f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}.{MessageAttributes.MESSAGE_ROLE}",- msg["role"],- )- # Set the content per message- span.set_attribute(- f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}.{MessageAttributes.MESSAGE_CONTENT}",- msg.get("content", ""),- )-- # The Generative AI Provider: Azure, OpenAI, etc.- _optional_params = ArizeLogger.make_json_serializable(optional_params)- _json_optional_params = json.dumps(_optional_params)- span.set_attribute(- SpanAttributes.LLM_INVOCATION_PARAMETERS, _json_optional_params- )-- if optional_params.get("user"):- span.set_attribute(SpanAttributes.USER_ID, optional_params.get("user"))-- #############################################- ########## LLM Response Attributes ##########- # https://docs.arize.com/arize/large-language-models/tracing/semantic-conventions- #############################################- for choice in response_obj.get("choices"):- response_message = choice.get("message", {})- span.set_attribute(- SpanAttributes.OUTPUT_VALUE, response_message.get("content", "")- )-- # This shows up under `output_messages` tab on the span page- # This code assumes a single response- span.set_attribute(- f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_ROLE}",- response_message["role"],- )- span.set_attribute(- f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_CONTENT}",- response_message.get("content", ""),- )-- usage = response_obj.get("usage")- if usage:- span.set_attribute(- SpanAttributes.LLM_TOKEN_COUNT_TOTAL,- usage.get("total_tokens"),- )-- # The number of tokens used in the LLM response (completion).- span.set_attribute(- SpanAttributes.LLM_TOKEN_COUNT_COMPLETION,- usage.get("completion_tokens"),- )-- # The number of tokens used in the LLM prompt.- span.set_attribute(- SpanAttributes.LLM_TOKEN_COUNT_PROMPT,- usage.get("prompt_tokens"),- )- pass- except Exception as e:- verbose_logger.error(f"Error setting arize attributes: {e}")-- ###################### Helper functions ######################-- @staticmethod- def _get_arize_config() -> ArizeConfig:- """- Helper function to get Arize configuration.-- Returns:- ArizeConfig: A Pydantic model containing Arize configuration.-- Raises:- ValueError: If required environment variables are not set.- """- space_key = os.environ.get("ARIZE_SPACE_KEY")- api_key = os.environ.get("ARIZE_API_KEY")-- if not space_key:- raise ValueError("ARIZE_SPACE_KEY not found in environment variables")- if not api_key:- raise ValueError("ARIZE_API_KEY not found in environment variables")-- grpc_endpoint = os.environ.get("ARIZE_ENDPOINT")- http_endpoint = os.environ.get("ARIZE_HTTP_ENDPOINT")- if grpc_endpoint is None and http_endpoint is None:- # use default arize grpc endpoint- verbose_logger.debug(- "No ARIZE_ENDPOINT or ARIZE_HTTP_ENDPOINT found, using default endpoint: https://otlp.arize.com/v1"- )- grpc_endpoint = "https://otlp.arize.com/v1"-- return ArizeConfig(- space_key=space_key,- api_key=api_key,- grpc_endpoint=grpc_endpoint,- http_endpoint=http_endpoint,- )-- @staticmethod- def get_arize_opentelemetry_config() -> Optional[OpenTelemetryConfig]:- """- Helper function to get OpenTelemetry configuration for Arize.-- Args:- arize_config (ArizeConfig): Arize configuration object.-- Returns:- OpenTelemetryConfig: Configuration for OpenTelemetry.- """- from .opentelemetry import OpenTelemetryConfig-- arize_config = ArizeLogger._get_arize_config()- if arize_config.http_endpoint:- return OpenTelemetryConfig(- exporter="otlp_http",- endpoint=arize_config.http_endpoint,- )-- # use default arize grpc endpoint- return OpenTelemetryConfig(- exporter="otlp_grpc",- endpoint=arize_config.grpc_endpoint,- )-- @staticmethod- def make_json_serializable(payload: dict) -> dict:- for key, value in payload.items():- try:- if isinstance(value, dict):- # recursively sanitize dicts- payload[key] = ArizeLogger.make_json_serializable(value.copy())- elif not isinstance(value, (str, int, float, bool, type(None))):- # everything else becomes a string- payload[key] = str(value)- except Exception:- # non blocking if it can't cast to a str- pass- return payloaddiff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.pyindex 8ca3ff7432a..0ec7358037d 100644--- a/litellm/integrations/opentelemetry.py+++ b/litellm/integrations/opentelemetry.py@@ -444,9 +444,13 @@ class OpenTelemetry(CustomLogger):):try:if self.callback_name == "arize":- from litellm.integrations.arize_ai import ArizeLogger+ from litellm.integrations.arize.arize import ArizeLogger+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ return+ elif self.callback_name == "arize_phoenix":+ from litellm.integrations.arize.arize_phoenix import ArizePhoenixLogger- ArizeLogger.set_arize_ai_attributes(span, kwargs, response_obj)+ ArizePhoenixLogger.set_arize_phoenix_attributes(span, kwargs, response_obj)returnelif self.callback_name == "langtrace":from litellm.integrations.langtrace import LangtraceAttributesdiff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 220306ee742..d44fb07637a 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -3,6 +3,7 @@# Logging function -> log the exact model details + what's being sent | Non-Blockingimport copyimport datetime+from functools import lru_cacheimport jsonimport osimport re@@ -12,7 +13,6 @@ import timeimport tracebackimport uuidfrom datetime import datetime as dt_object-from functools import lru_cachefrom typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union, castfrom pydantic import BaseModel@@ -69,7 +69,8 @@ from litellm.types.utils import (from litellm.utils import _get_base_model_from_metadata, executor, print_verbosefrom ..integrations.argilla import ArgillaLogger-from ..integrations.arize_ai import ArizeLogger+from ..integrations.arize.arize import ArizeLogger+from ..integrations.arize.arize_phoenix import ArizePhoenixLoggerfrom ..integrations.athina import AthinaLoggerfrom ..integrations.azure_storage.azure_storage import AzureBlobStorageLoggerfrom ..integrations.braintrust_logging import BraintrustLogger@@ -831,7 +832,7 @@ class Logging(LiteLLMLoggingBaseClass):except Exception as e: # error creating kwargs for cost calculationdebug_info = StandardLoggingModelCostFailureDebugInformation(error_str=str(e),- traceback_str=traceback.format_exc(),+ traceback_str=_get_traceback_str_for_error(str(e)),)verbose_logger.debug(f"response_cost_failure_debug_information: {debug_info}"@@ -2476,13 +2477,18 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915OpenTelemetryConfig,)- otel_config = ArizeLogger.get_arize_opentelemetry_config()- if otel_config is None:+ arize_config = ArizeLogger.get_arize_config()+ if arize_config.endpoint is None:raise ValueError("No valid endpoint found for Arize, please set 'ARIZE_ENDPOINT' to your GRPC endpoint or 'ARIZE_HTTP_ENDPOINT' to your HTTP endpoint")+ otel_config = OpenTelemetryConfig(+ exporter=arize_config.protocol,+ endpoint=arize_config.endpoint,+ )+os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = (- f"space_key={os.getenv('ARIZE_SPACE_KEY')},api_key={os.getenv('ARIZE_API_KEY')}"+ f"space_key={arize_config.space_key},api_key={arize_config.api_key}")for callback in _in_memory_loggers:if (@@ -2493,6 +2499,31 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915_otel_logger = OpenTelemetry(config=otel_config, callback_name="arize")_in_memory_loggers.append(_otel_logger)return _otel_logger # type: ignore+ elif logging_integration == "arize_phoenix":+ from litellm.integrations.opentelemetry import (+ OpenTelemetry,+ OpenTelemetryConfig,+ )++ arize_phoenix_config = ArizePhoenixLogger.get_arize_phoenix_config()+ otel_config = OpenTelemetryConfig(+ exporter=arize_phoenix_config.protocol,+ endpoint=arize_phoenix_config.endpoint,+ )++ # auth can be disabled on local deployments of arize phoenix+ if arize_phoenix_config.otlp_auth_headers is not None:+ os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = arize_phoenix_config.otlp_auth_headers++ for callback in _in_memory_loggers:+ if (+ isinstance(callback, OpenTelemetry)+ and callback.callback_name == "arize_phoenix"+ ):+ return callback # type: ignore+ _otel_logger = OpenTelemetry(config=otel_config, callback_name="arize_phoenix")+ _in_memory_loggers.append(_otel_logger)+ return _otel_logger # type: ignoreelif logging_integration == "otel":from litellm.integrations.opentelemetry import OpenTelemetrydiff --git a/litellm/types/integrations/arize.py b/litellm/types/integrations/arize.pyindex 3c0bbcde0e2..24298fc3636 100644--- a/litellm/types/integrations/arize.py+++ b/litellm/types/integrations/arize.py@@ -1,10 +1,14 @@-from typing import Optional+from typing import TYPE_CHECKING, Literal, Anyfrom pydantic import BaseModel-+if TYPE_CHECKING:+ Protocol = Literal["otlp_grpc", "otlp_http"]+else:+ Protocol = Any+class ArizeConfig(BaseModel):space_key: strapi_key: str- grpc_endpoint: Optional[str] = None- http_endpoint: Optional[str] = None+ protocol: Protocol+ endpoint: strdiff --git a/litellm/types/integrations/arize_phoenix.py b/litellm/types/integrations/arize_phoenix.pynew file mode 100644index 00000000000..4566022d17f--- /dev/null+++ b/litellm/types/integrations/arize_phoenix.py@@ -0,0 +1,9 @@+from typing import TYPE_CHECKING, Literal, Optional++from pydantic import BaseModel+from .arize import Protocol++class ArizePhoenixConfig(BaseModel):+ otlp_auth_headers: Optional[str] = None+ protocol: Protocol+ endpoint: strdiff --git a/tests/local_testing/test_arize_ai.py b/tests/local_testing/test_arize_ai.pyindex 24aed3da7a3..9d2f27ca30c 100644--- a/tests/local_testing/test_arize_ai.py+++ b/tests/local_testing/test_arize_ai.py@@ -1,16 +1,12 @@import asyncioimport logging-import os-import timeimport pytestfrom dotenv import load_dotenv-from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterimport litellmfrom litellm._logging import verbose_logger, verbose_proxy_logger-from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig-from litellm.integrations.arize_ai import ArizeConfig, ArizeLogger+from litellm.integrations.arize.arize import ArizeConfig, ArizeLoggerload_dotenv()@@ -44,12 +40,12 @@ def test_get_arize_config(mock_env_vars):"""Use Arize default endpoint when no endpoints are provided"""- config = ArizeLogger._get_arize_config()+ config = ArizeLogger.get_arize_config()assert isinstance(config, ArizeConfig)assert config.space_key == "test_space_key"assert config.api_key == "test_api_key"- assert config.grpc_endpoint == "https://otlp.arize.com/v1"- assert config.http_endpoint is None+ assert config.endpoint == "https://otlp.arize.com/v1"+ assert config.protocol == "otlp_grpc"def test_get_arize_config_with_endpoints(mock_env_vars, monkeypatch):@@ -59,30 +55,6 @@ def test_get_arize_config_with_endpoints(mock_env_vars, monkeypatch):monkeypatch.setenv("ARIZE_ENDPOINT", "grpc://test.endpoint")monkeypatch.setenv("ARIZE_HTTP_ENDPOINT", "http://test.endpoint")- config = ArizeLogger._get_arize_config()- assert config.grpc_endpoint == "grpc://test.endpoint"- assert config.http_endpoint == "http://test.endpoint"---def test_get_arize_opentelemetry_config_grpc(mock_env_vars, monkeypatch):- """- Use provided GRPC endpoint when it is set- """- monkeypatch.setenv("ARIZE_ENDPOINT", "grpc://test.endpoint")-- config = ArizeLogger.get_arize_opentelemetry_config()- assert isinstance(config, OpenTelemetryConfig)- assert config.exporter == "otlp_grpc"+ config = ArizeLogger.get_arize_config()assert config.endpoint == "grpc://test.endpoint"---def test_get_arize_opentelemetry_config_http(mock_env_vars, monkeypatch):- """- Use provided HTTP endpoint when it is set- """- monkeypatch.setenv("ARIZE_HTTP_ENDPOINT", "http://test.endpoint")-- config = ArizeLogger.get_arize_opentelemetry_config()- assert isinstance(config, OpenTelemetryConfig)- assert config.exporter == "otlp_http"- assert config.endpoint == "http://test.endpoint"+ assert config.protocol == "otlp_grpc"diff --git a/tests/local_testing/test_arize_phoenix.py b/tests/local_testing/test_arize_phoenix.pynew file mode 100644index 00000000000..4892b1ca77d--- /dev/null+++ b/tests/local_testing/test_arize_phoenix.py@@ -0,0 +1,94 @@+import asyncio+import logging+import pytest+from dotenv import load_dotenv++import litellm+from litellm._logging import verbose_logger, verbose_proxy_logger+from litellm.integrations.arize.arize_phoenix import ArizePhoenixConfig, ArizePhoenixLogger++load_dotenv()+++async def test_async_otel_callback():+ litellm.set_verbose = True++ verbose_proxy_logger.setLevel(logging.DEBUG)+ verbose_logger.setLevel(logging.DEBUG)+ litellm.success_callback = ["arize_phoenix"]++ await litellm.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "this is arize phoenix"}],+ mock_response="hello",+ temperature=0.1,+ user="OTEL_USER",+ )++ await asyncio.sleep(2)+++ "env_vars, expected_headers, expected_endpoint, expected_protocol",+ [+ pytest.param(+ {"PHOENIX_API_KEY": "test_api_key"},+ "api_key=test_api_key",+ "https://app.phoenix.arize.com/v1/traces",+ "otlp_grpc",+ id="default to grpc protocol and Arize hosted Phoenix endpoint",+ ),+ pytest.param(+ {"PHOENIX_COLLECTOR_ENDPOINT": "https://localhost:6006", "PHOENIX_API_KEY": "test_api_key"},+ "Authorization=Bearer test_api_key",+ "https://localhost:6006",+ "otlp_grpc",+ id="custom grpc endpoint",+ ),+ pytest.param(+ {"PHOENIX_COLLECTOR_ENDPOINT": "https://localhost:6006"},+ None,+ "https://localhost:6006",+ "otlp_grpc",+ id="custom grpc endpoint with no auth",+ ),+ pytest.param(+ {"PHOENIX_COLLECTOR_HTTP_ENDPOINT": "https://localhost:6006", "PHOENIX_API_KEY": "test_api_key"},+ "Authorization=Bearer test_api_key",+ "https://localhost:6006",+ "otlp_http",+ id="custom http endpoint",+ ),+ ],+)+def test_get_arize_phoenix_config(monkeypatch, env_vars, expected_headers, expected_endpoint, expected_protocol):+ for key, value in env_vars.items():+ monkeypatch.setenv(key, value)++ config = ArizePhoenixLogger.get_arize_phoenix_config()++ assert isinstance(config, ArizePhoenixConfig)+ assert config.otlp_auth_headers == expected_headers+ assert config.endpoint == expected_endpoint+ assert config.protocol == expected_protocol++ "env_vars",+ [+ pytest.param(+ {"PHOENIX_COLLECTOR_ENDPOINT": "https://app.phoenix.arize.com/v1/traces"},+ id="missing api_key with explicit Arize Phoenix endpoint"+ ),+ pytest.param(+ {},+ id="missing api_key with no endpoint (defaults to Arize Phoenix)"+ ),+ ],+)+def test_get_arize_phoenix_config_expection_on_missing_api_key(monkeypatch, env_vars):+ for key, value in env_vars.items():+ monkeypatch.setenv(key, value)++ with pytest.raises(ValueError, match=f"PHOENIX_API_KEY must be set when the Arize hosted Phoenix endpoint is used."):+ ArizePhoenixLogger.get_arize_phoenix_config()diff --git a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py b/tests/logging_callback_tests/test_unit_tests_init_callbacks.pyindex 7d77e26aafe..fcba3ebbc35 100644--- a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py+++ b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py@@ -66,6 +66,7 @@ callback_class_str_to_classType = {# OTEL compatible loggers"logfire": OpenTelemetry,"arize": OpenTelemetry,+ "arize_phoenix": OpenTelemetry,"langtrace": OpenTelemetry,"mlflow": MlflowLogger,"langfuse": LangfusePromptManagement,@@ -90,6 +91,7 @@ expected_env_vars = {"LOGFIRE_TOKEN": "logfire_token","ARIZE_SPACE_KEY": "arize_space_key","ARIZE_API_KEY": "arize_api_key",+ "PHOENIX_API_KEY": "phoenix_api_key","ARGILLA_API_KEY": "argilla_api_key","PAGERDUTY_API_KEY": "pagerduty_api_key","GCS_PUBSUB_TOPIC_ID": "gcs_pubsub_topic_id",