hyperinfer-llamaindex 0.2.0__tar.gz
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.
- hyperinfer_llamaindex-0.2.0/.gitignore +218 -0
- hyperinfer_llamaindex-0.2.0/CHANGELOG.md +7 -0
- hyperinfer_llamaindex-0.2.0/PKG-INFO +52 -0
- hyperinfer_llamaindex-0.2.0/README.md +42 -0
- hyperinfer_llamaindex-0.2.0/package.json +8 -0
- hyperinfer_llamaindex-0.2.0/pyproject.toml +21 -0
- hyperinfer_llamaindex-0.2.0/src/hyperinfer_llamaindex/__init__.py +143 -0
- hyperinfer_llamaindex-0.2.0/src/hyperinfer_llamaindex/_sync.py +90 -0
- hyperinfer_llamaindex-0.2.0/tests/conftest.py +1 -0
- hyperinfer_llamaindex-0.2.0/tests/test_llamaindex.py +333 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Generated by Cargo
|
|
2
|
+
# will have compiled files and executables
|
|
3
|
+
debug
|
|
4
|
+
target
|
|
5
|
+
|
|
6
|
+
# These are backup files generated by rustfmt
|
|
7
|
+
**/*.rs.bk
|
|
8
|
+
|
|
9
|
+
# MSVC Windows builds of rustc generate these, which store debugging information
|
|
10
|
+
*.pdb
|
|
11
|
+
|
|
12
|
+
# Generated by cargo mutants
|
|
13
|
+
# Contains mutation testing data
|
|
14
|
+
**/mutants.out*/
|
|
15
|
+
|
|
16
|
+
# RustRover
|
|
17
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
18
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
19
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
20
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
21
|
+
#.idea/
|
|
22
|
+
.plan
|
|
23
|
+
.scannerwork
|
|
24
|
+
.opencode
|
|
25
|
+
.env
|
|
26
|
+
|
|
27
|
+
# Python bytecode and caches
|
|
28
|
+
__pycache__/
|
|
29
|
+
*.py[cod]
|
|
30
|
+
*.pyo
|
|
31
|
+
*$py.class
|
|
32
|
+
.pytest_cache/
|
|
33
|
+
.mypy_cache/
|
|
34
|
+
.ruff_cache/
|
|
35
|
+
|
|
36
|
+
# Python compiled extension modules (built by maturin / setuptools)
|
|
37
|
+
*.so
|
|
38
|
+
*.pyd
|
|
39
|
+
*.dylib
|
|
40
|
+
*.dSYM/
|
|
41
|
+
|
|
42
|
+
# Python packaging / build artefacts
|
|
43
|
+
*.egg-info/
|
|
44
|
+
*.eggs/
|
|
45
|
+
dist/
|
|
46
|
+
build/
|
|
47
|
+
wheels/
|
|
48
|
+
sdist/
|
|
49
|
+
|
|
50
|
+
# Python virtual environments
|
|
51
|
+
.venv/
|
|
52
|
+
venv/
|
|
53
|
+
env/
|
|
54
|
+
|
|
55
|
+
# uv lock files (generated, not meant to be committed for libraries)
|
|
56
|
+
uv.lock
|
|
57
|
+
|
|
58
|
+
# Coverage reports
|
|
59
|
+
.coverage
|
|
60
|
+
.coverage.*
|
|
61
|
+
htmlcov/
|
|
62
|
+
.vscode/
|
|
63
|
+
.desloppify/
|
|
64
|
+
.worktrees
|
|
65
|
+
|
|
66
|
+
# NodeJS
|
|
67
|
+
|
|
68
|
+
# Logs
|
|
69
|
+
logs
|
|
70
|
+
*.log
|
|
71
|
+
npm-debug.log*
|
|
72
|
+
yarn-debug.log*
|
|
73
|
+
yarn-error.log*
|
|
74
|
+
lerna-debug.log*
|
|
75
|
+
|
|
76
|
+
# Diagnostic reports (https://nodejs.org/api/report.html)
|
|
77
|
+
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
|
78
|
+
|
|
79
|
+
# Runtime data
|
|
80
|
+
pids
|
|
81
|
+
*.pid
|
|
82
|
+
*.seed
|
|
83
|
+
*.pid.lock
|
|
84
|
+
|
|
85
|
+
# Directory for instrumented libs generated by jscoverage/JSCover
|
|
86
|
+
lib-cov
|
|
87
|
+
|
|
88
|
+
# Coverage directory used by tools like istanbul
|
|
89
|
+
coverage
|
|
90
|
+
*.lcov
|
|
91
|
+
|
|
92
|
+
# nyc test coverage
|
|
93
|
+
.nyc_output
|
|
94
|
+
|
|
95
|
+
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
|
96
|
+
.grunt
|
|
97
|
+
|
|
98
|
+
# Bower dependency directory (https://bower.io/)
|
|
99
|
+
bower_components
|
|
100
|
+
|
|
101
|
+
# node-waf configuration
|
|
102
|
+
.lock-wscript
|
|
103
|
+
|
|
104
|
+
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
|
105
|
+
build/Release
|
|
106
|
+
|
|
107
|
+
# Dependency directories
|
|
108
|
+
node_modules/
|
|
109
|
+
jspm_packages/
|
|
110
|
+
|
|
111
|
+
# Snowpack dependency directory (https://snowpack.dev/)
|
|
112
|
+
web_modules/
|
|
113
|
+
|
|
114
|
+
# TypeScript cache
|
|
115
|
+
*.tsbuildinfo
|
|
116
|
+
|
|
117
|
+
# Optional npm cache directory
|
|
118
|
+
.npm
|
|
119
|
+
|
|
120
|
+
# Optional eslint cache
|
|
121
|
+
.eslintcache
|
|
122
|
+
|
|
123
|
+
# Optional stylelint cache
|
|
124
|
+
.stylelintcache
|
|
125
|
+
|
|
126
|
+
# Optional REPL history
|
|
127
|
+
.node_repl_history
|
|
128
|
+
|
|
129
|
+
# Output of 'npm pack'
|
|
130
|
+
*.tgz
|
|
131
|
+
|
|
132
|
+
# Yarn Integrity file
|
|
133
|
+
.yarn-integrity
|
|
134
|
+
|
|
135
|
+
# dotenv environment variable files
|
|
136
|
+
.env
|
|
137
|
+
.env.*
|
|
138
|
+
!.env.example
|
|
139
|
+
|
|
140
|
+
# parcel-bundler cache (https://parceljs.org/)
|
|
141
|
+
.cache
|
|
142
|
+
.parcel-cache
|
|
143
|
+
|
|
144
|
+
# Next.js build output
|
|
145
|
+
.next
|
|
146
|
+
out
|
|
147
|
+
|
|
148
|
+
# Nuxt.js build / generate output
|
|
149
|
+
.nuxt
|
|
150
|
+
dist
|
|
151
|
+
.output
|
|
152
|
+
|
|
153
|
+
# Gatsby files
|
|
154
|
+
.cache/
|
|
155
|
+
# Comment in the public line in if your project uses Gatsby and not Next.js
|
|
156
|
+
# https://nextjs.org/blog/next-9-1#public-directory-support
|
|
157
|
+
# public
|
|
158
|
+
|
|
159
|
+
# vuepress build output
|
|
160
|
+
.vuepress/dist
|
|
161
|
+
|
|
162
|
+
# vuepress v2.x temp and cache directory
|
|
163
|
+
.temp
|
|
164
|
+
.cache
|
|
165
|
+
|
|
166
|
+
# Sveltekit cache directory
|
|
167
|
+
.svelte-kit/
|
|
168
|
+
|
|
169
|
+
# vitepress build output
|
|
170
|
+
**/.vitepress/dist
|
|
171
|
+
|
|
172
|
+
# vitepress cache directory
|
|
173
|
+
**/.vitepress/cache
|
|
174
|
+
|
|
175
|
+
# Docusaurus cache and generated files
|
|
176
|
+
.docusaurus
|
|
177
|
+
|
|
178
|
+
# Serverless directories
|
|
179
|
+
.serverless/
|
|
180
|
+
|
|
181
|
+
# FuseBox cache
|
|
182
|
+
.fusebox/
|
|
183
|
+
|
|
184
|
+
# DynamoDB Local files
|
|
185
|
+
.dynamodb/
|
|
186
|
+
|
|
187
|
+
# Firebase cache directory
|
|
188
|
+
.firebase/
|
|
189
|
+
|
|
190
|
+
# TernJS port file
|
|
191
|
+
.tern-port
|
|
192
|
+
|
|
193
|
+
# Stores VSCode versions used for testing VSCode extensions
|
|
194
|
+
.vscode-test
|
|
195
|
+
|
|
196
|
+
# pnpm
|
|
197
|
+
.pnpm-store
|
|
198
|
+
|
|
199
|
+
# yarn v3
|
|
200
|
+
.pnp.*
|
|
201
|
+
.yarn/*
|
|
202
|
+
!.yarn/patches
|
|
203
|
+
!.yarn/plugins
|
|
204
|
+
!.yarn/releases
|
|
205
|
+
!.yarn/sdks
|
|
206
|
+
!.yarn/versions
|
|
207
|
+
|
|
208
|
+
# Vite files
|
|
209
|
+
vite.config.js.timestamp-*
|
|
210
|
+
vite.config.ts.timestamp-*
|
|
211
|
+
.vite/json
|
|
212
|
+
|
|
213
|
+
# MkDocs build output
|
|
214
|
+
site/
|
|
215
|
+
|
|
216
|
+
# Internal planning documents (superpowers specs/plans)
|
|
217
|
+
# These are private working files - do not publish or commit
|
|
218
|
+
docs/superpowers/
|
|
@@ -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,42 @@
|
|
|
1
|
+
# hyperinfer-llamaindex
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/hyperinfer-llamaindex/)
|
|
4
|
+
[](https://pypi.org/project/hyperinfer-llamaindex/)
|
|
5
|
+
|
|
6
|
+
LlamaIndex integration for HyperInfer LLM Gateway — wraps `HyperInferClient` as a LlamaIndex `CustomLLM`.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install hyperinfer-llamaindex
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from hyperinfer import Config
|
|
18
|
+
from hyperinfer_llamaindex import HyperInferLLM
|
|
19
|
+
|
|
20
|
+
config = (
|
|
21
|
+
Config()
|
|
22
|
+
.with_api_key("openai", "sk-...")
|
|
23
|
+
.with_alias("fast", "gpt-4o-mini")
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
llm = HyperInferLLM.from_config(
|
|
27
|
+
config=config,
|
|
28
|
+
model="fast",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# Completion
|
|
32
|
+
response = llm.complete("Hello!")
|
|
33
|
+
print(response.text)
|
|
34
|
+
|
|
35
|
+
# Streaming
|
|
36
|
+
for chunk in llm.stream_complete("Tell me a story"):
|
|
37
|
+
print(chunk.text, end="", flush=True)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## License
|
|
41
|
+
|
|
42
|
+
MIT
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "hyperinfer-llamaindex"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "LlamaIndex integration for HyperInfer LLM Gateway"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = { text = "AGPL-3.0-only" }
|
|
7
|
+
requires-python = ">=3.11"
|
|
8
|
+
dependencies = [
|
|
9
|
+
"hyperinfer",
|
|
10
|
+
"llama-index-core>=0.10"
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[build-system]
|
|
14
|
+
requires = ["hatchling"]
|
|
15
|
+
build-backend = "hatchling.build"
|
|
16
|
+
|
|
17
|
+
[tool.hatch.build.targets.wheel]
|
|
18
|
+
packages = ["src/hyperinfer_llamaindex"]
|
|
19
|
+
|
|
20
|
+
[tool.uv.sources]
|
|
21
|
+
hyperinfer = { workspace = true }
|
|
@@ -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 @@
|
|
|
1
|
+
"""Pytest configuration for LlamaIndex tests."""
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""Tests for LlamaIndex integration."""
|
|
2
|
+
|
|
3
|
+
from unittest.mock import AsyncMock, patch
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from hyperinfer_llamaindex import HyperInferLLM
|
|
7
|
+
from llama_index.core.llms import CompletionResponse
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TestRunSyncBridge:
|
|
11
|
+
"""Verify complete / stream_complete are safe when called from an async context."""
|
|
12
|
+
|
|
13
|
+
@pytest.mark.asyncio
|
|
14
|
+
async def test_complete_safe_inside_running_loop(self):
|
|
15
|
+
"""complete() must not raise 'This event loop is already running'."""
|
|
16
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
17
|
+
|
|
18
|
+
with patch.object(llm, "_acomplete", new_callable=AsyncMock) as mock:
|
|
19
|
+
mock.return_value = CompletionResponse(text="ok")
|
|
20
|
+
# Calling the *sync* method from inside a running async test should
|
|
21
|
+
# not raise RuntimeError even though there is already a loop.
|
|
22
|
+
result = llm.complete("hello")
|
|
23
|
+
assert result.text == "ok"
|
|
24
|
+
mock.assert_called_once()
|
|
25
|
+
|
|
26
|
+
@pytest.mark.asyncio
|
|
27
|
+
async def test_stream_complete_safe_inside_running_loop(self):
|
|
28
|
+
"""stream_complete() must not raise 'This event loop is already running'."""
|
|
29
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
30
|
+
|
|
31
|
+
async def mock_stream(**kwargs):
|
|
32
|
+
yield {
|
|
33
|
+
"delta": "hello",
|
|
34
|
+
"finish_reason": None,
|
|
35
|
+
"usage": None,
|
|
36
|
+
"id": "1",
|
|
37
|
+
"model": "gpt-4",
|
|
38
|
+
}
|
|
39
|
+
yield {
|
|
40
|
+
"delta": "!",
|
|
41
|
+
"finish_reason": "stop",
|
|
42
|
+
"usage": None,
|
|
43
|
+
"id": "1",
|
|
44
|
+
"model": "gpt-4",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
with patch.object(llm.client, "stream", side_effect=mock_stream):
|
|
48
|
+
chunks = list(llm.stream_complete("hi"))
|
|
49
|
+
|
|
50
|
+
assert len(chunks) == 2
|
|
51
|
+
assert chunks[-1].text == "hello!"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class TestHyperInferLLM:
|
|
55
|
+
"""Test suite for HyperInferLLM."""
|
|
56
|
+
|
|
57
|
+
def test_metadata(self):
|
|
58
|
+
"""Test that metadata returns correct values."""
|
|
59
|
+
llm = HyperInferLLM()
|
|
60
|
+
metadata = llm.metadata
|
|
61
|
+
assert metadata.context_window == 4096
|
|
62
|
+
assert metadata.num_output == 256
|
|
63
|
+
assert metadata.model_name == "gpt-4"
|
|
64
|
+
|
|
65
|
+
def test_default_attributes(self):
|
|
66
|
+
"""Test default attribute values."""
|
|
67
|
+
llm = HyperInferLLM()
|
|
68
|
+
assert llm.model == "gpt-4"
|
|
69
|
+
assert llm.virtual_key == "default"
|
|
70
|
+
assert llm.temperature is None
|
|
71
|
+
assert llm.max_tokens is None
|
|
72
|
+
assert llm.context_window == 4096
|
|
73
|
+
assert llm.num_output == 256
|
|
74
|
+
|
|
75
|
+
def test_custom_attributes(self):
|
|
76
|
+
"""Test custom attribute values."""
|
|
77
|
+
llm = HyperInferLLM(
|
|
78
|
+
model="claude-3",
|
|
79
|
+
virtual_key="test-key",
|
|
80
|
+
temperature=0.7,
|
|
81
|
+
max_tokens=100,
|
|
82
|
+
context_window=8192,
|
|
83
|
+
num_output=512,
|
|
84
|
+
)
|
|
85
|
+
assert llm.model == "claude-3"
|
|
86
|
+
assert llm.virtual_key == "test-key"
|
|
87
|
+
assert llm.temperature == 0.7
|
|
88
|
+
assert llm.max_tokens == 100
|
|
89
|
+
assert llm.context_window == 8192
|
|
90
|
+
assert llm.num_output == 512
|
|
91
|
+
|
|
92
|
+
@pytest.mark.asyncio
|
|
93
|
+
async def test_acomplete(self):
|
|
94
|
+
"""Test async completion."""
|
|
95
|
+
llm = HyperInferLLM(
|
|
96
|
+
model="gpt-4",
|
|
97
|
+
virtual_key="test-key",
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
mock_response = {"choices": [{"message": {"content": "Hello, world!"}}]}
|
|
101
|
+
|
|
102
|
+
with patch.object(llm.client, "chat", new_callable=AsyncMock) as mock_chat:
|
|
103
|
+
mock_chat.return_value = mock_response
|
|
104
|
+
|
|
105
|
+
result = await llm._acomplete("Hello")
|
|
106
|
+
|
|
107
|
+
assert isinstance(result, CompletionResponse)
|
|
108
|
+
assert result.text == "Hello, world!"
|
|
109
|
+
mock_chat.assert_called_once()
|
|
110
|
+
call_kwargs = mock_chat.call_args.kwargs
|
|
111
|
+
assert call_kwargs["key"] == "test-key"
|
|
112
|
+
assert call_kwargs["model"] == "gpt-4"
|
|
113
|
+
assert call_kwargs["messages"] == [{"role": "user", "content": "Hello"}]
|
|
114
|
+
|
|
115
|
+
@pytest.mark.asyncio
|
|
116
|
+
async def test_acomplete_with_temperature(self):
|
|
117
|
+
"""Test async completion with temperature parameter."""
|
|
118
|
+
llm = HyperInferLLM(
|
|
119
|
+
model="gpt-4",
|
|
120
|
+
temperature=0.5,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
mock_response = {"choices": [{"message": {"content": "Response"}}]}
|
|
124
|
+
|
|
125
|
+
with patch.object(llm.client, "chat", new_callable=AsyncMock) as mock_chat:
|
|
126
|
+
mock_chat.return_value = mock_response
|
|
127
|
+
|
|
128
|
+
await llm._acomplete("Test")
|
|
129
|
+
|
|
130
|
+
call_kwargs = mock_chat.call_args.kwargs
|
|
131
|
+
assert call_kwargs["temperature"] == 0.5
|
|
132
|
+
|
|
133
|
+
@pytest.mark.asyncio
|
|
134
|
+
async def test_acomplete_with_max_tokens(self):
|
|
135
|
+
"""Test async completion with max_tokens parameter."""
|
|
136
|
+
llm = HyperInferLLM(
|
|
137
|
+
model="gpt-4",
|
|
138
|
+
max_tokens=50,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
mock_response = {"choices": [{"message": {"content": "Response"}}]}
|
|
142
|
+
|
|
143
|
+
with patch.object(llm.client, "chat", new_callable=AsyncMock) as mock_chat:
|
|
144
|
+
mock_chat.return_value = mock_response
|
|
145
|
+
|
|
146
|
+
await llm._acomplete("Test")
|
|
147
|
+
|
|
148
|
+
call_kwargs = mock_chat.call_args.kwargs
|
|
149
|
+
assert call_kwargs["max_tokens"] == 50
|
|
150
|
+
|
|
151
|
+
@pytest.mark.asyncio
|
|
152
|
+
async def test_acomplete_error_handling(self):
|
|
153
|
+
"""Test error handling in async completion."""
|
|
154
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
155
|
+
|
|
156
|
+
with patch.object(llm.client, "chat", new_callable=AsyncMock) as mock_chat:
|
|
157
|
+
mock_chat.side_effect = Exception("API error")
|
|
158
|
+
|
|
159
|
+
with pytest.raises(RuntimeError) as exc_info:
|
|
160
|
+
await llm._acomplete("Test")
|
|
161
|
+
|
|
162
|
+
assert "LLM completion failed" in str(exc_info.value)
|
|
163
|
+
|
|
164
|
+
def test_complete_sync(self):
|
|
165
|
+
"""Test synchronous completion."""
|
|
166
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
167
|
+
|
|
168
|
+
mock_response = {"choices": [{"message": {"content": "Sync response"}}]}
|
|
169
|
+
|
|
170
|
+
with patch.object(llm, "_acomplete", new_callable=AsyncMock) as mock_acomplete:
|
|
171
|
+
mock_acomplete.return_value = CompletionResponse(
|
|
172
|
+
text="Sync response", raw=mock_response
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
result = llm.complete("Test")
|
|
176
|
+
|
|
177
|
+
assert result.text == "Sync response"
|
|
178
|
+
mock_acomplete.assert_called_once()
|
|
179
|
+
|
|
180
|
+
def test_from_config(self):
|
|
181
|
+
"""Test creating instance from config."""
|
|
182
|
+
from hyperinfer import Client, Config
|
|
183
|
+
|
|
184
|
+
config = Config()
|
|
185
|
+
with patch("hyperinfer_llamaindex.Client", spec=Client) as MockClient:
|
|
186
|
+
llm = HyperInferLLM.from_config(
|
|
187
|
+
config=config,
|
|
188
|
+
model="claude-3",
|
|
189
|
+
virtual_key="my-key",
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
assert llm.model == "claude-3"
|
|
193
|
+
assert llm.virtual_key == "my-key"
|
|
194
|
+
MockClient.assert_called_once_with(redis_url="redis://localhost:6379", config=config)
|
|
195
|
+
|
|
196
|
+
def test_from_config_custom_redis_url(self):
|
|
197
|
+
"""Test creating instance from config with custom redis URL."""
|
|
198
|
+
from hyperinfer import Client, Config
|
|
199
|
+
|
|
200
|
+
config = Config()
|
|
201
|
+
with patch("hyperinfer_llamaindex.Client", spec=Client) as MockClient:
|
|
202
|
+
HyperInferLLM.from_config(
|
|
203
|
+
config=config,
|
|
204
|
+
redis_url="redis://custom:6379",
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
MockClient.assert_called_once_with(redis_url="redis://custom:6379", config=config)
|
|
208
|
+
|
|
209
|
+
@pytest.mark.asyncio
|
|
210
|
+
async def test_acomplete_empty_response(self):
|
|
211
|
+
"""Test handling of empty response."""
|
|
212
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
213
|
+
|
|
214
|
+
mock_response = {"choices": []}
|
|
215
|
+
|
|
216
|
+
with patch.object(llm.client, "chat", new_callable=AsyncMock) as mock_chat:
|
|
217
|
+
mock_chat.return_value = mock_response
|
|
218
|
+
|
|
219
|
+
result = await llm._acomplete("Test")
|
|
220
|
+
|
|
221
|
+
assert result.text == ""
|
|
222
|
+
|
|
223
|
+
@pytest.mark.asyncio
|
|
224
|
+
async def test_acomplete_response_without_message(self):
|
|
225
|
+
"""Test handling of response without message."""
|
|
226
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
227
|
+
|
|
228
|
+
mock_response = {"choices": [{}]}
|
|
229
|
+
|
|
230
|
+
with patch.object(llm.client, "chat", new_callable=AsyncMock) as mock_chat:
|
|
231
|
+
mock_chat.return_value = mock_response
|
|
232
|
+
|
|
233
|
+
result = await llm._acomplete("Test")
|
|
234
|
+
|
|
235
|
+
assert result.text == ""
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class TestHyperInferLLMStreaming:
|
|
239
|
+
"""Tests for astream_complete and stream_complete."""
|
|
240
|
+
|
|
241
|
+
@pytest.mark.asyncio
|
|
242
|
+
async def test_astream_complete_yields_cumulative_text(self):
|
|
243
|
+
"""Each chunk should carry cumulative text and the incremental delta."""
|
|
244
|
+
llm = HyperInferLLM(model="gpt-4", virtual_key="test-key")
|
|
245
|
+
|
|
246
|
+
chunks = [
|
|
247
|
+
{
|
|
248
|
+
"id": "1",
|
|
249
|
+
"model": "gpt-4",
|
|
250
|
+
"delta": "The ",
|
|
251
|
+
"finish_reason": None,
|
|
252
|
+
"usage": None,
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
"id": "1",
|
|
256
|
+
"model": "gpt-4",
|
|
257
|
+
"delta": "answer",
|
|
258
|
+
"finish_reason": None,
|
|
259
|
+
"usage": None,
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
"id": "1",
|
|
263
|
+
"model": "gpt-4",
|
|
264
|
+
"delta": " is 42",
|
|
265
|
+
"finish_reason": "stop",
|
|
266
|
+
"usage": None,
|
|
267
|
+
},
|
|
268
|
+
]
|
|
269
|
+
|
|
270
|
+
async def mock_stream(**kwargs):
|
|
271
|
+
for chunk in chunks:
|
|
272
|
+
yield chunk
|
|
273
|
+
|
|
274
|
+
with patch.object(llm.client, "stream", side_effect=mock_stream):
|
|
275
|
+
gen = await llm.astream_complete("What is the answer?")
|
|
276
|
+
results = [r async for r in gen]
|
|
277
|
+
|
|
278
|
+
assert len(results) == 3
|
|
279
|
+
assert all(isinstance(r, CompletionResponse) for r in results)
|
|
280
|
+
assert results[0].delta == "The "
|
|
281
|
+
assert results[1].delta == "answer"
|
|
282
|
+
assert results[2].delta == " is 42"
|
|
283
|
+
assert results[0].text == "The "
|
|
284
|
+
assert results[1].text == "The answer"
|
|
285
|
+
assert results[2].text == "The answer is 42"
|
|
286
|
+
|
|
287
|
+
@pytest.mark.asyncio
|
|
288
|
+
async def test_astream_complete_empty_delta_on_final_chunk(self):
|
|
289
|
+
"""Empty delta on the final usage chunk still yields a response."""
|
|
290
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
291
|
+
|
|
292
|
+
chunks = [
|
|
293
|
+
{
|
|
294
|
+
"id": "1",
|
|
295
|
+
"model": "gpt-4",
|
|
296
|
+
"delta": "Hi",
|
|
297
|
+
"finish_reason": None,
|
|
298
|
+
"usage": None,
|
|
299
|
+
},
|
|
300
|
+
{
|
|
301
|
+
"id": "1",
|
|
302
|
+
"model": "gpt-4",
|
|
303
|
+
"delta": "",
|
|
304
|
+
"finish_reason": "stop",
|
|
305
|
+
"usage": {"input_tokens": 3, "output_tokens": 1},
|
|
306
|
+
},
|
|
307
|
+
]
|
|
308
|
+
|
|
309
|
+
async def mock_stream(**kwargs):
|
|
310
|
+
for chunk in chunks:
|
|
311
|
+
yield chunk
|
|
312
|
+
|
|
313
|
+
with patch.object(llm.client, "stream", side_effect=mock_stream):
|
|
314
|
+
gen = await llm.astream_complete("Hello")
|
|
315
|
+
results = [r async for r in gen]
|
|
316
|
+
|
|
317
|
+
assert len(results) == 2
|
|
318
|
+
assert results[-1].text == "Hi"
|
|
319
|
+
|
|
320
|
+
@pytest.mark.asyncio
|
|
321
|
+
async def test_astream_complete_propagates_errors(self):
|
|
322
|
+
"""Provider errors are wrapped as RuntimeError."""
|
|
323
|
+
llm = HyperInferLLM(model="gpt-4")
|
|
324
|
+
|
|
325
|
+
async def mock_stream(**kwargs):
|
|
326
|
+
raise ConnectionError("network failure")
|
|
327
|
+
yield # make it a generator
|
|
328
|
+
|
|
329
|
+
with patch.object(llm.client, "stream", side_effect=mock_stream):
|
|
330
|
+
with pytest.raises(RuntimeError, match="Streaming completion failed"):
|
|
331
|
+
gen = await llm.astream_complete("Hi")
|
|
332
|
+
async for _ in gen:
|
|
333
|
+
pass
|