Tony20100/langchain_full huggingface dataset:
This class allows interacting with the MariTalk chatbot API.
    To use it, you must provide an API key either through the constructor.
    Example:
        .. code-block:: python
            from langchain_community.chat_models import ChatMaritalk
            chat = ChatMaritalk(api_key="your_api_key_here")
    """
    api_key: str
    """Your MariTalk API key."""
    model: str
    """Chose one of the available models: 
    - `sabia-2-medium`
    - `sabia-2-small`
    - `sabia-2-medium-2024-03-13`
    - `sabia-2-small-2024-03-13`
    - `maritalk-2024-01-08` (deprecated)"""
    temperature: float = Field(default=0.7, gt=0.0, lt=1.0)
    """Run inference with this temperature. 
    Must be in the closed interval [0.0, 1.0]."""
    max_tokens: int = Field(default=512, gt=0)
    """The maximum number of tokens to generate in the reply."""
    do_sample: bool = Field(default=True)
    """Whether or not to use sampling; use `True` to enable."""
    top_p: float = Field(default=0.95, gt=0.0, lt=1.0)
    """Nucleus sampling parameter controlling the size of 
    the probability mass considered for sampling."""
    @property
    def _llm_type(self) -> str:
        """Identifies the LLM type as 'maritalk'."""
        return "maritalk"
[docs]    def parse_messages_for_model(
return "maritalk"
[docs]    def parse_messages_for_model(
        self, messages: List[BaseMessage]
    ) -> List[Dict[str, Union[str, List[Union[str, Dict[Any, Any]]]]]]:
        """
        Parses messages from LangChain's format to the format expected by
        the MariTalk API.
        Parameters:
            messages (List[BaseMessage]): A list of messages in LangChain
            format to be parsed.
        Returns:
            A list of messages formatted for the MariTalk API.
        """
        parsed_messages = []
        for message in messages:
            if isinstance(message, HumanMessage):
                role = "user"
            elif isinstance(message, AIMessage):
                role = "assistant"
            elif isinstance(message, SystemMessage):
                role = "system"
            parsed_messages.append({"role": role, "content": message.content})
        return parsed_messages
    def _call(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> str:
        """
        Sends the parsed messages to the MariTalk API and returns the generated
        response or an error message.
        This method makes an HTTP POST request to the MariTalk API with the
        provided messages and other parameters.
        If the request is successful and the API returns a response,
        this method returns a string containing the answer.
        If the request is rate-limited or encounters another error,
        it returns a string with the error message.
        Parameters:
            messages (List[BaseMessage]): Messages to send to the model.
Parameters:
            messages (List[BaseMessage]): Messages to send to the model.
            stop (Optional[List[str]]): Tokens that will signal the model
                to stop generating further tokens.
        Returns:
            str: If the API call is successful, returns the answer.
                 If an error occurs (e.g., rate limiting), returns a string
                 describing the error.
        """
        url = "https://chat.maritaca.ai/api/chat/inference"
        headers = {"authorization": f"Key {self.api_key}"}
        stopping_tokens = stop if stop is not None else []
        parsed_messages = self.parse_messages_for_model(messages)
        data = {
            "messages": parsed_messages,
            "model": self.model,
            "do_sample": self.do_sample,
            "max_tokens": self.max_tokens,
            "temperature": self.temperature,
            "top_p": self.top_p,
            "stopping_tokens": stopping_tokens,
            **kwargs,
        }
        response = requests.post(url, json=data, headers=headers)
        if response.ok:
            return response.json().get("answer", "No answer found")
        else:
            raise MaritalkHTTPError(response)
    async def _acall(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> str:
        """
        Asynchronously sends the parsed messages to the MariTalk API and returns
        the generated response or an error message.
        This method makes an HTTP POST request to the MariTalk API with the
        provided messages and other parameters using async I/O.
