hyperinfer-langchain 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.
@@ -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,7 @@
1
+ # hyperinfer-langchain
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - hyperinfer-python@0.1.1
@@ -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
+ [![PyPI](https://img.shields.io/pypi/v/hyperinfer-langchain?style=flat-square)](https://pypi.org/project/hyperinfer-langchain/)
15
+ [![Python Versions](https://img.shields.io/pypi/pyversions/hyperinfer-langchain?style=flat-square)](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,49 @@
1
+ # hyperinfer-langchain
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/hyperinfer-langchain?style=flat-square)](https://pypi.org/project/hyperinfer-langchain/)
4
+ [![Python Versions](https://img.shields.io/pypi/pyversions/hyperinfer-langchain?style=flat-square)](https://pypi.org/project/hyperinfer-langchain/)
5
+
6
+ LangChain integration for HyperInfer LLM Gateway — wraps `HyperInferClient` as a drop-in LangChain `BaseChatModel`.
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ pip install hyperinfer-langchain
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```python
17
+ import asyncio
18
+
19
+ from hyperinfer import Config
20
+ from hyperinfer_langchain import HyperInferChatModel
21
+ from langchain_core.messages import HumanMessage
22
+
23
+ async def main():
24
+ config = (
25
+ Config()
26
+ .with_api_key("openai", "sk-...")
27
+ .with_alias("fast", "gpt-4o-mini")
28
+ )
29
+
30
+ llm = await HyperInferChatModel.from_config(
31
+ config=config,
32
+ model="fast",
33
+ virtual_key="my-team",
34
+ )
35
+
36
+ # Non-streaming
37
+ response = llm.invoke([HumanMessage(content="Hello!")])
38
+ print(response.content)
39
+
40
+ # Streaming
41
+ for chunk in llm.stream([HumanMessage(content="Tell me a joke")]):
42
+ print(chunk.content, end="", flush=True)
43
+
44
+ asyncio.run(main())
45
+ ```
46
+
47
+ ## License
48
+
49
+ MIT
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "hyperinfer-langchain",
3
+ "version": "0.2.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "hyperinfer-python": "workspace:*"
7
+ }
8
+ }
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "hyperinfer-langchain"
3
+ version = "0.2.0"
4
+ description = "LangChain 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
+ "langchain-core~=1.2",
11
+ "langchain-community~=0.4"
12
+ ]
13
+ [build-system]
14
+ requires = ["hatchling"]
15
+ build-backend = "hatchling.build"
16
+
17
+ [tool.hatch.build.targets.wheel]
18
+ packages = ["src/hyperinfer_langchain"]
19
+
20
+ [tool.uv.sources]
21
+ hyperinfer = { workspace = true }
22
+
23
+ [tool.bandit]
24
+ exclude_dirs = ["tests", "venv"]
25
+
26
+ [dependency-groups]
27
+ dev = [
28
+ "bandit>=1.9.4",
29
+ "pre-commit>=4.5.1",
30
+ ]
@@ -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 @@
1
+ """Pytest configuration for LangChain tests."""
@@ -0,0 +1,305 @@
1
+ """Tests for LangChain integration."""
2
+
3
+ from unittest.mock import AsyncMock, MagicMock, patch
4
+
5
+ import pytest
6
+ from hyperinfer_langchain import HyperInferChatModel
7
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
8
+ from langchain_core.outputs import ChatGenerationChunk
9
+
10
+
11
+ class TestRunSyncBridge:
12
+ """Verify _generate / _stream are safe when called from an async context."""
13
+
14
+ @pytest.mark.asyncio
15
+ async def test_generate_safe_inside_running_loop(self):
16
+ """_generate must not raise 'This event loop is already running'."""
17
+ model = HyperInferChatModel(model="gpt-4")
18
+
19
+ with patch.object(model, "_agenerate", new_callable=AsyncMock) as mock:
20
+ mock.return_value = MagicMock()
21
+ # Calling the *sync* method from inside a running async test should
22
+ # not raise RuntimeError even though there is already a loop.
23
+ model._generate([HumanMessage(content="hi")])
24
+ mock.assert_called_once()
25
+
26
+ @pytest.mark.asyncio
27
+ async def test_stream_safe_inside_running_loop(self):
28
+ """_stream must not raise 'This event loop is already running'."""
29
+ model = HyperInferChatModel(model="gpt-4")
30
+
31
+ async def _fake_astream(*_args, **_kwargs):
32
+ yield MagicMock(spec=ChatGenerationChunk, message=MagicMock(content="x"))
33
+
34
+ with patch.object(model, "_astream", side_effect=_fake_astream):
35
+ chunks = list(model._stream([HumanMessage(content="hi")]))
36
+ assert len(chunks) == 1
37
+
38
+
39
+ class TestHyperInferChatModel:
40
+ """Test suite for HyperInferChatModel."""
41
+
42
+ def test_llm_type(self):
43
+ """Test that _llm_type returns correct value."""
44
+ model = HyperInferChatModel()
45
+ assert model._llm_type == "hyperinfer"
46
+
47
+ def test_default_attributes(self):
48
+ """Test default attribute values."""
49
+ model = HyperInferChatModel()
50
+ assert model.model == "gpt-4"
51
+ assert model.virtual_key == "default"
52
+ assert model.temperature is None
53
+ assert model.max_tokens is None
54
+
55
+ def test_custom_attributes(self):
56
+ """Test custom attribute values."""
57
+ model = HyperInferChatModel(
58
+ model="claude-3",
59
+ virtual_key="test-key",
60
+ temperature=0.7,
61
+ max_tokens=100,
62
+ )
63
+ assert model.model == "claude-3"
64
+ assert model.virtual_key == "test-key"
65
+ assert model.temperature == 0.7
66
+ assert model.max_tokens == 100
67
+
68
+ @pytest.mark.asyncio
69
+ async def test_agenerate_with_human_message(self):
70
+ """Test async generation with HumanMessage."""
71
+ model = HyperInferChatModel(
72
+ model="gpt-4",
73
+ virtual_key="test-key",
74
+ )
75
+
76
+ mock_response = {"choices": [{"message": {"content": "Hello, human!"}}]}
77
+
78
+ with patch.object(model.client, "chat", new_callable=AsyncMock) as mock_chat:
79
+ mock_chat.return_value = mock_response
80
+
81
+ messages = [HumanMessage(content="Hi")]
82
+ result = await model._agenerate(messages)
83
+
84
+ assert len(result.generations) == 1
85
+ assert result.generations[0].message.content == "Hello, human!"
86
+ mock_chat.assert_called_once()
87
+ call_kwargs = mock_chat.call_args.kwargs
88
+ assert call_kwargs["key"] == "test-key"
89
+ assert call_kwargs["model"] == "gpt-4"
90
+
91
+ @pytest.mark.asyncio
92
+ async def test_agenerate_with_system_message(self):
93
+ """Test async generation with SystemMessage."""
94
+ model = HyperInferChatModel(model="gpt-4")
95
+
96
+ mock_response = {"choices": [{"message": {"content": "Response with system context"}}]}
97
+
98
+ with patch.object(model.client, "chat", new_callable=AsyncMock) as mock_chat:
99
+ mock_chat.return_value = mock_response
100
+
101
+ messages = [
102
+ SystemMessage(content="You are a helpful assistant"),
103
+ HumanMessage(content="Hello"),
104
+ ]
105
+ result = await model._agenerate(messages)
106
+
107
+ assert len(result.generations) == 1
108
+ call_kwargs = mock_chat.call_args.kwargs
109
+ assert len(call_kwargs["messages"]) == 2
110
+
111
+ @pytest.mark.asyncio
112
+ async def test_agenerate_with_ai_message(self):
113
+ """Test async generation with AIMessage."""
114
+ model = HyperInferChatModel(model="gpt-4")
115
+
116
+ mock_response = {"choices": [{"message": {"content": "Continuing conversation"}}]}
117
+
118
+ with patch.object(model.client, "chat", new_callable=AsyncMock) as mock_chat:
119
+ mock_chat.return_value = mock_response
120
+
121
+ messages = [
122
+ HumanMessage(content="Hello"),
123
+ AIMessage(content="Hi there!"),
124
+ HumanMessage(content="How are you?"),
125
+ ]
126
+ result = await model._agenerate(messages)
127
+
128
+ assert len(result.generations) == 1
129
+ call_kwargs = mock_chat.call_args.kwargs
130
+ assert len(call_kwargs["messages"]) == 3
131
+
132
+ def test_generate_sync(self):
133
+ """Test synchronous generation."""
134
+ model = HyperInferChatModel(model="gpt-4")
135
+
136
+ with patch.object(model, "_agenerate", new_callable=AsyncMock) as mock_agenerate:
137
+ mock_agenerate.return_value = MagicMock()
138
+
139
+ messages = [HumanMessage(content="Test")]
140
+ model._generate(messages)
141
+
142
+ mock_agenerate.assert_called_once()
143
+
144
+ @pytest.mark.asyncio
145
+ async def test_agenerate_with_temperature(self):
146
+ """Test async generation with temperature parameter."""
147
+ model = HyperInferChatModel(
148
+ model="gpt-4",
149
+ temperature=0.5,
150
+ )
151
+
152
+ mock_response = {"choices": [{"message": {"content": "Response"}}]}
153
+
154
+ with patch.object(model.client, "chat", new_callable=AsyncMock) as mock_chat:
155
+ mock_chat.return_value = mock_response
156
+
157
+ messages = [HumanMessage(content="Test")]
158
+ await model._agenerate(messages)
159
+
160
+ call_kwargs = mock_chat.call_args.kwargs
161
+ assert call_kwargs["temperature"] == 0.5
162
+
163
+ @pytest.mark.asyncio
164
+ async def test_agenerate_with_max_tokens(self):
165
+ """Test async generation with max_tokens parameter."""
166
+ model = HyperInferChatModel(
167
+ model="gpt-4",
168
+ max_tokens=50,
169
+ )
170
+
171
+ mock_response = {"choices": [{"message": {"content": "Response"}}]}
172
+
173
+ with patch.object(model.client, "chat", new_callable=AsyncMock) as mock_chat:
174
+ mock_chat.return_value = mock_response
175
+
176
+ messages = [HumanMessage(content="Test")]
177
+ await model._agenerate(messages)
178
+
179
+ call_kwargs = mock_chat.call_args.kwargs
180
+ assert call_kwargs["max_tokens"] == 50
181
+
182
+ @pytest.mark.asyncio
183
+ async def test_from_config(self):
184
+ """Test creating instance from config."""
185
+ from hyperinfer import Client, Config
186
+
187
+ with patch("hyperinfer_langchain.Client") as MockClient:
188
+ mock_client_instance = MagicMock(spec=Client)
189
+ mock_client_instance.init = AsyncMock()
190
+ MockClient.return_value = mock_client_instance
191
+
192
+ config = Config()
193
+ model = await HyperInferChatModel.from_config(
194
+ config=config,
195
+ model="claude-3",
196
+ virtual_key="my-key",
197
+ )
198
+
199
+ assert model.model == "claude-3"
200
+ assert model.virtual_key == "my-key"
201
+ MockClient.assert_called_once_with("redis://localhost:6379", config)
202
+ mock_client_instance.init.assert_called_once()
203
+
204
+
205
+ class TestHyperInferChatModelStreaming:
206
+ """Tests for _astream and _stream."""
207
+
208
+ @pytest.mark.asyncio
209
+ async def test_astream_yields_chunks(self):
210
+ """_astream yields ChatGenerationChunk for each delta."""
211
+ model = HyperInferChatModel(model="gpt-4", virtual_key="test-key")
212
+
213
+ chunks = [
214
+ {
215
+ "id": "1",
216
+ "model": "gpt-4",
217
+ "delta": "Hello",
218
+ "finish_reason": None,
219
+ "usage": None,
220
+ },
221
+ {
222
+ "id": "1",
223
+ "model": "gpt-4",
224
+ "delta": " world",
225
+ "finish_reason": None,
226
+ "usage": None,
227
+ },
228
+ {
229
+ "id": "1",
230
+ "model": "gpt-4",
231
+ "delta": "",
232
+ "finish_reason": "stop",
233
+ "usage": {"input_tokens": 5, "output_tokens": 2},
234
+ },
235
+ ]
236
+
237
+ async def mock_stream(**kwargs):
238
+ for chunk in chunks:
239
+ yield chunk
240
+
241
+ with patch.object(model.client, "stream", side_effect=mock_stream):
242
+ messages = [HumanMessage(content="Hi")]
243
+ result = []
244
+ async for chunk in model._astream(messages):
245
+ result.append(chunk)
246
+
247
+ assert len(result) == 3
248
+ assert all(isinstance(c, ChatGenerationChunk) for c in result)
249
+ assert result[0].message.content == "Hello"
250
+ assert result[1].message.content == " world"
251
+ assert result[2].generation_info == {"finish_reason": "stop"}
252
+
253
+ @pytest.mark.asyncio
254
+ async def test_astream_concatenates_to_full_response(self):
255
+ """Concatenating all deltas should produce the full response."""
256
+ model = HyperInferChatModel(model="gpt-4")
257
+
258
+ chunks = [
259
+ {
260
+ "id": "1",
261
+ "model": "gpt-4",
262
+ "delta": "The ",
263
+ "finish_reason": None,
264
+ "usage": None,
265
+ },
266
+ {
267
+ "id": "1",
268
+ "model": "gpt-4",
269
+ "delta": "answer",
270
+ "finish_reason": None,
271
+ "usage": None,
272
+ },
273
+ {
274
+ "id": "1",
275
+ "model": "gpt-4",
276
+ "delta": " is 42",
277
+ "finish_reason": "stop",
278
+ "usage": None,
279
+ },
280
+ ]
281
+
282
+ async def mock_stream(**kwargs):
283
+ for chunk in chunks:
284
+ yield chunk
285
+
286
+ with patch.object(model.client, "stream", side_effect=mock_stream):
287
+ result = []
288
+ async for chunk in model._astream([HumanMessage(content="What?")]):
289
+ result.append(chunk.message.content)
290
+
291
+ assert "".join(result) == "The answer is 42"
292
+
293
+ @pytest.mark.asyncio
294
+ async def test_astream_propagates_errors(self):
295
+ """_astream wraps provider errors as RuntimeError."""
296
+ model = HyperInferChatModel(model="gpt-4")
297
+
298
+ async def mock_stream(**kwargs):
299
+ raise ValueError("provider down")
300
+ yield # make it a generator
301
+
302
+ with patch.object(model.client, "stream", side_effect=mock_stream):
303
+ with pytest.raises(RuntimeError, match="Streaming request failed"):
304
+ async for _ in model._astream([HumanMessage(content="Hi")]):
305
+ pass