From d791e9f3d1f3f400fc63ff67022f3846282a974c Mon Sep 17 00:00:00 2001 From: Akileo Date: Sat, 17 May 2025 19:47:42 +0900 Subject: [PATCH] Fix: Improve langchain import error handling and add img_path to handler Addresses issue #1784: - Raises ImportError if langchain is not installed when LangChainOpenAIHandler is initialized. - Adds img_path parameter to LangChainOpenAIHandler.chat_completion for interface consistency. - Logs a warning if img_path is used with LangChainOpenAIHandler. --- pr_agent/algo/ai_handlers/langchain_ai_handler.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/pr_agent/algo/ai_handlers/langchain_ai_handler.py b/pr_agent/algo/ai_handlers/langchain_ai_handler.py index 4d708fcb..b796f859 100644 --- a/pr_agent/algo/ai_handlers/langchain_ai_handler.py +++ b/pr_agent/algo/ai_handlers/langchain_ai_handler.py @@ -1,10 +1,14 @@ +_LANGCHAIN_INSTALLED = False + try: from langchain_core.messages import HumanMessage, SystemMessage from langchain_openai import AzureChatOpenAI, ChatOpenAI + _LANGCHAIN_INSTALLED = True except: # we don't enforce langchain as a dependency, so if it's not installed, just move on pass import functools +from typing import Optional import openai from tenacity import retry, retry_if_exception_type, retry_if_not_exception_type, stop_after_attempt @@ -18,7 +22,9 @@ OPENAI_RETRIES = 5 class LangChainOpenAIHandler(BaseAiHandler): def __init__(self): - # Initialize OpenAIHandler specific attributes here + if not _LANGCHAIN_INSTALLED: + raise ImportError("LangChain is not installed. Please install it with `pip install langchain`.") + super().__init__() self.azure = get_settings().get("OPENAI.API_TYPE", "").lower() == "azure" @@ -40,7 +46,9 @@ class LangChainOpenAIHandler(BaseAiHandler): retry=retry_if_exception_type(openai.APIError) & retry_if_not_exception_type(openai.RateLimitError), stop=stop_after_attempt(OPENAI_RETRIES), ) - async def chat_completion(self, model: str, system: str, user: str, temperature: float = 0.2): + async def chat_completion(self, model: str, system: str, user: str, temperature: float = 0.2, img_path: Optional[str] = None): + if img_path: + get_logger().warning(f"Image path is not supported for LangChainOpenAIHandler. Ignoring image path: {img_path}") try: messages = [SystemMessage(content=system), HumanMessage(content=user)]