File size: 4,637 Bytes
27f6252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""
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