Skip to content

Maritalk

Maritalk #

Bases: LLM

Maritalk LLM.

Examples:

pip install llama-index-llms-maritalk

from llama_index.core.llms import ChatMessage
from llama_index.llms.maritalk import Maritalk

# To customize your API key, do this
# otherwise it will lookup MARITALK_API_KEY from your env variable
# llm = Maritalk(api_key="<your_maritalk_api_key>")

llm = Maritalk()

# Call chat with a list of messages
messages = [
    ChatMessage(
        role="system",
        content="You are an assistant specialized in suggesting pet names. Given the animal, you must suggest 4 names.",
    ),
    ChatMessage(role="user", content="I have a dog."),
]

response = llm.chat(messages)
print(response)
Source code in llama-index-integrations/llms/llama-index-llms-maritalk/llama_index/llms/maritalk/base.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
class Maritalk(LLM):
    """Maritalk LLM.

    Examples:
        `pip install llama-index-llms-maritalk`

        ```python
        from llama_index.core.llms import ChatMessage
        from llama_index.llms.maritalk import Maritalk

        # To customize your API key, do this
        # otherwise it will lookup MARITALK_API_KEY from your env variable
        # llm = Maritalk(api_key="<your_maritalk_api_key>")

        llm = Maritalk()

        # Call chat with a list of messages
        messages = [
            ChatMessage(
                role="system",
                content="You are an assistant specialized in suggesting pet names. Given the animal, you must suggest 4 names.",
            ),
            ChatMessage(role="user", content="I have a dog."),
        ]

        response = llm.chat(messages)
        print(response)
        ```
    """

    api_key: Optional[str] = Field(default=None, description="Your MariTalk API key.")
    temperature: float = Field(
        default=0.7,
        gt=0.0,
        lt=1.0,
        description="Run inference with this temperature. Must be in the"
        "closed interval [0.0, 1.0].",
    )
    max_tokens: int = Field(
        default=512,
        gt=0,
        description="The maximum number of tokens to" "generate in the reply.",
    )
    do_sample: bool = Field(
        default=True,
        description="Whether or not to use sampling; use `True` to enable.",
    )
    top_p: float = Field(
        default=0.95,
        gt=0.0,
        lt=1.0,
        description="Nucleus sampling parameter controlling the size of"
        " the probability mass considered for sampling.",
    )

    _endpoint: str = PrivateAttr("https://chat.maritaca.ai/api/chat/inference")

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
        # If an API key is not provided during instantiation,
        # fall back to the MARITALK_API_KEY environment variable
        self.api_key = self.api_key or os.getenv("MARITALK_API_KEY")
        if not self.api_key:
            raise ValueError(
                "An API key must be provided or set in the "
                "'MARITALK_API_KEY' environment variable."
            )

    @classmethod
    def class_name(cls) -> str:
        return "Maritalk"

    @property
    def metadata(self) -> LLMMetadata:
        return LLMMetadata(
            model_name="maritalk",
            context_window=self.max_tokens,
            is_chat_model=True,
        )

    @llm_chat_callback()
    def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
        # Prepare the data payload for the Maritalk API
        formatted_messages = []
        for msg in messages:
            if msg.role == MessageRole.SYSTEM:
                # Add system message as a user message
                formatted_messages.append({"role": "user", "content": msg.content})
                # Follow it by an assistant message acknowledging it, to maintain conversation flow
                formatted_messages.append({"role": "assistant", "content": "ok"})
            else:
                # Format user and assistant messages as before
                formatted_messages.append(
                    {
                        "role": "user" if msg.role == MessageRole.USER else "assistant",
                        "content": msg.content,
                    }
                )

        data = {
            "messages": formatted_messages,
            "do_sample": self.do_sample,
            "max_tokens": self.max_tokens,
            "temperature": self.temperature,
            "top_p": self.top_p,
        }

        # Update data payload with additional kwargs if any
        data.update(kwargs)

        headers = {"authorization": f"Key {self.api_key}"}

        response = requests.post(self._endpoint, json=data, headers=headers)
        if response.status_code == 429:
            return ChatResponse(
                message=ChatMessage(
                    role=MessageRole.SYSTEM,
                    content="Rate limited, please try again soon",
                ),
                raw=response.text,
            )
        elif response.ok:
            answer = response.json()["answer"]
            return ChatResponse(
                message=ChatMessage(role=MessageRole.ASSISTANT, content=answer),
                raw=response.json(),
            )
        else:
            response.raise_for_status()  # noqa: RET503

    @llm_completion_callback()
    def complete(
        self, prompt: str, formatted: bool = False, **kwargs: Any
    ) -> CompletionResponse:
        # Prepare the data payload for the Maritalk API
        data = {
            "messages": prompt,
            "do_sample": self.do_sample,
            "max_tokens": self.max_tokens,
            "temperature": self.temperature,
            "top_p": self.top_p,
            "chat_mode": False,
        }

        # Update data payload with additional kwargs if any
        data.update(kwargs)

        headers = {"authorization": f"Key {self.api_key}"}

        response = requests.post(self._endpoint, json=data, headers=headers)
        if response.status_code == 429:
            return CompletionResponse(
                text="Rate limited, please try again soon",
                raw=response.text,
            )
        elif response.ok:
            answer = response.json()["answer"]
            return CompletionResponse(
                text=answer,
                raw=response.json(),
            )
        else:
            response.raise_for_status()  # noqa: RET503

    def stream_chat(
        self, messages: Sequence[ChatMessage], **kwargs: Any
    ) -> ChatResponseGen:
        raise NotImplementedError(
            "Maritalk does not currently support streaming completion."
        )

    def stream_complete(
        self, prompt: str, formatted: bool = False, **kwargs: Any
    ) -> CompletionResponseGen:
        raise NotImplementedError(
            "Maritalk does not currently support streaming completion."
        )

    @llm_chat_callback()
    async def achat(
        self, messages: Sequence[ChatMessage], **kwargs: Any
    ) -> ChatResponse:
        return self.chat(messages, **kwargs)

    @llm_completion_callback()
    async def acomplete(
        self, prompt: str, formatted: bool = False, **kwargs: Any
    ) -> CompletionResponse:
        return self.complete(prompt, formatted, **kwargs)

    @llm_chat_callback()
    async def astream_chat(
        self, messages: Sequence[ChatMessage], **kwargs: Any
    ) -> ChatResponseAsyncGen:
        raise NotImplementedError(
            "Maritalk does not currently support streaming completion."
        )

    @llm_completion_callback()
    async def astream_complete(
        self, prompt: str, formatted: bool = False, **kwargs: Any
    ) -> CompletionResponseAsyncGen:
        raise NotImplementedError(
            "Maritalk does not currently support streaming completion."
        )