hyperinfer-llamaindex 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,143 @@
|
|
|
1
|
+
"""LlamaIndex integration for HyperInfer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
from hyperinfer import Client, Config
|
|
8
|
+
from llama_index.core.base.llms.types import (
|
|
9
|
+
CompletionResponseAsyncGen,
|
|
10
|
+
CompletionResponseGen,
|
|
11
|
+
)
|
|
12
|
+
from llama_index.core.llms import CompletionResponse, CustomLLM, LLMMetadata
|
|
13
|
+
from llama_index.core.llms.callbacks import llm_completion_callback
|
|
14
|
+
from pydantic import Field
|
|
15
|
+
|
|
16
|
+
from ._sync import run_sync, run_sync_generator
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class HyperInferLLM(CustomLLM):
|
|
20
|
+
"""LlamaIndex LLM backed by HyperInfer."""
|
|
21
|
+
|
|
22
|
+
client: Client = Field(default_factory=Client)
|
|
23
|
+
model: str = Field(default="gpt-4")
|
|
24
|
+
virtual_key: str = Field(default="default")
|
|
25
|
+
temperature: float | None = Field(default=None)
|
|
26
|
+
max_tokens: int | None = Field(default=None)
|
|
27
|
+
context_window: int = Field(default=4096)
|
|
28
|
+
num_output: int = Field(default=256)
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def metadata(self) -> LLMMetadata:
|
|
32
|
+
return LLMMetadata(
|
|
33
|
+
context_window=self.context_window,
|
|
34
|
+
num_output=self.num_output,
|
|
35
|
+
model_name=self.model,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
@llm_completion_callback()
|
|
39
|
+
def complete(self, prompt: str, formatted: bool = False, **kwargs: Any) -> CompletionResponse:
|
|
40
|
+
return cast(CompletionResponse, run_sync(self._acomplete(prompt, **kwargs)))
|
|
41
|
+
|
|
42
|
+
@llm_completion_callback()
|
|
43
|
+
async def _acomplete(self, prompt: str, **kwargs: Any) -> CompletionResponse:
|
|
44
|
+
try:
|
|
45
|
+
messages = [{"role": "user", "content": prompt}]
|
|
46
|
+
|
|
47
|
+
response = await self.client.chat(
|
|
48
|
+
key=self.virtual_key,
|
|
49
|
+
model=self.model,
|
|
50
|
+
messages=messages,
|
|
51
|
+
temperature=self.temperature,
|
|
52
|
+
max_tokens=self.max_tokens,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
choices = response.get("choices", [])
|
|
56
|
+
if not choices:
|
|
57
|
+
content = ""
|
|
58
|
+
else:
|
|
59
|
+
content = choices[0].get("message", {}).get("content", "")
|
|
60
|
+
return CompletionResponse(text=content, raw=response)
|
|
61
|
+
except Exception as e:
|
|
62
|
+
raise RuntimeError(f"LLM completion failed: {e}") from e
|
|
63
|
+
|
|
64
|
+
@llm_completion_callback()
|
|
65
|
+
def stream_complete(
|
|
66
|
+
self, prompt: str, formatted: bool = False, **kwargs: Any
|
|
67
|
+
) -> CompletionResponseGen:
|
|
68
|
+
"""Synchronous streaming — yields chunks as they arrive from the async generator.
|
|
69
|
+
|
|
70
|
+
Uses the shared persistent background event loop so chunks are
|
|
71
|
+
forwarded incrementally rather than collected into a list first. Safe
|
|
72
|
+
to call from both plain-sync and already-running-async contexts
|
|
73
|
+
(FastAPI, Jupyter, LangGraph nodes).
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
async def _producer() -> CompletionResponseAsyncGen:
|
|
77
|
+
async for chunk in await self.astream_complete(prompt, formatted=formatted, **kwargs):
|
|
78
|
+
yield chunk
|
|
79
|
+
|
|
80
|
+
def _gen() -> CompletionResponseGen:
|
|
81
|
+
for chunk in run_sync_generator(_producer):
|
|
82
|
+
yield cast(CompletionResponse, chunk)
|
|
83
|
+
|
|
84
|
+
return _gen()
|
|
85
|
+
|
|
86
|
+
@llm_completion_callback()
|
|
87
|
+
async def astream_complete(
|
|
88
|
+
self, prompt: str, formatted: bool = False, **kwargs: Any
|
|
89
|
+
) -> CompletionResponseAsyncGen:
|
|
90
|
+
"""Async token-by-token streaming via the HyperInfer data plane.
|
|
91
|
+
|
|
92
|
+
Returns an async generator where each :class:`CompletionResponse` has:
|
|
93
|
+
|
|
94
|
+
- ``text``: cumulative text assembled so far.
|
|
95
|
+
- ``delta``: the incremental token(s) for this chunk.
|
|
96
|
+
- ``raw``: the raw chunk dict from the provider.
|
|
97
|
+
"""
|
|
98
|
+
messages = [{"role": "user", "content": prompt}]
|
|
99
|
+
client = self.client
|
|
100
|
+
virtual_key = self.virtual_key
|
|
101
|
+
model = self.model
|
|
102
|
+
temperature = self.temperature
|
|
103
|
+
max_tokens = self.max_tokens
|
|
104
|
+
|
|
105
|
+
async def _gen() -> CompletionResponseAsyncGen:
|
|
106
|
+
accumulated = ""
|
|
107
|
+
try:
|
|
108
|
+
async for chunk in client.stream(
|
|
109
|
+
key=virtual_key,
|
|
110
|
+
model=model,
|
|
111
|
+
messages=messages,
|
|
112
|
+
temperature=temperature,
|
|
113
|
+
max_tokens=max_tokens,
|
|
114
|
+
):
|
|
115
|
+
delta = chunk.get("delta", "")
|
|
116
|
+
accumulated += delta
|
|
117
|
+
yield CompletionResponse(text=accumulated, delta=delta, raw=chunk)
|
|
118
|
+
except Exception as e:
|
|
119
|
+
raise RuntimeError(f"Streaming completion failed: {e}") from e
|
|
120
|
+
|
|
121
|
+
return _gen()
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
def from_config(
|
|
125
|
+
cls,
|
|
126
|
+
config: Config,
|
|
127
|
+
model: str = "gpt-4",
|
|
128
|
+
virtual_key: str = "default",
|
|
129
|
+
redis_url: str = "redis://localhost:6379",
|
|
130
|
+
**kwargs: Any,
|
|
131
|
+
) -> HyperInferLLM:
|
|
132
|
+
"""Create an instance with configuration.
|
|
133
|
+
|
|
134
|
+
The underlying :class:`~hyperinfer.Client` is constructed eagerly here.
|
|
135
|
+
Call :meth:`~hyperinfer.Client.init` (or use an ``async with`` block)
|
|
136
|
+
before invoking :meth:`complete` or :meth:`_acomplete` if you need the
|
|
137
|
+
connection to be established before the first request.
|
|
138
|
+
"""
|
|
139
|
+
client = Client(redis_url=redis_url, config=config)
|
|
140
|
+
return cls(client=client, model=model, virtual_key=virtual_key, **kwargs)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
__all__ = ["HyperInferLLM"]
|
|
@@ -0,0 +1,90 @@
|
|
|
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
|
+
gen_holder: list[Any] = []
|
|
70
|
+
|
|
71
|
+
async def _get_next() -> Any:
|
|
72
|
+
if not gen_holder:
|
|
73
|
+
gen_holder.append(agen(*args, **kwargs))
|
|
74
|
+
try:
|
|
75
|
+
return await gen_holder[0].__anext__()
|
|
76
|
+
except StopAsyncIteration:
|
|
77
|
+
raise
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
while True:
|
|
81
|
+
future = asyncio.run_coroutine_threadsafe(_get_next(), loop)
|
|
82
|
+
try:
|
|
83
|
+
yield future.result()
|
|
84
|
+
except StopIteration:
|
|
85
|
+
break
|
|
86
|
+
except StopAsyncIteration:
|
|
87
|
+
break
|
|
88
|
+
finally:
|
|
89
|
+
if gen_holder:
|
|
90
|
+
asyncio.run_coroutine_threadsafe(gen_holder[0].aclose(), loop).result()
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hyperinfer-llamaindex
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: LlamaIndex integration for HyperInfer LLM Gateway
|
|
5
|
+
License: AGPL-3.0-only
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Requires-Dist: hyperinfer
|
|
8
|
+
Requires-Dist: llama-index-core>=0.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# hyperinfer-llamaindex
|
|
12
|
+
|
|
13
|
+
[](https://pypi.org/project/hyperinfer-llamaindex/)
|
|
14
|
+
[](https://pypi.org/project/hyperinfer-llamaindex/)
|
|
15
|
+
|
|
16
|
+
LlamaIndex integration for HyperInfer LLM Gateway — wraps `HyperInferClient` as a LlamaIndex `CustomLLM`.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install hyperinfer-llamaindex
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from hyperinfer import Config
|
|
28
|
+
from hyperinfer_llamaindex import HyperInferLLM
|
|
29
|
+
|
|
30
|
+
config = (
|
|
31
|
+
Config()
|
|
32
|
+
.with_api_key("openai", "sk-...")
|
|
33
|
+
.with_alias("fast", "gpt-4o-mini")
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
llm = HyperInferLLM.from_config(
|
|
37
|
+
config=config,
|
|
38
|
+
model="fast",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Completion
|
|
42
|
+
response = llm.complete("Hello!")
|
|
43
|
+
print(response.text)
|
|
44
|
+
|
|
45
|
+
# Streaming
|
|
46
|
+
for chunk in llm.stream_complete("Tell me a story"):
|
|
47
|
+
print(chunk.text, end="", flush=True)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
|
|
52
|
+
MIT
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
hyperinfer_llamaindex/__init__.py,sha256=gChYgRYpxq2J-18rjUyjpHwrPcs3C5tUhDr2aOXJKyA,5224
|
|
2
|
+
hyperinfer_llamaindex/_sync.py,sha256=Z8XrVfFJA2XQT9D54TqTYh-atoyraWCCaGkwnYLJ4QU,2978
|
|
3
|
+
hyperinfer_llamaindex-0.2.0.dist-info/METADATA,sha256=gi3S3wogOrajPuw1bcrguKeez3OtN-ucMR3qmBJzCa4,1228
|
|
4
|
+
hyperinfer_llamaindex-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
hyperinfer_llamaindex-0.2.0.dist-info/RECORD,,
|