hyperinfer-langchain 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""LangChain integration for HyperInfer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Iterator
|
|
6
|
+
from typing import Any, cast
|
|
7
|
+
|
|
8
|
+
from hyperinfer import Client, Config
|
|
9
|
+
from langchain_community.adapters.openai import convert_message_to_dict
|
|
10
|
+
from langchain_core.callbacks.manager import (
|
|
11
|
+
AsyncCallbackManagerForLLMRun,
|
|
12
|
+
CallbackManagerForLLMRun,
|
|
13
|
+
)
|
|
14
|
+
from langchain_core.language_models.chat_models import BaseChatModel
|
|
15
|
+
from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage
|
|
16
|
+
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
|
|
17
|
+
from pydantic import Field
|
|
18
|
+
|
|
19
|
+
from ._sync import run_sync, run_sync_generator
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _format_messages(messages: list[BaseMessage]) -> list[dict[str, Any]]:
|
|
23
|
+
"""Convert a list of LangChain ``BaseMessage`` objects to OpenAI-style dicts.
|
|
24
|
+
|
|
25
|
+
Delegates to :func:`langchain_community.adapters.openai.convert_message_to_dict`
|
|
26
|
+
which handles all standard message types (Human, AI, System, Tool, Function,
|
|
27
|
+
Chat) and preserves extra fields such as ``tool_calls``, ``tool_call_id``,
|
|
28
|
+
and ``function_call`` from ``additional_kwargs``.
|
|
29
|
+
"""
|
|
30
|
+
return [convert_message_to_dict(msg) for msg in messages]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class HyperInferChatModel(BaseChatModel):
|
|
34
|
+
"""LangChain chat model backed by HyperInfer."""
|
|
35
|
+
|
|
36
|
+
client: Client = Field(default_factory=Client)
|
|
37
|
+
model: str = Field(default="gpt-4")
|
|
38
|
+
virtual_key: str = Field(default="default")
|
|
39
|
+
temperature: float | None = Field(default=None)
|
|
40
|
+
max_tokens: int | None = Field(default=None)
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def _llm_type(self) -> str:
|
|
44
|
+
return "hyperinfer"
|
|
45
|
+
|
|
46
|
+
def _generate(
|
|
47
|
+
self,
|
|
48
|
+
messages: list[BaseMessage],
|
|
49
|
+
stop: list[str] | None = None,
|
|
50
|
+
run_manager: CallbackManagerForLLMRun | None = None,
|
|
51
|
+
**kwargs: Any,
|
|
52
|
+
) -> ChatResult:
|
|
53
|
+
# run_manager here is a sync CallbackManagerForLLMRun; _agenerate
|
|
54
|
+
# expects the async variant, so we pass None — the non-streaming path
|
|
55
|
+
# does not invoke any token callbacks.
|
|
56
|
+
return run_sync(self._agenerate(messages, stop, None, **kwargs))
|
|
57
|
+
|
|
58
|
+
async def _agenerate(
|
|
59
|
+
self,
|
|
60
|
+
messages: list[BaseMessage],
|
|
61
|
+
stop: list[str] | None = None,
|
|
62
|
+
run_manager: AsyncCallbackManagerForLLMRun | None = None,
|
|
63
|
+
**kwargs: Any,
|
|
64
|
+
) -> ChatResult:
|
|
65
|
+
formatted_messages = _format_messages(messages)
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
response = await self.client.chat(
|
|
69
|
+
key=self.virtual_key,
|
|
70
|
+
model=self.model,
|
|
71
|
+
messages=formatted_messages,
|
|
72
|
+
temperature=self.temperature,
|
|
73
|
+
max_tokens=self.max_tokens,
|
|
74
|
+
**({"stop": stop} if stop else {}),
|
|
75
|
+
)
|
|
76
|
+
except Exception as e:
|
|
77
|
+
raise RuntimeError(f"Chat request failed: {e}") from e
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
content = response.get("choices", [{}])[0].get("message", {}).get("content", "")
|
|
81
|
+
except (KeyError, IndexError, TypeError) as e:
|
|
82
|
+
raise RuntimeError(f"Invalid response structure: {e}") from e
|
|
83
|
+
|
|
84
|
+
ai_message = AIMessage(content=content)
|
|
85
|
+
generation = ChatGeneration(message=ai_message)
|
|
86
|
+
|
|
87
|
+
return ChatResult(generations=[generation])
|
|
88
|
+
|
|
89
|
+
def _stream(
|
|
90
|
+
self,
|
|
91
|
+
messages: list[BaseMessage],
|
|
92
|
+
stop: list[str] | None = None,
|
|
93
|
+
run_manager: CallbackManagerForLLMRun | None = None,
|
|
94
|
+
**kwargs: Any,
|
|
95
|
+
) -> Iterator[ChatGenerationChunk]:
|
|
96
|
+
"""Synchronous streaming — yields chunks as they arrive from the async generator.
|
|
97
|
+
|
|
98
|
+
Uses the shared persistent background event loop so chunks are
|
|
99
|
+
forwarded incrementally rather than collected into a list first. Safe
|
|
100
|
+
to call from both plain-sync and already-running-async contexts
|
|
101
|
+
(FastAPI, Jupyter, LangGraph nodes).
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
async def _producer() -> AsyncIterator[ChatGenerationChunk]:
|
|
105
|
+
# run_manager here is a sync CallbackManagerForLLMRun; _astream
|
|
106
|
+
# expects the async variant, so we pass None — token callbacks
|
|
107
|
+
# are not available when bridging from a sync context.
|
|
108
|
+
async for chunk in self._astream(messages, stop, None, **kwargs):
|
|
109
|
+
yield chunk
|
|
110
|
+
|
|
111
|
+
for chunk in run_sync_generator(_producer):
|
|
112
|
+
yield cast(ChatGenerationChunk, chunk)
|
|
113
|
+
|
|
114
|
+
async def _astream(
|
|
115
|
+
self,
|
|
116
|
+
messages: list[BaseMessage],
|
|
117
|
+
stop: list[str] | None = None,
|
|
118
|
+
run_manager: AsyncCallbackManagerForLLMRun | None = None,
|
|
119
|
+
**kwargs: Any,
|
|
120
|
+
) -> AsyncIterator[ChatGenerationChunk]:
|
|
121
|
+
"""Async token-by-token streaming via the HyperInfer data plane."""
|
|
122
|
+
formatted_messages = _format_messages(messages)
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
async for chunk in self.client.stream(
|
|
126
|
+
key=self.virtual_key,
|
|
127
|
+
model=self.model,
|
|
128
|
+
messages=formatted_messages,
|
|
129
|
+
temperature=self.temperature,
|
|
130
|
+
max_tokens=self.max_tokens,
|
|
131
|
+
**({"stop": stop} if stop else {}),
|
|
132
|
+
):
|
|
133
|
+
delta = chunk.get("delta", "")
|
|
134
|
+
finish_reason = chunk.get("finish_reason")
|
|
135
|
+
ai_chunk = AIMessageChunk(content=delta)
|
|
136
|
+
gen_chunk = ChatGenerationChunk(
|
|
137
|
+
message=ai_chunk,
|
|
138
|
+
generation_info=({"finish_reason": finish_reason} if finish_reason else None),
|
|
139
|
+
)
|
|
140
|
+
if run_manager:
|
|
141
|
+
await run_manager.on_llm_new_token(delta, chunk=gen_chunk)
|
|
142
|
+
yield gen_chunk
|
|
143
|
+
except Exception as e:
|
|
144
|
+
raise RuntimeError(f"Streaming request failed: {e}") from e
|
|
145
|
+
|
|
146
|
+
@classmethod
|
|
147
|
+
async def from_config(
|
|
148
|
+
cls,
|
|
149
|
+
config: Config,
|
|
150
|
+
model: str = "gpt-4",
|
|
151
|
+
virtual_key: str = "default",
|
|
152
|
+
redis_url: str = "redis://localhost:6379",
|
|
153
|
+
**kwargs: Any,
|
|
154
|
+
) -> HyperInferChatModel:
|
|
155
|
+
"""Create instance with configuration."""
|
|
156
|
+
client = Client(redis_url, config)
|
|
157
|
+
await client.init()
|
|
158
|
+
|
|
159
|
+
instance = cls(
|
|
160
|
+
client=client,
|
|
161
|
+
model=model,
|
|
162
|
+
virtual_key=virtual_key,
|
|
163
|
+
**kwargs,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
return instance
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
__all__ = ["HyperInferChatModel"]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Reusable background event loop for running async code from sync contexts.
|
|
2
|
+
|
|
3
|
+
Creates a single daemon thread that owns an asyncio event loop running
|
|
4
|
+
``loop.run_forever()``. Coroutines are dispatched to it via
|
|
5
|
+
``asyncio.run_coroutine_threadsafe`` and the caller blocks on the result.
|
|
6
|
+
|
|
7
|
+
This avoids the per-call thread/loop overhead of ``ThreadPoolExecutor`` +
|
|
8
|
+
``asyncio.run`` and works correctly whether the caller is on a plain sync
|
|
9
|
+
thread or already inside a running event loop (FastAPI, Jupyter, LangGraph).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import threading
|
|
16
|
+
from collections.abc import Callable, Coroutine
|
|
17
|
+
from typing import Any, TypeVar
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T")
|
|
20
|
+
|
|
21
|
+
_loop_thread: threading.Thread | None = None
|
|
22
|
+
_loop: asyncio.AbstractEventLoop | None = None
|
|
23
|
+
_loop_ready = threading.Event()
|
|
24
|
+
_loop_lock = threading.Lock()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _ensure_loop() -> asyncio.AbstractEventLoop:
|
|
28
|
+
"""Lazily start the background event loop thread if it isn't running."""
|
|
29
|
+
global _loop_thread, _loop, _loop_ready
|
|
30
|
+
|
|
31
|
+
with _loop_lock:
|
|
32
|
+
if _loop_thread is not None and _loop_thread.is_alive():
|
|
33
|
+
return _loop # type: ignore[return-value]
|
|
34
|
+
|
|
35
|
+
_loop_ready = threading.Event()
|
|
36
|
+
|
|
37
|
+
def _run_loop() -> None:
|
|
38
|
+
global _loop
|
|
39
|
+
_loop = asyncio.new_event_loop()
|
|
40
|
+
asyncio.set_event_loop(_loop)
|
|
41
|
+
_loop_ready.set()
|
|
42
|
+
_loop.run_forever()
|
|
43
|
+
|
|
44
|
+
_loop_thread = threading.Thread(target=_run_loop, daemon=True, name="hyperinfer-sync-loop")
|
|
45
|
+
_loop_thread.start()
|
|
46
|
+
_loop_ready.wait(timeout=5.0)
|
|
47
|
+
|
|
48
|
+
if _loop is None:
|
|
49
|
+
raise RuntimeError("Background event loop failed to start")
|
|
50
|
+
return _loop
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def run_sync(coro: Coroutine[Any, Any, T]) -> T:
|
|
54
|
+
"""Run *coro* on the persistent background event loop and return its result."""
|
|
55
|
+
loop = _ensure_loop()
|
|
56
|
+
future = asyncio.run_coroutine_threadsafe(coro, loop)
|
|
57
|
+
return future.result()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def run_sync_generator(agen: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
|
|
61
|
+
"""Run an async generator function on the background loop, yielding results.
|
|
62
|
+
|
|
63
|
+
The generator is advanced via ``asyncio.wait_for`` on each ``__anext__``
|
|
64
|
+
call so the caller can consume chunks incrementally.
|
|
65
|
+
"""
|
|
66
|
+
loop = _ensure_loop()
|
|
67
|
+
|
|
68
|
+
# We need to keep the generator object alive across calls.
|
|
69
|
+
# Use a wrapper that stores it.
|
|
70
|
+
gen_holder: list[Any] = []
|
|
71
|
+
|
|
72
|
+
async def _get_next() -> Any:
|
|
73
|
+
if not gen_holder:
|
|
74
|
+
gen_holder.append(agen(*args, **kwargs))
|
|
75
|
+
try:
|
|
76
|
+
return await gen_holder[0].__anext__()
|
|
77
|
+
except StopAsyncIteration:
|
|
78
|
+
raise
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
while True:
|
|
82
|
+
future = asyncio.run_coroutine_threadsafe(_get_next(), loop)
|
|
83
|
+
try:
|
|
84
|
+
yield future.result()
|
|
85
|
+
except StopIteration:
|
|
86
|
+
break
|
|
87
|
+
except StopAsyncIteration:
|
|
88
|
+
break
|
|
89
|
+
finally:
|
|
90
|
+
if gen_holder:
|
|
91
|
+
asyncio.run_coroutine_threadsafe(gen_holder[0].aclose(), loop).result()
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hyperinfer-langchain
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: LangChain integration for HyperInfer LLM Gateway
|
|
5
|
+
License: AGPL-3.0-only
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Requires-Dist: hyperinfer
|
|
8
|
+
Requires-Dist: langchain-community~=0.4
|
|
9
|
+
Requires-Dist: langchain-core~=1.2
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# hyperinfer-langchain
|
|
13
|
+
|
|
14
|
+
[](https://pypi.org/project/hyperinfer-langchain/)
|
|
15
|
+
[](https://pypi.org/project/hyperinfer-langchain/)
|
|
16
|
+
|
|
17
|
+
LangChain integration for HyperInfer LLM Gateway — wraps `HyperInferClient` as a drop-in LangChain `BaseChatModel`.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install hyperinfer-langchain
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import asyncio
|
|
29
|
+
|
|
30
|
+
from hyperinfer import Config
|
|
31
|
+
from hyperinfer_langchain import HyperInferChatModel
|
|
32
|
+
from langchain_core.messages import HumanMessage
|
|
33
|
+
|
|
34
|
+
async def main():
|
|
35
|
+
config = (
|
|
36
|
+
Config()
|
|
37
|
+
.with_api_key("openai", "sk-...")
|
|
38
|
+
.with_alias("fast", "gpt-4o-mini")
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
llm = await HyperInferChatModel.from_config(
|
|
42
|
+
config=config,
|
|
43
|
+
model="fast",
|
|
44
|
+
virtual_key="my-team",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# Non-streaming
|
|
48
|
+
response = llm.invoke([HumanMessage(content="Hello!")])
|
|
49
|
+
print(response.content)
|
|
50
|
+
|
|
51
|
+
# Streaming
|
|
52
|
+
for chunk in llm.stream([HumanMessage(content="Tell me a joke")]):
|
|
53
|
+
print(chunk.content, end="", flush=True)
|
|
54
|
+
|
|
55
|
+
asyncio.run(main())
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
hyperinfer_langchain/__init__.py,sha256=6IuQTaYmLII4rQmj6pPx8fUlWuWjVFWhqkTafrKJVjI,6249
|
|
2
|
+
hyperinfer_langchain/_sync.py,sha256=SjQrDzoSrpxcDSRVqdrH9gPW0wGR-4wWhQZuvH_X2wE,3014
|
|
3
|
+
hyperinfer_langchain-0.2.0.dist-info/METADATA,sha256=P044I3OSFNNNZ8WN-zV2uQ2i5dbkho7Y0r-l3Q-jTVU,1524
|
|
4
|
+
hyperinfer_langchain-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
hyperinfer_langchain-0.2.0.dist-info/RECORD,,
|