repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
langfuse-python
github_2023
python
981
langfuse
greptile-apps[bot]
@@ -140,6 +135,22 @@ def _parse_token_usage( if additional_kwargs := getattr(response, "additional_kwargs", None): return _parse_usage_from_mapping(additional_kwargs) + def _get_generation_client(self, id: str) -> StatefulGenerationClient: + trace_id = self._context.trace_id + if trace_id is None: + logger.warning( + "Trace ID is not set. Creating generation client with new trace id." + ) + trace_id = str(create_uuid()) + + return StatefulGenerationClient( + client=self._langfuse.client, + id=id, + trace_id=trace_id, + task_manager=self._langfuse.task_manager, + state_type=StateType.OBSERVATION, + )
logic: Creating a new StatefulGenerationClient for each update could lead to race conditions or inconsistent state. Consider caching the client instances by ID.
langfuse-python
github_2023
python
981
langfuse
greptile-apps[bot]
@@ -140,6 +135,22 @@ def _parse_token_usage( if additional_kwargs := getattr(response, "additional_kwargs", None): return _parse_usage_from_mapping(additional_kwargs) + def _get_generation_client(self, id: str) -> StatefulGenerationClient: + trace_id = self._context.trace_id + if trace_id is None: + logger.warning( + "Trace ID is not set. Creating generation client with new trace id." + ) + trace_id = str(create_uuid()) +
logic: Creating a new trace_id when context.trace_id is None could lead to orphaned or disconnected traces. This should be handled at a higher level.
langfuse-python
github_2023
python
981
langfuse
greptile-apps[bot]
@@ -99,14 +99,8 @@ def __init__( sdk_integration="llama-index_instrumentation", ) self._observation_updates = {}
logic: observation_updates dict is declared but never used after initialization
langfuse-python
github_2023
python
981
langfuse
greptile-apps[bot]
@@ -217,7 +201,10 @@ def _is_generation(self, id_: str, instance: Optional[Any] = None) -> bool: def _get_generation_client(self, id: str) -> StatefulGenerationClient: trace_id = self._context.trace_id if trace_id is None: - raise ValueError("Trace ID is not set") + logger.warning( + "Trace ID is not set. Creating generation client with new trace id." + ) + trace_id = str(uuid.uuid4())
logic: Auto-generating trace IDs could lead to orphaned spans if the trace ID is missing due to a bug rather than normal operation
langfuse-python
github_2023
python
967
langfuse
greptile-apps[bot]
@@ -322,6 +325,13 @@ def add_task(self, event: dict): if not self._sampler.sample_event(event): return # event was sampled out + # mask input/output + if self._mask: + body = event["body"] + for key in ("input", "output"): + if key in body: + body[key] = self._mask(body[key]) + json.dumps(event, cls=EventSerializer)
logic: Move the JSON serialization after the masking to ensure the masked data is what gets serialized.
langfuse-python
github_2023
python
967
langfuse
greptile-apps[bot]
@@ -322,6 +325,13 @@ def add_task(self, event: dict): if not self._sampler.sample_event(event): return # event was sampled out + # mask input/output + if self._mask: + body = event["body"] + for key in ("input", "output"): + if key in body: + body[key] = self._mask(body[key])
logic: Move the JSON serialization after the masking to ensure the masked data is what gets serialized
langfuse-python
github_2023
python
977
langfuse
greptile-apps[bot]
@@ -322,6 +328,11 @@ def __init__( self.prompt_cache = PromptCache() + def _apply_mask(self, data: Any) -> Any: + if self.mask: + return self.mask(data) + return data
logic: The _apply_mask method should handle exceptions from the user-provided mask function to prevent crashes if the masking fails
langfuse-python
github_2023
python
977
langfuse
greptile-apps[bot]
@@ -322,6 +325,13 @@ def add_task(self, event: dict): if not self._sampler.sample_event(event): return # event was sampled out + # mask input/output + if self._mask: + body = event["body"] + for key in ("input", "output"): + if key in body: + body[key] = self._mask(body[key])
logic: Missing null check on `event['body']` before accessing it. Could raise KeyError if event doesn't have a body field.
langfuse-python
github_2023
python
977
langfuse
greptile-apps[bot]
@@ -544,3 +545,48 @@ def test_truncate_item_in_place(httpserver): <= MAX_MSG_SIZE ) assert complex_item["body"]["input"] is None + + +def test_mask_body_input_output(httpserver: HTTPServer): + langfuse_client = setup_langfuse_client( + get_host(httpserver.url_for("/api/public/ingestion")) + ) + + def mask(data): + return {**data, "foo": "redacted"}
logic: This mask function modifies the data structure by adding a new field rather than actually masking sensitive data. Consider testing with a more realistic mask function that replaces sensitive values.
langfuse-python
github_2023
python
977
langfuse
greptile-apps[bot]
@@ -544,3 +545,48 @@ def test_truncate_item_in_place(httpserver): <= MAX_MSG_SIZE ) assert complex_item["body"]["input"] is None + + +def test_mask_body_input_output(httpserver: HTTPServer): + langfuse_client = setup_langfuse_client( + get_host(httpserver.url_for("/api/public/ingestion")) + ) + + def mask(data): + return {**data, "foo": "redacted"} + + tm = TaskManager( + langfuse_client, + 10, + 0.1, + 3, + 100, + "public_key", + "test-sdk", + "1.0.0", + "default", + True, + 10, + 1, + mask, + ) + + tm._queue = Mock() + + mock_body = { + "input": {"foo": "bar"}, + "output": {"foo": "bar"}, + } + + tm.add_task({"body": mock_body.copy()})
logic: Using .copy() only creates a shallow copy. Use deepcopy if mock_body contains nested structures to prevent unintended mutations.
langfuse-python
github_2023
python
977
langfuse
greptile-apps[bot]
@@ -334,8 +340,22 @@ def add_task(self, event: dict): return False + def _apply_mask_in_place(self, event: dict): + """Apply the mask function to the event. This is done in place.""" + if not self._mask: + return + + body = event["body"]
logic: Missing null check on `event['body']` before accessing it. Could raise KeyError if event doesn't have a body field.
langfuse-python
github_2023
python
977
langfuse
greptile-apps[bot]
@@ -322,6 +326,8 @@ def add_task(self, event: dict): if not self._sampler.sample_event(event): return # event was sampled out + self._apply_mask_in_place(event) + json.dumps(event, cls=EventSerializer)
logic: logic: Serialization check should happen before masking to fail fast if event is not serializable
langfuse-python
github_2023
python
977
langfuse
greptile-apps[bot]
@@ -334,8 +340,22 @@ def add_task(self, event: dict): return False + def _apply_mask_in_place(self, event: dict): + """Apply the mask function to the event. This is done in place.""" + if not self._mask: + return + + body = event["body"] + for key in ("input", "output"): + if key in body: + try: + body[key] = self._mask(data=body[key])
logic: logic: No validation that mask function returns serializable data. Could cause runtime errors.
langfuse-python
github_2023
python
402
langfuse
maxdeichmann
@@ -10,3 +10,4 @@ def clean_logger(): backoff_logger = logging.getLogger("backoff") backoff_logger.setLevel(logging.WARNING) # Set the desired log level backoff_logger.addHandler(console_handler) + backoff_logger.propagate = False # Stop propagation to the root logger
https://docs.python.org/3/library/logging.html#logging.Logger.propagate I just found this here. If our users use backoff and hence import it as well, i think we will turn off logs for them too with this implementation.
langfuse-python
github_2023
python
961
langfuse
ellipsis-dev[bot]
@@ -2095,3 +2095,11 @@ def test_get_langchain_chat_prompt_with_precompiled_prompt(): assert system_message.content == "This is a dog." assert user_message.content == "This is a langchain chain." + + +def test_bedrock(): + from langchain_aws import ChatBedrockConverse + + llm = ChatBedrockConverse(model="eu.anthropic.claude-3-5-sonnet-20240620-v1:0") + + print(llm.invoke("what's the best burger in SF"))
Replace the print statement with assertions to verify the expected behavior.
langfuse-python
github_2023
python
961
langfuse
ellipsis-dev[bot]
@@ -1110,7 +1110,9 @@ def auth_check(self) -> bool: try: return self.client_instance.auth_check() except Exception as e: - self._log.error("No Langfuse object found in the current context", e) + self._log.error( + "No Langfuse object found in the current context", exc_info=e
The `exc_info` parameter should be set to `True` to include the stack trace in the log, not `e`. ```suggestion "No Langfuse object found in the current context", exc_info=True ```
langfuse-python
github_2023
python
946
langfuse
ellipsis-dev[bot]
@@ -0,0 +1,166 @@ +from typing import Optional, Any, Union, Dict, Mapping + +from langfuse.client import ( + Langfuse, +) +from langfuse.model import ModelUsage + + +try: + from llama_index.core.base.llms.types import ( + ChatResponse, + CompletionResponse, + ) + from llama_index.core.instrumentation.events import BaseEvent + from llama_index.core.instrumentation.event_handlers import BaseEventHandler + from llama_index.core.instrumentation.events.llm import ( + LLMCompletionEndEvent, + LLMCompletionStartEvent, + LLMChatEndEvent, + LLMChatStartEvent, + ) +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + +from logging import getLogger + +logger = getLogger(__name__) + + +class LlamaIndexEventHandler(BaseEventHandler, extra="allow"):
The `extra="allow"` argument is not valid for a standard Python class. It should be removed.
langfuse-python
github_2023
python
946
langfuse
greptile-apps[bot]
@@ -0,0 +1,166 @@ +from typing import Optional, Any, Union, Dict, Mapping + +from langfuse.client import ( + Langfuse, +) +from langfuse.model import ModelUsage + + +try: + from llama_index.core.base.llms.types import ( + ChatResponse, + CompletionResponse, + ) + from llama_index.core.instrumentation.events import BaseEvent + from llama_index.core.instrumentation.event_handlers import BaseEventHandler + from llama_index.core.instrumentation.events.llm import ( + LLMCompletionEndEvent, + LLMCompletionStartEvent, + LLMChatEndEvent, + LLMChatStartEvent, + ) +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + +from logging import getLogger + +logger = getLogger(__name__) + + +class LlamaIndexEventHandler(BaseEventHandler, extra="allow"): + def __init__( + self, + *, + langfuse_client: Langfuse, + observation_updates: Dict[str, Dict[str, Any]], + ): + super().__init__() + + self._langfuse = langfuse_client + self._observation_updates = observation_updates + + @classmethod + def class_name(cls) -> str: + """Class name.""" + return "LangfuseEventHandler" + + def handle(self, event: BaseEvent) -> None: + logger.debug(f"Event {type(event).__name__} received: {event}") + + if isinstance(event, (LLMCompletionStartEvent, LLMChatStartEvent)): + self.update_generation_from_start_event(event) + elif isinstance(event, (LLMCompletionEndEvent, LLMChatEndEvent)): + self.update_generation_from_end_event(event) + + def update_generation_from_start_event( + self, event: Union[LLMCompletionStartEvent, LLMChatStartEvent] + ) -> None: + if event.span_id is None: + logger.warning("Span ID is not set") + return + + model_data = event.model_dict + model = model_data.pop("model", None) + traced_model_data = { + k: str(v) + for k, v in model_data.items() + if v is not None + and k + in [ + "max_tokens", + "max_retries", + "temperature", + "timeout", + "strict", + "top_logprobs", + "logprobs", + ] + } + + self._update_observation_updates( + event.span_id, model=model, model_parameters=traced_model_data + ) + + def update_generation_from_end_event( + self, event: Union[LLMCompletionEndEvent, LLMChatEndEvent] + ) -> None: + if event.span_id is None: + logger.warning("Span ID is not set") + return + + usage = self._parse_token_usage(event.response) if event.response else None + + self._update_observation_updates(event.span_id, usage=usage) + + def _update_observation_updates(self, id_: str, **kwargs) -> None: + if id_ not in self._observation_updates: + return + + self._observation_updates[id_].update(kwargs) + + def _parse_token_usage( + self, response: Union[ChatResponse, CompletionResponse] + ) -> Optional[ModelUsage]: + if ( + (raw := getattr(response, "raw", None)) + and hasattr(raw, "get") + and (usage := raw.get("usage")) + ): + return _parse_usage_from_mapping(usage) + + if additional_kwargs := getattr(response, "additional_kwargs", None): + return _parse_usage_from_mapping(additional_kwargs) + + +def _parse_usage_from_mapping( + usage: Union[object, Mapping[str, Any]], +) -> ModelUsage: + if isinstance(usage, Mapping): + return _get_token_counts_from_mapping(usage) + if isinstance(usage, object): + return _parse_usage_from_object(usage)
logic: The check 'isinstance(usage, object)' will always be True. Consider removing this condition or using a more specific type check
langfuse-python
github_2023
python
946
langfuse
greptile-apps[bot]
@@ -0,0 +1,183 @@ +import httpx +import uuid +from contextlib import contextmanager +from typing import Optional, Dict, Any, List +from logging import getLogger +from langfuse import Langfuse + +from langfuse.client import StatefulTraceClient, StateType +from langfuse.utils.langfuse_singleton import LangfuseSingleton + +from ._context import InstrumentorContext +from ._span_handler import LlamaIndexSpanHandler +from ._event_handler import LlamaIndexEventHandler + + +try: + from llama_index.core.instrumentation import get_dispatcher +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + +logger = getLogger(__name__) + + +class LlamaIndexInstrumentor: + def __init__( + self, + *, + public_key: Optional[str] = None, + secret_key: Optional[str] = None, + host: Optional[str] = None, + debug: Optional[bool] = None, + threads: Optional[int] = None, + flush_at: Optional[int] = None, + flush_interval: Optional[int] = None, + max_retries: Optional[int] = None, + timeout: Optional[int] = None, + httpx_client: Optional[httpx.Client] = None, + enabled: Optional[bool] = None, + sample_rate: Optional[float] = None, + ): + self._langfuse = LangfuseSingleton().get( + public_key=public_key, + secret_key=secret_key, + host=host, + debug=debug, + threads=threads, + flush_at=flush_at, + flush_interval=flush_interval, + max_retries=max_retries, + timeout=timeout, + httpx_client=httpx_client, + enabled=enabled, + sample_rate=sample_rate, + sdk_integration="llama-index_instrumentation", + ) + self._observation_updates = {} + self._span_handler = LlamaIndexSpanHandler( + langfuse_client=self._langfuse, + observation_updates=self._observation_updates, + ) + self._event_handler = LlamaIndexEventHandler( + langfuse_client=self._langfuse, + observation_updates=self._observation_updates, + ) + self._context = InstrumentorContext() + + def start(self): + self._context.reset() + dispatcher = get_dispatcher() + + # Span Handler + if not any( + isinstance(handler, type(self._span_handler)) + for handler in dispatcher.span_handlers + ): + dispatcher.add_span_handler(self._span_handler) + + # Event Handler + if not any( + isinstance(handler, type(self._event_handler)) + for handler in dispatcher.event_handlers + ): + dispatcher.add_event_handler(self._event_handler) + + def stop(self): + self._context.reset() + dispatcher = get_dispatcher() + + # Span Handler, in-place filter + dispatcher.span_handlers[:] = filter( + lambda h: not isinstance(h, type(self._span_handler)), + dispatcher.span_handlers, + ) + + # Event Handler, in-place filter + dispatcher.event_handlers[:] = filter( + lambda h: not isinstance(h, type(self._event_handler)), + dispatcher.event_handlers, + ) + + @contextmanager + def observe( + self, + *, + trace_id: Optional[str] = None, + parent_observation_id: Optional[str] = None, + update_parent: Optional[bool] = None, + trace_name: Optional[str] = None, + user_id: Optional[str] = None, + session_id: Optional[str] = None, + version: Optional[str] = None, + release: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + tags: Optional[List[str]] = None, + public: Optional[bool] = None, + ): + was_instrumented = self._is_instrumented + + if not was_instrumented: + self.start() + + if parent_observation_id is not None and trace_id is None: + logger.warning( + "trace_id must be provided if parent_observation_id is provided. Ignoring parent_observation_id." + ) + parent_observation_id = None
logic: Consider raising an exception instead of ignoring parent_observation_id when trace_id is None
langfuse-python
github_2023
python
946
langfuse
greptile-apps[bot]
@@ -0,0 +1,183 @@ +import httpx +import uuid +from contextlib import contextmanager +from typing import Optional, Dict, Any, List +from logging import getLogger +from langfuse import Langfuse + +from langfuse.client import StatefulTraceClient, StateType +from langfuse.utils.langfuse_singleton import LangfuseSingleton + +from ._context import InstrumentorContext +from ._span_handler import LlamaIndexSpanHandler +from ._event_handler import LlamaIndexEventHandler + + +try: + from llama_index.core.instrumentation import get_dispatcher +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + +logger = getLogger(__name__) + + +class LlamaIndexInstrumentor: + def __init__( + self, + *, + public_key: Optional[str] = None, + secret_key: Optional[str] = None, + host: Optional[str] = None, + debug: Optional[bool] = None, + threads: Optional[int] = None, + flush_at: Optional[int] = None, + flush_interval: Optional[int] = None, + max_retries: Optional[int] = None, + timeout: Optional[int] = None, + httpx_client: Optional[httpx.Client] = None, + enabled: Optional[bool] = None, + sample_rate: Optional[float] = None, + ): + self._langfuse = LangfuseSingleton().get( + public_key=public_key, + secret_key=secret_key, + host=host, + debug=debug, + threads=threads, + flush_at=flush_at, + flush_interval=flush_interval, + max_retries=max_retries, + timeout=timeout, + httpx_client=httpx_client, + enabled=enabled, + sample_rate=sample_rate, + sdk_integration="llama-index_instrumentation", + ) + self._observation_updates = {} + self._span_handler = LlamaIndexSpanHandler( + langfuse_client=self._langfuse, + observation_updates=self._observation_updates, + ) + self._event_handler = LlamaIndexEventHandler( + langfuse_client=self._langfuse, + observation_updates=self._observation_updates, + ) + self._context = InstrumentorContext() + + def start(self): + self._context.reset() + dispatcher = get_dispatcher() + + # Span Handler + if not any( + isinstance(handler, type(self._span_handler)) + for handler in dispatcher.span_handlers + ): + dispatcher.add_span_handler(self._span_handler) + + # Event Handler + if not any( + isinstance(handler, type(self._event_handler)) + for handler in dispatcher.event_handlers + ): + dispatcher.add_event_handler(self._event_handler) + + def stop(self): + self._context.reset() + dispatcher = get_dispatcher() + + # Span Handler, in-place filter + dispatcher.span_handlers[:] = filter( + lambda h: not isinstance(h, type(self._span_handler)), + dispatcher.span_handlers, + ) + + # Event Handler, in-place filter + dispatcher.event_handlers[:] = filter( + lambda h: not isinstance(h, type(self._event_handler)), + dispatcher.event_handlers, + ) + + @contextmanager + def observe( + self, + *, + trace_id: Optional[str] = None, + parent_observation_id: Optional[str] = None, + update_parent: Optional[bool] = None, + trace_name: Optional[str] = None, + user_id: Optional[str] = None, + session_id: Optional[str] = None, + version: Optional[str] = None, + release: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + tags: Optional[List[str]] = None, + public: Optional[bool] = None, + ): + was_instrumented = self._is_instrumented + + if not was_instrumented: + self.start() + + if parent_observation_id is not None and trace_id is None: + logger.warning( + "trace_id must be provided if parent_observation_id is provided. Ignoring parent_observation_id." + ) + parent_observation_id = None + + final_trace_id = trace_id or str(uuid.uuid4()) + + self._context.update( + is_user_managed_trace=True, + trace_id=final_trace_id, + parent_observation_id=parent_observation_id, + update_parent=update_parent, + trace_name=trace_name, + user_id=user_id, + session_id=session_id, + version=version, + release=release, + metadata=metadata, + tags=tags, + public=public, + ) + + yield self._get_trace_client(final_trace_id) + + self._context.reset() + + if not was_instrumented: + self.stop() + + @property + def _is_instrumented(self) -> bool: + """Check if the dispatcher is instrumented.""" + dispatcher = get_dispatcher() + + return any( + isinstance(handler, type(self._span_handler)) + for handler in dispatcher.span_handlers + ) and any( + isinstance(handler, type(self._event_handler)) + for handler in dispatcher.event_handlers + ) + + def _get_trace_client(self, trace_id: str) -> StatefulTraceClient: + return StatefulTraceClient( + client=self._langfuse.client, + id=trace_id, + trace_id=trace_id, + task_manager=self._langfuse.task_manager, + state_type=StateType.TRACE, + )
logic: Consider adding error handling for cases where trace_id is None
langfuse-python
github_2023
python
946
langfuse
greptile-apps[bot]
@@ -32,7 +32,7 @@ def validate_llm_generation(generation, model_name="openai_llm"): [ generation.name == model_name, generation.usage.input > 0, - generation.usage.output > 0, + # generation.usage.output > 0, todo: enable when streaming output tokens are working
logic: The check for output tokens is commented out. Ensure this doesn't affect the overall functionality of the tests.
langfuse-python
github_2023
others
947
langfuse
greptile-apps[bot]
@@ -14,11 +14,16 @@ backoff = ">=1.10.0" openai = { version = ">=0.27.8", optional = true } wrapt = "^1.14" langchain = { version = ">=0.0.309", optional = true } +<<<<<<< Updated upstream llama-index = {version = ">=0.10.12, <2.0.0", optional = true} packaging = ">=23.2,<25.0" +======= +packaging = "^24.1" +>>>>>>> Stashed changes
logic: Resolve merge conflict for packaging and llama-index dependencies
langfuse-python
github_2023
others
947
langfuse
greptile-apps[bot]
@@ -14,11 +14,16 @@ backoff = ">=1.10.0" openai = { version = ">=0.27.8", optional = true } wrapt = "^1.14" langchain = { version = ">=0.0.309", optional = true } +<<<<<<< Updated upstream llama-index = {version = ">=0.10.12, <2.0.0", optional = true}
logic: llama-index is defined twice with different versions
langfuse-python
github_2023
others
947
langfuse
greptile-apps[bot]
@@ -14,11 +14,16 @@ backoff = ">=1.10.0" openai = { version = ">=0.27.8", optional = true } wrapt = "^1.14" langchain = { version = ">=0.0.309", optional = true } +<<<<<<< Updated upstream llama-index = {version = ">=0.10.12, <2.0.0", optional = true} packaging = ">=23.2,<25.0" +======= +packaging = "^24.1" +>>>>>>> Stashed changes idna = "^3.7" anyio = "^4.4.0" +llama-index = "0.10.38"
logic: This line conflicts with the earlier llama-index specification
langfuse-python
github_2023
python
544
langfuse
marcklingen
@@ -124,6 +124,7 @@ def __init__( user_id=None, tags=None, parent_observation_id=None, + langfuse_prompt=None,
thanks, super helpful, added as comment for future reference
langfuse-python
github_2023
python
544
langfuse
marcklingen
@@ -197,6 +197,31 @@ def test_openai_chat_completion_with_trace(): assert generation.data[0].trace_id == trace_id +def test_openai_chat_completion_with_langfuse_prompt(): + api = get_api() + generation_name = create_uuid() + langfuse = Langfuse() + prompt_name = create_uuid() + prompt_client = langfuse.create_prompt( + name=prompt_name, prompt="test prompt", is_active=True + ) + + chat_func( + name=generation_name, + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Make me laugh"}], + langfuse_prompt=prompt_client, + ) + + openai.flush_langfuse() + + generation = api.observations.get_many(name=generation_name, type="GENERATION") + + assert len(generation.data) != 0 + assert generation.data[0].name == generation_name + assert isinstance(generation.data[0].prompt_id, str)
merged
langfuse-python
github_2023
python
543
langfuse
maxdeichmann
@@ -73,17 +72,56 @@ def get_langchain_prompt(self): pass @staticmethod - def get_langchain_prompt_string(content: str): + def _get_langchain_prompt_string(content: str): return re.sub(r"\{\{(.*?)\}\}", r"{\g<1>}", content) + @staticmethod + def _compile_template_string(content: str, **kwargs) -> str:
Did you try to implement that with regex? I would prefer that over looping ourselves through the string.
langfuse-python
github_2023
python
543
langfuse
maxdeichmann
@@ -0,0 +1,37 @@ +def compile_template_string(content: str, **kwargs) -> str: + opening = "{{" + closing = "}}" + + result_list = [] + curr_idx = 0 + + while curr_idx < len(content): + # Find the next opening tag + var_start = content.find(opening, curr_idx) + + if var_start == -1: + result_list.append(content[curr_idx:]) + break + + # Find the next closing tag + var_end = content.find(closing, var_start) + + if var_end == -1: + result_list.append(content[curr_idx:])
This here would happen in case of a male formatted sting, right? `{{var1}} something{{random {{var2}}` would not match var2, right?
langfuse-python
github_2023
python
532
langfuse
maxdeichmann
@@ -325,6 +330,8 @@ async def _get_langfuse_data_from_async_streaming_response( resource, responses ) + langfuse.trace(id=generation.trace_id, output=completion)
In these cases, we do not know anymore whether the trace was generated by the user becore and whether he provided the traceId himself. Can we somehow get that information here and only update in this case? Similar to how we do that with the input.
langfuse-python
github_2023
python
526
langfuse
maxdeichmann
@@ -3,6 +3,9 @@ from .resources import ( AccessDeniedError, BaseEvent, + BasePrompt,
Can you generate fern again for your changes? As discussed, i fixed something there. Important: before generating, please merge main again in your langfuse/langfuse feature branch to make that work.
langfuse-python
github_2023
python
518
langfuse
maxdeichmann
@@ -743,6 +743,9 @@ def _update_trace(self, run_id: str, parent_run_id: Optional[str], output: any): ): self.trace = self.trace.update(output=output) + # Remove the run details after updating the trace.
Can we quickly rename the function? E.g. _update_trace_and_remove_state(...) to make this more readable?
langfuse-python
github_2023
python
907
langfuse
greptile-apps[bot]
@@ -673,7 +673,7 @@ def _parse_output_from_event(self, event: CallbackEvent): payload["num_chunks"] = len(chunks) if EventPayload.COMPLETION in payload: - return payload.get(EventPayload.COMPLETION) + return str(payload.get(EventPayload.COMPLETION))
logic: Converting CompletionResponse to string may lose structured data
langfuse-python
github_2023
python
913
langfuse
greptile-apps[bot]
@@ -0,0 +1,53 @@ +import logging +from typing import Union + +from openai import APIError + +from langfuse.request import APIErrors + +SUPPORT_URL = "https://langfuse.com/support" +API_DOCS_URL = "https://api.reference.langfuse.com" +RBAC_DOCS_URL = "https://langfuse.com/docs/rbac" +RATE_LIMITS_URL = "https://langfuse.com/faq/all/api-limits" +NPM_PACKAGE_URL = "https://pypi.org/project/langfuse/"
logic: NPM_PACKAGE_URL points to PyPI, not npm. Rename to PYPI_PACKAGE_URL for clarity
langfuse-python
github_2023
python
913
langfuse
greptile-apps[bot]
@@ -0,0 +1,53 @@ +import logging +from typing import Union + +from openai import APIError + +from langfuse.request import APIErrors + +SUPPORT_URL = "https://langfuse.com/support" +API_DOCS_URL = "https://api.reference.langfuse.com" +RBAC_DOCS_URL = "https://langfuse.com/docs/rbac" +RATE_LIMITS_URL = "https://langfuse.com/faq/all/api-limits" +NPM_PACKAGE_URL = "https://pypi.org/project/langfuse/" + +# Error messages +updatePromptResponse = ( + f"Make sure to keep your SDK updated, refer to {NPM_PACKAGE_URL} for details." +) +defaultErrorResponse = f"Unexpected error occurred. Please check your request and contact support: {SUPPORT_URL}." + +# Error response map +errorResponseByCode = { + "500": f"Internal server error occurred. Please contact support: {SUPPORT_URL}", + "501": f"Not implemented. Please check your request and contact support: {SUPPORT_URL}", + "502": f"Bad gateway. Please try again later and contact support: {SUPPORT_URL}.", + "503": f"Service unavailable. Please try again later and contact support if the error persists: {SUPPORT_URL}.", + "504": "Gateway timeout. Please try again later and contact support: {SUPPORT_URL}.", + "404": f"Internal error occurred. Likely caused by race condition, please escalate to support if seen in high volume: {SUPPORT_URL}", + "400": f"Bad request. Please check your request for any missing or incorrect parameters. Refer to our API docs: {API_DOCS_URL} for details.", + "401": "Unauthorized. Please check your public/private host settings.", + "403": f"Forbidden. Please check your access control settings. Refer to our RBAC docs: {RBAC_DOCS_URL} for details.", + "429": f"Rate limit exceeded. Please try again later. For more information on rate limits please see: {RATE_LIMITS_URL}", +} + + +def handle_exception(exception: Union[APIError, APIErrors, Exception]) -> None: + log = logging.getLogger("langfuse") + + log.debug(exception) + + if isinstance(exception, APIError): + error_message = f"API error occurred: {errorResponseByCode.get(exception.status_code, defaultErrorResponse)}" + log.error(error_message)
logic: APIError.status_code might be an int, but errorResponseByCode uses string keys. Convert to str
langfuse-python
github_2023
others
911
langfuse
greptile-apps[bot]
@@ -0,0 +1,161 @@ +# Finto Python Library + +[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-SDK%20generated%20by%20Fern-brightgreen)](https://github.com/fern-api/fern) +[![pypi](https://img.shields.io/pypi/v/finto)](https://pypi.python.org/pypi/finto) + +The Finto Python library provides convenient access to the Finto API from Python.
logic: Inconsistent naming: README refers to 'Finto' but the repository is 'langfuse'
langfuse-python
github_2023
others
911
langfuse
greptile-apps[bot]
@@ -0,0 +1,161 @@ +# Finto Python Library + +[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-SDK%20generated%20by%20Fern-brightgreen)](https://github.com/fern-api/fern) +[![pypi](https://img.shields.io/pypi/v/finto)](https://pypi.python.org/pypi/finto) + +The Finto Python library provides convenient access to the Finto API from Python. + +## Installation + +```sh +pip install finto
logic: Installation command uses 'finto' instead of 'langfuse'
langfuse-python
github_2023
others
911
langfuse
greptile-apps[bot]
@@ -0,0 +1,161 @@ +# Finto Python Library + +[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-SDK%20generated%20by%20Fern-brightgreen)](https://github.com/fern-api/fern) +[![pypi](https://img.shields.io/pypi/v/finto)](https://pypi.python.org/pypi/finto) + +The Finto Python library provides convenient access to the Finto API from Python. + +## Installation + +```sh +pip install finto +``` + +## Usage + +Instantiate and use the client with the following: + +```python +from finto import CreateDatasetItemRequest, DatasetStatus +from finto.client import FernLangfuse
logic: Imports use 'finto' instead of 'langfuse'
langfuse-python
github_2023
python
911
langfuse
greptile-apps[bot]
@@ -13,36 +13,28 @@ class BaseScore(pydantic_v1.BaseModel): trace_id: str = pydantic_v1.Field(alias="traceId") name: str source: ScoreSource - observation_id: typing.Optional[str] = pydantic_v1.Field( - alias="observationId", default=None - ) + observation_id: typing.Optional[str] = pydantic_v1.Field(alias="observationId", default=None) timestamp: dt.datetime created_at: dt.datetime = pydantic_v1.Field(alias="createdAt") updated_at: dt.datetime = pydantic_v1.Field(alias="updatedAt") - author_user_id: typing.Optional[str] = pydantic_v1.Field( - alias="authorUserId", default=None - ) + author_user_id: typing.Optional[str] = pydantic_v1.Field(alias="authorUserId", default=None) comment: typing.Optional[str] = None config_id: typing.Optional[str] = pydantic_v1.Field(alias="configId", default=None) """ Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range """ def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = { - "by_alias": True, - "exclude_unset": True, - **kwargs, - } + kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = { - "by_alias": True, - "exclude_unset": True, - **kwargs, - } - return super().dict(**kwargs_with_defaults) + kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + + return deep_union_pydantic_dicts( + super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + )
logic: This change merges two dict representations with different exclusion rules. Ensure this doesn't unintentionally expose sensitive or default data.
langfuse-python
github_2023
others
909
langfuse
greptile-apps[bot]
@@ -15,7 +15,7 @@ openai = { version = ">=0.27.8", optional = true } wrapt = "^1.14" langchain = { version = ">=0.0.309", optional = true } llama-index = {version = ">=0.10.12, <2.0.0", optional = true} -packaging = "^24.1" +packaging = "23.2"
logic: Downgrading packaging from '^24.1' to '23.2' may cause compatibility issues. Ensure this change is necessary and doesn't break any functionality.
langfuse-python
github_2023
python
902
langfuse
greptile-apps[bot]
@@ -22,11 +28,122 @@ def get_epoch_seconds() -> int: return int(datetime.now().timestamp()) +class PromptCacheRefreshConsumer(Thread): + _log = logging.getLogger("langfuse") + _queue: Queue + _identifier: int + running: bool = True + + def __init__(self, queue: Queue, identifier: int): + super().__init__() + self.daemon = True + self._queue = queue + self._identifier = identifier + + def run(self): + while self.running: + try: + task = self._queue.get(timeout=1) + self._log.debug( + f"PromptCacheRefreshConsumer processing task, {self._identifier}" + ) + try: + task() + # Task failed, but we still consider it processed + except Exception as e: + self._log.warning( + f"PromptCacheRefreshConsumer encountered an error, cache was not refreshed: {self._identifier}, {e}" + ) + + self._queue.task_done() + except Empty: + pass + + def pause(self): + """Pause the consumer.""" + self.running = False + + +class PromptCacheTaskManager(object): + _log = logging.getLogger("langfuse") + _consumers: List[PromptCacheRefreshConsumer] + _threads: int + _queue: Queue + _processing_keys: Set[str] + + def __init__(self, threads: int = 1): + self._queue = Queue() + self._consumers = [] + self._threads = threads + self._processing_keys = set() + + for i in range(self._threads): + consumer = PromptCacheRefreshConsumer(self._queue, i) + consumer.start() + self._consumers.append(consumer) + + atexit.register(self.shutdown) + + def add_task(self, key: str, task): + if key not in self._processing_keys: + self._log.debug(f"Adding prompt cache refresh task for key: {key}") + self._processing_keys.add(key) + wrapped_task = self._wrap_task(key, task) + self._queue.put((wrapped_task)) + else: + self._log.debug( + f"Prompt cache refresh task already submitted for key: {key}" + ) + + def active_tasks(self) -> int: + return len(self._processing_keys) + + def _wrap_task(self, key: str, task): + def wrapped(): + self._log.debug(f"Refreshing prompt cache for key: {key}") + try: + task() + finally: + self._processing_keys.remove(key) + self._log.debug(f"Refreshed prompt cache for key: {key}") + + return wrapped + + def shutdown(self): + self._log.debug( + f"Shutting down prompt cache refresh task manager, {len(self._consumers)} consumers..." + ) + for consumer in self._consumers: + consumer.pause() + + for consumer in self._consumers: + try: + consumer.join() + except RuntimeError: + # consumer thread has not started + pass + + self._log.debug("Consumers joined.") + + class PromptCache: _cache: Dict[str, PromptCacheItem] - def __init__(self): + _refreshing_keys: Dict[str, Event]
logic: _refreshing_keys is defined but never used in the provided code
langfuse-python
github_2023
python
902
langfuse
maxdeichmann
@@ -1058,21 +1058,30 @@ def get_prompt( raise e if cached_prompt.is_expired(): + self.log.debug(f"Stale prompt '{cache_key}' found in cache.") try: - return self._fetch_prompt_and_update_cache( - name, - version=version, - label=label, - ttl_seconds=cache_ttl_seconds, - max_retries=bounded_max_retries, - fetch_timeout_seconds=fetch_timeout_seconds, + # refresh prompt in background thread, refresh_prompt deduplicates tasks + self.log.debug(f"Refreshing prompt '{cache_key}' in background.") + self.prompt_cache.add_refresh_prompt_task( + cache_key, + lambda: self._fetch_prompt_and_update_cache( + name, + version=version, + label=label, + ttl_seconds=cache_ttl_seconds, + max_retries=bounded_max_retries, + fetch_timeout_seconds=fetch_timeout_seconds, + ), ) + self.log.debug(f"Returning stale prompt '{cache_key}' from cache.") + # return stale prompt + return cached_prompt.value except Exception as e: - self.log.warn( - f"Returning expired prompt cache for '{cache_key}' due to fetch error: {e}" + self.log.warning(
Please adjust all the error / warning logs here so that user can do something with it.
langfuse-python
github_2023
python
902
langfuse
maxdeichmann
@@ -22,11 +28,119 @@ def get_epoch_seconds() -> int: return int(datetime.now().timestamp()) +class PromptCacheRefreshConsumer(Thread): + _log = logging.getLogger("langfuse") + _queue: Queue + _identifier: int + running: bool = True + + def __init__(self, queue: Queue, identifier: int): + super().__init__() + self.daemon = True + self._queue = queue + self._identifier = identifier + + def run(self): + while self.running: + try: + task = self._queue.get(timeout=1) + self._log.debug( + f"PromptCacheRefreshConsumer processing task, {self._identifier}" + ) + try: + task() + # Task failed, but we still consider it processed + except Exception as e: + self._log.warning( + f"PromptCacheRefreshConsumer encountered an error, cache was not refreshed: {self._identifier}, {e}" + ) + + self._queue.task_done() + except Empty: + pass + + def pause(self): + """Pause the consumer.""" + self.running = False + + +class PromptCacheTaskManager(object): + _log = logging.getLogger("langfuse") + _consumers: List[PromptCacheRefreshConsumer] + _threads: int + _queue: Queue + _processing_keys: Set[str] + + def __init__(self, threads: int = 1): + self._queue = Queue() + self._consumers = [] + self._threads = threads + self._processing_keys = set() + + for i in range(self._threads): + consumer = PromptCacheRefreshConsumer(self._queue, i) + consumer.start() + self._consumers.append(consumer) + + atexit.register(self.shutdown)
This should be done only once. As discussed.
langfuse-python
github_2023
python
874
langfuse
maxdeichmann
@@ -26,6 +26,8 @@ def sample_event(self, event: dict): trace_id = event["body"]["trace_id"] elif "traceId" in event["body"]: trace_id = event["body"]["traceId"] + elif "id" in event["body"]: + trace_id = event["body"]["id"]
Why did you make this change? Above, we get the event.body.id, in case the event is a trace-create type.
langfuse-python
github_2023
python
874
langfuse
maxdeichmann
@@ -67,8 +67,10 @@ def _convert_usage_input(usage: typing.Union[pydantic.BaseModel, ModelUsage]): for k in ( "promptTokens", "prompt_tokens", + "input_token_count", "completionTokens", "completion_tokens", + "generated_token_count",
Can we revert this change and handle this in the Langchain callback handler? - Functionality in here should be abstracted for Langfuse. Hence, everything going in here should already have been converted to prompt_tokens, completion_tokens etc. How does this work in the langchain case for IBM? We parse the usage from all the different models [here](https://github.com/langfuse/langfuse-python/blob/4d7112a4b293bff5a329a4351abfefbc468d87b0/langfuse/callback/langchain.py#L731). Could you add your logic to `_parse_usage`? Thanks
langfuse-python
github_2023
python
871
langfuse
greptile-apps[bot]
@@ -88,8 +85,7 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: return super().dict(**kwargs_with_defaults) -def get_llama_index_index(callback, force_rebuild: bool = False): - Settings.callback_manager = CallbackManager([callback]) +def get_llama_index_index(handler, force_rebuild: bool = False):
logic: The `handler` parameter is not used in the function body. Consider how it should be integrated with the index creation or loading process.
langfuse-python
github_2023
python
851
langfuse
hassiebp
@@ -558,13 +558,13 @@ async def _wrap_async( openai_response = await wrapped(**arg_extractor.get_openai_args()) if _is_streaming_response(openai_response): - return LangfuseResponseGeneratorAsync( + return aiter(LangfuseResponseGeneratorAsync(
The `LangfuseResponseGeneratorAsync` should already support async iteration as implemented by the `__aiter__` method [here](https://github.com/sinwoobang/langfuse-python/blob/e8cc42110512939fa3a22c2650b073a4759c2b3b/langfuse/openai.py#L755). @sinwoobang Could you please explain what issue you ran into that required this change? Thanks!
langfuse-python
github_2023
python
863
langfuse
greptile-apps[bot]
@@ -31,6 +31,9 @@ def default(self, obj: Any): # Timezone-awareness check return serialize_datetime(obj) + if isinstance(obj, Exception): + return obj.message
logic: This change may not handle all Exception types correctly. Some exceptions might not have a 'message' attribute, leading to potential AttributeError. Consider using str(obj) or obj.args[0] as a fallback.
langfuse-python
github_2023
python
863
langfuse
vegetablest
@@ -31,6 +31,9 @@ def default(self, obj: Any): # Timezone-awareness check return serialize_datetime(obj) + if isinstance(obj, Exception):
I suggest changing it to this, WDYT? ``` if isinstance(obj, (Exception, KeyboardInterrupt)): return f"{type(obj).__name__}: {str(obj)}" ```
langfuse-python
github_2023
python
831
langfuse
hassiebp
@@ -0,0 +1,51 @@ +import logging +import random + +log = logging.getLogger("langfuse") + + +class Sampler: + sample_rate: float + + def __init__(self, sample_rate: float): + self.sample_rate = sample_rate + random.seed(42) # Fixed seed for reproducibility + + def sample_event(self, event: dict): + # need to get trace_id from a given event + + if "type" in event and "body" in event: + event_type = event["type"] + + trace_id = None + + if event_type == "trace-create" and "id" in event["body"]: + trace_id = event["body"]["id"] + elif "trace_id" in event["body"]: + trace_id = event["body"]["trace_id"] + elif "traceId" in event["body"]: + trace_id = event["body"]["traceId"] + else: + log.error(event) + raise Exception("No trace id found in event") + + return self.deterministic_sample(trace_id, self.sample_rate) + + else: + raise Exception("Event has no type or body") + + def deterministic_sample(self, trace_id: str, sample_rate: float): + log.debug( + f"Applying deterministic sampling to trace_id: {trace_id} with rate {sample_rate}" + ) + hash_value = hash(trace_id)
*question*: where does the `hash` function come from?
langfuse-python
github_2023
python
831
langfuse
hassiebp
@@ -174,6 +174,7 @@ def __init__( sdk_integration: Optional[str] = "default", httpx_client: Optional[httpx.Client] = None, enabled: Optional[bool] = True, + sample_rate: Optional[float] = None,
We should add this to the docstring
langfuse-python
github_2023
python
831
langfuse
hassiebp
@@ -212,6 +213,20 @@ def __init__( self.enabled = enabled public_key = public_key or os.environ.get("LANGFUSE_PUBLIC_KEY") secret_key = secret_key or os.environ.get("LANGFUSE_SECRET_KEY") + sample_rate = ( + sample_rate + if sample_rate + is not None # needs explicit None check, as 0 is a valid value + else os.environ.get("LANGFUSE_SAMPLE_RATE")
We might run into issues when setting via env var as it might get parsed as string. We had this issue in the past where we had to force the env variable to an integer via `int()`
langfuse-python
github_2023
python
821
langfuse
hassiebp
@@ -312,7 +312,7 @@ def add_task(self, event: dict): try: json.dumps(event, cls=EventSerializer) - event["timestamp"] = datetime.utcnow().replace(tzinfo=timezone.utc) + event["timestamp"] = datetime.now(timezone.utc)
Thanks @abhishek-compro! We have a util for that `from langfuse.utils import _get_timestamp` could you please use that one?
langfuse-python
github_2023
python
789
langfuse
hassiebp
@@ -78,7 +78,7 @@ def test_shutdown(): assert langfuse.task_manager._queue.empty() -def test_create_score(): +def test_create_numeric_score():
For the default (i.e. no data_type passed), are we allowing both string and floats as values or only floats?
langfuse-python
github_2023
python
768
langfuse
hassiebp
@@ -309,25 +328,51 @@ def auth_check(self) -> bool: self.log.exception(e) raise e + def get_dataset_runs( + self, + dataset_name: str, + *, + page: typing.Optional[int] = None, + limit: typing.Optional[int] = None,
*question*: Docstring below mentions that limit has default 50, but here initialized to None. Will the default be enforced elsewhere?
langfuse-python
github_2023
python
768
langfuse
hassiebp
@@ -2817,7 +2862,7 @@ class DatasetClient: created_at: dt.datetime updated_at: dt.datetime items: typing.List[DatasetItemClient] - runs: typing.List[str] + runs: typing.List[str] = [] # deprecated
I'd recommend either to maintain the previous behavior (option 1) or remove the attribute entirely (option 3) to force an AttributeError. Option 2 (empty array) might lead to unexpected / puzzling results (no runs in that array) for users with previously working code
langfuse-python
github_2023
python
714
langfuse
maxdeichmann
@@ -648,3 +602,97 @@ def _filter_image_data(messages: List[dict]): del content[index]["image_url"] return output_messages + + +class LangfuseResponseGeneratorSync: + def __init__( + self, + *, + resource, + response, + generation, + langfuse, + is_nested_trace, + ): + self.items = [] + + self.resource = resource + self.response = response + self.generation = generation + self.langfuse = langfuse + self.is_nested_trace = is_nested_trace + + def __iter__(self): + try: + for i in self.response: + self.items.append(i) + + yield i + finally: + self._finalize() + + def __enter__(self): + return self.__iter__() + + def __exit__(self, exc_type, exc_value, traceback): + pass + + def _finalize(self): + model, completion_start_time, completion = _extract_openai_response( + self.resource, self.items + ) + + # Avoiding the trace-update if trace-id is provided by user. + if not self.is_nested_trace: + self.langfuse.trace(id=self.generation.trace_id, output=completion) + + _create_langfuse_update( + completion, self.generation, completion_start_time, model=model + ) + + +class LangfuseResponseGeneratorAsync:
what about typing this as the openai sdk does it? We could subclass from `AsyncResponseContextManager`
langfuse-python
github_2023
python
669
langfuse
marcklingen
@@ -163,15 +171,15 @@ def __init__( ) if not public_key: - self.log.warning("public_key is not set.") - raise ValueError( - "public_key is required, set as a parameter or environment variable 'LANGFUSE_PUBLIC_KEY'" + self.enabled = False + self.log.warning( + "Langfuse client is disabled since no public_key was provided as a parameter or environment variable 'LANGFUSE_PUBLIC_KEY'." ) if not secret_key: - self.log.warning("secret_key is not set.") - raise ValueError( - "secret_key is required, set as parameter or environment variable 'LANGFUSE_SECRET_KEY'" + self.enabled = False + self.log.warning(
dx improvement: log only a single warning when disabled and state reason in this warning. currently user gets up to 3 warnings
langfuse-python
github_2023
python
669
langfuse
marcklingen
@@ -251,6 +254,9 @@ def init_resources(self): self._consumers.append(consumer) def add_task(self, event: dict): + if not self._enabled:
this is so clean 🤩
langfuse-python
github_2023
python
669
langfuse
maxdeichmann
@@ -140,6 +142,27 @@ def __init__( langfuse = Langfuse() ``` """ + self.enabled = enabled + public_key = public_key or os.environ.get("LANGFUSE_PUBLIC_KEY") + secret_key = secret_key or os.environ.get("LANGFUSE_SECRET_KEY") + + if not self.enabled: + self.log.warning( + "Langfuse client is disabled. No observability data will be sent." + ) + + elif not public_key: + self.enabled = False + self.log.warning( + "Langfuse client is disabled since no public_key was provided as a parameter or environment variable 'LANGFUSE_PUBLIC_KEY'." + ) + + elif not secret_key: + self.enabled = False + self.log.warning( + "Langfuse client is disabled since no secret_key was provided as a parameter or environment variable 'LANGFUSE_SECRET_KEY'."
can we add a link to the docs here on how to set up?
langfuse-python
github_2023
python
646
langfuse
marcklingen
@@ -120,8 +120,23 @@ def __init__( ] = {} def set_root( - self, root: Optional[Union[StatefulTraceClient, StatefulSpanClient]] + self, + root: Optional[Union[StatefulTraceClient, StatefulSpanClient]], + *, + update_root: bool = False, ) -> None: + """Set the root trace or span for the callback handler. + + Args: + root (Optional[Union[StatefulTraceClient, StatefulSpanClient]]): The root trace or span to
```suggestion root (Optional[Union[StatefulTraceClient, StatefulSpanClient]]): The root trace or observation to ```
langfuse-python
github_2023
python
644
langfuse
marcklingen
@@ -2251,12 +2253,15 @@ def update( task_manager=self.task_manager, ) - def get_langchain_handler(self): + def get_langchain_handler(self, update_parent: bool = False): """Get langchain callback handler associated with the current trace. This method creates and returns a CallbackHandler instance, linking it with the current trace. Use this if you want to group multiple Langchain runs within a single trace. + Args: + update_parent (bool): If set to True, the parent trace or span will be updated with the outcome of the Langchain run.
```suggestion update_parent (bool): If set to True, the parent trace or observation will be updated with the outcome of the Langchain run. ```
langfuse-python
github_2023
python
633
langfuse
maxdeichmann
@@ -151,11 +158,13 @@ def get_langchain_prompt(self): class ChatPromptClient(BasePromptClient): def __init__(self, prompt: Prompt_Chat): super().__init__(prompt) - self.prompt = prompt.prompt + self.prompt = [ + ChatMessageDict(role=p.role, content=p.content) for p in prompt.prompt + ] - def compile(self, **kwargs) -> List[ChatMessage]: + def compile(self, **kwargs) -> List[ChatMessageDict]:
Is this a breaking change if someone imported `ChatMessage` originally? I think yes. The import path would have involved a path to the api module, correct? If yes, this is hard to change, if no, i would suggest to keep the naming of the exported package.
langfuse-python
github_2023
python
633
langfuse
maxdeichmann
@@ -38,5 +38,19 @@ def set(self, key: str, value: PromptClient, ttl_seconds: Optional[int]): self._cache[key] = PromptCacheItem(value, ttl_seconds) @staticmethod - def generate_cache_key(name: str, version: Optional[int]) -> str: - return f"{name}-{version or 'latest'}" + def generate_cache_key( + name: str, *, version: Optional[int], label: Optional[str] + ) -> str: + parts = [name] + + if version is not None: + parts.append(f"version:{version}") + + elif label is not None: + parts.append(f"label:{label}") + + else: + # Default to production labeled prompt + parts.append("label:production")
this assumption makes sense.
langfuse-python
github_2023
python
633
langfuse
maxdeichmann
@@ -167,6 +209,38 @@ def test_create_prompt_with_null_config(): assert prompt.config == {} +def test_get_prompt_by_version_or_label(): + langfuse = Langfuse() + prompt_name = create_uuid() + + for i in range(3): + langfuse.create_prompt( + name=prompt_name, + prompt="test prompt " + str(i + 1), + labels=["production"] if i == 1 else [], + ) + + default_prompt_client = langfuse.get_prompt(prompt_name) + assert default_prompt_client.version == 2 + assert default_prompt_client.prompt == "test prompt 2" + assert default_prompt_client.labels == ["production"] + + first_prompt_client = langfuse.get_prompt(prompt_name, 1) + assert first_prompt_client.version == 1 + assert first_prompt_client.prompt == "test prompt 1" + assert first_prompt_client.labels == [] + + second_prompt_client = langfuse.get_prompt(prompt_name, version=2)
![image](https://github.com/langfuse/langfuse-python/assets/17686849/57d6246c-44c3-4315-99c2-6adcd1784901) Do you have the same signature when hovering?
langfuse-python
github_2023
python
633
langfuse
maxdeichmann
@@ -538,6 +542,7 @@ def get_prompt( name: str, version: Optional[int] = None, *, + label: Optional[str] = None,
would it make sense to add another overload like: ``` @overload def get_prompt( self, name: str, *, version: Optional[int] = None, label: Optional[str] = None, type: Literal["text"] = "text", cache_ttl_seconds: Optional[int] = None, ) -> TextPromptClient: ... ```
langfuse-python
github_2023
python
633
langfuse
maxdeichmann
@@ -566,26 +572,34 @@ def get_prompt( Exception: Propagates any exceptions raised during the fetching of a new prompt, unless there is an expired prompt in the cache, in which case it logs a warning and returns the expired prompt. """ - self.log.debug(f"Getting prompt {name}, version {version or 'latest'}") + if version is not None and label is not None: + raise ValueError("Cannot specify both version and label at the same time.")
Idea: wdyt about defaulting to one of the values here so that we do not break the application? I dont think there is a a clear assumption to default to one of the two, so i think we should keep it as is.
langfuse-python
github_2023
python
633
langfuse
maxdeichmann
@@ -648,7 +666,8 @@ def create_prompt( *, name: str, prompt: Union[str, List[ChatMessage]], - is_active: bool, + is_active: Optional[bool] = None, # deprecated + labels: List[str] = [],
as these are all named arguments, order does not matter - correct?
langfuse-python
github_2023
python
460
langfuse
maxdeichmann
@@ -29,6 +30,8 @@ def default(self, obj: Any): if is_dataclass(obj): return asdict(obj) + if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes)):
In general, i like this approach. Should this condition come below line 48 `isinstance(obj, (dict, list, str, int, float, type(None)))`? Also, is it possible that obj is a Sequence and a str at the same time? If no, i think the second condition is not necessary, right?
langfuse-python
github_2023
python
508
langfuse
maxdeichmann
@@ -47,3 +49,254 @@ def test_entire_llm_call_using_langchain_openai(expected_model, model): generation = list(filter(lambda o: o.type == "GENERATION", trace.observations))[0] assert generation.model == expected_model + + +@pytest.mark.asyncio +@pytest.mark.parametrize( # noqa: F821 + "expected_model,model", + [ + ("gpt-3.5-turbo", ChatOpenAI()), + ("gpt-3.5-turbo-instruct", OpenAI()), + ( + "gpt-3.5-turbo", + AzureChatOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + ), + ), + ( + "gpt-3.5-turbo-instruct", + AzureOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + ), + ), + ], +) +async def test_ainvoke_on_llm_call_using_langchain_openai(expected_model, model): + callback = CallbackHandler() + try: + # LLM calls are failing, because of missing API keys etc. + # However, we are still able to extract the model names beforehand.
Do you have an openai key at hand? You can set the OPENAI_API_KEY env variable and we can test the entire LLM call and dont need the try..except block. This is also how we do it in our CI pipeline.
langfuse-python
github_2023
python
508
langfuse
maxdeichmann
@@ -1,7 +1,9 @@ from langchain_openai import AzureChatOpenAI, AzureOpenAI, ChatOpenAI, OpenAI import pytest - +import types from langfuse.callback import CallbackHandler +from langchain.prompts import ChatPromptTemplate +from langchain.schema import StrOutputParser
FAILED tests/test_extract_model_langchain_openai.py::test_chain_streaming_llm_call_with_langchain_openai[gpt-3.5-turbo-model0] - assert 2 == 4 FAILED tests/test_extract_model_langchain_openai.py::test_chain_streaming_llm_call_with_langchain_openai[gpt-3.5-turbo-instruct-model1] - assert 2 == 4 FAILED tests/test_extract_model_langchain_openai.py::test_chain_streaming_llm_call_with_langchain_openai[gpt-4-0613-model2] - assert 2 == 4 FAILED tests/test_extract_model_langchain_openai.py::test_chain_async_streaming_llm_call_with_langchain_openai[gpt-3.5-turbo-model0] - assert 2 == 4 FAILED tests/test_extract_model_langchain_openai.py::test_chain_async_streaming_llm_call_with_langchain_openai[gpt-3.5-turbo-instruct-model1] - assert 2 == 4 FAILED tests/test_extract_model_langchain_openai.py::test_chain_async_streaming_llm_call_with_langchain_openai[gpt-4-0613-model2] - assert 2 == 4 FAILED tests/test_extract_model_langchain_openai.py::test_chain_async_invoke_llm_call_with_langchain_openai[gpt-3.5-turbo-model0] - UnboundLocalError: local variable 'res' referenced before assignment FAILED tests/test_extract_model_langchain_openai.py::test_chain_async_invoke_llm_call_with_langchain_openai[gpt-3.5-turbo-instruct-model1] - UnboundLocalError: local variable 'res' referenced before assignment FAILED tests/test_extract_model_langchain_openai.py::test_chain_async_invoke_llm_call_with_langchain_openai[gpt-4-0613-model2] - UnboundLocalError: local variable 'res' referenced before assignment FAILED tests/test_extract_model_langchain_openai.py::test_chain_invoke_llm_call_with_langchain_openai[gpt-3.5-turbo-model0] - UnboundLocalError: local variable 'res' referenced before assignment FAILED tests/test_extract_model_langchain_openai.py::test_chain_invoke_llm_call_with_langchain_openai[gpt-3.5-turbo-instruct-model1] - UnboundLocalError: local variable 'res' referenced before assignment FAILED tests/test_extract_model_langchain_openai.py::test_chain_invoke_llm_call_with_langchain_openai[gpt-4-0613-model2] - UnboundLocalError: local variable 'res' referenced before assignment Is it possible we have somewhat different setups? Tests seem to be failing here. Happy to jump on a call :)
langfuse-python
github_2023
python
508
langfuse
maxdeichmann
@@ -47,3 +49,254 @@ def test_entire_llm_call_using_langchain_openai(expected_model, model): generation = list(filter(lambda o: o.type == "GENERATION", trace.observations))[0] assert generation.model == expected_model + + +@pytest.mark.asyncio +@pytest.mark.parametrize( # noqa: F821 + "expected_model,model", + [ + ("gpt-3.5-turbo", ChatOpenAI()), + ("gpt-3.5-turbo-instruct", OpenAI()), + ( + "gpt-3.5-turbo", + AzureChatOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + ), + ), + ( + "gpt-3.5-turbo-instruct", + AzureOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + ), + ), + ], +) +async def test_ainvoke_on_llm_call_using_langchain_openai(expected_model, model): + callback = CallbackHandler() + try: + # LLM calls are failing, because of missing API keys etc. + # However, we are still able to extract the model names beforehand. + await model.ainvoke("Hello, how are you?", config={"callbacks": [callback]}) + except Exception as e: + print(e) + pass + + callback.flush() + api = get_api() + + trace = api.trace.get(callback.get_trace_id()) + assert len(trace.observations) == 1 + + generation = list(filter(lambda o: o.type == "GENERATION", trace.observations))[0] + assert generation.model == expected_model
We would probably want to assert that we have input, output set to some value here to ensure we are tracing this.
langfuse-python
github_2023
python
508
langfuse
maxdeichmann
@@ -47,3 +49,254 @@ def test_entire_llm_call_using_langchain_openai(expected_model, model): generation = list(filter(lambda o: o.type == "GENERATION", trace.observations))[0] assert generation.model == expected_model + + +@pytest.mark.asyncio +@pytest.mark.parametrize( # noqa: F821 + "expected_model,model", + [ + ("gpt-3.5-turbo", ChatOpenAI()), + ("gpt-3.5-turbo-instruct", OpenAI()), + ( + "gpt-3.5-turbo", + AzureChatOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + ), + ), + ( + "gpt-3.5-turbo-instruct", + AzureOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + ), + ), + ], +) +async def test_ainvoke_on_llm_call_using_langchain_openai(expected_model, model): + callback = CallbackHandler() + try: + # LLM calls are failing, because of missing API keys etc. + # However, we are still able to extract the model names beforehand. + await model.ainvoke("Hello, how are you?", config={"callbacks": [callback]}) + except Exception as e: + print(e) + pass + + callback.flush() + api = get_api() + + trace = api.trace.get(callback.get_trace_id()) + assert len(trace.observations) == 1 + + generation = list(filter(lambda o: o.type == "GENERATION", trace.observations))[0] + assert generation.model == expected_model + + +@pytest.mark.parametrize( # noqa: F821 + "expected_model,model", + [ + ("gpt-3.5-turbo", ChatOpenAI(streaming=True)), + ("gpt-3.5-turbo-instruct", OpenAI(streaming=True)), + ( + "gpt-3.5-turbo", + AzureChatOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + streaming=True, + ), + ), + ( + "gpt-3.5-turbo-instruct", + AzureOpenAI( + openai_api_version="2023-05-15", + azure_deployment="your-deployment-name", + azure_endpoint="https://your-endpoint-name.azurewebsites.net", + streaming=True, + ), + ), + ], +) +def test_simple_streaming_llm_call_with_langchain_openai(expected_model, model): + callback = CallbackHandler() + try: + res = model.stream("Hello, how are you?", config={"callbacks": [callback]}) + for chunk in res: + chunk + except Exception as e: + print(e) + pass + + callback.flush() + api = get_api() + + trace = api.trace.get(callback.get_trace_id()) + + assert _is_streaming_response(res) + assert len(trace.observations) == 1 + + generation = list(filter(lambda o: o.type == "GENERATION", trace.observations))[0] + assert generation.model == expected_model + + +def _is_streaming_response(response):
Minor: you can import this function also from https://github.com/noble-varghese/langfuse-python/blob/318f3238c0dcb7c0bf361c0bad58433386dc46e4/langfuse/openai.py#L451
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -840,7 +841,7 @@ def generation( start_time: typing.Optional[dt.datetime] = None, end_time: typing.Optional[dt.datetime] = None, metadata: typing.Optional[typing.Any] = None, - level: typing.Optional[Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"]] = None, + level: typing.Optional[SpanLevel] = None,
In general i like this change for DRY. However, it has the downside, that users wont see all the literals in intellisense. SpanLevel could be anything then. Hence i would probably leave that out here.
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -0,0 +1,23 @@ +from datetime import datetime +from typing import Any, List, Optional, TypedDict, Literal + +SpanLevel = Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"] + + +class TraceMetadata(TypedDict): + name: Optional[str] + user_id: Optional[str] + session_id: Optional[str] + version: Optional[str] + release: Optional[str] + metadata: Optional[Any] + tags: Optional[List[str]] + + +class ObservationParams(TraceMetadata, TypedDict):
Observations do not have session_id, tags, user_id
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -0,0 +1,388 @@ +from collections import defaultdict +from contextvars import ContextVar +from datetime import datetime +from functools import wraps +import logging +import os +from typing import Any, Callable, DefaultDict, List, Optional, Union + +from langfuse.client import Langfuse, StatefulSpanClient, StatefulTraceClient +from langfuse.llama_index import LlamaIndexCallbackHandler +from langfuse.types import ObservationParams, SpanLevel +from langfuse.utils import _get_timestamp + + +langfuse_context: ContextVar[Optional[Langfuse]] = ContextVar( + "langfuse_context", default=None +) +observation_stack_context: ContextVar[ + List[Union[StatefulTraceClient, StatefulSpanClient]] +] = ContextVar("observation_stack_context", default=[]) +observation_params_context: ContextVar[ + DefaultDict[str, ObservationParams] +] = ContextVar( + "observation_params_context", + default=defaultdict( + lambda: { + "name": None, + "user_id": None, + "session_id": None, + "version": None, + "release": None, + "metadata": None, + "tags": None, + "input": None, + "output": None, + "level": None, + "status_message": None, + "start_time": None, + "end_time": None, + }, + ), +) + + +class LangfuseDecorator: + log = logging.getLogger("langfuse") + + def __init__(self): + self._langfuse: Optional[Langfuse] = None + + def trace(self, func: Callable) -> Callable: + """ + Wraps a function to automatically create and manage Langfuse tracing around its execution. + + This decorator captures the start and end times of the function, along with input parameters and output results, and automatically updates the observation context. + It creates traces for top-level function calls and spans for nested function calls, ensuring that each observation is correctly associated with its parent observation. + In the event of an exception, the observation is updated with error details. + + Usage: + @langfuse.trace\n + def your_function_name(args): + # Your function implementation + + Parameters: + func (Callable): The function to be wrapped by the decorator. + + Returns: + Callable: A wrapper function that, when called, executes the original function within a Langfuse observation context. + + Raises: + Exception: Propagates any exceptions raised by the wrapped function, after logging and updating the observation with error details. + + Note: + - The decorator automatically manages observation IDs and context, but you can manually specify an observation ID using the `langfuse_observation_id` keyword argument when calling the wrapped function. + - To update observation or trace parameters (e.g., metadata, session_id), use `langfuse.update_current_observation` and `langfuse.set_current_trace_params` within the wrapped function. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + langfuse = self._get_langfuse() + stack = observation_stack_context.get().copy() + parent = stack[-1] if stack else None + + # Collect default observation data + name = func.__name__ + observation_id = kwargs.pop("langfuse_observation_id", None) + id = str(observation_id) if observation_id else None + input = {"args": args, "kwargs": kwargs} + start_time = _get_timestamp() + + # Create observation + observation = ( + parent.span(id=id, name=name, start_time=start_time, input=input) + if parent + else langfuse.trace( + id=id, name=name, start_time=start_time, input=input + ) + ) + + # Add observation to top of stack + observation_stack_context.set(stack + [observation]) + + # Call the wrapped function + result = None + try: + result = func(*args, **kwargs) + except Exception as e: + observation_params_context.get()[observation.id].update( + level="ERROR", status_message=str(e) + ) + raise e + finally: + # Collect final observation data + observation_params = observation_params_context.get()[observation.id] + end_time = observation_params["end_time"] or _get_timestamp() + output = observation_params["output"] or str(result) if result else None + observation_params.update(end_time=end_time, output=output) + + if isinstance(observation, StatefulSpanClient): + observation.end(**observation_params) + elif isinstance(observation, StatefulTraceClient): + observation.update(**observation_params) + + # Remove observation from top of stack by resetting to initial stack + observation_stack_context.set(stack) + + return result + + return wrapper + + def get_current_llama_index_handler(self): + """ + Retrieves the current LlamaIndexCallbackHandler associated with the most recent observation in the observation stack. + + This method fetches the current observation from the observation stack and returns a LlamaIndexCallbackHandler initialized with this observation. + It is intended to be used within the context of a trace, allowing access to a callback handler for operations that require interaction with the LlamaIndex API based on the current observation context. + + See the Langfuse documentation for more information on integrating the LlamaIndexCallbackHandler. + + Returns: + LlamaIndexCallbackHandler or None: Returns a LlamaIndexCallbackHandler instance if there is an active observation in the current context; otherwise, returns None if no observation is found. + + Note: + - This method should be called within the context of a trace (i.e., within a function wrapped by @langfuse.trace) to ensure that an observation context exists. + - If no observation is found in the current context (e.g., if called outside of a trace or if the observation stack is empty), the method logs a warning and returns None. + """ + + observation = observation_stack_context.get()[-1] + + if observation is None: + self.log.warn("No observation found in the current context") + + return None + + callback_handler = LlamaIndexCallbackHandler() + callback_handler.set_root(observation) + + return callback_handler + + def get_current_langchain_handler(self): + """ + Retrieves the current LangchainCallbackHandler associated with the most recent observation in the observation stack. + + This method fetches the current observation from the observation stack and returns a LangchainCallbackHandler initialized with this observation. + It is intended to be used within the context of a trace, allowing access to a callback handler for operations that require interaction with Langchain based on the current observation context. + + See the Langfuse documentation for more information on integrating the LangchainCallbackHandler. + + Returns: + LangchainCallbackHandler or None: Returns a LangchainCallbackHandler instance if there is an active observation in the current context; otherwise, returns None if no observation is found. + + Note: + - This method should be called within the context of a trace (i.e., within a function wrapped by @langfuse.trace) to ensure that an observation context exists. + - If no observation is found in the current context (e.g., if called outside of a trace or if the observation stack is empty), the method logs a warning and returns None. + """ + observation = observation_stack_context.get()[-1] + + if observation is None: + self.log.warn("No observation found in the current context") + + return None + + return observation.get_langchain_handler() + + def get_current_trace_id(self): + """ + Retrieves the ID of the current trace from the observation stack context. + + This method examines the observation stack to find the root trace and returns its ID. It is useful for operations that require the trace ID, + such as setting trace parameters or querying trace information. The trace ID is typically the ID of the first observation in the stack, + representing the entry point of the traced execution context. + + Returns: + str or None: The ID of the current trace if available; otherwise, None. A return value of None indicates that there is no active trace in the current context, + possibly due to the method being called outside of any @langfuse.trace-decorated function execution. + + Note: + - This method should be called within the context of a trace (i.e., inside a function wrapped with the @langfuse.trace decorator) to ensure that a current trace is indeed present and its ID can be retrieved. + - If called outside of a trace context, or if the observation stack has somehow been corrupted or improperly managed, this method will log a warning and return None, indicating the absence of a traceable context. + """ + stack = observation_stack_context.get() + + if not stack: + self.log.warn("No trace found in the current context") + + return None + + return stack[0].id + + def set_current_trace_params( + self, + name: Optional[str] = None, + user_id: Optional[str] = None, + session_id: Optional[str] = None, + version: Optional[str] = None, + release: Optional[str] = None, + metadata: Optional[Any] = None, + tags: Optional[List[str]] = None, + ): + """ + Sets parameters for the current trace, updating the trace's metadata and context information. + + This method allows for dynamically updating the trace parameters at any point during the execution of a trace. + It updates the parameters of the current trace based on the provided arguments. These parameters include metadata, session information, + and other trace attributes that can be useful for categorization, filtering, and analysis in the Langfuse UI. + + + Parameters: + - name (Optional[str]): Identifier of the trace. Useful for sorting/filtering in the UI.. + - user_id (Optional[str]): The id of the user that triggered the execution. Used to provide user-level analytics. + - session_id (Optional[str]): Used to group multiple traces into a session in Langfuse. Use your own session/thread identifier. + - version (Optional[str]): The version of the trace type. Used to understand how changes to the trace type affect metrics. Useful in debugging. + - release (Optional[str]): The release identifier of the current deployment. Used to understand how changes of different deployments affect metrics. Useful in debugging. + - metadata (Optional[Any]): Additional metadata of the trace. Can be any JSON object. Metadata is merged when being updated via the API. + - tags (Optional[List[str]]): Tags are used to categorize or label traces. Traces can be filtered by tags in the Langfuse UI and GET API. + + Returns: + None + + Note: + - This method should be used within the context of an active trace, typically within a function that is being traced using the @langfuse.trace decorator. + - The method updates the trace parameters for the currently executing trace. In nested trace scenarios, it affects the most recent trace context. + - If called outside of an active trace context, a warning is logged, and a ValueError is raised to indicate the absence of a traceable context. + """ + trace_id = self.get_current_trace_id() + + if trace_id is None: + self.log.warn("No trace found in the current context") + + return + + observation_params_context.get()[trace_id].update( + { + "name": name, + "user_id": user_id, + "session_id": session_id, + "version": version, + "release": release, + "metadata": metadata, + "tags": tags, + } + ) + + def update_current_observation( + self, + *, + input: Optional[Any] = None, + output: Optional[Any] = None, + name: Optional[str] = None, + version: Optional[str] = None, + metadata: Optional[Any] = None, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + release: Optional[str] = None, + tags: Optional[List[str]] = None, + user_id: Optional[str] = None, + session_id: Optional[str] = None, + level: Optional[SpanLevel] = None, + status_message: Optional[str] = None, + ): + """ + Updates parameters for the current observation within an active trace context. + + This method dynamically adjusts the parameters of the most recent observation on the observation stack. + It allows for the enrichment of observation data with additional details such as input parameters, output results, metadata, and more, + enhancing the observability and traceability of the execution context. + + Parameters: + - input (Optional[Any]): The input parameters of the observation, providing context about the observed operation or function call. + - output (Optional[Any]): The output or result of the observation + - name (Optional[str]): Identifier of the trace. Useful for sorting/filtering in the UI.. + - user_id (Optional[str]): The id of the user that triggered the execution. Used to provide user-level analytics. + - session_id (Optional[str]): Used to group multiple traces into a session in Langfuse. Use your own session/thread identifier. + - version (Optional[str]): The version of the trace type. Used to understand how changes to the trace type affect metrics. Useful in debugging. + - release (Optional[str]): The release identifier of the current deployment. Used to understand how changes of different deployments affect metrics. Useful in debugging. + - metadata (Optional[Any]): Additional metadata of the trace. Can be any JSON object. Metadata is merged when being updated via the API. + - tags (Optional[List[str]]): Tags are used to categorize or label traces. Traces can be filtered by tags in the Langfuse UI and GET API. + - start_time (Optional[datetime]): The start time of the observation, allowing for custom time range specification. + - end_time (Optional[datetime]): The end time of the observation, enabling precise control over the observation duration. + - level (Optional[SpanLevel]): The severity or importance level of the observation, such as "INFO", "WARNING", or "ERROR". + - status_message (Optional[str]): A message or description associated with the observation's status, particularly useful for error reporting. + + Returns: + None + + Raises: + ValueError: If no current observation is found in the context, indicating that this method was called outside of an observation's execution scope. + + Note: + - This method is intended to be used within the context of an active observation, typically within a function wrapped by the @langfuse.trace decorator. + - It updates the parameters of the most recently created observation on the observation stack. Care should be taken in nested observation contexts to ensure the updates are applied as intended. + - Parameters set to `None` will not overwrite existing values for those parameters. This behavior allows for selective updates without clearing previously set information. + """ + stack = observation_stack_context.get() + observation = stack[-1] if stack else None + + if not observation: + self.log.warn("No observation found in the current context") + + return + + observation_params_context.get()[observation.id].update( + input=input, + output=output, + name=name, + version=version, + metadata=metadata, + start_time=start_time, + end_time=end_time, + release=release, + tags=tags, + user_id=user_id, + session_id=session_id, + level=level, + status_message=status_message, + ) + + def flush(self): + """ + Forces the immediate flush of all buffered observations to the Langfuse backend. + + This method triggers the explicit sending of all accumulated trace and observation data that has not yet been sent to Langfuse servers. + It is typically used to ensure that data is promptly available for analysis, especially at the end of an execution context or before the application exits. + + Usage: + - This method can be called at strategic points in the application where it's crucial to ensure that all telemetry data captured up to that point is made persistent and visible on the Langfuse platform. + - It's particularly useful in scenarios where the application might terminate abruptly or in batch processing tasks that require periodic flushing of trace data. + + Returns: + None + + Raises: + ValueError: If it fails to find a Langfuse client object in the current context, indicating potential misconfiguration or initialization issues. + + Note: + - The flush operation may involve network I/O to send data to the Langfuse backend, which could impact performance if called too frequently in performance-sensitive contexts. + - In long-running applications, it's often sufficient to rely on the automatic flushing mechanism provided by the Langfuse client. + However, explicit calls to `flush` can be beneficial in certain edge cases or for debugging purposes. + """ + + langfuse = self._get_langfuse() + if langfuse: + langfuse.flush() + else: + self.log.warn("No langfuse object found in the current context") + + def _get_langfuse(self) -> Langfuse:
This here might be called concurrently / parallel. I guess we shoudl make sure this behaves like a singleton. We have a similar implementation in the openai integration. Feel free to check that out.
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -0,0 +1,388 @@ +from collections import defaultdict +from contextvars import ContextVar +from datetime import datetime +from functools import wraps +import logging +import os +from typing import Any, Callable, DefaultDict, List, Optional, Union + +from langfuse.client import Langfuse, StatefulSpanClient, StatefulTraceClient +from langfuse.llama_index import LlamaIndexCallbackHandler +from langfuse.types import ObservationParams, SpanLevel +from langfuse.utils import _get_timestamp + + +langfuse_context: ContextVar[Optional[Langfuse]] = ContextVar( + "langfuse_context", default=None +) +observation_stack_context: ContextVar[ + List[Union[StatefulTraceClient, StatefulSpanClient]] +] = ContextVar("observation_stack_context", default=[]) +observation_params_context: ContextVar[ + DefaultDict[str, ObservationParams] +] = ContextVar( + "observation_params_context", + default=defaultdict( + lambda: { + "name": None, + "user_id": None, + "session_id": None, + "version": None, + "release": None, + "metadata": None, + "tags": None, + "input": None, + "output": None, + "level": None, + "status_message": None, + "start_time": None, + "end_time": None, + }, + ), +) + + +class LangfuseDecorator: + log = logging.getLogger("langfuse") + + def __init__(self): + self._langfuse: Optional[Langfuse] = None + + def trace(self, func: Callable) -> Callable: + """ + Wraps a function to automatically create and manage Langfuse tracing around its execution. + + This decorator captures the start and end times of the function, along with input parameters and output results, and automatically updates the observation context. + It creates traces for top-level function calls and spans for nested function calls, ensuring that each observation is correctly associated with its parent observation. + In the event of an exception, the observation is updated with error details. + + Usage: + @langfuse.trace\n + def your_function_name(args): + # Your function implementation + + Parameters: + func (Callable): The function to be wrapped by the decorator. + + Returns: + Callable: A wrapper function that, when called, executes the original function within a Langfuse observation context. + + Raises: + Exception: Propagates any exceptions raised by the wrapped function, after logging and updating the observation with error details. + + Note: + - The decorator automatically manages observation IDs and context, but you can manually specify an observation ID using the `langfuse_observation_id` keyword argument when calling the wrapped function. + - To update observation or trace parameters (e.g., metadata, session_id), use `langfuse.update_current_observation` and `langfuse.set_current_trace_params` within the wrapped function. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + langfuse = self._get_langfuse() + stack = observation_stack_context.get().copy() + parent = stack[-1] if stack else None
Quick question: say i have a function and annotate it with a trace. Within that function i start two threads, which execute two annotated functions. Will both get the same parent?
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -0,0 +1,388 @@ +from collections import defaultdict +from contextvars import ContextVar +from datetime import datetime +from functools import wraps +import logging +import os +from typing import Any, Callable, DefaultDict, List, Optional, Union + +from langfuse.client import Langfuse, StatefulSpanClient, StatefulTraceClient +from langfuse.llama_index import LlamaIndexCallbackHandler +from langfuse.types import ObservationParams, SpanLevel +from langfuse.utils import _get_timestamp + + +langfuse_context: ContextVar[Optional[Langfuse]] = ContextVar( + "langfuse_context", default=None +) +observation_stack_context: ContextVar[ + List[Union[StatefulTraceClient, StatefulSpanClient]] +] = ContextVar("observation_stack_context", default=[]) +observation_params_context: ContextVar[ + DefaultDict[str, ObservationParams] +] = ContextVar( + "observation_params_context", + default=defaultdict( + lambda: { + "name": None, + "user_id": None, + "session_id": None, + "version": None, + "release": None, + "metadata": None, + "tags": None, + "input": None, + "output": None, + "level": None, + "status_message": None, + "start_time": None, + "end_time": None, + }, + ), +) + + +class LangfuseDecorator: + log = logging.getLogger("langfuse") + + def __init__(self): + self._langfuse: Optional[Langfuse] = None + + def trace(self, func: Callable) -> Callable: + """ + Wraps a function to automatically create and manage Langfuse tracing around its execution. + + This decorator captures the start and end times of the function, along with input parameters and output results, and automatically updates the observation context. + It creates traces for top-level function calls and spans for nested function calls, ensuring that each observation is correctly associated with its parent observation. + In the event of an exception, the observation is updated with error details. + + Usage: + @langfuse.trace\n + def your_function_name(args): + # Your function implementation + + Parameters: + func (Callable): The function to be wrapped by the decorator. + + Returns: + Callable: A wrapper function that, when called, executes the original function within a Langfuse observation context. + + Raises: + Exception: Propagates any exceptions raised by the wrapped function, after logging and updating the observation with error details. + + Note: + - The decorator automatically manages observation IDs and context, but you can manually specify an observation ID using the `langfuse_observation_id` keyword argument when calling the wrapped function. + - To update observation or trace parameters (e.g., metadata, session_id), use `langfuse.update_current_observation` and `langfuse.set_current_trace_params` within the wrapped function. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + langfuse = self._get_langfuse() + stack = observation_stack_context.get().copy() + parent = stack[-1] if stack else None + + # Collect default observation data + name = func.__name__ + observation_id = kwargs.pop("langfuse_observation_id", None) + id = str(observation_id) if observation_id else None + input = {"args": args, "kwargs": kwargs} + start_time = _get_timestamp() + + # Create observation + observation = ( + parent.span(id=id, name=name, start_time=start_time, input=input) + if parent + else langfuse.trace( + id=id, name=name, start_time=start_time, input=input + ) + ) + + # Add observation to top of stack + observation_stack_context.set(stack + [observation]) + + # Call the wrapped function + result = None + try: + result = func(*args, **kwargs) + except Exception as e: + observation_params_context.get()[observation.id].update( + level="ERROR", status_message=str(e) + ) + raise e + finally: + # Collect final observation data + observation_params = observation_params_context.get()[observation.id] + end_time = observation_params["end_time"] or _get_timestamp() + output = observation_params["output"] or str(result) if result else None + observation_params.update(end_time=end_time, output=output) + + if isinstance(observation, StatefulSpanClient): + observation.end(**observation_params) + elif isinstance(observation, StatefulTraceClient): + observation.update(**observation_params) + + # Remove observation from top of stack by resetting to initial stack + observation_stack_context.set(stack) + + return result + + return wrapper + + def get_current_llama_index_handler(self):
This is great DX!!!!
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -0,0 +1,536 @@ +import asyncio +from collections import defaultdict +from contextvars import ContextVar +from datetime import datetime +from functools import wraps +import logging +import os +from typing import ( + Any, + Callable, + DefaultDict, + List, + Optional, + Union, + Literal, + Dict, + Tuple, +) + +from langfuse.client import ( + Langfuse, + StatefulSpanClient, + StatefulTraceClient, + StatefulGenerationClient, + PromptClient, + ModelUsage, + MapValue, +) +from langfuse.llama_index import LlamaIndexCallbackHandler +from langfuse.types import ObservationParams, SpanLevel +from langfuse.utils import _get_timestamp +from langfuse.utils.langfuse_singleton import LangfuseSingleton +from langfuse.utils.error_logging import catch_and_log_errors + +from pydantic import BaseModel + +langfuse_context: ContextVar[Optional[Langfuse]] = ContextVar( + "langfuse_context", default=None +) +observation_stack_context: ContextVar[ + List[Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient]] +] = ContextVar("observation_stack_context", default=[]) +observation_params_context: ContextVar[ + DefaultDict[str, ObservationParams] +] = ContextVar( + "observation_params_context", + default=defaultdict( + lambda: { + "name": None, + "user_id": None, + "session_id": None, + "version": None, + "release": None, + "metadata": None, + "tags": None, + "input": None, + "output": None, + "level": None, + "status_message": None, + "start_time": None, + "end_time": None, + "completion_start_time": None, + "model": None, + "model_parameters": None, + "usage": None, + "prompt": None, + }, + ), +) + + +class LangfuseDecorator: + log = logging.getLogger("langfuse") + + def __init__(self): + self._langfuse: Optional[Langfuse] = None + + def trace( + self, + as_type: Optional[Literal["generation"]] = None, + ) -> Callable: + """ + Wraps a function to automatically create and manage Langfuse tracing around its execution. Handles both synchronous and asynchronous functions. + + This decorator captures the start and end times of the function, along with input parameters and output results, and automatically updates the observation context. + It creates traces for top-level function calls and spans for nested function calls, ensuring that each observation is correctly associated with its parent observation. + In the event of an exception, the observation is updated with error details. + + Usage: + @langfuse.trace\n + def your_function_name(args): + # Your function implementation + + Parameters: + func (Callable): The function to be wrapped by the decorator. + + Returns: + Callable: A wrapper function that, when called, executes the original function within a Langfuse observation context. + + Raises: + Exception: Propagates any exceptions raised by the wrapped function, after logging and updating the observation with error details. + + Note: + - The decorator automatically manages observation IDs and context, but you can manually specify an observation ID using the `langfuse_observation_id` keyword argument when calling the wrapped function. + - To update observation or trace parameters (e.g., metadata, session_id), use `langfuse.update_current_observation` and `langfuse.set_current_trace_params` within the wrapped function. + """ + + def decorator(func: Callable) -> Callable: + return ( + self.async_trace(func, as_type=as_type) + if asyncio.iscoroutinefunction(func) + else self.sync_trace(func, as_type=as_type) + )
Good implementation above, i think this is the way to go!
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -0,0 +1,497 @@ +import asyncio +from contextvars import ContextVar +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor +import pytest + +from langchain_community.chat_models import ChatOpenAI +from langchain.prompts import ChatPromptTemplate +from langfuse.decorators import langfuse +from tests.utils import create_uuid, get_api, get_llama_index_index +from typing import Optional + +mock_metadata = "mock_metadata" +mock_deep_metadata = "mock_deep_metadata" +mock_session_id = "session-id-1" +mock_args = (1, 2, 3) +mock_kwargs = {"a": 1, "b": 2, "c": 3} + + +def test_nested_observations(): + mock_name = "test_nested_observations" + mock_trace_id = create_uuid() + + @langfuse.trace(as_type="generation") + def level_3_function(): + langfuse.update_current_observation(metadata=mock_metadata) + langfuse.update_current_observation( + metadata=mock_deep_metadata, + usage={"input": 150, "output": 50, "total": 300}, + model="gpt-3.5-turbo", + ) + + langfuse.set_current_trace_params(session_id=mock_session_id, name=mock_name) + + return "level_3" + + @langfuse.trace() + def level_2_function(): + level_3_function() + langfuse.update_current_observation(metadata=mock_metadata) + + return "level_2" + + @langfuse.trace() + def level_1_function(*args, **kwargs): + level_2_function() + + return "level_1" + + result = level_1_function( + *mock_args, **mock_kwargs, langfuse_observation_id=mock_trace_id + ) + langfuse.flush() + + assert result == "level_1" # Wrapped function returns correctly + + # ID setting for span or trace + + trace_data = get_api().trace.get(mock_trace_id) + assert ( + len(trace_data.observations) == 2 + ) # Top-most function is trace, so it's not an observations + + assert trace_data.input == {"args": list(mock_args), "kwargs": mock_kwargs} + assert trace_data.output == "level_1" + + # trace parameters if set anywhere in the call stack + assert trace_data.session_id == mock_session_id + assert trace_data.name == mock_name + + # Check correct nesting + adjacencies = defaultdict(list) + for o in trace_data.observations: + adjacencies[o.parent_observation_id or o.trace_id].append(o) + + assert len(adjacencies[mock_trace_id]) == 1 # Trace has only one child + assert len(adjacencies) == 2 # Only trace and one observation have children + + level_2_observation = adjacencies[mock_trace_id][0] + level_3_observation = adjacencies[level_2_observation.id][0] + + assert level_2_observation.metadata == mock_metadata + assert level_3_observation.metadata == mock_deep_metadata + assert level_3_observation.type == "GENERATION" + assert level_3_observation.calculated_total_cost > 0 + + +# behavior on exceptions +def test_exception_in_wrapped_function(): + mock_name = "test_exception_in_wrapped_function" + mock_trace_id = create_uuid() + + @langfuse.trace(as_type="generation") + def level_3_function(): + langfuse.update_current_observation(metadata=mock_metadata) + langfuse.update_current_observation( + metadata=mock_deep_metadata, + usage={"input": 150, "output": 50, "total": 300}, + model="gpt-3.5-turbo", + ) + langfuse.set_current_trace_params(session_id=mock_session_id, name=mock_name) + + raise ValueError("Mock exception") + + @langfuse.trace() + def level_2_function(): + level_3_function() + langfuse.update_current_observation(metadata=mock_metadata) + + return "level_2" + + @langfuse.trace() + def level_1_function(*args, **kwargs): + level_2_function() + + return "level_1" + + # Check that the exception is raised + with pytest.raises(ValueError): + level_1_function( + *mock_args, **mock_kwargs, langfuse_observation_id=mock_trace_id + ) + + langfuse.flush() + + trace_data = get_api().trace.get(mock_trace_id) + + assert trace_data.input == {"args": list(mock_args), "kwargs": mock_kwargs} + assert trace_data.output is None # Output is None if exception is raised + + # trace parameters if set anywhere in the call stack + assert trace_data.session_id == mock_session_id + assert trace_data.name == mock_name + + # Check correct nesting + adjacencies = defaultdict(list) + for o in trace_data.observations: + adjacencies[o.parent_observation_id or o.trace_id].append(o) + + assert len(adjacencies[mock_trace_id]) == 1 # Trace has only one child + assert len(adjacencies) == 2 # Only trace and one observation have children + + level_2_observation = adjacencies[mock_trace_id][0] + level_3_observation = adjacencies[level_2_observation.id][0] + + assert ( + level_2_observation.metadata is None + ) # Exception is raised before metadata is set + assert level_3_observation.metadata == mock_deep_metadata + assert level_3_observation.status_message == "Mock exception" + assert level_3_observation.level == "ERROR" + + +# behavior on concurrency +def test_concurrent_decorator_executions(): + mock_name = "test_concurrent_decorator_executions" + mock_trace_id_1 = create_uuid() + mock_trace_id_2 = create_uuid() + + @langfuse.trace(as_type="generation") + def level_3_function(): + langfuse.update_current_observation(metadata=mock_metadata) + langfuse.update_current_observation(metadata=mock_deep_metadata) + langfuse.update_current_observation( + metadata=mock_deep_metadata, + usage={"input": 150, "output": 50, "total": 300}, + model="gpt-3.5-turbo", + ) + langfuse.set_current_trace_params(session_id=mock_session_id, name=mock_name) + + return "level_3" + + @langfuse.trace() + def level_2_function(): + level_3_function() + langfuse.update_current_observation(metadata=mock_metadata) + + return "level_2" + + @langfuse.trace() + def level_1_function(*args, **kwargs): + level_2_function() + + return "level_1" + + with ThreadPoolExecutor(max_workers=2) as executor: + future1 = executor.submit( + level_1_function, + *mock_args, + mock_trace_id_1, + **mock_kwargs, + langfuse_observation_id=mock_trace_id_1, + ) + future2 = executor.submit( + level_1_function, + *mock_args, + mock_trace_id_2, + **mock_kwargs, + langfuse_observation_id=mock_trace_id_2, + ) + + future1.result() + future2.result() + + langfuse.flush() + + print("mock_id_1", mock_trace_id_1) + print("mock_id_2", mock_trace_id_2) + + for mock_id in [mock_trace_id_1, mock_trace_id_2]: + trace_data = get_api().trace.get(mock_id) + assert ( + len(trace_data.observations) == 2 + ) # Top-most function is trace, so it's not an observations + + assert trace_data.input == { + "args": list(mock_args) + [mock_id], + "kwargs": mock_kwargs, + } + assert trace_data.output == "level_1" + + # trace parameters if set anywhere in the call stack + assert trace_data.session_id == mock_session_id + assert trace_data.name == mock_name + + # Check correct nesting + adjacencies = defaultdict(list) + for o in trace_data.observations: + adjacencies[o.parent_observation_id or o.trace_id].append(o) + + assert len(adjacencies[mock_id]) == 1 # Trace has only one child + assert len(adjacencies) == 2 # Only trace and one observation have children + + level_2_observation = adjacencies[mock_id][0] + level_3_observation = adjacencies[level_2_observation.id][0] + + assert level_2_observation.metadata == mock_metadata + assert level_3_observation.metadata == mock_deep_metadata + assert level_3_observation.type == "GENERATION" + assert level_3_observation.calculated_total_cost > 0 + + +def test_decorators_llama_index(): + mock_name = "test_decorators_llama_index" + mock_trace_id = create_uuid() + + @langfuse.trace() + def llama_index_operations(*args, **kwargs): + callback = langfuse.get_current_llama_index_handler() + index = get_llama_index_index(callback, force_rebuild=True) + + return index.as_query_engine().query(kwargs["query"]) + + @langfuse.trace() + def level_3_function(*args, **kwargs): + langfuse.update_current_observation(metadata=mock_metadata) + langfuse.update_current_observation(metadata=mock_deep_metadata) + langfuse.set_current_trace_params(session_id=mock_session_id, name=mock_name) + + return llama_index_operations(*args, **kwargs) + + @langfuse.trace() + def level_2_function(*args, **kwargs): + langfuse.update_current_observation(metadata=mock_metadata) + + return level_3_function(*args, **kwargs) + + @langfuse.trace() + def level_1_function(*args, **kwargs): + return level_2_function(*args, **kwargs) + + level_1_function( + query="What is the authors ambition?", langfuse_observation_id=mock_trace_id + ) + + langfuse.flush() + + trace_data = get_api().trace.get(mock_trace_id) + assert len(trace_data.observations) > 2 + + # Check correct nesting + adjacencies = defaultdict(list) + for o in trace_data.observations: + adjacencies[o.parent_observation_id or o.trace_id].append(o) + + assert len(adjacencies[mock_trace_id]) == 1 # Trace has only one child + + # Check that the llama_index_operations is at the correct level + lvl = 1 + curr_id = mock_trace_id + llama_index_root_span = None + + while len(adjacencies[curr_id]) > 0: + o = adjacencies[curr_id][0] + if o.name == "llama_index_operations": + llama_index_root_span = o + break + + curr_id = adjacencies[curr_id][0].id + lvl += 1 + + assert lvl == 3 + + assert llama_index_root_span is not None + assert any([o.name == "OpenAIEmbedding" for o in trace_data.observations]) + + +def test_decorators_langchain(): + mock_name = "test_decorators_langchain" + mock_trace_id = create_uuid() + + @langfuse.trace() + def langchain_operations(*args, **kwargs): + handler = langfuse.get_current_langchain_handler() + prompt = ChatPromptTemplate.from_template("tell me a short joke about {topic}") + model = ChatOpenAI(temperature=0) + + chain = prompt | model + + return chain.invoke( + {"topic": kwargs["topic"]}, + config={ + "callbacks": [handler], + }, + ) + + @langfuse.trace() + def level_3_function(*args, **kwargs): + langfuse.update_current_observation(metadata=mock_metadata) + langfuse.update_current_observation(metadata=mock_deep_metadata) + langfuse.set_current_trace_params(session_id=mock_session_id, name=mock_name) + + return langchain_operations(*args, **kwargs) + + @langfuse.trace() + def level_2_function(*args, **kwargs): + langfuse.update_current_observation(metadata=mock_metadata) + + return level_3_function(*args, **kwargs) + + @langfuse.trace() + def level_1_function(*args, **kwargs): + return level_2_function(*args, **kwargs) + + level_1_function(topic="socks", langfuse_observation_id=mock_trace_id) + + langfuse.flush() + + trace_data = get_api().trace.get(mock_trace_id) + assert len(trace_data.observations) > 2 + + # Check correct nesting + adjacencies = defaultdict(list) + for o in trace_data.observations: + adjacencies[o.parent_observation_id or o.trace_id].append(o) + + assert len(adjacencies[mock_trace_id]) == 1 # Trace has only one child + + # Check that the langchain_operations is at the correct level + lvl = 1 + curr_id = mock_trace_id + llama_index_root_span = None + + while len(adjacencies[curr_id]) > 0: + o = adjacencies[curr_id][0] + if o.name == "langchain_operations": + llama_index_root_span = o + break + + curr_id = adjacencies[curr_id][0].id + lvl += 1 + + assert lvl == 3 + + assert llama_index_root_span is not None + assert any([o.name == "ChatPromptTemplate" for o in trace_data.observations]) + + +@pytest.mark.asyncio +async def test_asyncio_concurrency_inside_nested_span():
Nice!
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -150,7 +160,13 @@ async def async_wrapper(*args, **kwargs): except Exception as e: self._handle_exception(observation, e) finally: + if inspect.isasyncgen(result):
Nice!
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -477,7 +485,7 @@ def get_current_langchain_handler(self): return observation.get_langchain_handler() - def get_current_trace_id(self): + def get_current_trace_id(self, log_warnings: bool = True):
Wdyt about always logging a warning here? I think this would be unexpected for the user to not get an id here.
langfuse-python
github_2023
python
425
langfuse
maxdeichmann
@@ -17,14 +17,28 @@ def __new__(cls): cls._instance = super(LangfuseSingleton, cls).__new__(cls) return cls._instance - def get(self) -> Langfuse: + def get( + self, + public_key: Optional[str] = None, + secret_key: Optional[str] = None, + host: Optional[str] = None, + debug: bool = False, + sdk_integration: Optional[str] = None, + ) -> Langfuse: if self._langfuse: return self._langfuse with self._lock: if self._langfuse: return self._langfuse - self._langfuse = Langfuse() + self._langfuse = Langfuse( + public_key=public_key, + secret_key=secret_key, + host=host, + debug=debug, + sdk_integration=sdk_integration, + ) + print("LangfuseSingleton: Langfuse instance created.")
can you remove this?
langfuse-python
github_2023
python
430
langfuse
maxdeichmann
@@ -72,3 +73,12 @@ def __eq__(self, other): ) return False + + def get_langchain_prompt(self) -> str: + """Converts string of Langfuse prompt template prompt into string compatible + with Lanchain PromptTemplate.
nit: type lanchain -> langchain
langfuse-python
github_2023
python
405
langfuse
maxdeichmann
@@ -480,24 +476,21 @@ def score( id: typing.Optional[str] = None, comment: typing.Optional[str] = None, observation_id: typing.Optional[str] = None, - kwargs=None,
Yes, this is a bug. Coudl you quickly add it?
langfuse-python
github_2023
python
405
langfuse
maxdeichmann
@@ -1,4 +1,12 @@ import logging + +log = logging.getLogger("langfuse") + +try: # Test that langchain is installed before proceeding + import langchain +except ImportError as e: + log.exception(f"Could not import langchain. Some functionality may be missing. {e}")
Thanks!
langfuse-python
github_2023
others
412
langfuse
maxdeichmann
@@ -7,15 +7,15 @@ license = "MIT" readme = "README.md" [tool.poetry.dependencies] -python = ">=3.8.1,<3.13"
The 13 was intended so that 12 is included. Alternatively, <= 3.12
langfuse-python
github_2023
others
412
langfuse
maxdeichmann
@@ -7,15 +7,15 @@ license = "MIT" readme = "README.md" [tool.poetry.dependencies] -python = ">=3.8.1,<3.13" +python = ">=3.8.1,<3.12" httpx = ">=0.15.4,<0.26.0" pydantic = ">=1.10.7, <3.0" backoff = "^2.2.1" openai = ">=0.27.8" wrapt = "1.14" langchain = { version = ">=0.0.309", optional = true } chevron = "^0.14.0" -llama-index = {version = "^0.10.6", optional = true} +llama-index = {version = "^0.10.12", optional = true}
Is this intended?
langfuse-python
github_2023
python
412
langfuse
maxdeichmann
@@ -33,3 +33,12 @@ class ParsedLLMEndPayload(TypedDict): output: Optional[dict] usage: Optional[ModelUsage] model: Optional[str] + + +class TraceMetadata(TypedDict): + name: Optional[str] + user_id: Optional[str] + session_id: Optional[str] + version: Optional[str] + metadata: Optional[Any] + tags: Optional[List[str]]
Can you also add `release` here?
langfuse-python
github_2023
python
412
langfuse
maxdeichmann
@@ -311,3 +311,54 @@ def test_callback_with_root_span(): second_embedding_generation, second_llm_generation = generations[-2:] assert validate_embedding_generation(second_embedding_generation) assert validate_llm_generation(second_llm_generation) + + +def test_callback_with_custom_trace_metadata(): + initial_name = "initial-name" + initial_user_id = "initial-user-id" + initial_session_id = "initial-session-id" + initial_tags = ["initial_value1", "initial_value2"] + + callback = LlamaIndexCallbackHandler( + trace_name=initial_name, + user_id=initial_user_id, + session_id=initial_session_id, + tags=initial_tags, + ) + + index = get_index(callback) + index.as_query_engine().query( + "What did the speaker achieve in the past twelve months?" + ) + + callback.flush() + trace_data = get_api().trace.get(callback.trace.id) + + assert trace_data.name == initial_name + assert trace_data.user_id == initial_user_id + assert trace_data.session_id == initial_session_id + assert trace_data.tags == initial_tags + + # Update trace metadata on existing handler + updated_name = "updated-name" + updated_user_id = "updated-user-id" + updated_session_id = "updated-session-id" + updated_tags = ["updated_value1", "updated_value2"] + + callback.set_trace_metadata(
maybe call it `callback.trace()`?
langfuse-python
github_2023
python
412
langfuse
maxdeichmann
@@ -92,13 +106,49 @@ def __init__( self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list) self._llama_index_trace_name: Optional[str] = None self._token_counter = TokenCounter(tokenizer) + self.tags = tags # For stream-chat, the last LLM end_event arrives after the trace has ended # Keep track of these orphans to upsert them with the correct trace_id after the trace has ended self._orphaned_LLM_generations: Dict[ str, Tuple[StatefulGenerationClient, StatefulTraceClient] ] = {} + def set_trace_metadata(
Please ensure that the context is cleared after llamaindex invocation so that no succeeding llamaindex usage gets the same contexts.
langfuse-python
github_2023
python
412
langfuse
maxdeichmann
@@ -182,16 +263,33 @@ def _create_observations_from_trace_map( ) def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]:
To reiterate on our dicussion earlier. We decided to: - do not create another span for roots - add the same llamaindex spans / generations for root as for non root cases - in case that trace was provide, do not override. I think this is implmented correctly.
langfuse-python
github_2023
python
401
langfuse
maxdeichmann
@@ -257,8 +276,59 @@ def _handle_LLM_events( }, ) + # Register orphaned LLM event (only start event, no end event) to be later upserted with the correct trace_id + if len(events) == 1: + self._orphaned_LLM_generations[event_id] = (generation, self.trace) + return generation + def _handle_orphaned_LLM_end_event( + self, + end_event: CallbackEvent, + generation: StatefulGenerationClient, + trace: StatefulTraceClient, + ) -> None: + input = output = usage = model = None + + if end_event.payload:
pls. refactor
langfuse-python
github_2023
python
400
langfuse
maxdeichmann
@@ -187,17 +189,24 @@ def _get_langfuse_data_from_kwargs( if user_id is not None and not isinstance(user_id, str): raise TypeError("user_id must be a string") + tags = kwargs.get("tags", None) + if tags is not None and ( + not isinstance(tags, list) or not all(isinstance(tag, str) for tag in tags)
I think we have to use `List` here. See import on top.
langfuse-python
github_2023
python
388
langfuse
maxdeichmann
@@ -29,19 +29,9 @@ SystemMessage, ) except ImportError: - logging.getLogger("langfuse").warning( - "Could not import langchain. Some functionality may be missing." + raise ModuleNotFoundError( + "Please install langchain to use the Langfuse langchain integration: 'pip install langchain'" ) - LLMResult = Any - AIMessage = Any - BaseMessage = Any - ChatMessage = Any - HumanMessage = Any - SystemMessage = Any - ChatGeneration = Any - Document = Any - AgentAction = Any - AgentFinish = Any
Thanks a lot!
langfuse-python
github_2023
python
384
langfuse
maxdeichmann
@@ -0,0 +1,366 @@ +from collections import defaultdict +from typing import Any, Dict, List, Optional, Union, Tuple, Callable +from uuid import uuid4 +import logging + +from langfuse.client import ( + StatefulSpanClient, + StatefulTraceClient, + StatefulGenerationClient, +) +from langfuse.decorators.error_logging import ( + auto_decorate_methods_with, + catch_and_log_errors, +) +from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler +from langfuse.callback.utils import CallbackEvent + +try: + from llama_index.core.callbacks.base_handler import ( + BaseCallbackHandler as LLamaIndexBaseCallbackHandler, + ) + from llama_index.core.callbacks.schema import ( + CBEventType, + BASE_TRACE_EVENT, + EventPayload, + ) + from llama_index.core.utilities.token_counting import TokenCounter +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + + +@auto_decorate_methods_with(catch_and_log_errors) +class LLamaIndexCallbackHandler( + LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler +): + log = logging.getLogger("langfuse") + + def __init__( + self, + *, + public_key: Optional[str] = None, + secret_key: Optional[str] = None, + host: Optional[str] = None, + debug: bool = False, + stateful_client: Optional[ + Union[StatefulTraceClient, StatefulSpanClient] + ] = None, + session_id: Optional[str] = None, + user_id: Optional[str] = None, + trace_name: Optional[str] = None, + release: Optional[str] = None, + version: Optional[str] = None, + threads: Optional[int] = None, + flush_at: Optional[int] = None, + flush_interval: Optional[int] = None, + max_retries: Optional[int] = None, + timeout: Optional[int] = None, + event_starts_to_ignore: Optional[List[CBEventType]] = None, + event_ends_to_ignore: Optional[List[CBEventType]] = None, + tokenizer: Optional[Callable[[str], list]] = None, + ) -> None: + LLamaIndexBaseCallbackHandler.__init__( + self, + event_starts_to_ignore=event_starts_to_ignore or [], + event_ends_to_ignore=event_ends_to_ignore or [], + ) + LangfuseBaseCallbackHandler.__init__( + self, + public_key=public_key, + secret_key=secret_key, + host=host, + debug=debug, + stateful_client=stateful_client, + session_id=session_id, + user_id=user_id, + trace_name=trace_name, + release=release, + version=version, + threads=threads, + flush_at=flush_at, + flush_interval=flush_interval, + max_retries=max_retries, + timeout=timeout, + sdk_integration="llama-index", + ) + + self.root = stateful_client + self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list) + self._cur_trace_id: Optional[str] = None + self._token_counter = TokenCounter(tokenizer) + + def start_trace(self, trace_id: Optional[str] = None) -> None: + """Run when an overall trace is launched.""" + self._cur_trace_id = trace_id + + def end_trace( + self, + trace_id: Optional[str] = None, + trace_map: Optional[Dict[str, List[str]]] = None, + ) -> None: + """Run when an overall trace is exited.""" + if not trace_map: + self.log.debug("No events in trace map to create the observation tree.") + return + + self._create_observations_from_trace_map( + event_id=BASE_TRACE_EVENT, trace_map=trace_map + ) + self.flush() + + def on_event_start( + self, + event_type: CBEventType, + payload: Optional[Dict[str, Any]] = None, + event_id: str = "", + parent_id: str = "", + **kwargs: Any, + ) -> str: + """Run when an event starts and return id of event.""" + start_event = CallbackEvent( + event_id=event_id, event_type=event_type, payload=payload + ) + self.event_map[event_id].append(start_event) + + return event_id + + def on_event_end( + self, + event_type: CBEventType, + payload: Optional[Dict[str, Any]] = None, + event_id: str = "", + **kwargs: Any, + ) -> None: + """Run when an event ends.""" + end_event = CallbackEvent( + event_id=event_id, event_type=event_type, payload=payload + ) + self.event_map[event_id].append(end_event) + + def _create_observations_from_trace_map( + self, + event_id: str, + trace_map: Dict[str, List[str]], + parent: Optional[ + Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient] + ] = None, + ) -> None: + """Recursively create langfuse observations based on the trace_map.""" + if event_id != BASE_TRACE_EVENT and not self.event_map.get(event_id): + return + + if event_id == BASE_TRACE_EVENT: + observation = self._get_root_observation() + else: + observation = self._create_observation( + event_id=event_id, parent=parent, trace_id=self.trace.id + ) + + for child_event_id in trace_map.get(event_id, []): + self._create_observations_from_trace_map( + event_id=child_event_id, parent=observation, trace_map=trace_map + ) + + def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]: + if self.root is not None: + return self.root # return user-provided root trace or span + + else: + self.trace = self.langfuse.trace( + id=str(uuid4()), + name=self.trace_name or f"LlamaIndex_{self._cur_trace_id}", + version=self.version, + session_id=self.session_id, + user_id=self.user_id, + ) + + return self.trace + + def _create_observation( + self, + event_id: str, + parent: Union[ + StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient + ], + trace_id: str, + ) -> Union[StatefulSpanClient, StatefulGenerationClient]: + event_type = self.event_map[event_id][0].event_type + + if event_type == CBEventType.LLM: + return self._handle_LLM_events(event_id, parent, trace_id) + elif event_type == CBEventType.EMBEDDING: + return self._handle_embedding_events(event_id, parent, trace_id) + else: + return self._handle_span_events(event_id, parent, trace_id) + + def _handle_LLM_events( + self, + event_id: str, + parent: Union[ + StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient + ], + trace_id: str, + ) -> StatefulGenerationClient: + start_event, end_event = self.event_map[event_id] + + if start_event.payload and EventPayload.SERIALIZED in start_event.payload: + serialized = start_event.payload.get(EventPayload.SERIALIZED, {}) + name = serialized.get("class_name", "LLM") + temperature = serialized.get("temperature", None) + max_tokens = serialized.get("max_tokens", None) + timeout = serialized.get("timeout", None) + + if end_event.payload: + if EventPayload.PROMPT in end_event.payload: + input = end_event.payload.get(EventPayload.PROMPT) + output = end_event.payload.get(EventPayload.COMPLETION) + + elif EventPayload.MESSAGES in end_event.payload: + input = end_event.payload.get(EventPayload.MESSAGES) + response = end_event.payload.get(EventPayload.RESPONSE, {}) + output = response.message + model = response.raw.get("model", None) + token_usage = dict(response.raw.get("usage", {})) + usage = None + if token_usage: + usage = { + "prompt_tokens": token_usage.get("prompt_tokens"), + "completion_tokens": token_usage.get("completion_tokens"), + "total_tokens": token_usage.get("total_tokens"),
Placeholder: our usage object
langfuse-python
github_2023
python
384
langfuse
maxdeichmann
@@ -0,0 +1,366 @@ +from collections import defaultdict +from typing import Any, Dict, List, Optional, Union, Tuple, Callable +from uuid import uuid4 +import logging + +from langfuse.client import ( + StatefulSpanClient, + StatefulTraceClient, + StatefulGenerationClient, +) +from langfuse.decorators.error_logging import ( + auto_decorate_methods_with, + catch_and_log_errors, +) +from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler +from langfuse.callback.utils import CallbackEvent + +try: + from llama_index.core.callbacks.base_handler import ( + BaseCallbackHandler as LLamaIndexBaseCallbackHandler, + ) + from llama_index.core.callbacks.schema import ( + CBEventType, + BASE_TRACE_EVENT, + EventPayload, + ) + from llama_index.core.utilities.token_counting import TokenCounter +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + + +@auto_decorate_methods_with(catch_and_log_errors) +class LLamaIndexCallbackHandler( + LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler +): + log = logging.getLogger("langfuse") + + def __init__( + self, + *, + public_key: Optional[str] = None, + secret_key: Optional[str] = None, + host: Optional[str] = None, + debug: bool = False, + stateful_client: Optional[ + Union[StatefulTraceClient, StatefulSpanClient] + ] = None, + session_id: Optional[str] = None, + user_id: Optional[str] = None, + trace_name: Optional[str] = None, + release: Optional[str] = None, + version: Optional[str] = None, + threads: Optional[int] = None, + flush_at: Optional[int] = None, + flush_interval: Optional[int] = None, + max_retries: Optional[int] = None, + timeout: Optional[int] = None, + event_starts_to_ignore: Optional[List[CBEventType]] = None, + event_ends_to_ignore: Optional[List[CBEventType]] = None, + tokenizer: Optional[Callable[[str], list]] = None, + ) -> None: + LLamaIndexBaseCallbackHandler.__init__( + self, + event_starts_to_ignore=event_starts_to_ignore or [], + event_ends_to_ignore=event_ends_to_ignore or [], + ) + LangfuseBaseCallbackHandler.__init__( + self, + public_key=public_key, + secret_key=secret_key, + host=host, + debug=debug, + stateful_client=stateful_client, + session_id=session_id, + user_id=user_id, + trace_name=trace_name, + release=release, + version=version, + threads=threads, + flush_at=flush_at, + flush_interval=flush_interval, + max_retries=max_retries, + timeout=timeout, + sdk_integration="llama-index", + ) + + self.root = stateful_client + self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list) + self._cur_trace_id: Optional[str] = None + self._token_counter = TokenCounter(tokenizer) + + def start_trace(self, trace_id: Optional[str] = None) -> None: + """Run when an overall trace is launched.""" + self._cur_trace_id = trace_id + + def end_trace( + self, + trace_id: Optional[str] = None, + trace_map: Optional[Dict[str, List[str]]] = None, + ) -> None: + """Run when an overall trace is exited.""" + if not trace_map: + self.log.debug("No events in trace map to create the observation tree.") + return + + self._create_observations_from_trace_map( + event_id=BASE_TRACE_EVENT, trace_map=trace_map + ) + self.flush() + + def on_event_start( + self, + event_type: CBEventType, + payload: Optional[Dict[str, Any]] = None, + event_id: str = "", + parent_id: str = "", + **kwargs: Any, + ) -> str: + """Run when an event starts and return id of event.""" + start_event = CallbackEvent( + event_id=event_id, event_type=event_type, payload=payload + ) + self.event_map[event_id].append(start_event) + + return event_id + + def on_event_end( + self, + event_type: CBEventType, + payload: Optional[Dict[str, Any]] = None, + event_id: str = "", + **kwargs: Any, + ) -> None: + """Run when an event ends.""" + end_event = CallbackEvent( + event_id=event_id, event_type=event_type, payload=payload + ) + self.event_map[event_id].append(end_event) + + def _create_observations_from_trace_map( + self, + event_id: str, + trace_map: Dict[str, List[str]], + parent: Optional[ + Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient] + ] = None, + ) -> None: + """Recursively create langfuse observations based on the trace_map.""" + if event_id != BASE_TRACE_EVENT and not self.event_map.get(event_id): + return + + if event_id == BASE_TRACE_EVENT: + observation = self._get_root_observation() + else: + observation = self._create_observation( + event_id=event_id, parent=parent, trace_id=self.trace.id + ) + + for child_event_id in trace_map.get(event_id, []): + self._create_observations_from_trace_map( + event_id=child_event_id, parent=observation, trace_map=trace_map + ) + + def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]: + if self.root is not None: + return self.root # return user-provided root trace or span + + else: + self.trace = self.langfuse.trace( + id=str(uuid4()), + name=self.trace_name or f"LlamaIndex_{self._cur_trace_id}", + version=self.version, + session_id=self.session_id, + user_id=self.user_id, + ) + + return self.trace + + def _create_observation( + self, + event_id: str, + parent: Union[ + StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient + ], + trace_id: str, + ) -> Union[StatefulSpanClient, StatefulGenerationClient]: + event_type = self.event_map[event_id][0].event_type + + if event_type == CBEventType.LLM: + return self._handle_LLM_events(event_id, parent, trace_id) + elif event_type == CBEventType.EMBEDDING: + return self._handle_embedding_events(event_id, parent, trace_id) + else: + return self._handle_span_events(event_id, parent, trace_id) + + def _handle_LLM_events( + self, + event_id: str, + parent: Union[ + StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient + ], + trace_id: str, + ) -> StatefulGenerationClient: + start_event, end_event = self.event_map[event_id] + + if start_event.payload and EventPayload.SERIALIZED in start_event.payload: + serialized = start_event.payload.get(EventPayload.SERIALIZED, {}) + name = serialized.get("class_name", "LLM") + temperature = serialized.get("temperature", None) + max_tokens = serialized.get("max_tokens", None) + timeout = serialized.get("timeout", None) + + if end_event.payload: + if EventPayload.PROMPT in end_event.payload: + input = end_event.payload.get(EventPayload.PROMPT) + output = end_event.payload.get(EventPayload.COMPLETION) + + elif EventPayload.MESSAGES in end_event.payload: + input = end_event.payload.get(EventPayload.MESSAGES) + response = end_event.payload.get(EventPayload.RESPONSE, {}) + output = response.message + model = response.raw.get("model", None) + token_usage = dict(response.raw.get("usage", {})) + usage = None + if token_usage: + usage = { + "prompt_tokens": token_usage.get("prompt_tokens"), + "completion_tokens": token_usage.get("completion_tokens"), + "total_tokens": token_usage.get("total_tokens"), + } + + generation = parent.generation(
We only start creating generations when this function is called?
langfuse-python
github_2023
python
384
langfuse
maxdeichmann
@@ -0,0 +1,366 @@ +from collections import defaultdict +from typing import Any, Dict, List, Optional, Union, Tuple, Callable +from uuid import uuid4 +import logging + +from langfuse.client import ( + StatefulSpanClient, + StatefulTraceClient, + StatefulGenerationClient, +) +from langfuse.decorators.error_logging import ( + auto_decorate_methods_with, + catch_and_log_errors, +) +from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler +from langfuse.callback.utils import CallbackEvent + +try: + from llama_index.core.callbacks.base_handler import ( + BaseCallbackHandler as LLamaIndexBaseCallbackHandler, + ) + from llama_index.core.callbacks.schema import ( + CBEventType, + BASE_TRACE_EVENT, + EventPayload, + ) + from llama_index.core.utilities.token_counting import TokenCounter +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + + +@auto_decorate_methods_with(catch_and_log_errors) +class LLamaIndexCallbackHandler( + LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler +): + log = logging.getLogger("langfuse") + + def __init__( + self, + *, + public_key: Optional[str] = None, + secret_key: Optional[str] = None, + host: Optional[str] = None, + debug: bool = False, + stateful_client: Optional[ + Union[StatefulTraceClient, StatefulSpanClient] + ] = None, + session_id: Optional[str] = None, + user_id: Optional[str] = None, + trace_name: Optional[str] = None, + release: Optional[str] = None, + version: Optional[str] = None, + threads: Optional[int] = None, + flush_at: Optional[int] = None, + flush_interval: Optional[int] = None, + max_retries: Optional[int] = None, + timeout: Optional[int] = None, + event_starts_to_ignore: Optional[List[CBEventType]] = None, + event_ends_to_ignore: Optional[List[CBEventType]] = None, + tokenizer: Optional[Callable[[str], list]] = None, + ) -> None: + LLamaIndexBaseCallbackHandler.__init__( + self, + event_starts_to_ignore=event_starts_to_ignore or [], + event_ends_to_ignore=event_ends_to_ignore or [], + ) + LangfuseBaseCallbackHandler.__init__( + self, + public_key=public_key, + secret_key=secret_key, + host=host, + debug=debug, + stateful_client=stateful_client, + session_id=session_id, + user_id=user_id, + trace_name=trace_name, + release=release, + version=version, + threads=threads, + flush_at=flush_at, + flush_interval=flush_interval, + max_retries=max_retries, + timeout=timeout, + sdk_integration="llama-index", + ) + + self.root = stateful_client + self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list) + self._cur_trace_id: Optional[str] = None + self._token_counter = TokenCounter(tokenizer)
Is this something our users need to provide?
langfuse-python
github_2023
others
384
langfuse
maxdeichmann
@@ -7,14 +7,15 @@ license = "MIT" readme = "README.md" [tool.poetry.dependencies] -python = ">=3.8.1,<4.0" +python = ">=3.8.1,<3.12"
:D
langfuse-python
github_2023
python
384
langfuse
maxdeichmann
@@ -0,0 +1,43 @@ +import functools +import logging + +logger = logging.getLogger("langfuse") + + +def catch_and_log_errors(func): + """Catch all exceptions and log them. Do NOT re-raise the exception.""" + + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except Exception as e: + logger.error(f"An error occurred in {func.__name__}: {e}", exc_info=True) + + return wrapper + + +def auto_decorate_methods_with(decorator): + """ + Class decorator to automatically apply a given decorator to all + methods of a class. + """ + + def class_decorator(cls):
add condition that init is excluded from this.
langfuse-python
github_2023
python
384
langfuse
maxdeichmann
@@ -0,0 +1,366 @@ +from collections import defaultdict +from typing import Any, Dict, List, Optional, Union, Tuple, Callable +from uuid import uuid4 +import logging + +from langfuse.client import ( + StatefulSpanClient, + StatefulTraceClient, + StatefulGenerationClient, +) +from langfuse.decorators.error_logging import ( + auto_decorate_methods_with, + catch_and_log_errors, +) +from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler +from langfuse.callback.utils import CallbackEvent + +try: + from llama_index.core.callbacks.base_handler import ( + BaseCallbackHandler as LLamaIndexBaseCallbackHandler, + ) + from llama_index.core.callbacks.schema import ( + CBEventType, + BASE_TRACE_EVENT, + EventPayload, + ) + from llama_index.core.utilities.token_counting import TokenCounter +except ImportError: + raise ModuleNotFoundError( + "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'" + ) + + +@auto_decorate_methods_with(catch_and_log_errors) +class LLamaIndexCallbackHandler( + LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler +): + log = logging.getLogger("langfuse") + + def __init__( + self, + *, + public_key: Optional[str] = None, + secret_key: Optional[str] = None, + host: Optional[str] = None, + debug: bool = False, + stateful_client: Optional[ + Union[StatefulTraceClient, StatefulSpanClient] + ] = None, + session_id: Optional[str] = None, + user_id: Optional[str] = None, + trace_name: Optional[str] = None, + release: Optional[str] = None, + version: Optional[str] = None, + threads: Optional[int] = None, + flush_at: Optional[int] = None, + flush_interval: Optional[int] = None, + max_retries: Optional[int] = None, + timeout: Optional[int] = None, + event_starts_to_ignore: Optional[List[CBEventType]] = None, + event_ends_to_ignore: Optional[List[CBEventType]] = None, + tokenizer: Optional[Callable[[str], list]] = None, + ) -> None: + LLamaIndexBaseCallbackHandler.__init__( + self, + event_starts_to_ignore=event_starts_to_ignore or [], + event_ends_to_ignore=event_ends_to_ignore or [], + ) + LangfuseBaseCallbackHandler.__init__( + self, + public_key=public_key, + secret_key=secret_key, + host=host, + debug=debug, + stateful_client=stateful_client, + session_id=session_id, + user_id=user_id, + trace_name=trace_name, + release=release, + version=version, + threads=threads, + flush_at=flush_at, + flush_interval=flush_interval, + max_retries=max_retries, + timeout=timeout, + sdk_integration="llama-index", + ) + + self.root = stateful_client + self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list) + self._cur_trace_id: Optional[str] = None + self._token_counter = TokenCounter(tokenizer) + + def start_trace(self, trace_id: Optional[str] = None) -> None: + """Run when an overall trace is launched.""" + self._cur_trace_id = trace_id + + def end_trace( + self, + trace_id: Optional[str] = None, + trace_map: Optional[Dict[str, List[str]]] = None, + ) -> None: + """Run when an overall trace is exited.""" + if not trace_map: + self.log.debug("No events in trace map to create the observation tree.") + return + + self._create_observations_from_trace_map( + event_id=BASE_TRACE_EVENT, trace_map=trace_map + ) + self.flush() + + def on_event_start( + self, + event_type: CBEventType, + payload: Optional[Dict[str, Any]] = None, + event_id: str = "", + parent_id: str = "", + **kwargs: Any, + ) -> str: + """Run when an event starts and return id of event.""" + start_event = CallbackEvent( + event_id=event_id, event_type=event_type, payload=payload + ) + self.event_map[event_id].append(start_event) + + return event_id + + def on_event_end( + self, + event_type: CBEventType, + payload: Optional[Dict[str, Any]] = None, + event_id: str = "", + **kwargs: Any, + ) -> None: + """Run when an event ends.""" + end_event = CallbackEvent( + event_id=event_id, event_type=event_type, payload=payload + ) + self.event_map[event_id].append(end_event) + + def _create_observations_from_trace_map( + self, + event_id: str, + trace_map: Dict[str, List[str]], + parent: Optional[ + Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient] + ] = None, + ) -> None: + """Recursively create langfuse observations based on the trace_map.""" + if event_id != BASE_TRACE_EVENT and not self.event_map.get(event_id): + return + + if event_id == BASE_TRACE_EVENT: + observation = self._get_root_observation() + else: + observation = self._create_observation( + event_id=event_id, parent=parent, trace_id=self.trace.id + ) + + for child_event_id in trace_map.get(event_id, []): + self._create_observations_from_trace_map( + event_id=child_event_id, parent=observation, trace_map=trace_map + ) + + def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]: + if self.root is not None: + return self.root # return user-provided root trace or span + + else: + self.trace = self.langfuse.trace( + id=str(uuid4()), + name=self.trace_name or f"LlamaIndex_{self._cur_trace_id}", + version=self.version, + session_id=self.session_id, + user_id=self.user_id, + ) + + return self.trace + + def _create_observation( + self, + event_id: str, + parent: Union[ + StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient + ], + trace_id: str, + ) -> Union[StatefulSpanClient, StatefulGenerationClient]: + event_type = self.event_map[event_id][0].event_type + + if event_type == CBEventType.LLM: + return self._handle_LLM_events(event_id, parent, trace_id) + elif event_type == CBEventType.EMBEDDING: + return self._handle_embedding_events(event_id, parent, trace_id) + else: + return self._handle_span_events(event_id, parent, trace_id) + + def _handle_LLM_events( + self, + event_id: str, + parent: Union[ + StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient + ], + trace_id: str, + ) -> StatefulGenerationClient: + start_event, end_event = self.event_map[event_id] + + if start_event.payload and EventPayload.SERIALIZED in start_event.payload: + serialized = start_event.payload.get(EventPayload.SERIALIZED, {}) + name = serialized.get("class_name", "LLM") + temperature = serialized.get("temperature", None) + max_tokens = serialized.get("max_tokens", None) + timeout = serialized.get("timeout", None) + + if end_event.payload: + if EventPayload.PROMPT in end_event.payload: + input = end_event.payload.get(EventPayload.PROMPT) + output = end_event.payload.get(EventPayload.COMPLETION) + + elif EventPayload.MESSAGES in end_event.payload: + input = end_event.payload.get(EventPayload.MESSAGES) + response = end_event.payload.get(EventPayload.RESPONSE, {}) + output = response.message + model = response.raw.get("model", None) + token_usage = dict(response.raw.get("usage", {})) + usage = None + if token_usage: + usage = { + "prompt_tokens": token_usage.get("prompt_tokens"), + "completion_tokens": token_usage.get("completion_tokens"), + "total_tokens": token_usage.get("total_tokens"), + } + + generation = parent.generation( + id=event_id, + trace_id=trace_id, + version=self.version, + name=name, + start_time=start_event.time, + end_time=end_event.time, + usage=usage or None, + model=model, + input=input,
chat format