provided messages and other parameters using async I/O.
        If the request is successful and the API returns a response,
        this method returns a string containing the answer.
        If the request is rate-limited or encounters another error,
        it returns a string with the error message.
        """
        try:
            import httpx
            url = "https://chat.maritaca.ai/api/chat/inference"
            headers = {"authorization": f"Key {self.api_key}"}
            stopping_tokens = stop if stop is not None else []
            parsed_messages = self.parse_messages_for_model(messages)
            data = {
                "messages": parsed_messages,
                "model": self.model,
                "do_sample": self.do_sample,
                "max_tokens": self.max_tokens,
                "temperature": self.temperature,
                "top_p": self.top_p,
                "stopping_tokens": stopping_tokens,
                **kwargs,
            }
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    url, json=data, headers=headers, timeout=None
                )
            if response.status_code == 200:
                return response.json().get("answer", "No answer found")
            else:
                raise MaritalkHTTPError(response)
        except ImportError:
            raise ImportError(
                "Could not import httpx python package. "
                "Please install it with `pip install httpx`."
            )
    def _stream(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> Iterator[ChatGenerationChunk]:
**kwargs: Any,
    ) -> Iterator[ChatGenerationChunk]:
        headers = {"Authorization": f"Key {self.api_key}"}
        stopping_tokens = stop if stop is not None else []
        parsed_messages = self.parse_messages_for_model(messages)
        data = {
            "messages": parsed_messages,
            "model": self.model,
            "do_sample": self.do_sample,
            "max_tokens": self.max_tokens,
            "temperature": self.temperature,
            "top_p": self.top_p,
            "stopping_tokens": stopping_tokens,
            "stream": True,
            **kwargs,
        }
        response = requests.post(
            "https://chat.maritaca.ai/api/chat/inference",
            data=json.dumps(data),
            headers=headers,
            stream=True,
        )
        if response.ok:
            for line in response.iter_lines():
                if line.startswith(b"data: "):
                    response_data = line.replace(b"data: ", b"").decode("utf-8")
                    if response_data:
                        parsed_data = json.loads(response_data)
                        if "text" in parsed_data:
                            delta = parsed_data["text"]
                            chunk = ChatGenerationChunk(
                                message=AIMessageChunk(content=delta)
                            )
                            if run_manager:
                                run_manager.on_llm_new_token(delta, chunk=chunk)
                            yield chunk
        else:
            raise MaritalkHTTPError(response)
    async def _astream(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> AsyncIterator[ChatGenerationChunk]:
        try:
) -> AsyncIterator[ChatGenerationChunk]:
        try:
            import httpx
            headers = {"Authorization": f"Key {self.api_key}"}
            stopping_tokens = stop if stop is not None else []
            parsed_messages = self.parse_messages_for_model(messages)
            data = {
                "messages": parsed_messages,
                "model": self.model,
                "do_sample": self.do_sample,
                "max_tokens": self.max_tokens,
                "temperature": self.temperature,
                "top_p": self.top_p,
                "stopping_tokens": stopping_tokens,
                "stream": True,
                **kwargs,
            }
            async with httpx.AsyncClient() as client:
                async with client.stream(
                    "POST",
                    "https://chat.maritaca.ai/api/chat/inference",
                    data=json.dumps(data),
                    headers=headers,
                    timeout=None,
                ) as response:
                    if response.status_code == 200:
                        async for line in response.aiter_lines():
                            if line.startswith("data: "):
                                response_data = line.replace("data: ", "")
                                if response_data:
                                    parsed_data = json.loads(response_data)
                                    if "text" in parsed_data:
                                        delta = parsed_data["text"]
                                        chunk = ChatGenerationChunk(
                                            message=AIMessageChunk(content=delta)
                                        )
                                        if run_manager:
                                            await run_manager.on_llm_new_token(
                                                delta, chunk=chunk
                                            )
                                        yield chunk
                    else:
                        raise MaritalkHTTPError(response)
        except ImportError:
            raise ImportError(
                "Could not import httpx python package. "
                "Please install it with `pip install httpx`."
            )
    def _generate(
)
    def _generate(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> ChatResult:
        output_str = self._call(messages, stop=stop, run_manager=run_manager, **kwargs)
        message = AIMessage(content=output_str)
        generation = ChatGeneration(message=message)
        return ChatResult(generations=[generation])
    async def _agenerate(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> ChatResult:
        output_str = await self._acall(
            messages, stop=stop, run_manager=run_manager, **kwargs
        )
        message = AIMessage(content=output_str)
        generation = ChatGeneration(message=message)
        return ChatResult(generations=[generation])
    @property
    def _identifying_params(self) -> Dict[str, Any]:
        """
        Identifies the key parameters of the chat model for logging
        or tracking purposes.
        Returns:
            A dictionary of the key configuration parameters.
        """
        return {
            "model": self.model,
            "temperature": self.temperature,
            "top_p": self.top_p,
            "max_tokens": self.max_tokens,
        }
Source code for langchain_community.chat_models.gigachat
from __future__ import annotations
import logging
from typing import (
    TYPE_CHECKING,
    Any,
    AsyncIterator,
    Dict,
    Iterator,
    List,
    Mapping,
    Optional,
    Type,
)
from langchain_core.callbacks import (
    AsyncCallbackManagerForLLMRun,
    CallbackManagerForLLMRun,
)
from langchain_core.language_models.chat_models import (
    BaseChatModel,
    agenerate_from_stream,
    generate_from_stream,
)
from langchain_core.messages import (
    AIMessage,
    AIMessageChunk,
    BaseMessage,
    BaseMessageChunk,
    ChatMessage,
    ChatMessageChunk,
    FunctionMessage,
    FunctionMessageChunk,
    HumanMessage,
    HumanMessageChunk,
    SystemMessage,
    SystemMessageChunk,
)
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
from langchain_community.llms.gigachat import _BaseGigaChat
if TYPE_CHECKING:
    import gigachat.models as gm
logger = logging.getLogger(__name__)
def _convert_dict_to_message(message: gm.Messages) -> BaseMessage:
    from gigachat.models import FunctionCall, MessagesRole
    additional_kwargs: Dict = {}
    if function_call := message.function_call:
        if isinstance(function_call, FunctionCall):
            additional_kwargs["function_call"] = dict(function_call)
        elif isinstance(function_call, dict):
            additional_kwargs["function_call"] = function_call
    if message.role == MessagesRole.SYSTEM:
        return SystemMessage(content=message.content)
    elif message.role == MessagesRole.USER:
        return HumanMessage(content=message.content)
    elif message.role == MessagesRole.ASSISTANT:
elif message.role == MessagesRole.ASSISTANT:
        return AIMessage(content=message.content, additional_kwargs=additional_kwargs)
    else:
        raise TypeError(f"Got unknown role {message.role} {message}")
def _convert_message_to_dict(message: gm.BaseMessage) -> gm.Messages:
    from gigachat.models import Messages, MessagesRole
    if isinstance(message, SystemMessage):
        return Messages(role=MessagesRole.SYSTEM, content=message.content)
    elif isinstance(message, HumanMessage):
        return Messages(role=MessagesRole.USER, content=message.content)
    elif isinstance(message, AIMessage):
        return Messages(
            role=MessagesRole.ASSISTANT,
            content=message.content,
            function_call=message.additional_kwargs.get("function_call", None),
        )
    elif isinstance(message, ChatMessage):
        return Messages(role=MessagesRole(message.role), content=message.content)
    elif isinstance(message, FunctionMessage):
        return Messages(role=MessagesRole.FUNCTION, content=message.content)
    else:
        raise TypeError(f"Got unknown type {message}")
def _convert_delta_to_message_chunk(
    _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
) -> BaseMessageChunk:
    role = _dict.get("role")
    content = _dict.get("content") or ""
    additional_kwargs: Dict = {}
    if _dict.get("function_call"):
        function_call = dict(_dict["function_call"])
        if "name" in function_call and function_call["name"] is None:
            function_call["name"] = ""
        additional_kwargs["function_call"] = function_call
    if role == "user" or default_class == HumanMessageChunk:
        return HumanMessageChunk(content=content)
return HumanMessageChunk(content=content)
    elif role == "assistant" or default_class == AIMessageChunk:
        return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
    elif role == "system" or default_class == SystemMessageChunk:
        return SystemMessageChunk(content=content)
    elif role == "function" or default_class == FunctionMessageChunk:
        return FunctionMessageChunk(content=content, name=_dict["name"])
    elif role or default_class == ChatMessageChunk:
        return ChatMessageChunk(content=content, role=role)  # type: ignore[arg-type]
    else:
        return default_class(content=content)  # type: ignore[call-arg]
[docs]class GigaChat(_BaseGigaChat, BaseChatModel):
    """`GigaChat` large language models API.
    To use, you should pass login and password to access GigaChat API or use token.
    Example:
        .. code-block:: python
            from langchain_community.chat_models import GigaChat
            giga = GigaChat(credentials=..., scope=..., verify_ssl_certs=False)
    """
    def _build_payload(self, messages: List[BaseMessage], **kwargs: Any) -> gm.Chat:
        from gigachat.models import Chat
        payload = Chat(
            messages=[_convert_message_to_dict(m) for m in messages],
        )
        payload.functions = kwargs.get("functions", None)
        payload.model = self.model
        if self.profanity_check is not None:
            payload.profanity_check = self.profanity_check
        if self.temperature is not None:
            payload.temperature = self.temperature
        if self.top_p is not None:
            payload.top_p = self.top_p
if self.top_p is not None:
            payload.top_p = self.top_p
        if self.max_tokens is not None:
            payload.max_tokens = self.max_tokens
        if self.repetition_penalty is not None:
            payload.repetition_penalty = self.repetition_penalty
        if self.update_interval is not None:
            payload.update_interval = self.update_interval
        if self.verbose:
            logger.warning("Giga request: %s", payload.dict())
        return payload
    def _create_chat_result(self, response: Any) -> ChatResult:
        generations = []
        for res in response.choices:
            message = _convert_dict_to_message(res.message)
            finish_reason = res.finish_reason
            gen = ChatGeneration(
                message=message,
                generation_info={"finish_reason": finish_reason},
            )
            generations.append(gen)
            if finish_reason != "stop":
                logger.warning(
                    "Giga generation stopped with reason: %s",
                    finish_reason,
                )
            if self.verbose:
                logger.warning("Giga response: %s", message.content)
        llm_output = {"token_usage": response.usage, "model_name": response.model}
        return ChatResult(generations=generations, llm_output=llm_output)
    def _generate(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        stream: Optional[bool] = None,
        **kwargs: Any,
    ) -> ChatResult:
        should_stream = stream if stream is not None else self.streaming
        if should_stream:
            stream_iter = self._stream(
                messages, stop=stop, run_manager=run_manager, **kwargs
messages, stop=stop, run_manager=run_manager, **kwargs
            )
            return generate_from_stream(stream_iter)
        payload = self._build_payload(messages, **kwargs)
        response = self._client.chat(payload)
        return self._create_chat_result(response)
    async def _agenerate(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
        stream: Optional[bool] = None,
        **kwargs: Any,
    ) -> ChatResult:
        should_stream = stream if stream is not None else self.streaming
        if should_stream:
            stream_iter = self._astream(
                messages, stop=stop, run_manager=run_manager, **kwargs
            )
            return await agenerate_from_stream(stream_iter)
        payload = self._build_payload(messages, **kwargs)
        response = await self._client.achat(payload)
        return self._create_chat_result(response)
    def _stream(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> Iterator[ChatGenerationChunk]:
        payload = self._build_payload(messages, **kwargs)
        for chunk in self._client.stream(payload):
            if not isinstance(chunk, dict):
                chunk = chunk.dict()
            if len(chunk["choices"]) == 0:
                continue
            choice = chunk["choices"][0]
            content = choice.get("delta", {}).get("content", {})
            chunk = _convert_delta_to_message_chunk(choice["delta"], AIMessageChunk)
chunk = _convert_delta_to_message_chunk(choice["delta"], AIMessageChunk)
            finish_reason = choice.get("finish_reason")
            generation_info = (
                dict(finish_reason=finish_reason) if finish_reason is not None else None
            )
            if run_manager:
                run_manager.on_llm_new_token(content)
            yield ChatGenerationChunk(message=chunk, generation_info=generation_info)
    async def _astream(
        self,
        messages: List[BaseMessage],
        stop: Optional[List[str]] = None,
        run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> AsyncIterator[ChatGenerationChunk]:
        payload = self._build_payload(messages, **kwargs)
        async for chunk in self._client.astream(payload):
            if not isinstance(chunk, dict):
                chunk = chunk.dict()
            if len(chunk["choices"]) == 0:
                continue
            choice = chunk["choices"][0]
            content = choice.get("delta", {}).get("content", {})
            chunk = _convert_delta_to_message_chunk(choice["delta"], AIMessageChunk)
            finish_reason = choice.get("finish_reason")
            generation_info = (
                dict(finish_reason=finish_reason) if finish_reason is not None else None
            )
            yield ChatGenerationChunk(message=chunk, generation_info=generation_info)
            if run_manager:
                await run_manager.on_llm_new_token(content)
def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
    role = _dict["role"]
    if role == "user":
        return HumanMessage(content=_dict["content"])
    elif role == "assistant":
        return AIMessage(content=_dict.get("content", "") or "")
    else:
        return ChatMessage(content=_dict["content"], role=role)
def _convert_delta_to_message_chunk(
    _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
) -> BaseMessageChunk:
    role = _dict.get("role")
    content = _dict.get("content") or ""
    if role == "user" or default_class == HumanMessageChunk:
        return HumanMessageChunk(content=content)
    elif role == "assistant" or default_class == AIMessageChunk:
        return AIMessageChunk(content=content)
    elif role or default_class == ChatMessageChunk:
        return ChatMessageChunk(content=content, role=role)  # type: ignore[arg-type]
    else:
        return default_class(content=content)  # type: ignore[call-arg]
# signature generation
# https://cloud.tencent.com/document/product/1729/97732#532252ce-e960-48a7-8821-940a9ce2ccf3
def _signature(secret_key: SecretStr, url: str, payload: Dict[str, Any]) -> str:
    sorted_keys = sorted(payload.keys())
    url_info = urlparse(url)
    sign_str = url_info.netloc + url_info.path + "?"
    for key in sorted_keys:
        value = payload[key]
        if isinstance(value, list) or isinstance(value, dict):
            value = json.dumps(value, separators=(",", ":"))