nvidia-nat-test 1.2.0__py3-none-any.whl → 1.4.0a20251212__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.

Potentially problematic release.


This version of nvidia-nat-test might be problematic. Click here for more details.

nat/test/functions.py CHANGED
@@ -21,6 +21,7 @@ from nat.cli.register_workflow import register_function
21
21
  from nat.data_models.api_server import ChatRequest
22
22
  from nat.data_models.api_server import ChatResponse
23
23
  from nat.data_models.api_server import ChatResponseChunk
24
+ from nat.data_models.api_server import Usage
24
25
  from nat.data_models.function import FunctionBaseConfig
25
26
 
26
27
 
@@ -35,7 +36,14 @@ async def echo_function(config: EchoFunctionConfig, builder: Builder):
35
36
  return message
36
37
 
37
38
  async def inner_oai(message: ChatRequest) -> ChatResponse:
38
- return ChatResponse.from_string(message.messages[0].content)
39
+ content = message.messages[0].content
40
+
41
+ # Create usage statistics for the response
42
+ prompt_tokens = sum(len(str(msg.content).split()) for msg in message.messages)
43
+ completion_tokens = len(content.split()) if content else 0
44
+ total_tokens = prompt_tokens + completion_tokens
45
+ usage = Usage(prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=total_tokens)
46
+ return ChatResponse.from_string(content, usage=usage)
39
47
 
40
48
  if (config.use_openai_api):
41
49
  yield inner_oai
nat/test/llm.py ADDED
@@ -0,0 +1,244 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # pylint: disable=unused-argument,missing-class-docstring,missing-function-docstring,import-outside-toplevel
17
+ # pylint: disable=too-few-public-methods
18
+
19
+ import asyncio
20
+ import time
21
+ from collections.abc import AsyncGenerator
22
+ from collections.abc import Iterator
23
+ from itertools import cycle as iter_cycle
24
+ from typing import Any
25
+
26
+ from pydantic import Field
27
+
28
+ from nat.builder.builder import Builder
29
+ from nat.builder.framework_enum import LLMFrameworkEnum
30
+ from nat.builder.llm import LLMProviderInfo
31
+ from nat.cli.register_workflow import register_llm_client
32
+ from nat.cli.register_workflow import register_llm_provider
33
+ from nat.data_models.llm import LLMBaseConfig
34
+
35
+
36
+ class TestLLMConfig(LLMBaseConfig, name="nat_test_llm"):
37
+ """Test LLM configuration."""
38
+ __test__ = False
39
+ response_seq: list[str] = Field(
40
+ default=[],
41
+ description="Returns the next element in order (wraps)",
42
+ )
43
+ delay_ms: int = Field(default=0, ge=0, description="Artificial per-call delay in milliseconds to mimic latency")
44
+
45
+
46
+ class _ResponseChooser:
47
+ """
48
+ Helper class to choose the next response according to config using itertools.cycle and provide synchronous and
49
+ asynchronous sleep functions.
50
+ """
51
+
52
+ def __init__(self, response_seq: list[str], delay_ms: int):
53
+ self._cycler = iter_cycle(response_seq) if response_seq else None
54
+ self._delay_ms = delay_ms
55
+
56
+ def next_response(self) -> str:
57
+ """Return the next response in the cycle, or an empty string if no responses are configured."""
58
+ if self._cycler is None:
59
+ return ""
60
+ return next(self._cycler)
61
+
62
+ def sync_sleep(self) -> None:
63
+ time.sleep(self._delay_ms / 1000.0)
64
+
65
+ async def async_sleep(self) -> None:
66
+ await asyncio.sleep(self._delay_ms / 1000.0)
67
+
68
+
69
+ @register_llm_provider(config_type=TestLLMConfig)
70
+ async def test_llm_provider(config: TestLLMConfig, builder: Builder):
71
+ """Register the `nat_test_llm` provider for the NAT registry."""
72
+ yield LLMProviderInfo(config=config, description="Test LLM provider")
73
+
74
+
75
+ @register_llm_client(config_type=TestLLMConfig, wrapper_type=LLMFrameworkEnum.LANGCHAIN)
76
+ async def test_llm_langchain(config: TestLLMConfig, builder: Builder):
77
+ """LLM client for LangChain/LangGraph."""
78
+
79
+ chooser = _ResponseChooser(response_seq=config.response_seq, delay_ms=config.delay_ms)
80
+
81
+ class LangChainTestLLM:
82
+
83
+ def invoke(self, messages: Any, **_kwargs: Any) -> str:
84
+ chooser.sync_sleep()
85
+ return chooser.next_response()
86
+
87
+ async def ainvoke(self, messages: Any, **_kwargs: Any) -> str:
88
+ await chooser.async_sleep()
89
+ return chooser.next_response()
90
+
91
+ def stream(self, messages: Any, **_kwargs: Any) -> Iterator[str]:
92
+ chooser.sync_sleep()
93
+ yield chooser.next_response()
94
+
95
+ async def astream(self, messages: Any, **_kwargs: Any) -> AsyncGenerator[str]:
96
+ await chooser.async_sleep()
97
+ yield chooser.next_response()
98
+
99
+ def bind_tools(self, tools: Any, **_kwargs: Any) -> "LangChainTestLLM":
100
+ """Bind tools to the LLM. Returns self to maintain fluent interface."""
101
+ return self
102
+
103
+ def bind(self, **_kwargs: Any) -> "LangChainTestLLM":
104
+ """Bind additional parameters to the LLM. Returns self to maintain fluent interface."""
105
+ return self
106
+
107
+ yield LangChainTestLLM()
108
+
109
+
110
+ @register_llm_client(config_type=TestLLMConfig, wrapper_type=LLMFrameworkEnum.LLAMA_INDEX)
111
+ async def test_llm_llama_index(config: TestLLMConfig, builder: Builder):
112
+
113
+ try:
114
+ from llama_index.core.base.llms.types import ChatMessage
115
+ from llama_index.core.base.llms.types import ChatResponse
116
+ except ImportError as exc:
117
+ raise ImportError("llama_index is required for using the test_llm with llama_index. "
118
+ "Please install the `nvidia-nat-llama-index` package. ") from exc
119
+
120
+ chooser = _ResponseChooser(response_seq=config.response_seq, delay_ms=config.delay_ms)
121
+
122
+ class LITestLLM:
123
+
124
+ def chat(self, messages: list[Any] | None = None, **_kwargs: Any) -> ChatResponse:
125
+ chooser.sync_sleep()
126
+ return ChatResponse(message=ChatMessage(chooser.next_response()))
127
+
128
+ async def achat(self, messages: list[Any] | None = None, **_kwargs: Any) -> ChatResponse:
129
+ await chooser.async_sleep()
130
+ return ChatResponse(message=ChatMessage(chooser.next_response()))
131
+
132
+ def stream_chat(self, messages: list[Any] | None = None, **_kwargs: Any) -> Iterator[ChatResponse]:
133
+ chooser.sync_sleep()
134
+ yield ChatResponse(message=ChatMessage(chooser.next_response()))
135
+
136
+ async def astream_chat(self,
137
+ messages: list[Any] | None = None,
138
+ **_kwargs: Any) -> AsyncGenerator[ChatResponse, None]:
139
+ await chooser.async_sleep()
140
+ yield ChatResponse(message=ChatMessage(chooser.next_response()))
141
+
142
+ yield LITestLLM()
143
+
144
+
145
+ @register_llm_client(config_type=TestLLMConfig, wrapper_type=LLMFrameworkEnum.CREWAI)
146
+ async def test_llm_crewai(config: TestLLMConfig, builder: Builder):
147
+ """LLM client for CrewAI."""
148
+
149
+ chooser = _ResponseChooser(response_seq=config.response_seq, delay_ms=config.delay_ms)
150
+
151
+ class CrewAITestLLM:
152
+
153
+ def call(self, messages: list[dict[str, str]] | None = None, **kwargs: Any) -> str:
154
+ chooser.sync_sleep()
155
+ return chooser.next_response()
156
+
157
+ yield CrewAITestLLM()
158
+
159
+
160
+ @register_llm_client(config_type=TestLLMConfig, wrapper_type=LLMFrameworkEnum.SEMANTIC_KERNEL)
161
+ async def test_llm_semantic_kernel(config: TestLLMConfig, builder: Builder):
162
+ """LLM client for SemanticKernel."""
163
+
164
+ try:
165
+ from semantic_kernel.contents.chat_message_content import ChatMessageContent
166
+ from semantic_kernel.contents.utils.author_role import AuthorRole
167
+ except ImportError as exc:
168
+ raise ImportError("Semantic Kernel is required for using the test_llm with semantic_kernel. "
169
+ "Please install the `nvidia-nat-semantic-kernel` package. ") from exc
170
+
171
+ chooser = _ResponseChooser(response_seq=config.response_seq, delay_ms=config.delay_ms)
172
+
173
+ class SKTestLLM:
174
+
175
+ async def get_chat_message_contents(self, chat_history: Any, **_kwargs: Any) -> list[ChatMessageContent]:
176
+ await chooser.async_sleep()
177
+ text = chooser.next_response()
178
+ return [ChatMessageContent(role=AuthorRole.ASSISTANT, content=text)]
179
+
180
+ async def get_streaming_chat_message_contents(self, chat_history: Any,
181
+ **_kwargs: Any) -> AsyncGenerator[ChatMessageContent, None]:
182
+ await chooser.async_sleep()
183
+ text = chooser.next_response()
184
+ yield ChatMessageContent(role=AuthorRole.ASSISTANT, content=text)
185
+
186
+ yield SKTestLLM()
187
+
188
+
189
+ @register_llm_client(config_type=TestLLMConfig, wrapper_type=LLMFrameworkEnum.AGNO)
190
+ async def test_llm_agno(config: TestLLMConfig, builder: Builder):
191
+ """LLM client for agno."""
192
+
193
+ chooser = _ResponseChooser(response_seq=config.response_seq, delay_ms=config.delay_ms)
194
+
195
+ class AgnoTestLLM:
196
+
197
+ def invoke(self, messages: Any | None = None, **_kwargs: Any) -> str:
198
+ chooser.sync_sleep()
199
+ return chooser.next_response()
200
+
201
+ async def ainvoke(self, messages: Any | None = None, **_kwargs: Any) -> str:
202
+ await chooser.async_sleep()
203
+ return chooser.next_response()
204
+
205
+ def invoke_stream(self, messages: Any | None = None, **_kwargs: Any) -> Iterator[str]:
206
+ chooser.sync_sleep()
207
+ yield chooser.next_response()
208
+
209
+ async def ainvoke_stream(self, messages: Any | None = None, **_kwargs: Any) -> AsyncGenerator[str, None]:
210
+ await chooser.async_sleep()
211
+ yield chooser.next_response()
212
+
213
+ yield AgnoTestLLM()
214
+
215
+
216
+ @register_llm_client(config_type=TestLLMConfig, wrapper_type=LLMFrameworkEnum.ADK)
217
+ async def test_llm_adk(config: TestLLMConfig, builder: Builder):
218
+ """LLM client for Google ADK."""
219
+
220
+ try:
221
+ from google.adk.models.base_llm import BaseLlm
222
+ from google.adk.models.llm_request import LlmRequest
223
+ from google.adk.models.llm_response import LlmResponse
224
+ from google.genai import types
225
+ except ImportError as exc:
226
+ raise ImportError("Google ADK is required for using the test_llm with ADK. "
227
+ "Please install the `nvidia-nat-adk` package. ") from exc
228
+
229
+ chooser = _ResponseChooser(response_seq=config.response_seq, delay_ms=config.delay_ms)
230
+
231
+ class ADKTestLLM(BaseLlm):
232
+
233
+ async def generate_content_async(self,
234
+ llm_request: LlmRequest,
235
+ stream: bool = False) -> AsyncGenerator[LlmResponse, None]:
236
+ self._maybe_append_user_content(llm_request)
237
+ await chooser.async_sleep()
238
+ text = chooser.next_response()
239
+ yield LlmResponse(content=types.Content(role="model", parts=[types.Part.from_text(text=text)]))
240
+
241
+ def connect(self, *_args: Any, **_kwargs: Any) -> None:
242
+ return None
243
+
244
+ yield ADKTestLLM(model="nat_test_llm")