Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Add `Groq` for `mo.ui.chat` (#2757)

Srihari Thyagarajan1f915e1b84e7
diff --git a/docs/api/inputs/chat.md b/docs/api/inputs/chat.md
index a5873ac5ab..bec1af3a0b 100644
--- a/docs/api/inputs/chat.md
+++ b/docs/api/inputs/chat.md
@@ -207,6 +207,35 @@ mo.ui.chat(
)
```
+```{eval-rst}
+.. autoclass:: marimo.ai.llm.google
+ :members:
+
+ .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.google
+```
+
+### Groq
+
+```python
+import marimo as mo
+
+mo.ui.chat(
+ mo.ai.llm.groq(
+ "llama-3.1-70b-versatile",
+ system_message="You are a helpful assistant.",
+ api_key="gsk-...",
+ ),
+ show_configuration_controls=True
+)
+```
+
+```{eval-rst}
+.. autoclass:: marimo.ai.llm.groq
+ :members:
+
+ .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.groq
+```
+
## Types
Chatbots can be implemented with a function that receives a list of
diff --git a/examples/ai/chat/anthropic_example.py b/examples/ai/chat/anthropic_example.py
index ca33948ca9..2277e12460 100644
--- a/examples/ai/chat/anthropic_example.py
+++ b/examples/ai/chat/anthropic_example.py
@@ -75,7 +75,7 @@ def __(key, mo):
@app.cell
def __(mo):
- mo.md("""Access the chatbot's historical messages with `chatbot.value`.""")
+ mo.md("""Access the chatbot's historical messages with [`chatbot.value`](https://docs.marimo.io/api/inputs/chat.html#accessing-chat-history).""")
return
diff --git a/examples/ai/chat/gemini.py b/examples/ai/chat/gemini.py
index be54a2b93d..e5618afdfd 100644
--- a/examples/ai/chat/gemini.py
+++ b/examples/ai/chat/gemini.py
@@ -71,7 +71,7 @@ def __(key, mo):
@app.cell(hide_code=True)
def __(mo):
- mo.md("""Access the chatbot's historical messages with `chatbot.value`.""")
+ mo.md("""Access the chatbot's historical messages with [`chatbot.value`](https://docs.marimo.io/api/inputs/chat.html#accessing-chat-history).""")
return
diff --git a/examples/ai/chat/groq-example.py b/examples/ai/chat/groq-example.py
new file mode 100644
index 0000000000..d5cc7be89f
--- /dev/null
+++ b/examples/ai/chat/groq-example.py
@@ -0,0 +1,104 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "marimo",
+# "groq==0.11.0",
+# "anthropic==0.37.1",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.14"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ # Using Groq
+
+ This example shows how to use [`mo.ui.chat`](https://docs.marimo.io/api/inputs/chat.html#marimo.ui.chat) to make a chatbot backed by [Groq](https://groq.com/).
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ # Hyperlinking the groq as it is mentioned here - https://console.groq.com/docs/badge
+ mo.md(
+ r"""
+ <a href="https://groq.com" target="_blank" rel="noopener noreferrer">
+ <img
+ src="https://groq.com/wp-content/uploads/2024/03/PBG-mark1-color.svg"
+ alt="Powered by Groq for fast inference."
+ width="80" height="800"
+ />
+ </a>
+ """
+ ).right()
+ return
+
+
+def __(mo):
+ import os
+
+ os_key = os.environ.get("GROQ_AI_API_KEY")
+ input_key = mo.ui.text(label="Groq AI API key", kind="password")
+ input_key if not os_key else None
+ return input_key, os, os_key
+
+
+def __(input_key, mo, os_key):
+ key = os_key or input_key.value
+
+ mo.stop(
+ not key,
+ mo.md("Please provide your Groq AI API key in the input field."),
+ )
+ return (key,)
+
+
+def __(key, mo):
+ chatbot = mo.ui.chat(
+ mo.ai.llm.groq(
+ model="llama-3.1-70b-versatile",
+ system_message="You are a helpful assistant.",
+ api_key=key,
+ ),
+ prompts=[
+ "Hello",
+ "How are you?",
+ "I'm doing great, how about you?",
+ ],
+ )
+ chatbot
+ return (chatbot,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md("""Access the chatbot's historical messages with [`chatbot.value`](https://docs.marimo.io/api/inputs/chat.html#accessing-chat-history).""")
+ return
+
+
+def __(chatbot):
+ # chatbot.value is the list of chat messages
+ chatbot.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/ai/chat/openai_example.py b/examples/ai/chat/openai_example.py
index 3f1d113888..3d76b3d59c 100644
--- a/examples/ai/chat/openai_example.py
+++ b/examples/ai/chat/openai_example.py
@@ -74,7 +74,7 @@ def __(mo, openai_key):
@app.cell
def __(mo):
- mo.md("""Access the chatbot's historical messages with `chatbot.value`.""")
+ mo.md("""Access the chatbot's historical messages with [`chatbot.value`](https://docs.marimo.io/api/inputs/chat.html#accessing-chat-history).""")
return
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index aca2a98227..a59dc4ecd5 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -165,6 +165,7 @@ class DependencyManager:
opentelemetry = Dependency("opentelemetry")
anthropic = Dependency("anthropic")
google_ai = Dependency("google.generativeai")
+ groq = Dependency("groq")
panel = Dependency("panel")
@staticmethod
diff --git a/marimo/_plugins/ui/_impl/chat/convert.py b/marimo/_plugins/ui/_impl/chat/convert.py
index a2f7f7bba8..6a00208c82 100644
--- a/marimo/_plugins/ui/_impl/chat/convert.py
+++ b/marimo/_plugins/ui/_impl/chat/convert.py
@@ -82,6 +82,38 @@ def convert_to_anthropic_messages(
return anthropic_messages
+def convert_to_groq_messages(
+ messages: List[ChatMessage],
+) -> List[Dict[Any, Any]]:
+ groq_messages: List[Dict[Any, Any]] = []
+
+ for message in messages:
+ # Currently only supports text content (Llava is deprecated now)
+ # See here - https://console.groq.com/docs/deprecations
+ if message.attachments:
+ # Convert attachments to text if possible
+ text_content = str(message.content) # Explicitly convert to string
+ for attachment in message.attachments:
+ content_type = attachment.content_type or "text/plain"
+ if content_type.startswith("text"):
+ text_content += "\n" + _extract_text(attachment.url)
+
+ groq_messages.append(
+ {"role": message.role, "content": text_content}
+ )
+ else:
+ groq_messages.append(
+ {
+ "role": message.role,
+ "content": str(
+ message.content
+ ), # Explicitly convert to string
+ }
+ )
+
+ return groq_messages
+
+
# Matches from google.generativeai.types import content_types
class BlobDict(TypedDict):
mime_type: str
diff --git a/marimo/_plugins/ui/_impl/chat/llm.py b/marimo/_plugins/ui/_impl/chat/llm.py
index 7208208d4a..6dba99adb1 100644
--- a/marimo/_plugins/ui/_impl/chat/llm.py
+++ b/marimo/_plugins/ui/_impl/chat/llm.py
@@ -8,6 +8,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.chat.convert import (
convert_to_anthropic_messages,
convert_to_google_messages,
+ convert_to_groq_messages,
convert_to_openai_messages,
)
from marimo._plugins.ui._impl.chat.types import (
@@ -140,6 +141,7 @@ class anthropic(ChatModel):
**Args:**
- model: The model to use.
+ Can be found on the [Anthropic models page](https://docs.anthropic.com/en/docs/about-claude/models)
- system_message: The system message to use
- api_key: The API key to use.
If not provided, the API key will be retrieved
@@ -237,6 +239,7 @@ class google(ChatModel):
**Args:**
- model: The model to use.
+ Can be found on the [Gemini models page](https://ai.google.dev/gemini-api/docs/models/gemini)
- system_message: The system message to use
- api_key: The API key to use.
If not provided, the API key will be retrieved
@@ -307,3 +310,87 @@ class google(ChatModel):
content = response.text
return content or ""
+
+
+class groq(ChatModel):
+ """
+ Groq ChatModel
+
+ **Args:**
+
+ - model: The model to use.
+ Can be found on the [Groq models page](https://console.groq.com/docs/models)
+ - system_message: The system message to use
+ - api_key: The API key to use.
+ If not provided, the API key will be retrieved
+ from the GROQ_API_KEY environment variable or the user's config.
+ - base_url: The base URL to use
+ """
+
+ def __init__(
+ self,
+ model: str,
+ *,
+ system_message: str = DEFAULT_SYSTEM_MESSAGE,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ ):
+ self.model = model
+ self.system_message = system_message
+ self.api_key = api_key
+ self.base_url = base_url
+
+ @property
+ def _require_api_key(self) -> str:
+ # If the api key is provided, use it
+ if self.api_key is not None:
+ return self.api_key
+
+ # Then check the environment variable
+ env_key = os.environ.get("GROQ_API_KEY")
+ if env_key is not None:
+ return env_key
+
+ # TODO(haleshot): Add config support later
+ # # Then check the user's config
+ # try:
+ # from marimo._runtime.context.types import get_context
+ #
+ # api_key = get_context().user_config["ai"]["groq"]["api_key"]
+ # if api_key:
+ # return api_key
+ # except Exception:
+ # pass
+
+ raise ValueError(
+ "groq api key not provided. Pass it as an argument or "
+ "set GROQ_API_KEY as an environment variable"
+ )
+
+ def __call__(
+ self, messages: List[ChatMessage], config: ChatModelConfig
+ ) -> object:
+ DependencyManager.groq.require(
+ "chat model requires groq. `pip install groq`"
+ )
+ from groq import Groq # type: ignore[import-not-found]
+
+ client = Groq(api_key=self._require_api_key, base_url=self.base_url)
+
+ groq_messages = convert_to_groq_messages(
+ [ChatMessage(role="system", content=self.system_message)]
+ + messages
+ )
+ response = client.chat.completions.create(
+ model=self.model,
+ messages=groq_messages,
+ max_tokens=config.max_tokens,
+ temperature=config.temperature,
+ top_p=config.top_p,
+ stop=None,
+ stream=False,
+ )
+
+ choice = response.choices[0]
+ content = choice.message.content
+ return content or ""
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index fb66d1eda5..fe3fe347ee 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -53,7 +53,7 @@ def get_openai_client(config: MarimoConfig) -> "OpenAI":
except ImportError:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
- detail="OpenAI not installed. Run `pip install openai`",
+ detail="OpenAI not installed. Add 'openai' using the package installer in the sidebar.",
) from None
if "ai" not in config:
@@ -91,7 +91,7 @@ def get_anthropic_client(config: MarimoConfig) -> "Client":
except ImportError:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
- detail="Anthropic not installed. Run `pip install anthropic`",
+ detail="Anthropic not installed. Add 'anthropic' using the package installer in the sidebar.",
) from None
if "ai" not in config:
@@ -217,7 +217,7 @@ def get_google_client(config: MarimoConfig, model: str) -> "GenerativeModel":
status_code=HTTPStatus.BAD_REQUEST,
detail=(
"Google AI not installed. "
- "Run `pip install google-generativeai`"
+ "Add 'google-generativeai' using the package installer in the sidebar."
),
) from None
diff --git a/marimo/_smoke_tests/chat/chatbot.py b/marimo/_smoke_tests/chat/chatbot.py
index 3e0dd6a69a..6c527da25c 100644
--- a/marimo/_smoke_tests/chat/chatbot.py
+++ b/marimo/_smoke_tests/chat/chatbot.py
@@ -11,17 +11,23 @@
import marimo
-__generated_with = "0.8.20"
+__generated_with = "0.9.14"
app = marimo.App(width="medium")
[email protected](hide_code=True)
+def __():
+ import marimo as mo
+ return (mo,)
+
+
[email protected](hide_code=True)
def __(mo):
mo.md(r"""# Built-in chatbots""")
return
[email protected](hide_code=True)
def __(mo):
mo.md(r"""## OpenAI""")
return
@@ -43,7 +49,7 @@ def __(mo):
return
[email protected](hide_code=True)
def __(mo):
mo.md(r"""## Anthropic""")
return
@@ -63,13 +69,27 @@ def __(mo):
return
-def __():
- import marimo as mo
- return (mo,)
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""## Google Gemini""")
+ return
@app.cell
+def __(mo):
+ mo.ui.chat(
+ mo.ai.llm.google("gemini-1.5-pro-001"),
+ show_configuration_controls=True,
+ prompts=[
+ "Tell me a joke",
+ "What is the meaning of life?",
+ "What is 2 + {{number}}",
+ ],
+ )
+ return
+
+
[email protected](hide_code=True)
def __(mo):
mo.md(r"""# Custom chatbots""")
return
@@ -107,7 +127,7 @@ def __(mo, openai_key):
return client, ell, openai
[email protected](hide_code=True)
def __(mo):
mo.md(r"""## Simple""")
return
@@ -125,7 +145,7 @@ def __(client, ell, mo):
return
[email protected](hide_code=True)
def __(mo):
mo.md(r"""## Complex""")
return
diff --git a/tests/_plugins/ui/_impl/chat/test_chat_convert.py b/tests/_plugins/ui/_impl/chat/test_chat_convert.py
index 8f23d5d9e4..58d584b769 100644
--- a/tests/_plugins/ui/_impl/chat/test_chat_convert.py
+++ b/tests/_plugins/ui/_impl/chat/test_chat_convert.py
@@ -8,6 +8,7 @@ import pytest
from marimo._plugins.ui._impl.chat.convert import (
convert_to_anthropic_messages,
convert_to_google_messages,
+ convert_to_groq_messages,
convert_to_openai_messages,
)
from marimo._plugins.ui._impl.chat.types import (
@@ -134,11 +135,29 @@ def test_convert_to_google_messages(sample_messages: List[ChatMessage]):
]
+def test_convert_to_groq_messages(sample_messages: List[ChatMessage]):
+ result = convert_to_groq_messages(sample_messages)
+
+ assert len(result) == 2
+
+ # Check user message with text attachment
+ assert result[0]["role"] == "user"
+ assert result[0]["content"] == "Hello, I have a question.\nA\n1\n2\n3\n"
+
+ # Check assistant message
+ assert result[1]["role"] == "assistant"
+ assert (
+ result[1]["content"]
+ == "Sure, I'd be happy to help. What's your question?"
+ )
+
+
def test_empty_messages():
empty_messages = []
assert convert_to_openai_messages(empty_messages) == []
assert convert_to_anthropic_messages(empty_messages) == []
assert convert_to_google_messages(empty_messages) == []
+ assert convert_to_groq_messages(empty_messages) == []
def test_message_without_attachments():
@@ -171,6 +190,11 @@ def test_message_without_attachments():
assert google_result[0]["role"] == "user"
assert google_result[0]["parts"] == ["Just a simple message"]
+ groq_result = convert_to_groq_messages(messages)
+ assert len(groq_result) == 1
+ assert groq_result[0]["role"] == "user"
+ assert groq_result[0]["content"] == "Just a simple message"
+
def test_from_chat_message_dict():
# Test case 1: ChatMessage with attachments