fix: graceful fallback when langfuse is not installed

- Use import importlib.util (not bare importlib) for find_spec
- Warn and fall back to standard openai instead of crashing with
  ImportError when LANGFUSE_SECRET_KEY is set but langfuse is missing

Made-with: Cursor
This commit is contained in:
Xubin Ren 2026-04-06 05:51:50 +00:00 committed by Xubin Ren
parent 4e06e12ab6
commit f82b5a1b02

View File

@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
import hashlib
import importlib
import importlib.util
import os
import secrets
import string
@ -14,13 +14,15 @@ from typing import TYPE_CHECKING, Any
import json_repair
if os.environ.get("LANGFUSE_SECRET_KEY"):
LANGFUSE_AVAILABLE = importlib.util.find_spec("langfuse") is not None
if not LANGFUSE_AVAILABLE:
raise ImportError("Langfuse is not available; please install it with `pip install langfuse`")
if os.environ.get("LANGFUSE_SECRET_KEY") and importlib.util.find_spec("langfuse"):
from langfuse.openai import AsyncOpenAI
else:
if os.environ.get("LANGFUSE_SECRET_KEY"):
import logging
logging.getLogger(__name__).warning(
"LANGFUSE_SECRET_KEY is set but langfuse is not installed; "
"install with `pip install langfuse` to enable tracing"
)
from openai import AsyncOpenAI
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest