""" LangChain Runnable adapter for BaseLLM. Wraps the custom BaseLLM so LangGraph's astream_events(version="v2") can capture per-token deltas from the generate_answer node. Providers that implement real stream() (Ollama, OpenAI/DeepSeek) yield genuine tokens. vLLM falls back to yielding the full response as a single chunk. """ from __future__ import annotations import asyncio import logging import os from typing import Any, AsyncIterator, Iterator, Optional from langchain_core.runnables import Runnable from langchain_core.runnables.config import RunnableConfig logger = logging.getLogger(__name__) class BaseLLMRunnable(Runnable): """Expose BaseLLM as a LangChain Runnable for astream_events token capture. LangGraph's astream_events(version="v2") wraps our stream() generator automatically and emits on_chain_stream events for each yielded token — no manual callback management needed. """ def __init__(self, llm: Any, **defaults: Any) -> None: self._llm = llm self._defaults = defaults # ── Sync paths ────────────────────────────────────────────────────────── def invoke( self, input: str, config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> str: params = {**self._defaults, **kwargs} return self._llm.generate(user_prompt=input, **params) def stream( self, input: str, config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> Iterator[str]: params = {**self._defaults, **kwargs} yield from self._llm.stream(user_prompt=input, **params) # ── Async paths ───────────────────────────────────────────────────────── async def ainvoke( self, input: str, config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> str: params = {**self._defaults, **kwargs} return await asyncio.to_thread(self._llm.generate, user_prompt=input, **params) async def astream( self, input: str, config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> AsyncIterator[str]: def _collect(): return list(self.stream(input, config, **kwargs)) tokens = await asyncio.get_event_loop().run_in_executor(None, _collect) for token in tokens: yield token def get_chat_model(llm_client: Any) -> Any: """ Return a LangChain BaseChatModel supporting .bind_tools() for ReAct use. Feature-detects provider from llm_client.get_model_info() and instantiates the appropriate LangChain chat model with temperature=0. Returns None if the provider has no LangChain adapter or if the import fails — callers fall back to the legacy hardcoded retrieve node in that case. """ if llm_client is None: return None try: cfg = llm_client.get_model_info() except Exception: cfg = {} provider = (cfg.get("provider") or "").lower() model = cfg.get("model_name") or "" base_url = cfg.get("base_url") or os.environ.get("LLM_BASE_URL", "") api_key = cfg.get("api_key") or os.environ.get("LLM_API_KEY") or os.environ.get("OPENAI_API_KEY", "") try: if provider == "anthropic": from langchain_anthropic import ChatAnthropic return ChatAnthropic(model=model, temperature=0, api_key=api_key or None) if provider == "openai": from langchain_openai import ChatOpenAI kwargs: dict = {"model": model, "temperature": 0} if api_key: kwargs["api_key"] = api_key if base_url: kwargs["base_url"] = base_url # DeepSeek v4 thinking mode requires reasoning_content forwarded in every # follow-up turn — create_react_agent doesn't do that, causing 400 errors. # Use extra_body to disable thinking at the HTTP request level. if "deepseek" in base_url.lower() or "deepseek" in model.lower(): kwargs["extra_body"] = {"thinking": {"type": "disabled"}} return ChatOpenAI(**kwargs) except ImportError as e: logger.warning("LangChain chat-model adapter unavailable for provider=%r: %s", provider, e) except Exception as e: logger.warning("Failed to build chat model for provider=%r: %s", provider, e) return None