|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023-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 | +"""Module for initializing LLM models with proper error handling and type checking.""" |
| 17 | + |
| 18 | +import logging |
| 19 | +from typing import Any, List, Optional |
| 20 | + |
| 21 | +from langchain_core.language_models import BaseChatModel |
| 22 | +from langchain_core.messages import AIMessage |
| 23 | +from pydantic import ConfigDict, Field |
| 24 | + |
| 25 | +from nemoguardrails.context import api_request_headers |
| 26 | + |
| 27 | +log = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +class HeaderAPIKeyWrapper(BaseChatModel): |
| 31 | + """Wrapper that injects API keys from request headers at runtime. |
| 32 | +
|
| 33 | + This wrapper intercepts LLM calls and reads the API key from the HTTP request |
| 34 | + headers (via the api_request_headers context variable from server.api) on every request. |
| 35 | +
|
| 36 | + From testing, this adds negligible time to each LLM call (~1e-06 seconds) |
| 37 | + """ |
| 38 | + |
| 39 | + wrapped_llm: BaseChatModel = Field(description="The LangChain LLM to wrap") |
| 40 | + api_key_header: str = Field(description="The name of the HTTP header containing the API key") |
| 41 | + model_config = ConfigDict(arbitrary_types_allowed=True) |
| 42 | + |
| 43 | + def __init__(self, llm: BaseChatModel, api_key_header: str, **kwargs): |
| 44 | + """Initialize the wrapper. |
| 45 | +
|
| 46 | + Args: |
| 47 | + llm: The LangChain LLM to wrap (must be a BaseChatModel) |
| 48 | + api_key_header: The name of the HTTP header containing the API key |
| 49 | + """ |
| 50 | + # Initialize with the data dict for Pydantic |
| 51 | + super().__init__(**{"wrapped_llm": llm, "api_key_header": api_key_header, **kwargs}) |
| 52 | + |
| 53 | + def _get_api_key_from_headers(self) -> Optional[str]: |
| 54 | + """Extract API key from the current request headers.""" |
| 55 | + try: |
| 56 | + headers = api_request_headers.get(None) |
| 57 | + if headers and self.api_key_header in headers: |
| 58 | + return headers[self.api_key_header] |
| 59 | + except LookupError: |
| 60 | + # Context variable not set (e.g., not in a server request context) |
| 61 | + pass |
| 62 | + return None |
| 63 | + |
| 64 | + def _get_llm_with_api_key(self, api_key: Optional[str]) -> BaseChatModel: |
| 65 | + """Get LLM instance with the specified API key. |
| 66 | +
|
| 67 | + Creates a new LLM instance if api_key is provided, otherwise returns |
| 68 | + the wrapped LLM. This ensures thread-safety by avoiding shared state mutation. |
| 69 | + """ |
| 70 | + if not api_key: |
| 71 | + return self.wrapped_llm |
| 72 | + |
| 73 | + # Try ChatOpenAI-specific approach (most common) |
| 74 | + try: |
| 75 | + from langchain_openai import ChatOpenAI |
| 76 | + |
| 77 | + if isinstance(self.wrapped_llm, ChatOpenAI): |
| 78 | + # Create a shallow copy with the new API key |
| 79 | + # We use model_dump() to get all current settings, then override the API key |
| 80 | + config = self.wrapped_llm.model_dump() |
| 81 | + # Try both parameter names for compatibility |
| 82 | + config["openai_api_key"] = api_key |
| 83 | + config["api_key"] = api_key |
| 84 | + return ChatOpenAI(**config) |
| 85 | + except Exception as e: |
| 86 | + log.warning(f"Failed to create ChatOpenAI with custom API key: {e}") |
| 87 | + |
| 88 | + # Fallback: Try generic model_copy for other providers |
| 89 | + if hasattr(self.wrapped_llm, "model_copy"): |
| 90 | + for key_param in ["api_key", "anthropic_api_key", "cohere_api_key"]: |
| 91 | + try: |
| 92 | + return self.wrapped_llm.model_copy(update={key_param: api_key}) |
| 93 | + except (TypeError, ValueError): |
| 94 | + continue |
| 95 | + |
| 96 | + # If all fails, log warning and use default |
| 97 | + log.warning( |
| 98 | + f"Unable to create new instance for {type(self.wrapped_llm).__name__}. " |
| 99 | + f"Using default API key. Multi-tenant isolation not available for this provider." |
| 100 | + ) |
| 101 | + return self.wrapped_llm |
| 102 | + |
| 103 | + def _generate(self, messages, stop=None, run_manager=None, **kwargs): |
| 104 | + """Generate response using the wrapped LLM with runtime API key.""" |
| 105 | + llm = self._get_llm_with_api_key(self._get_api_key_from_headers()) |
| 106 | + return llm._generate(messages, stop=stop, run_manager=run_manager, **kwargs) |
| 107 | + |
| 108 | + async def _agenerate(self, messages, stop=None, run_manager=None, **kwargs): |
| 109 | + """Async generate response using the wrapped LLM with runtime API key.""" |
| 110 | + llm = self._get_llm_with_api_key(self._get_api_key_from_headers()) |
| 111 | + return await llm._agenerate(messages, stop=stop, run_manager=run_manager, **kwargs) |
| 112 | + |
| 113 | + def invoke( |
| 114 | + self, |
| 115 | + input: Any, |
| 116 | + config: Optional[Any] = None, |
| 117 | + *, |
| 118 | + stop: Optional[List[str]] = None, |
| 119 | + **kwargs: Any, |
| 120 | + ) -> AIMessage: |
| 121 | + """Invoke the LLM with runtime API key from headers.""" |
| 122 | + llm = self._get_llm_with_api_key(self._get_api_key_from_headers()) |
| 123 | + return llm.invoke(input, config=config, stop=stop, **kwargs) |
| 124 | + |
| 125 | + async def ainvoke( |
| 126 | + self, |
| 127 | + input: Any, |
| 128 | + config: Optional[Any] = None, |
| 129 | + *, |
| 130 | + stop: Optional[List[str]] = None, |
| 131 | + **kwargs: Any, |
| 132 | + ) -> AIMessage: |
| 133 | + """Async invoke the LLM with runtime API key from headers.""" |
| 134 | + llm = self._get_llm_with_api_key(self._get_api_key_from_headers()) |
| 135 | + return await llm.ainvoke(input, config=config, stop=stop, **kwargs) |
| 136 | + |
| 137 | + def _stream(self, messages, stop=None, run_manager=None, **kwargs): |
| 138 | + """Stream response using the wrapped LLM with runtime API key.""" |
| 139 | + llm = self._get_llm_with_api_key(self._get_api_key_from_headers()) |
| 140 | + yield from llm._stream(messages, stop=stop, run_manager=run_manager, **kwargs) |
| 141 | + |
| 142 | + async def _astream(self, messages, stop=None, run_manager=None, **kwargs): |
| 143 | + """Async stream response using the wrapped LLM with runtime API key.""" |
| 144 | + llm = self._get_llm_with_api_key(self._get_api_key_from_headers()) |
| 145 | + async for chunk in llm._astream(messages, stop=stop, run_manager=run_manager, **kwargs): |
| 146 | + yield chunk |
| 147 | + |
| 148 | + @property |
| 149 | + def _llm_type(self) -> str: |
| 150 | + """Return the LLM type.""" |
| 151 | + return f"header_api_key_wrapper_{self.wrapped_llm._llm_type}" |
| 152 | + |
| 153 | + |
| 154 | +__all__ = ["HeaderAPIKeyWrapper"] |
0 commit comments