How to create a ChatModel with secrets #28510
felipebcs
announced in
Ask Dosu (Archived)
Replies: 1 comment 6 replies
-
To create a from typing import Optional, Dict, Any, List
from pydantic import Field, SecretStr
from langchain_openai.chat_models.base import BaseChatOpenAI
from langchain_core.utils import secret_from_env
class CustomChatModel(BaseChatOpenAI):
"""Custom Chat Model extending ChatOpenAI with additional secret fields."""
model_name: str = Field(alias="model")
custom_api_key: Optional[SecretStr] = Field(
alias="api_key",
default_factory=secret_from_env("CUSTOM_API_KEY", default=None),
)
"""Custom API key, automatically read from env variable `CUSTOM_API_KEY` if not provided."""
custom_api_base: str = Field(default="https://api.custom.com/v1/")
"""Base URL path for API requests."""
model_config = ConfigDict(
populate_by_name=True,
)
@property
def lc_secrets(self) -> Dict[str, str]:
"""A map of constructor argument names to secret ids."""
return {"custom_api_key": "CUSTOM_API_KEY"}
@classmethod
def get_lc_namespace(cls) -> List[str]:
"""Get the namespace of the langchain object."""
return ["custom_namespace", "chat_models"]
@property
def lc_attributes(self) -> Dict[str, Any]:
"""List of attribute names that should be included in the serialized kwargs."""
attributes: Dict[str, Any] = {}
if self.custom_api_base:
attributes["custom_api_base"] = self.custom_api_base
return attributes
@classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this model can be serialized by Langchain."""
return True
@property
def _llm_type(self) -> str:
"""Return type of chat model."""
return "custom-chat"
# Additional methods and properties can be added here as needed This class extends |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
@dosu-bot, how can I create a
ChatModel
that extendsChatOpenAI
, but adds custom secret fields and that still can be serialized?Beta Was this translation helpful? Give feedback.
All reactions