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.

feat: support gemini in AI Assist and mo.ui.chat() (#2479)

Myles Scolnick56f62da01e2d
diff --git a/docs/api/inputs/chat.md b/docs/api/inputs/chat.md
index a0fe6f31ae..86deae6cd2 100644
--- a/docs/api/inputs/chat.md
+++ b/docs/api/inputs/chat.md
@@ -98,38 +98,68 @@ This example demonstrates how you can implement a Retrieval-Augmented Generation
marimo provides several built-in AI models that you can use with the chat UI element.
+### OpenAI
+
```python
import marimo as mo
mo.ui.chat(
- mo.ai.openai(
- "gpt-4",
+ mo.ai.llm.openai(
+ "gpt-4o",
system_message="You are a helpful assistant.",
- api_key="sk-...",
+ api_key="sk-proj-...",
),
show_configuration_controls=True
)
+```
+
+```{eval-rst}
+.. autoclass:: marimo.ai.llm.openai
+ :members:
+
+ .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.openai
+```
+
+### Anthropic
+
+```python
+import marimo as mo
mo.ui.chat(
- mo.ai.anthropic(
+ mo.ai.llm.anthropic(
"claude-3-5-sonnet-20240602",
system_message="You are a helpful assistant.",
- api_key="sk-...",
+ api_key="sk-ant-...",
),
show_configuration_controls=True
)
```
```{eval-rst}
-.. autoclass:: marimo.ai.models.openai
+.. autoclass:: marimo.ai.llm.anthropic
:members:
- .. autoclasstoc:: marimo._plugins.ui._impl.chat.models.openai
+ .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.anthropic
+```
+
+### Google AI
+
+```python
+import marimo as mo
+
+mo.ui.chat(
+ mo.ai.llm.google(
+ "gemini-1.5-pro-latest",
+ system_message="You are a helpful assistant.",
+ api_key="AI..",
+ ),
+ show_configuration_controls=True
+)
```
```{eval-rst}
-.. autoclass:: marimo.ai.models.anthropic
+.. autoclass:: marimo.ai.llm.google
:members:
- .. autoclasstoc:: marimo._plugins.ui._impl.chat.models.anthropic
+ .. autoclasstoc:: marimo._plugins.ui._impl.chat.llm.google
```
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.md
index 9e0ac4b758..0bee37da68 100644
--- a/docs/guides/editor_features/ai_completion.md
+++ b/docs/guides/editor_features/ai_completion.md
@@ -36,6 +36,7 @@ codeium_api_key = ""
```
### Alternative: Obtain Codeium API key using VS Code
+
1. Go to the Codeium website and sign up for an account: <https://codeium.com/>
2. Install the [Codeium Visual Studio Code extension](vscode:extension/codeium.codeium) (see [here](https://codeium.com/vscode_tutorial) for complete guide)
3. Sign in to your Codeium account in the VS Code extension
@@ -95,7 +96,7 @@ the bottom of your notebook. You can also refactor existing cells by inputting
```toml
[ai.open_ai]
# Get your API key from https://platform.openai.com/account/api-keys
-api_key = "sk-..."
+api_key = "sk-proj-..."
# Choose a model, we recommend "gpt-4-turbo"
model = "gpt-4-turbo"
# Change the base_url if you are using a different OpenAI-compatible API
@@ -115,7 +116,7 @@ model = "claude-3-5-sonnet-20240620"
# or any model from https://docs.anthropic.com/en/docs/about-claude/models
[ai.anthropic]
-api_key = "sk-..."
+api_key = "sk-ant-..."
```
### Using other AI providers
@@ -143,3 +144,22 @@ api_key = "ollama" # This is not used, but required
model = "llama2" # or the model you downloaded from above
base_url = "http://localhost:11434/v1"
```
+
+### Using Google AI
+
+To use Google AI with marimo:
+
+1. Sign up for an account at [Google AI Studio](https://aistudio.google.com/app/apikey) and obtain your API key.
+2. Install the Google AI Python client: `pip install google-generativeai`
+3. Add the following to your `marimo.toml`:
+
+```toml
+[ai.open_ai]
+model = "gemini-1.5-flash"
+# or any model from https://ai.google.dev/gemini-api/docs/models/gemini
+
+[ai.google]
+api_key = "AI..."
+```
+
+You can now use Google AI for code generation and refactoring in marimo.
diff --git a/examples/ai/simple_chatbot.py b/examples/ai/simple_chatbot.py
index e1987a1656..8b18df080c 100644
--- a/examples/ai/simple_chatbot.py
+++ b/examples/ai/simple_chatbot.py
@@ -56,7 +56,7 @@ def __(client, ell, mo):
mo.ui.chat(
- mo.ai.models.simple(_my_model),
+ mo.ai.llm.simple(_my_model),
prompts=[
"Hello",
"How are you?",
diff --git a/frontend/src/components/app-config/constants.ts b/frontend/src/components/app-config/constants.ts
new file mode 100644
index 0000000000..0b47dac5bf
--- /dev/null
+++ b/frontend/src/components/app-config/constants.ts
@@ -0,0 +1,23 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+export const KNOWN_AI_MODELS = [
+ // OpenAI
+ "gpt-4o",
+ "gpt-4-turbo",
+ "gpt-4",
+ "gpt-3.5-turbo",
+
+ // Anthropic
+ "claude-3-opus-20240229",
+ "claude-3-sonnet-20240229",
+ "claude-3-haiku-20240307",
+ "claude-3-5-sonnet-20240620",
+
+ // Google
+ "gemini-pro",
+ "gemini-1.5-pro-001",
+ "gemini-1.5-flash-001",
+ "gemini-1.5-pro-001",
+ "gemini-1.5-flash-002",
+ "gemini-1.5-pro-002",
+ "gemini-1.5-flash-002",
+] as const;
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index ab9c89874d..936656761b 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -1,10 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { SettingSubtitle } from "./common";
-import React, { useRef, useState } from "react";
+import React, { useRef } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
-import { useSetAtom } from "jotai";
+import { atom, useAtom, useSetAtom } from "jotai";
import {
Form,
FormControl,
@@ -42,6 +42,7 @@ import {
BrainIcon,
} from "lucide-react";
import { cn } from "@/utils/cn";
+import { KNOWN_AI_MODELS } from "./constants";
const formItemClasses = "flex flex-row items-center space-x-1 space-y-0";
@@ -80,12 +81,14 @@ const categories = [
type CategoryId = (typeof categories)[number]["id"];
+export const activeUserConfigCategoryAtom = atom<CategoryId>(categories[0].id);
+
export const UserConfigForm: React.FC = () => {
const [config, setConfig] = useUserConfig();
const formElement = useRef<HTMLFormElement>(null);
const setKeyboardShortcutsOpen = useSetAtom(keyboardShortcutsAtom);
- const [activeCategory, setActiveCategory] = useState<CategoryId>(
- categories[0].id,
+ const [activeCategory, setActiveCategory] = useAtom(
+ activeUserConfigCategoryAtom,
);
// Create form
@@ -736,6 +739,7 @@ export const UserConfigForm: React.FC = () => {
<FormLabel>Model</FormLabel>
<FormControl>
<Input
+ list="ai-model-datalist"
data-testid="ai-model-input"
className="m-0 inline-flex"
placeholder="gpt-4-turbo"
@@ -744,14 +748,143 @@ export const UserConfigForm: React.FC = () => {
</FormControl>
<FormMessage />
</FormItem>
+ <datalist id="ai-model-datalist">
+ {KNOWN_AI_MODELS.map((model) => (
+ <option value={model} key={model}>
+ {model}
+ </option>
+ ))}
+ </datalist>
<FormDescription>
If the model starts with "claude-", we will use your
- Anthropic API key. Otherwise, we will use your OpenAI API
- key.
+ Anthropic API key. If the model starts with "gemini-", we
+ will use your Google AI API key. Otherwise, we will use
+ your OpenAI API key.
</FormDescription>
</div>
)}
/>
+ <SettingGroup title="AI Keys">
+ <FormField
+ control={form.control}
+ name="ai.open_ai.api_key"
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>OpenAI API Key</FormLabel>
+ <FormControl>
+ <Input
+ data-testid="ai-openai-api-key-input"
+ className="m-0 inline-flex"
+ placeholder="sk-proj..."
+ {...field}
+ onChange={(e) => {
+ const value = e.target.value;
+ // Don't allow *
+ if (!value.includes("*")) {
+ field.onChange(value);
+ }
+ }}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ <FormDescription>
+ Your OpenAI API key from{" "}
+ <a
+ className="text-link hover:underline"
+ href="https://platform.openai.com/account/api-keys"
+ target="_blank"
+ rel="noreferrer"
+ >
+ platform.openai.com
+ </a>
+ .
+ </FormDescription>
+ </div>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="ai.anthropic.api_key"
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>Anthropic API Key</FormLabel>
+ <FormControl>
+ <Input
+ data-testid="ai-anthropic-api-key-input"
+ className="m-0 inline-flex"
+ placeholder="sk-ant..."
+ {...field}
+ onChange={(e) => {
+ const value = e.target.value;
+ // Don't allow *
+ if (!value.includes("*")) {
+ field.onChange(value);
+ }
+ }}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ <FormDescription>
+ Your Anthropic API key from{" "}
+ <a
+ className="text-link hover:underline"
+ href="https://console.anthropic.com/settings/keys"
+ target="_blank"
+ rel="noreferrer"
+ >
+ console.anthropic.com
+ </a>
+ .
+ </FormDescription>
+ </div>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="ai.google.api_key"
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>Google AI API Key</FormLabel>
+ <FormControl>
+ <Input
+ data-testid="ai-google-api-key-input"
+ className="m-0 inline-flex"
+ placeholder="AI..."
+ {...field}
+ onChange={(e) => {
+ const value = e.target.value;
+ // Don't allow *
+ if (!value.includes("*")) {
+ field.onChange(value);
+ }
+ }}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ <FormDescription>
+ Your Google AI API key from{" "}
+ <a
+ className="text-link hover:underline"
+ href="https://aistudio.google.com/app/apikey"
+ target="_blank"
+ rel="noreferrer"
+ >
+ aistudio.google.com
+ </a>
+ .
+ </FormDescription>
+ </div>
+ )}
+ />
+ </SettingGroup>
</SettingGroup>
<SettingGroup title="AI Code Completion">
<p className="text-sm text-muted-secondary">
diff --git a/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx b/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx
index 6acca383b4..adad1b0111 100644
--- a/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx
@@ -1,19 +1,68 @@
/* Copyright 2024 Marimo. All rights reserved. */
import React from "react";
-import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/utils/cn";
import { Spinner } from "@/components/icons/spinner";
import {
isGitHubCopilotSignedInState,
githubCopilotLoadingVersion,
} from "@/core/codemirror/copilot/state";
-import { atom, useAtomValue } from "jotai";
-import { userConfigAtom } from "@/core/config/config";
+import { atom, useAtomValue, useSetAtom } from "jotai";
+import { aiEnabledAtom, userConfigAtom } from "@/core/config/config";
import { GitHubCopilotIcon } from "@/components/icons/github-copilot";
+import { SparklesIcon } from "lucide-react";
+import { FooterItem } from "./footer-item";
+import { activeUserConfigCategoryAtom } from "@/components/app-config/user-config-form";
+import { settingDialogAtom } from "@/components/app-config/app-config-button";
+
+export const AIStatusIcon: React.FC = () => {
+ const ai = useAtomValue(aiAtom);
+ const aiEnabled = useAtomValue(aiEnabledAtom);
+ const model = ai.open_ai.model || "gpt-4-turbo";
+ const { handleClick } = useOpenAISettings();
+
+ if (!aiEnabled) {
+ return (
+ <FooterItem
+ tooltip="Assist is disabled"
+ selected={false}
+ onClick={handleClick}
+ >
+ <SparklesIcon className="h-4 w-4 opacity-60" />
+ </FooterItem>
+ );
+ }
+
+ return (
+ <FooterItem
+ tooltip={
+ <>
+ <b>Assist model:</b> {model}
+ </>
+ }
+ onClick={handleClick}
+ selected={false}
+ >
+ <SparklesIcon className="h-4 w-4" />
+ </FooterItem>
+ );
+};
const copilotAtom = atom((get) => {
return get(userConfigAtom).completion.copilot;
});
+const aiAtom = atom((get) => {
+ return get(userConfigAtom).ai;
+});
+
+export function useOpenAISettings() {
+ const setActiveCategory = useSetAtom(activeUserConfigCategoryAtom);
+ const setSettingsDialog = useSetAtom(settingDialogAtom);
+ const handleClick = () => {
+ setActiveCategory("ai");
+ setSettingsDialog(true);
+ };
+ return { handleClick };
+}
export const CopilotStatusIcon: React.FC = () => {
const copilot = useAtomValue(copilotAtom);
@@ -30,11 +79,20 @@ export const CopilotStatusIcon: React.FC = () => {
const GitHubCopilotStatus: React.FC = () => {
const isGitHubCopilotSignedIn = useAtomValue(isGitHubCopilotSignedInState);
const isLoading = useAtomValue(githubCopilotLoadingVersion) !== null;
+ const { handleClick } = useOpenAISettings();
const label = isGitHubCopilotSignedIn ? "Ready" : "Not connected";
return (
- <Tooltip content={`GitHub Copilot: ${label}`}>
+ <FooterItem
+ tooltip={
+ <>
+ <b>GitHub Copilot:</b> {label}
+ </>
+ }
+ selected={false}
+ onClick={handleClick}
+ >
<span>
{isLoading ? (
<Spinner className="h-4 w-4" />
@@ -44,6 +102,6 @@ const GitHubCopilotStatus: React.FC = () => {
/>
)}
</span>
- </Tooltip>
+ </FooterItem>
);
};
diff --git a/frontend/src/components/editor/chrome/wrapper/footer-item.tsx b/frontend/src/components/editor/chrome/wrapper/footer-item.tsx
new file mode 100644
index 0000000000..77b00f2370
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/footer-item.tsx
@@ -0,0 +1,38 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { Tooltip } from "@/components/ui/tooltip";
+import { cn } from "@/utils/cn";
+import type React from "react";
+import type { PropsWithChildren } from "react";
+
+export const FooterItem: React.FC<
+ PropsWithChildren<
+ {
+ selected: boolean;
+ tooltip: React.ReactNode;
+ } & React.HTMLAttributes<HTMLDivElement>
+ >
+> = ({ children, tooltip, selected, className, ...rest }) => {
+ const content = (
+ <div
+ className={cn(
+ "h-full flex items-center p-2 text-sm shadow-inset font-mono cursor-pointer rounded",
+ !selected && "hover:bg-[var(--sage-3)]",
+ selected && "bg-[var(--sage-4)]",
+ className,
+ )}
+ {...rest}
+ >
+ {children}
+ </div>
+ );
+
+ if (tooltip) {
+ return (
+ <Tooltip content={tooltip} side="top" delayDuration={200}>
+ {content}
+ </Tooltip>
+ );
+ }
+
+ return content;
+};
diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsx
index aa2566e1f2..c89f5ee142 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx
@@ -1,6 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type React from "react";
-import type { PropsWithChildren } from "react";
import { cn } from "@/utils/cn";
import { useChromeActions, useChromeState } from "../state";
import { Tooltip } from "@/components/ui/tooltip";
@@ -27,6 +26,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ChevronDownIcon } from "lucide-react";
+import { FooterItem } from "./footer-item";
export const Footer: React.FC = () => {
const { selectedPanel, isTerminalOpen } = useChromeState();
@@ -199,36 +199,3 @@ export const Footer: React.FC = () => {
</footer>
);
};
-
-const FooterItem: React.FC<
- PropsWithChildren<
- {
- selected: boolean;
- tooltip: React.ReactNode;
- } & React.HTMLAttributes<HTMLDivElement>
- >
-> = ({ children, tooltip, selected, className, ...rest }) => {
- const content = (
- <div
- className={cn(
- "h-full flex items-center p-2 text-sm mx-[1px] shadow-inset font-mono cursor-pointer rounded",
- !selected && "hover:bg-[var(--sage-3)]",
- selected && "bg-[var(--sage-4)]",
- className,
- )}
- {...rest}
- >
- {children}
- </div>
- );
-
- if (tooltip) {
- return (
- <Tooltip content={tooltip} side="top" delayDuration={200}>
- {content}
- </Tooltip>
- );
- }
-
- return content;
-};
diff --git a/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx b/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx
index 0c4b774a41..d2ae9f451b 100644
--- a/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx
@@ -18,7 +18,7 @@ import {
} from "lucide-react";
import type React from "react";
import { useState } from "react";
-import { CopilotStatusIcon } from "./copilot-status";
+import { AIStatusIcon, CopilotStatusIcon } from "./copilot-status";
export const MachineStats: React.FC = (props) => {
const [nonce, setNonce] = useState(0);
@@ -40,7 +40,7 @@ export const MachineStats: React.FC = (props) => {
}, [nonce, connection.state]);
return (
- <div className="flex gap-3">
+ <div className="flex gap-2 items-center">
{data && (
<MemoryUsageBar
memory={data.memory}
@@ -49,7 +49,10 @@ export const MachineStats: React.FC = (props) => {
/>
)}
{data && <CPUBar cpu={data.cpu} />}
- <CopilotStatusIcon />
+ <div className="flex items-center">
+ <AIStatusIcon />
+ <CopilotStatusIcon />
+ </div>
<BackendConnection connection={connection.state} />
</div>
);
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index b41f0f1f13..ca9248a8c2 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -106,6 +106,11 @@ export const UserConfigSchema = z
api_key: z.string().optional(),
})
.optional(),
+ google: z
+ .object({
+ api_key: z.string().optional(),
+ })
+ .optional(),
})
.default({}),
experimental: z
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.ts
index a89d1f8692..ebbb373753 100644
--- a/frontend/src/core/config/config.ts
+++ b/frontend/src/core/config/config.ts
@@ -44,7 +44,9 @@ export const aiEnabledAtom = atom<boolean>((get) => {
export function isAiEnabled(config: UserConfig) {
return (
- Boolean(config.ai.open_ai?.api_key) || Boolean(config.ai.anthropic?.api_key)
+ Boolean(config.ai.open_ai?.api_key) ||
+ Boolean(config.ai.anthropic?.api_key) ||
+ Boolean(config.ai.google?.api_key)
);
}
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index bcf7786504..78c7a5eb87 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -173,10 +173,12 @@ class AiConfig(TypedDict):
- `open_ai`: the OpenAI config
- `anthropic`: the Anthropic config
+ - `google`: the Google AI config
"""
open_ai: OpenAiConfig
anthropic: AnthropicConfig
+ google: GoogleAiConfig
@dataclass
@@ -208,6 +210,18 @@ class AnthropicConfig(TypedDict):
api_key: str
+@dataclass
+class GoogleAiConfig(TypedDict):
+ """Configuration options for Google AI.
+
+ **Keys.**
+
+ - `api_key`: the Google AI API key
+ """
+
+ api_key: str
+
+
@mddoc
@dataclass
class MarimoConfig(TypedDict):
@@ -316,7 +330,11 @@ def mask_secrets(config: MarimoConfig) -> MarimoConfig:
else:
deep_remove_from_path(path[1:], cast(Dict[str, Any], obj[key]))
- secrets = [["ai", "open_ai", "api_key"], ["ai", "anthropic", "api_key"]]
+ secrets = [
+ ["ai", "open_ai", "api_key"],
+ ["ai", "anthropic", "api_key"],
+ ["ai", "google", "api_key"],
+ ]
new_config = _deep_copy(config)
for secret in secrets:
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index a5810a4aca..982ca09015 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -18,9 +18,9 @@ class Dependency:
def has(self) -> bool:
"""Return True if the dependency is installed."""
- has_dep = importlib.util.find_spec(self.pkg) is not None
- if not has_dep:
- return False
+ for pkg in self.pkg.split("."):
+ if importlib.util.find_spec(pkg) is None:
+ return False
if self.min_version or self.max_version:
self.warn_if_mismatch_version(self.min_version, self.max_version)
@@ -161,6 +161,7 @@ class DependencyManager:
geopandas = Dependency("geopandas")
opentelemetry = Dependency("opentelemetry")
anthropic = Dependency("anthropic")
+ google_ai = Dependency("google.generativeai")
@staticmethod
def has(pkg: str) -> bool:
diff --git a/marimo/_plugins/ai/__init__.py b/marimo/_plugins/ai/__init__.py
index 1ea6d3eab9..1371b8dd98 100644
--- a/marimo/_plugins/ai/__init__.py
+++ b/marimo/_plugins/ai/__init__.py
@@ -4,7 +4,7 @@
from __future__ import annotations
__all__ = [
- "models",
+ "llm",
]
-from marimo._plugins.ui._impl.chat import models
+from marimo._plugins.ui._impl.chat import llm
diff --git a/marimo/_plugins/ui/_impl/chat/convert.py b/marimo/_plugins/ui/_impl/chat/convert.py
index 91a2d41a5f..2a5c709954 100644
--- a/marimo/_plugins/ui/_impl/chat/convert.py
+++ b/marimo/_plugins/ui/_impl/chat/convert.py
@@ -60,3 +60,27 @@ def convert_to_anthropic_messages(
anthropic_messages.append({"role": message.role, "content": parts})
return anthropic_messages
+
+
+def convert_to_google_messages(
+ messages: List[ChatMessage],
+) -> List[Dict[Any, Any]]:
+ google_messages: List[Dict[Any, Any]] = []
+
+ for message in messages:
+ content = message.content
+ if message.attachments:
+ for attachment in message.attachments:
+ if attachment.content_type.startswith("image"):
+ content += f"\n[Image: {attachment.url}]"
+ elif attachment.content_type.startswith("text"):
+ content += f"\n[Text: {attachment.url}]"
+
+ google_messages.append(
+ {
+ "role": "user" if message.role == "user" else "model",
+ "parts": [content],
+ }
+ )
+
+ return google_messages
diff --git a/marimo/_plugins/ui/_impl/chat/models.py b/marimo/_plugins/ui/_impl/chat/llm.py
similarity index 73%
rename from marimo/_plugins/ui/_impl/chat/models.py
rename to marimo/_plugins/ui/_impl/chat/llm.py
index 2f60d5480b..3589494cc3 100644
--- a/marimo/_plugins/ui/_impl/chat/models.py
+++ b/marimo/_plugins/ui/_impl/chat/llm.py
@@ -7,6 +7,7 @@ from typing import Callable, List, Optional, cast
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.chat.convert import (
convert_to_anthropic_messages,
+ convert_to_google_messages,
convert_to_openai_messages,
)
from marimo._plugins.ui._impl.chat.types import (
@@ -227,3 +228,82 @@ class anthropic(ChatModel):
elif content[0].type == "tool_use":
return content
return ""
+
+
+class google(ChatModel):
+ """
+ Google AI ChatModel
+
+ **Args:**
+
+ - model (str): The model to use.
+ - system_message (str): The system message to use
+ - api_key (Optional[str]): The API key to use.
+ If not provided, the API key will be retrieved
+ from the GOOGLE_AI_API_KEY environment variable
+ or the user's config.
+ """
+
+ def __init__(
+ self,
+ model: str,
+ *,
+ system_message: str = DEFAULT_SYSTEM_MESSAGE,
+ api_key: Optional[str] = None,
+ ):
+ self.model = model
+ self.system_message = system_message
+ self.api_key = api_key
+
+ @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 user's config
+ try:
+ from marimo._runtime.context.types import get_context
+
+ api_key = get_context().user_config["ai"]["google"]["api_key"]
+ if api_key:
+ return api_key
+ except Exception:
+ pass
+
+ # Then check the environment variable
+ env_key = os.environ.get("GOOGLE_AI_API_KEY")
+ if env_key is not None:
+ return env_key
+
+ raise ValueError(
+ "Google AI api key not provided. Pass it as an argument or "
+ "set GOOGLE_AI_API_KEY as an environment variable"
+ )
+
+ def __call__(
+ self, messages: List[ChatMessage], config: ChatModelConfig
+ ) -> object:
+ DependencyManager.google_ai.require(
+ "chat model requires google. `pip install google-generativeai`"
+ )
+ import google.generativeai as genai # type: ignore[import-not-found]
+
+ genai.configure(api_key=self._require_api_key)
+ client = genai.GenerativeModel(
+ model_name=self.model,
+ generation_config=genai.GenerationConfig(
+ max_output_tokens=config.max_tokens,
+ temperature=config.temperature,
+ top_p=config.top_p,
+ top_k=config.top_k,
+ frequency_penalty=config.frequency_penalty,
+ presence_penalty=config.presence_penalty,
+ ),
+ )
+
+ google_messages = convert_to_google_messages(messages)
+ response = client.generate_content(google_messages)
+
+ content = response.text
+ return content or ""
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index ef2e207d71..c2631ce657 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -26,6 +26,12 @@ if TYPE_CHECKING:
from anthropic.types import ( # type: ignore[import-not-found]
RawMessageStreamEvent,
)
+ from google.generativeai import ( # type: ignore[import-not-found]
+ GenerativeModel,
+ )
+ from google.generativeai.types import ( # type: ignore[import-not-found]
+ GenerateContentResponse,
+ )
from openai import ( # type: ignore[import-not-found]
OpenAI,
Stream as OpenAiStream,
@@ -125,12 +131,17 @@ def get_model(config: MarimoConfig) -> str:
def get_content(
- response: RawMessageStreamEvent | ChatCompletionChunk,
+ response: RawMessageStreamEvent
+ | ChatCompletionChunk
+ | GenerateContentResponse,
) -> str | None:
if hasattr(response, "choices"):
return response.choices[0].delta.content # type: ignore
- from anthropic.types import (
+ if hasattr(response, "text"):
+ return response.text # type: ignore
+
+ from anthropic.types import ( # type: ignore[import-not-found]
RawContentBlockDeltaEvent,
TextDelta,
)
@@ -144,7 +155,8 @@ def get_content(
def make_stream_response(
response: OpenAiStream[ChatCompletionChunk]
- | AnthropicStream[RawMessageStreamEvent],
+ | AnthropicStream[RawMessageStreamEvent]
+ | GenerateContentResponse,
) -> Generator[str, None, None]:
original_content = ""
buffer = ""
@@ -197,6 +209,47 @@ def make_stream_response(
LOGGER.debug(f"Completion content: {original_content}")
+def get_google_client(config: MarimoConfig, model: str) -> "GenerativeModel":
+ try:
+ import google.generativeai as genai # type: ignore[import-not-found]
+ except ImportError:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail=(
+ "Google AI not installed. "
+ "Run `pip install google-generativeai`"
+ ),
+ ) from None
+
+ if "ai" not in config or "google" not in config["ai"]:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Google AI not configured",
+ )
+ if "api_key" not in config["ai"]["google"]:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Google AI API key not configured",
+ )
+
+ key: str = config["ai"]["google"]["api_key"]
+
+ if not key:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Google AI API key not configured",
+ )
+
+ genai.configure(api_key=key)
+ return genai.GenerativeModel(
+ model_name=model,
+ generation_config=genai.GenerationConfig(
+ max_output_tokens=1000,
+ temperature=0,
+ ),
+ )
+
+
@router.post("/completion")
@requires("edit")
async def ai_completion(
@@ -253,6 +306,19 @@ async def ai_completion(
media_type="application/json",
)
+ # If the model starts with google/gemini, use Google AI
+ if model.startswith("google") or model.startswith("gemini"):
+ google_client = get_google_client(config, model)
+ google_response = google_client.generate_content(
+ contents=prompt,
+ stream=True,
+ )
+
+ return StreamingResponse(
+ content=make_stream_response(google_response),
+ media_type="application/json",
+ )
+
openai_client = get_openai_client(config)
response = openai_client.chat.completions.create(
model=get_model(config),
diff --git a/marimo/_smoke_tests/chat/chatbot.py b/marimo/_smoke_tests/chat/chatbot.py
index ab7efa38bc..3e0dd6a69a 100644
--- a/marimo/_smoke_tests/chat/chatbot.py
+++ b/marimo/_smoke_tests/chat/chatbot.py
@@ -30,7 +30,7 @@ def __(mo):
@app.cell
def __(mo):
mo.ui.chat(
- mo.ai.models.openai(
+ mo.ai.llm.openai(
"gpt-4-turbo", system_message="You are a helpful data scientist"
),
show_configuration_controls=True,
@@ -52,7 +52,7 @@ def __(mo):
@app.cell
def __(mo):
mo.ui.chat(
- mo.ai.models.anthropic("claude-3-5-sonnet-20240620"),
+ mo.ai.llm.anthropic("claude-3-5-sonnet-20240620"),
show_configuration_controls=True,
prompts=[
"Tell me a joke",
@@ -121,7 +121,7 @@ def __(client, ell, mo):
return prompt
- mo.ui.chat(mo.ai.models.simple(_my_model))
+ mo.ui.chat(mo.ai.llm.simple(_my_model))
return
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 534ce11be5..05e7b0e7b4 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1037,6 +1037,13 @@ components:
required:
- api_key
type: object
+ google:
+ properties:
+ api_key:
+ type: string
+ required:
+ - api_key
+ type: object
open_ai:
properties:
api_key:
@@ -1053,6 +1060,7 @@ components:
required:
- open_ai
- anthropic
+ - google
type: object
completion:
properties:
@@ -1911,7 +1919,7 @@ components:
type: object
info:
title: marimo API
- version: 0.8.18
+ version: 0.8.22
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index ac16fb1376..0cb9c0108c 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2389,6 +2389,9 @@ export interface components {
anthropic: {
api_key: string;
};
+ google: {
+ api_key: string;
+ };
open_ai: {
api_key: string;
base_url: string;
diff --git a/pyproject.toml b/pyproject.toml
index d084c4961c..74f6fb2c15 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -146,6 +146,7 @@ testoptional = [
"openai~=1.41.1",
"ibis-framework[duckdb]~=9.5.0; python_version > \"3.9\"",
"anthropic==0.34.1",
+ "google-generativeai==0.8.2",
# exporting as ipynb
"nbformat >=5.10.4",
"sympy>=1.13.2",
diff --git a/tests/_config/test_config.py b/tests/_config/test_config.py
index ca414ecb11..dcbbac29d5 100644
--- a/tests/_config/test_config.py
+++ b/tests/_config/test_config.py
@@ -55,11 +55,15 @@ def test_merge_config() -> None:
ai={
"open_ai": {
"api_key": "super_secret",
- }
+ },
+ "google": {
+ "api_key": "google_secret",
+ },
},
)
)
assert prev_config["ai"]["open_ai"]["api_key"] == "super_secret"
+ assert prev_config["ai"]["google"]["api_key"] == "google_secret"
new_config = merge_config(
prev_config,
@@ -67,13 +71,18 @@ def test_merge_config() -> None:
ai={
"open_ai": {
"model": "davinci",
- }
+ },
+ "google": {
+ "model": "gemini-1.5-pro",
+ },
},
),
)
assert new_config["ai"]["open_ai"]["api_key"] == "super_secret"
assert new_config["ai"]["open_ai"]["model"] == "davinci"
+ assert new_config["ai"]["google"]["api_key"] == "google_secret"
+ assert new_config["ai"]["google"]["model"] == "gemini-1.5-pro"
def test_merge_config_with_keymap_overrides() -> None:
@@ -121,44 +130,80 @@ def test_merge_config_with_keymap_overrides() -> None:
def test_mask_secrets() -> None:
- config = MarimoConfig(ai={"open_ai": {"api_key": "super_secret"}})
+ config = MarimoConfig(
+ ai={
+ "open_ai": {"api_key": "super_secret"},
+ "anthropic": {"api_key": "anthropic_secret"},
+ "google": {"api_key": "google_secret"},
+ }
+ )
assert config["ai"]["open_ai"]["api_key"] == "super_secret"
+ assert config["ai"]["anthropic"]["api_key"] == "anthropic_secret"
+ assert config["ai"]["google"]["api_key"] == "google_secret"
new_config = mask_secrets(config)
assert new_config["ai"]["open_ai"]["api_key"] == "********"
+ assert new_config["ai"]["anthropic"]["api_key"] == "********"
+ assert new_config["ai"]["google"]["api_key"] == "********"
# Ensure the original config is not modified
assert config["ai"]["open_ai"]["api_key"] == "super_secret"
+ assert config["ai"]["anthropic"]["api_key"] == "anthropic_secret"
+ assert config["ai"]["google"]["api_key"] == "google_secret"
def test_mask_secrets_empty() -> None:
- config = MarimoConfig(ai={"open_ai": {"model": "davinci"}})
+ config = MarimoConfig(
+ ai={
+ "open_ai": {"model": "davinci"},
+ "google": {},
+ "anthropic": {},
+ }
+ )
assert config["ai"]["open_ai"]["model"] == "davinci"
new_config = mask_secrets(config)
assert new_config["ai"]["open_ai"]["model"] == "davinci"
# Not added until the key is present
assert "api_key" not in new_config["ai"]["open_ai"]
-
+ assert "api_key" not in new_config["ai"]["google"]
+ assert "api_key" not in new_config["ai"]["anthropic"]
# Ensure the original config is not modified
assert config["ai"]["open_ai"]["model"] == "davinci"
# Not added when key is ""
config["ai"]["open_ai"]["api_key"] = ""
+ config["ai"]["google"]["api_key"] = ""
+ config["ai"]["anthropic"]["api_key"] = ""
new_config = mask_secrets(config)
assert new_config["ai"]["open_ai"]["api_key"] == ""
+ assert new_config["ai"]["google"]["api_key"] == ""
+ assert new_config["ai"]["anthropic"]["api_key"] == ""
+ # Ensure the original config is not modified
assert config["ai"]["open_ai"]["api_key"] == ""
+ assert config["ai"]["google"]["api_key"] == ""
+ assert config["ai"]["anthropic"]["api_key"] == ""
def test_remove_secret_placeholders() -> None:
- config = MarimoConfig(ai={"open_ai": {"api_key": "********"}})
+ config = MarimoConfig(
+ ai={
+ "open_ai": {"api_key": "********"},
+ "google": {"api_key": "********"},
+ "anthropic": {"api_key": "********"},
+ }
+ )
assert config["ai"]["open_ai"]["api_key"] == "********"
-
+ assert config["ai"]["google"]["api_key"] == "********"
+ assert config["ai"]["anthropic"]["api_key"] == "********"
new_config = remove_secret_placeholders(config)
assert "api_key" not in new_config["ai"]["open_ai"]
-
+ assert "api_key" not in new_config["ai"]["google"]
+ assert "api_key" not in new_config["ai"]["anthropic"]
# Ensure the original config is not modified
assert config["ai"]["open_ai"]["api_key"] == "********"
+ assert config["ai"]["google"]["api_key"] == "********"
+ assert config["ai"]["anthropic"]["api_key"] == "********"
@contextmanager
diff --git a/tests/_plugins/ui/_impl/chat/test_chat_convert.py b/tests/_plugins/ui/_impl/chat/test_chat_convert.py
index a7f9010a8a..a650b1d35d 100644
--- a/tests/_plugins/ui/_impl/chat/test_chat_convert.py
+++ b/tests/_plugins/ui/_impl/chat/test_chat_convert.py
@@ -6,6 +6,7 @@ import pytest
from marimo._plugins.ui._impl.chat.convert import (
convert_to_anthropic_messages,
+ convert_to_google_messages,
convert_to_openai_messages,
)
from marimo._plugins.ui._impl.chat.types import (
@@ -102,10 +103,31 @@ def test_convert_to_anthropic_messages(sample_messages: List[ChatMessage]):
}
+def test_convert_to_google_messages(sample_messages: List[ChatMessage]):
+ result = convert_to_google_messages(sample_messages)
+
+ assert len(result) == 2
+
+ # Check user message
+ assert result[0]["role"] == "user"
+ assert result[0]["parts"] == [
+ "Hello, I have a question.\n"
+ "[Image: http://example.com/image.png]\n"
+ "[Text: http://example.com/text.txt]"
+ ]
+
+ # Check assistant message
+ assert result[1]["role"] == "model"
+ assert result[1]["parts"] == [
+ "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) == []
def test_message_without_attachments():
@@ -133,6 +155,11 @@ def test_message_without_attachments():
"text": "Just a simple message",
}
+ google_result = convert_to_google_messages(messages)
+ assert len(google_result) == 1
+ assert google_result[0]["role"] == "user"
+ assert google_result[0]["parts"] == ["Just a simple message"]
+
def test_from_chat_message_dict():
# Test case 1: ChatMessage with attachments
diff --git a/tests/_plugins/ui/_impl/chat/test_chat_model.py b/tests/_plugins/ui/_impl/chat/test_chat_model.py
index 7780ce8839..33590ca4c3 100644
--- a/tests/_plugins/ui/_impl/chat/test_chat_model.py
+++ b/tests/_plugins/ui/_impl/chat/test_chat_model.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from marimo._plugins.ui._impl.chat.models import simple
+from marimo._plugins.ui._impl.chat.llm import simple
from marimo._plugins.ui._impl.chat.types import ChatMessage, ChatModelConfig
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index 4db4d266e1..a656598b81 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -24,7 +24,9 @@ HEADERS = {
**token_header("fake-token"),
}
-HAS_DEPS = DependencyManager.openai.has()
+HAS_OPEN_AI_DEPS = DependencyManager.openai.has()
+HAS_ANTHROPIC_DEPS = DependencyManager.anthropic.has()
+HAS_GOOGLE_AI_DEPS = DependencyManager.google_ai.has()
# Anthropic
@@ -57,8 +59,10 @@ class FakeChoices:
choices: List[Choice]
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-class TestAiEndpoints:
+ not HAS_OPEN_AI_DEPS, reason="optional dependencies not installed"
+)
+class TestOpenAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
@patch("openai.OpenAI")
@@ -83,14 +87,22 @@ class TestAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("anthropic.Client")
- def test_anthropic_completion_without_token(
- client: TestClient, anthropic_mock: Any
+ @patch("openai.OpenAI")
+ def test_completion_without_code(
+ client: TestClient, openai_mock: Any
) -> None:
- del anthropic_mock
user_config_manager = get_user_config_manager(client)
- with no_anthropic_config(user_config_manager):
+ oaiclient = MagicMock()
+ openai_mock.return_value = oaiclient
+
+ oaiclient.chat.completions.create.return_value = [
+ FakeChoices(
+ choices=[Choice(delta=Delta(content="import pandas as pd"))]
+ )
+ ]
+
+ with openai_config(user_config_manager):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -100,18 +112,17 @@ class TestAiEndpoints:
"code": "",
},
)
- assert response.status_code == 400, response.text
- assert response.json() == {
- "detail": "Anthropic API key not configured"
- }
+ assert response.status_code == 200, "nope"
+ # Assert the prompt it was called with
+ prompt = oaiclient.chat.completions.create.call_args.kwargs[
+ "messages"
+ ][1]["content"]
+ assert prompt == ("Help me create a dataframe")
@staticmethod
@with_session(SESSION_ID)
- @pytest.mark.skipif(
- not HAS_DEPS, reason="optional dependencies not installed"
- )
@patch("openai.OpenAI")
- def test_completion_without_code(
+ def test_completion_with_code(
client: TestClient, openai_mock: Any
) -> None:
user_config_manager = get_user_config_manager(client)
@@ -131,24 +142,23 @@ class TestAiEndpoints:
headers=HEADERS,
json={
"prompt": "Help me create a dataframe",
+ "code": "import pandas as pd",
"include_other_code": "",
- "code": "",
},
)
- assert response.status_code == 200, "nope"
+ assert response.status_code == 200, response.text
# Assert the prompt it was called with
prompt = oaiclient.chat.completions.create.call_args.kwargs[
"messages"
][1]["content"]
- assert prompt == ("Help me create a dataframe")
+ assert prompt == (
+ "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
+ )
@staticmethod
@with_session(SESSION_ID)
- @pytest.mark.skipif(
- not HAS_DEPS, reason="optional dependencies not installed"
- )
@patch("openai.OpenAI")
- def test_completion_with_code(
+ def test_completion_with_custom_model(
client: TestClient, openai_mock: Any
) -> None:
user_config_manager = get_user_config_manager(client)
@@ -162,7 +172,7 @@ class TestAiEndpoints:
)
]
- with openai_config(user_config_manager):
+ with openai_config_custom_model(user_config_manager):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -173,19 +183,73 @@ class TestAiEndpoints:
},
)
assert response.status_code == 200, response.text
- # Assert the prompt it was called with
- prompt = oaiclient.chat.completions.create.call_args.kwargs[
- "messages"
- ][1]["content"]
- assert prompt == (
- "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
+ # Assert the model it was called with
+ model = oaiclient.chat.completions.create.call_args.kwargs["model"]
+ assert model == "gpt-marimo"
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("openai.OpenAI")
+ def test_completion_with_custom_base_url(
+ client: TestClient, openai_mock: Any
+ ) -> None:
+ user_config_manager = get_user_config_manager(client)
+
+ oaiclient = MagicMock()
+ openai_mock.return_value = oaiclient
+
+ oaiclient.chat.completions.create.return_value = [
+ FakeChoices(
+ choices=[Choice(delta=Delta(content="import pandas as pd"))]
+ )
+ ]
+
+ with openai_config_custom_base_url(user_config_manager):
+ response = client.post(
+ "/api/ai/completion",
+ headers=HEADERS,
+ json={
+ "prompt": "Help me create a dataframe",
+ "code": "import pandas as pd",
+ "include_other_code": "",
+ },
+ )
+ assert response.status_code == 200, response.text
+ # Assert the base_url it was called with
+ base_url = openai_mock.call_args.kwargs["base_url"]
+ assert base_url == "https://my-openai-instance.com"
+
+
+ not HAS_ANTHROPIC_DEPS, reason="optional dependencies not installed"
+)
+class TestAnthropicAiEndpoints:
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("anthropic.Client")
+ def test_anthropic_completion_without_token(
+ client: TestClient, anthropic_mock: Any
+ ) -> None:
+ del anthropic_mock
+ user_config_manager = get_user_config_manager(client)
+
+ with no_anthropic_config(user_config_manager):
+ response = client.post(
+ "/api/ai/completion",
+ headers=HEADERS,
+ json={
+ "prompt": "Help me create a dataframe",
+ "include_other_code": "",
+ "code": "",
+ },
)
+ assert response.status_code == 400, response.text
+ assert response.json() == {
+ "detail": "Anthropic API key not configured"
+ }
@staticmethod
@with_session(SESSION_ID)
- @pytest.mark.skipif(
- not HAS_DEPS, reason="optional dependencies not installed"
- )
@patch("anthropic.Client")
def test_anthropic_completion_with_code(
client: TestClient, anthropic_mock: Any
@@ -218,27 +282,27 @@ class TestAiEndpoints:
"Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
)
+
+ not HAS_GOOGLE_AI_DEPS, reason="optional dependencies not installed"
+)
+class TestGoogleAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @pytest.mark.skipif(
- not HAS_DEPS, reason="optional dependencies not installed"
- )
- @patch("openai.OpenAI")
- def test_completion_with_custom_model(
- client: TestClient, openai_mock: Any
+ @patch("google.generativeai.GenerativeModel")
+ def test_google_ai_completion_with_code(
+ client: TestClient, google_ai_mock: Any
) -> None:
user_config_manager = get_user_config_manager(client)
- oaiclient = MagicMock()
- openai_mock.return_value = oaiclient
+ google_client = MagicMock()
+ google_ai_mock.return_value = google_client
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
- choices=[Choice(delta=Delta(content="import pandas as pd"))]
- )
- ]
+ google_client.predict.return_value = MagicMock(
+ text="import pandas as pd"
+ )
- with openai_config_custom_model(user_config_manager):
+ with google_ai_config(user_config_manager):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
@@ -249,44 +313,37 @@ class TestAiEndpoints:
},
)
assert response.status_code == 200, response.text
- # Assert the model it was called with
- model = oaiclient.chat.completions.create.call_args.kwargs["model"]
- assert model == "gpt-marimo"
+ # Assert the prompt it was called with
+ prompt = google_client.generate_content.call_args.kwargs[
+ "contents"
+ ]
+ assert prompt == (
+ "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
+ )
@staticmethod
@with_session(SESSION_ID)
- @pytest.mark.skipif(
- not HAS_DEPS, reason="optional dependencies not installed"
- )
- @patch("openai.OpenAI")
- def test_completion_with_custom_base_url(
- client: TestClient, openai_mock: Any
+ @patch("google.generativeai.GenerativeModel")
+ def test_google_ai_completion_without_token(
+ client: TestClient, google_ai_mock: Any
) -> None:
+ del google_ai_mock
user_config_manager = get_user_config_manager(client)
- oaiclient = MagicMock()
- openai_mock.return_value = oaiclient
-
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
- choices=[Choice(delta=Delta(content="import pandas as pd"))]
- )
- ]
-
- with openai_config_custom_base_url(user_config_manager):
+ with no_google_ai_config(user_config_manager):
response = client.post(
"/api/ai/completion",
headers=HEADERS,
json={
"prompt": "Help me create a dataframe",
- "code": "import pandas as pd",
"include_other_code": "",
+ "code": "",
},
)
- assert response.status_code == 200, response.text
- # Assert the base_url it was called with
- base_url = openai_mock.call_args.kwargs["base_url"]
- assert base_url == "https://my-openai-instance.com"
+ assert response.status_code == 400, response.text
+ assert response.json() == {
+ "detail": "Google AI API key not configured"
+ }
@contextmanager
@@ -384,6 +441,40 @@ def anthropic_config(config: UserConfigManager):
config.save_config(prev_config)
+@contextmanager
+def google_ai_config(config: UserConfigManager):
+ prev_config = config.get_config()
+ try:
+ config.save_config(
+ {
+ "ai": {
+ "open_ai": {"model": "gemini-1.5-pro"},
+ "google": {"api_key": "fake-key"},
+ }
+ }
+ )
+ yield
+ finally:
+ config.save_config(prev_config)
+
+
+@contextmanager
+def no_google_ai_config(config: UserConfigManager):
+ prev_config = config.get_config()
+ try:
+ config.save_config(
+ {
+ "ai": {
+ "open_ai": {"model": "gemini-1.5-pro"},
+ "google": {"api_key": ""},
+ }
+ }
+ )
+ yield
+ finally:
+ config.save_config(prev_config)
+
+
class TestStreamResponse(unittest.TestCase):
def simulate_stream(self, contents: List[str]) -> Any:
class MockContent: