Skip to content

Conversation

@vprashrex
Copy link
Collaborator

@vprashrex vprashrex commented Jan 21, 2026

  • Added try-catch blocks to prevent Langfuse failures from blocking main flow
  • Ensure tracer is always initialized (disabled if no credentials)
  • Added graceful degradation for all tracer methods
  • Created comprehensive test suite covering all failure scenarios
  • Tests verify OpenAI responses work regardless of Langfuse state

Fixes issue where Langfuse connection failures could block API responses.

Summary

Target issue is #510
Explain the motivation for making this change. What existing problem does the pull request solve?

Summary by CodeRabbit

  • Bug Fixes
    • Observability/tracing is now defensive: initialization/runtime failures are caught, tracing becomes a safe no-op when unavailable, errors no longer affect core flows, session/context resumption is preserved, and richer metadata is recorded on success.
  • Tests
    • Added comprehensive unit and integration tests covering init, failure modes, no-op semantics, error handling, full tracing lifecycle, end-to-end response processing, and a fixture to bypass global DB seeding during these tests.

✏️ Tip: You can customize this high-level summary in your review settings.

- Added try-catch blocks to prevent Langfuse failures from blocking main flow
- Ensure tracer is always initialized (disabled if no credentials)
- Added graceful degradation for all tracer methods
- Created comprehensive test suite covering all failure scenarios
- Tests verify OpenAI responses work regardless of Langfuse state

Fixes issue where Langfuse connection failures could block API responses.
@coderabbitai
Copy link

coderabbitai bot commented Jan 21, 2026

📝 Walkthrough

Walkthrough

Adds defensive failure handling to LangfuseTracer: introduces a _failed flag and a _langfuse_call wrapper; Langfuse init and all tracer operations now short‑circuit on failure. Also adds a session-scoped test conftest and an extensive unit test suite for tracer behaviors and integrations.

Changes

Cohort / File(s) Summary
Core Langfuse Tracer Logic
backend/app/core/langfuse/langfuse.py
Introduced private _failed attribute and _langfuse_call helper. Wrapped initialization, fetch_traces, and all tracer methods (start_trace, start_generation, end_generation, update_trace, log_error, flush, and observe_llm_execution internals) in safe try/except paths so operations become no-ops after failure and propagate soft-failure state. Signatures adjusted to return None where applicable.
Test Configuration
backend/app/tests/core/test_langfuse/conftest.py
Added session-scoped, autouse seed_baseline fixture that yields immediately to bypass global DB seeding during Langfuse tracer tests.
Comprehensive Test Suite
backend/app/tests/core/test_langfuse/test_langfuse_tracer.py
New extensive tests covering init scenarios (missing/invalid creds, init exceptions, fetch_traces), resumed sessions, no-op semantics when disabled, exception resilience for each tracer method, generate_response/process_response integration paths, and full successful tracer lifecycle flows. Multiple test classes and fixtures added.

Sequence Diagram(s)

(omitted — changes are defensive wrappers and tests; no new multi-component control flow requiring visualization)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I’m a rabbit on a tracing quest,
I hop through code to do my best,
If Langfuse stumbles, I stand guard,
I catch the faults and keep them barred,
Then flush the hops when skies are clear. 🐇✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'Langfuse: Add comprehensive error handling and tests' directly and accurately summarizes the main changes: adding error handling to the Langfuse tracer and introducing a comprehensive test suite to verify the changes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Jan 21, 2026

Codecov Report

❌ Patch coverage is 98.07692% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
backend/app/core/langfuse/langfuse.py 89.04% 8 Missing ⚠️

📢 Thoughts on this report? Let us know!

"[LangfuseTracer] Langfuse tracing disabled due to missing credentials"
)
logger.info(
f"[LangfuseTracer] Langfuse tracing enabled | session_id={self.session_id}"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is somehow still populating in the logs even though the credentials are revoked

Comment on lines 29 to 31
# =============================================================================
# Fixtures
# =============================================================================
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lots of unnecessary formatting

Copy link
Collaborator

@Prajna1999 Prajna1999 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overall sudo_code is
if langfuse_fail: continue
I think there are far simpler ways to implement this logic instead of having individual try_catch blocks for oneliner method invocations.

- No credentials (None)
- Incomplete credentials (missing keys)
- Langfuse initialization exception
- fetch_traces failure (non-critical)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: isn't fetch_traces failure is critical? Like am I missing some context here

if not self.langfuse.enabled:
return
try:
self.langfuse.flush()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is try_catch really needed for one line method invocation? May be keep the one liner langfuse.flush() wherever it needs to be invoked without this extra abstraction.


def safe_langfuse_op(op: Callable, *args, **kwargs):
try:
return op(*args, **kwargs)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto as above. Does really a oneliner require its own try_catch

if self.trace:
self.trace.update(tags=tags, output=output)
if not self.langfuse.enabled or not self.trace:
return
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto as above

Address PR review feedback - replace multiple try/catch blocks with
single _langfuse_call wrapper that auto-disables on first failure.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
backend/app/core/langfuse/langfuse.py (3)

1-5: CI formatting failure — run Black on this file.

Black reformatting failed in CI for this file; please re-run Black to match the configured style.


141-168: Add type hints to decorator, wrapper, and langfuse_call functions.

The observe_llm_execution decorator is missing critical type annotations: the function lacks a return type, the decorator parameter type for func is too generic, the wrapper function has no return type and **kwargs lacks type annotation, and the nested langfuse_call function has no parameter or return type hints.

♻️ Proposed fix
-def observe_llm_execution(
-    session_id: str | None = None,
-    credentials: dict | None = None,
-):
+def observe_llm_execution(
+    session_id: str | None = None,
+    credentials: dict | None = None,
+) -> Callable[
+    [Callable[..., tuple[LLMCallResponse | None, str | None]]],
+    Callable[..., tuple[LLMCallResponse | None, str | None]],
+]:
@@
-    def decorator(func: Callable) -> Callable:
+    def decorator(
+        func: Callable[..., tuple[LLMCallResponse | None, str | None]]
+    ) -> Callable[..., tuple[LLMCallResponse | None, str | None]]:
@@
-        def wrapper(
-            completion_config: NativeCompletionConfig, query: QueryParams, **kwargs
-        ):
+        def wrapper(
+            completion_config: NativeCompletionConfig,
+            query: QueryParams,
+            **kwargs: Any,
+        ) -> tuple[LLMCallResponse | None, str | None]:
@@
-            def langfuse_call(fn, *args, **kwargs):
+            def langfuse_call(
+                fn: Callable[..., Any], *args: Any, **kwargs: Any
+            ) -> Any | None:

Also applies to: 183-189


72-138: Add explicit -> None return types to all tracer methods.

These methods lack return type annotations required by coding guidelines. All parameter types are present; only return types are missing.

♻️ Proposed fix
-    def start_trace(
+    def start_trace(
         self,
         name: str,
         input: Dict[str, Any],
         metadata: Optional[Dict[str, Any]] = None,
         tags: list[str] | None = None,
-    ):
+    ) -> None:
@@
-    def start_generation(
+    def start_generation(
         self,
         name: str,
         input: Dict[str, Any],
         metadata: Optional[Dict[str, Any]] = None,
-    ):
+    ) -> None:
@@
-    def end_generation(
+    def end_generation(
         self,
         output: Dict[str, Any],
         usage: Optional[Dict[str, Any]] = None,
         model: Optional[str] = None,
-    ):
+    ) -> None:
@@
-    def update_trace(self, tags: list[str], output: Dict[str, Any]):
+    def update_trace(self, tags: list[str], output: Dict[str, Any]) -> None:
@@
-    def log_error(self, error_message: str, response_id: Optional[str] = None):
+    def log_error(self, error_message: str, response_id: Optional[str] = None) -> None:
@@
-    def flush(self):
+    def flush(self) -> None:
🤖 Fix all issues with AI agents
In `@backend/app/core/langfuse/langfuse.py`:
- Around line 174-176: Update the logger.info calls that print Langfuse tracing
state to include the current function name as a prefix (e.g. "[<function_name>]
Tracing enabled ..."); specifically modify the logger.info line that logs
session_id and the subsequent logger calls around lines 191-192 to start with
that prefix. Locate the logger.info calls (the ones referencing session_id and
the later Langfuse logs) inside the function that contains them (the function
where these logger calls live—e.g., the enable_langfuse-related function) and
prepend the function name (either hard-coded with the function identifier or
generated via the function's __name__) to the log message; also update the
earlier similar log (around the earlier logger call near line 165) for
consistency. Ensure formatting remains f-string-compatible (e.g.
f"[{function_name}] Tracing enabled | session_id={session_id or 'auto'}").
- Around line 62-70: Add type hints and include the function-name prefix in the
log: annotate _langfuse_call with proper typing (e.g., add "from typing import
Callable, TypeVar, Optional, Any", define T = TypeVar('T'), and change the
signature to def _langfuse_call(self, fn: Callable[..., T], *args: Any,
**kwargs: Any) -> Optional[T]:), keep the existing self._failed handling and
return None where appropriate, and update the logger.warning message to include
the method name prefix (for example include
"LangfuseTracer._langfuse_call:{getattr(fn, '__name__', 'operation')}" at the
start of the log message) so logs follow the coding guideline.

In `@backend/app/tests/core/test_langfuse/test_langfuse_tracer.py`:
- Around line 1-5: This file fails CI formatting; run Black to reformat
backend/app/tests/core/test_langfuse/test_langfuse_tracer.py (or run black .)
and commit the updated file so imports, docstring, and overall formatting match
the project's Black configuration; no code changes required—just apply Black
formatting.
- Around line 14-36: The fixtures valid_credentials and assistant_mock currently
return concrete objects; change them to factory-style fixtures that return
callables which produce the data when invoked (i.e., valid_credentials -> a
function that returns a dict and assistant_mock -> a function that returns an
Assistant instance), update tests to call the factories by invoking
valid_credentials()() and assistant_mock()() (or simply calling the returned
callable) wherever they currently use the fixture values; ensure the fixture
names remain the same and reference the Assistant constructor signature used in
the snippet (Assistant with id, assistant_id, name, model, temperature,
instructions, vector_store_ids, max_num_results, project_id, organization_id).

Comment on lines 62 to 70
def _langfuse_call(self, fn, *args, **kwargs):
if self._failed:
return None
try:
return fn(*args, **kwargs)
except Exception as e:
logger.warning(f"[LangfuseTracer] {getattr(fn, '__name__', 'operation')} failed: {e}")
self._failed = True
return None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n backend/app/core/langfuse/langfuse.py | head -100

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 3988


Add type hints and function-name log prefix in _langfuse_call.

Missing parameter and return type annotations, and the log message prefix must include the method name per coding guidelines.

♻️ Proposed fix
-    def _langfuse_call(self, fn, *args, **kwargs):
+    def _langfuse_call(
+        self,
+        fn: Callable[..., Any],
+        *args: Any,
+        **kwargs: Any,
+    ) -> Any | None:
         if self._failed:
             return None
         try:
             return fn(*args, **kwargs)
         except Exception as e:
-            logger.warning(f"[LangfuseTracer] {getattr(fn, '__name__', 'operation')} failed: {e}")
+            logger.warning(
+                f"[LangfuseTracer._langfuse_call] {getattr(fn, '__name__', 'operation')} failed: {e}"
+            )
             self._failed = True
             return None
🤖 Prompt for AI Agents
In `@backend/app/core/langfuse/langfuse.py` around lines 62 - 70, Add type hints
and include the function-name prefix in the log: annotate _langfuse_call with
proper typing (e.g., add "from typing import Callable, TypeVar, Optional, Any",
define T = TypeVar('T'), and change the signature to def _langfuse_call(self,
fn: Callable[..., T], *args: Any, **kwargs: Any) -> Optional[T]:), keep the
existing self._failed handling and return None where appropriate, and update the
logger.warning message to include the method name prefix (for example include
"LangfuseTracer._langfuse_call:{getattr(fn, '__name__', 'operation')}" at the
start of the log message) so logs follow the coding guideline.

Comment on lines 14 to 36
@pytest.fixture
def valid_credentials() -> dict:
return {
"public_key": "pk-test-123",
"secret_key": "sk-test-456",
"host": "https://langfuse.example.com",
}


@pytest.fixture
def assistant_mock() -> Assistant:
return Assistant(
id=123,
assistant_id="asst_test123",
name="Test Assistant",
model="gpt-4",
temperature=0.7,
instructions="You are a helpful assistant.",
vector_store_ids=["vs1"],
max_num_results=5,
project_id=1,
organization_id=1,
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's check if the file exists and examine its current content
cd backend/app/tests/core/test_langfuse || find . -name "test_langfuse_tracer.py" -type f

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 57


🏁 Script executed:

# Search for the test file in the repository
find . -name "test_langfuse_tracer.py" -type f 2>/dev/null

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 137


🏁 Script executed:

# Let's explore the directory structure to find test files
find . -path "*/backend/app/tests/*" -name "*.py" -type f | head -20

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 1245


🏁 Script executed:

# Look for patterns of factory fixtures in existing test files
rg "def.*_factory\(\)" --type py -A 3 | head -50

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 57


🏁 Script executed:

# Check how the current fixtures are being used
rg "valid_credentials|assistant_mock" --type py | head -30

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 3589


🏁 Script executed:

# Let's read the actual test file content
cat -n ./backend/app/tests/core/test_langfuse/test_langfuse_tracer.py

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 26201


🏁 Script executed:

# Check for existing factory pattern examples in other test files
rg "@pytest.fixture" -A 8 backend/app/tests/ --type py | grep -A 8 "_factory" | head -50

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 57


🏁 Script executed:

# Look at conftest.py files to see how fixtures are structured
find ./backend/app/tests -name "conftest.py" -exec cat -n {} + | head -100

Repository: ProjectTech4DevAI/kaapi-backend

Length of output: 3829


Convert fixtures to factory pattern as required by coding guidelines.

Test fixtures in backend/app/tests/ must follow the factory pattern. Currently, valid_credentials() and assistant_mock() return concrete objects directly. They should return callables that can generate test data, allowing flexibility for test variations.

♻️ Update fixtures to factory pattern
+from typing import Callable
+
 `@pytest.fixture`
-def valid_credentials() -> dict:
-    return {
-        "public_key": "pk-test-123",
-        "secret_key": "sk-test-456",
-        "host": "https://langfuse.example.com",
-    }
+def valid_credentials() -> Callable[..., dict]:
+    def _factory(
+        public_key: str = "pk-test-123",
+        secret_key: str = "sk-test-456",
+        host: str = "https://langfuse.example.com",
+    ) -> dict:
+        return {
+            "public_key": public_key,
+            "secret_key": secret_key,
+            "host": host,
+        }
+
+    return _factory


 `@pytest.fixture`
-def assistant_mock() -> Assistant:
-    return Assistant(
+def assistant_mock() -> Callable[..., Assistant]:
+    def _factory() -> Assistant:
+        return Assistant(
             id=123,
             assistant_id="asst_test123",
             name="Test Assistant",
             model="gpt-4",
             temperature=0.7,
             instructions="You are a helpful assistant.",
             vector_store_ids=["vs1"],
             max_num_results=5,
             project_id=1,
             organization_id=1,
-    )
+        )
+
+    return _factory

Update all test methods to call these fixtures: valid_credentials()valid_credentials()()

🤖 Prompt for AI Agents
In `@backend/app/tests/core/test_langfuse/test_langfuse_tracer.py` around lines 14
- 36, The fixtures valid_credentials and assistant_mock currently return
concrete objects; change them to factory-style fixtures that return callables
which produce the data when invoked (i.e., valid_credentials -> a function that
returns a dict and assistant_mock -> a function that returns an Assistant
instance), update tests to call the factories by invoking valid_credentials()()
and assistant_mock()() (or simply calling the returned callable) wherever they
currently use the fixture values; ensure the fixture names remain the same and
reference the Assistant constructor signature used in the snippet (Assistant
with id, assistant_id, name, model, temperature, instructions, vector_store_ids,
max_num_results, project_id, organization_id).

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/app/core/langfuse/langfuse.py (1)

162-166: Add type hints for wrapper and local langfuse_call.

Both functions lack required type annotations per coding guidelines. The wrapper function's **kwargs parameter and return type are untyped; it returns a tuple of (LLMCallResponse | None, str | None). The langfuse_call function's fn, *args, and **kwargs parameters lack type annotations, and its return type Any | None is unspecified.

♻️ Proposed fix
-        def wrapper(
-            completion_config: NativeCompletionConfig, query: QueryParams, **kwargs
-        ):
+        def wrapper(
+            completion_config: NativeCompletionConfig,
+            query: QueryParams,
+            **kwargs: Any,
+        ) -> tuple[LLMCallResponse | None, str | None]:
@@
-            def langfuse_call(fn, *args, **kwargs):
+            def langfuse_call(
+                fn: Callable[..., Any],
+                *args: Any,
+                **kwargs: Any,
+            ) -> Any | None:
♻️ Duplicate comments (2)
backend/app/core/langfuse/langfuse.py (2)

62-72: Add typing + function-name log prefix in _langfuse_call.
This repeats an earlier note: _langfuse_call still lacks type annotations and the log prefix should include the method name. As per coding guidelines, ...

♻️ Proposed fix
-    def _langfuse_call(self, fn, *args, **kwargs):
+    def _langfuse_call(
+        self,
+        fn: Callable[..., Any],
+        *args: Any,
+        **kwargs: Any,
+    ) -> Any | None:
         if self._failed:
             return None
         try:
             return fn(*args, **kwargs)
         except Exception as e:
             logger.warning(
-                f"[LangfuseTracer] {getattr(fn, '__name__', 'operation')} failed: {e}"
+                f"[LangfuseTracer._langfuse_call] {getattr(fn, '__name__', 'operation')} failed: {e}"
             )
             self._failed = True
             return None
#!/bin/bash
# Verify current signature/log prefix for _langfuse_call
rg -n "def _langfuse_call" backend/app/core/langfuse/langfuse.py
rg -n "LangfuseTracer\._langfuse_call" backend/app/core/langfuse/langfuse.py

168-183: Prefix wrapper logs with the function name.
These log lines should use a function-name prefix (e.g., [observe_llm_execution.wrapper] / [observe_llm_execution.langfuse_call]) rather than [Langfuse]. As per coding guidelines, ...

♻️ Proposed fix
-                logger.info("[Langfuse] No credentials - skipping observability")
+                logger.info(
+                    "[observe_llm_execution.wrapper] No credentials - skipping observability"
+                )
@@
-                logger.info(
-                    f"[Langfuse] Tracing enabled | session_id={session_id or 'auto'}"
-                )
+                logger.info(
+                    f"[observe_llm_execution.wrapper] Tracing enabled | session_id={session_id or 'auto'}"
+                )
@@
-                logger.warning(f"[Langfuse] Failed to initialize client: {e}")
+                logger.warning(
+                    f"[observe_llm_execution.wrapper] Failed to initialize client: {e}"
+                )
@@
-                    logger.warning(
-                        f"[Langfuse] {getattr(fn, '__name__', 'operation')} failed: {e}"
-                    )
+                    logger.warning(
+                        f"[observe_llm_execution.langfuse_call] {getattr(fn, '__name__', 'operation')} failed: {e}"
+                    )

Also applies to: 195-197

🧹 Nitpick comments (1)
backend/app/core/langfuse/langfuse.py (1)

35-44: Log Langfuse init failures for diagnosability.
Silently returning on init failure makes troubleshooting hard; consider logging the exception with the function-name prefix. As per coding guidelines, ...

♻️ Proposed tweak
-            except Exception:
+            except Exception as e:
+                logger.warning(
+                    f"[LangfuseTracer.__init__] Failed to initialize Langfuse: {e}"
+                )
                 self._failed = True
                 return

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/app/core/langfuse/langfuse.py (1)

161-197: Add missing type hints for wrapper and langfuse_call.

The wrapper function lacks **kwargs: Any and return type tuple[LLMCallResponse | None, str | None]. The inner langfuse_call function lacks annotations for fn, *args, **kwargs, and its return type Any | None. Per coding guidelines, all function parameters and return values must have type hints.

♻️ Proposed fix
-        def wrapper(
-            completion_config: NativeCompletionConfig, query: QueryParams, **kwargs
-        ):
+        def wrapper(
+            completion_config: NativeCompletionConfig,
+            query: QueryParams,
+            **kwargs: Any,
+        ) -> tuple[LLMCallResponse | None, str | None]:
@@
-            def langfuse_call(fn, *args, **kwargs):
+            def langfuse_call(
+                fn: Callable[..., Any],
+                *args: Any,
+                **kwargs: Any,
+            ) -> Any | None:
🤖 Fix all issues with AI agents
In `@backend/app/core/langfuse/langfuse.py`:
- Around line 35-60: Update the log messages in LangfuseTracer.__init__ to
follow the logging convention by prefixing them with
"[LangfuseTracer.__init__]": change the logger.warning that logs initialization
failure (inside the except for Langfuse(...)), the logger.debug in the except
when fetch_traces/session resume fails, the logger.info that announces tracing
enabled with session_id, and the logger.warning that reports tracing disabled
due to missing credentials; keep the same messages and exception interpolation
but prepend the required function-name tag so all logs from the constructor use
"[LangfuseTracer.__init__]".
♻️ Duplicate comments (2)
backend/app/core/langfuse/langfuse.py (2)

61-71: Use a function-name prefix inside _langfuse_call logs.

Line 67 should include the method name prefix to align with the logging convention. As per coding guidelines, ...

♻️ Proposed fix
-            logger.warning(
-                f"[LangfuseTracer] {getattr(fn, '__name__', 'operation')} failed: {e}"
-            )
+            logger.warning(
+                f"[LangfuseTracer._langfuse_call] {getattr(fn, '__name__', 'operation')} failed: {e}"
+            )

198-200: Use a function-name prefix inside langfuse_call logs.

Line 198 should reflect the inner function name for consistency with the logging convention. As per coding guidelines, ...

♻️ Proposed fix
-                    logger.warning(
-                        f"[observe_llm_execution] {getattr(fn, '__name__', 'operation')} failed: {e}"
-                    )
+                    logger.warning(
+                        f"[observe_llm_execution.langfuse_call] {getattr(fn, '__name__', 'operation')} failed: {e}"
+                    )

Comment on lines +35 to +60
try:
self.langfuse = Langfuse(
public_key=credentials["public_key"],
secret_key=credentials["secret_key"],
host=credentials["host"],
enabled=True, # This ensures the client is active
)
except Exception as e:
logger.warning(f"[LangfuseTracer] Failed to initialize: {e}")
self._failed = True
return

if response_id:
traces = self.langfuse.fetch_traces(tags=response_id).data
if traces:
self.session_id = traces[0].session_id
try:
traces = self.langfuse.fetch_traces(tags=response_id).data
if traces:
self.session_id = traces[0].session_id
except Exception as e:
logger.debug(f"[LangfuseTracer] Session resume failed: {e}")

logger.info(
f"[LangfuseTracer] Langfuse tracing enabled | session_id={self.session_id}"
f"[LangfuseTracer] Tracing enabled | session_id={self.session_id}"
)
else:
self.langfuse = Langfuse(enabled=False)
logger.warning("[LangfuseTracer] Tracing disabled - missing credentials")

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Prefix __init__ logs with the function name.

Lines 43, 53, 55-59 should use [LangfuseTracer.__init__] to match the logging convention. As per coding guidelines, ...

♻️ Proposed fix
-                logger.warning(f"[LangfuseTracer] Failed to initialize: {e}")
+                logger.warning(f"[LangfuseTracer.__init__] Failed to initialize: {e}")
@@
-                    logger.debug(f"[LangfuseTracer] Session resume failed: {e}")
+                    logger.debug(f"[LangfuseTracer.__init__] Session resume failed: {e}")
@@
-            logger.info(
-                f"[LangfuseTracer] Tracing enabled | session_id={self.session_id}"
-            )
+            logger.info(
+                f"[LangfuseTracer.__init__] Tracing enabled | session_id={self.session_id}"
+            )
@@
-            logger.warning("[LangfuseTracer] Tracing disabled - missing credentials")
+            logger.warning("[LangfuseTracer.__init__] Tracing disabled - missing credentials")
🤖 Prompt for AI Agents
In `@backend/app/core/langfuse/langfuse.py` around lines 35 - 60, Update the log
messages in LangfuseTracer.__init__ to follow the logging convention by
prefixing them with "[LangfuseTracer.__init__]": change the logger.warning that
logs initialization failure (inside the except for Langfuse(...)), the
logger.debug in the except when fetch_traces/session resume fails, the
logger.info that announces tracing enabled with session_id, and the
logger.warning that reports tracing disabled due to missing credentials; keep
the same messages and exception interpolation but prepend the required
function-name tag so all logs from the constructor use
"[LangfuseTracer.__init__]".

@vprashrex vprashrex requested a review from Prajna1999 January 24, 2026 09:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants