|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 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 | +import httpx |
| 17 | +import pytest |
| 18 | + |
| 19 | +from nemoguardrails.llm.clients.openai_compatible import OpenAICompatibleClient |
| 20 | +from nemoguardrails.llm.models.openai_chat import OpenAIChatModel |
| 21 | +from tests.recorded.utils import DUMMY_OPENAI_API_KEY, api_key_for_record_mode |
| 22 | + |
| 23 | +pytestmark = [pytest.mark.recorded, pytest.mark.vcr, pytest.mark.asyncio] |
| 24 | + |
| 25 | + |
| 26 | +async def test_openai_chat_generate_text(record_mode): |
| 27 | + api_key = api_key_for_record_mode("OPENAI_API_KEY", DUMMY_OPENAI_API_KEY, record_mode) |
| 28 | + |
| 29 | + async with httpx.AsyncClient() as http_client: |
| 30 | + client = OpenAICompatibleClient( |
| 31 | + base_url="https://api.openai.com/v1", |
| 32 | + api_key=api_key, |
| 33 | + http_client=http_client, |
| 34 | + max_retries=0, |
| 35 | + ) |
| 36 | + model = OpenAIChatModel(client=client, model="gpt-4o-mini") |
| 37 | + |
| 38 | + result = await model.generate_async("Say hello in one word") |
| 39 | + |
| 40 | + assert isinstance(result.content, str) |
| 41 | + assert result.content |
| 42 | + assert result.finish_reason in {"stop", "length", "tool_calls", "content_filter", "other"} |
| 43 | + assert result.request_id |
| 44 | + assert result.usage is not None |
| 45 | + assert result.usage.input_tokens > 0 |
| 46 | + assert result.usage.output_tokens > 0 |
| 47 | + assert result.usage.total_tokens >= result.usage.input_tokens + result.usage.output_tokens |
0 commit comments