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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Add bedrock support (#4988)
Clay Rosenthalb3db90d9db4f
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.mdindex 440b69208d..405ba0eaf8 100644--- a/docs/guides/editor_features/ai_completion.md+++ b/docs/guides/editor_features/ai_completion.md@@ -170,6 +170,39 @@ model = "claude-3-7-sonnet-20250219"api_key = "sk-ant-..."```+#### AWS Bedrock++AWS Bedrock provides access to foundation models from leading AI companies through a unified AWS API.++To use AWS Bedrock with marimo:++1. Set up an [AWS account](https://aws.amazon.com/) with access to the AWS Bedrock service.+2. [Enable model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) for the specific models you want to use in the AWS Bedrock console.+3. Install the boto3 Python client: `pip install boto3`+4. Configure AWS credentials using one of these methods:+ - AWS CLI: Run `aws configure` to set up credentials+ - Environment variables: Set `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`+ - AWS credentials file at `~/.aws/credentials`+5. Add the following to your `marimo.toml`:++```toml title="marimo.toml"+[ai.open_ai]+model = "bedrock/anthropic.claude-3-sonnet-20240229"+# Models are identified by bedrock/provider.model_name+# Examples:+# - bedrock/anthropic.claude-3-sonnet-20240229+# - bedrock/meta.llama3-8b-instruct-v1:0+# - bedrock/amazon.titan-text-express-v1+# - bedrock/cohere.command-r-plus-v1++[ai.bedrock]+region_name = "us-east-1" # AWS region where Bedrock is available+# Optional AWS profile name (from ~/.aws/credentials)+profile_name = "my-profile"+```++If you're using an AWS named profile different from your default, specify the profile_name. For explicit credentials (not recommended), you can use environment variables instead.+#### Google AITo use Google AI with marimo:diff --git a/examples/ai/chat/anthropic_example.py b/examples/ai/chat/anthropic_example.pyindex bc288dcf12..794f76824e 100644--- a/examples/ai/chat/anthropic_example.py+++ b/examples/ai/chat/anthropic_example.py@@ -2,45 +2,46 @@# requires-python = ">=3.11"# dependencies = [# "marimo",+# "anthropic",# ]# ///import marimo-__generated_with = "0.9.9"+__generated_with = "0.13.10"app = marimo.App(width="medium")@app.cell-def __():+def _():import marimo as moreturn (mo,)@app.cell-def __(mo):+def _(mo):mo.md(r"""- # Using Anthropic+ # Using Anthropic- 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 Anthropic.- """+ 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 Anthropic.+ """)return@app.cell-def __(mo):+def _(mo):import osos_key = os.environ.get("ANTHROPIC_API_KEY")input_key = mo.ui.text(label="Anthropic API key", kind="password")input_key if not os_key else None- return input_key, os, os_key+ return input_key, os_key@app.cell-def __(input_key, mo, os_key):+def _(input_key, mo, os_key):key = os_key or input_key.valuemo.stop(@@ -51,7 +52,7 @@ def __(input_key, mo, os_key):@app.cell-def __(key, mo):+def _(key, mo):chatbot = mo.ui.chat(mo.ai.llm.anthropic("claude-3-7-sonnet-20250219",@@ -74,13 +75,13 @@ def __(key, mo):@app.cell-def __(mo):+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@app.cell-def __(chatbot):+def _(chatbot):# chatbot.value is the list of chat messageschatbot.valuereturndiff --git a/examples/ai/chat/bedrock_example.py b/examples/ai/chat/bedrock_example.pynew file mode 100644index 0000000000..3fe235da3a--- /dev/null+++ b/examples/ai/chat/bedrock_example.py@@ -0,0 +1,252 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "boto3",+# "litellm",+# "marimo",+# ]+# ///++import marimo++__generated_with = "0.13.10"+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"""+ # AWS Bedrock Chat Example++ This example demonstrates using AWS Bedrock with marimo's chat interface.++ AWS Bedrock provides access to foundation models from leading AI companies like Anthropic, Meta, and others.++ ⚠️ **Note:** You'll need an AWS account with access to the AWS Bedrock service and the specific model you want to use.+ """+ )+ return++[email protected](hide_code=True)+def _():+ import os+ import boto3+++ # For this example, let's add a helper to check AWS configuration+ def check_aws_config():+ """Check if AWS configuration is available"""+ # Check for credentials+ has_creds = False+ try:+ session = boto3.Session()+ credentials = session.get_credentials()+ if credentials:+ has_creds = True+ except:+ pass++ return {"has_credentials": has_creds}+++ # Run the check+ aws_config = check_aws_config()+ return (aws_config,)+++def _(aws_config, mo):+ # Display AWS configuration status+ mo.stop(+ not aws_config["has_credentials"],+ mo.md("""+ ### ⚠️ AWS Credentials Not Found++ To use AWS Bedrock, you need AWS credentials configured.+ Options:+ 1. Set environment variables:+ ```+ export AWS_ACCESS_KEY_ID=your_key+ export AWS_SECRET_ACCESS_KEY=your_secret+ ```++ 2. Configure AWS CLI:+ ```+ aws configure+ ```++ 3. Use an AWS profile in ~/.aws/credentials+ """),+ )+ return++[email protected](hide_code=True)+def _(mo):+ # UI for model configuration++ # Predefined model options+ model_options = [+ "bedrock/us.amazon.nova-pro-v1:0",+ "bedrock/anthropic.claude-3-sonnet-20240229",+ "bedrock/anthropic.claude-3-haiku-20240307",+ "bedrock/meta.llama3-8b-instruct-v1:0",+ "bedrock/amazon.titan-text-express-v1",+ "bedrock/cohere.command-r-plus-v1",+ ]++ # Region options+ region_options = [+ "us-east-1",+ "us-west-2",+ "eu-central-1",+ "ap-northeast-1",+ "ap-southeast-1",+ ]++ # Model selection+ model = mo.ui.dropdown(+ options=model_options, value=model_options[0], label="AWS Bedrock Model"+ )++ # Region selection+ region = mo.ui.dropdown(+ options=region_options, value="us-east-1", label="AWS Region"+ )++ # Optional profile name+ profile = mo.ui.text(+ value="",+ label="AWS Profile (optional)",+ placeholder="Leave empty to use default credentials",+ )++ # System message+ system_message = mo.ui.text_area(+ value="You are a helpful, harmless assistant. Provide clear, concise answers.",+ label="System Message",+ rows=2,+ )++ # Create a form to wrap all inputs+ config_form = (+ mo.md("""+ AWS Bedrock Chat Configuration:+ {model}+ {region}+ {profile}+ {system_message}+ """)+ .batch(+ model=model,+ region=region,+ profile=profile,+ system_message=system_message,+ )+ .form(+ submit_button_label="Update Chat Configuration",+ )+ )++ config_form+ return (config_form,)+++def _(mo):+ mo.md(r"""## AWS Bedrock Chat""")+ return+++def _(config_form, max_tokens, mo, temperature):+ # Create a refreshable chat component that updates when the form is submitted+ def create_chat(config_form):+ # temperature = config_form.value["temperature"]+ # max_tokens = config_form.value["max_tokens"]+ model = config_form.value["model"]+ region = config_form.value["region"]+ system_message = config_form.value["system_message"]+ profile = config_form.value["profile"]+ try:+ # Create chat config+ chat_config = mo.ai.ChatModelConfig(+ temperature=temperature,+ max_tokens=max_tokens,+ # top_k=1,+ # top_p=1.0,+ # frequency_penalty=1,+ # presence_penalty=1,+ )++ # Create model with optional profile+ model_kwargs = {+ "model": model,+ "region_name": region,+ "system_message": system_message,+ }++ # Add profile if specified+ if profile.strip():+ model_kwargs["profile_name"] = profile.strip()++ # Create chat interface+ chatbot = mo.ui.chat(+ mo.ai.llm.bedrock(**model_kwargs),+ allow_attachments=[+ "image/png",+ "image/jpeg",+ ],+ prompts=[+ "Hello",+ "How are you?",+ "I'm doing great, how about you?",+ ],+ max_height=400,+ config=chat_config,+ )+ return chatbot+ except Exception as e:+ mo.md(f"**Error initializing chat**: {str(e)}")+ return None+++ # Display the chat interface+ chatbot = create_chat(config_form)+ chatbot+ return+++def _(mo):+ mo.md(+ r"""+ ## Notes on AWS Bedrock Usage++ 1. **Model Access**: You need to request access to the specific models you want to use in the AWS Bedrock console.++ 2. **Pricing**: Using AWS Bedrock incurs usage costs based on the number of input and output tokens. Check the [AWS Bedrock pricing](https://aws.amazon.com/bedrock/pricing/) for details.++ 3. **Regions**: AWS Bedrock is not available in all AWS regions. Make sure to choose a region where Bedrock is available.++ 4. **Authentication**: This example uses the standard AWS credential chain (environment variables, AWS config files, or instance profiles). You can also provide explicit credentials when creating the model.++ 5. **Troubleshooting**: If you encounter issues, check:+ - That your AWS credentials are configured correctly+ - That you have requested model access in the AWS Bedrock console+ - That you're using a region where the selected model is available+ """+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/frontend/package.json b/frontend/package.jsonindex 1a2ae65704..937bec8271 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -13,6 +13,7 @@"dist"],"dependencies": {+ "@ai-sdk/react": "^1.2.12","@anywidget/types": "^0.2.0","@codemirror/autocomplete": "^6.18.6","@codemirror/commands": "^6.8.1",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 53a870e8bd..7259bd2d53 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -15,6 +15,9 @@ importers:.:dependencies:+ '@ai-sdk/react':+ specifier: ^1.2.12+ version: 1.2.12([email protected])([email protected])'@anywidget/types':specifier: ^0.2.0version: 0.2.0@@ -650,6 +653,12 @@ packages:peerDependencies:zod: ^3.23.8+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.23.8+'@ai-sdk/[email protected]':resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}engines: {node: '>=18'}@@ -664,12 +673,28 @@ packages:zod:optional: true+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-jK1IZZ22evPZoQW3vlkZ7wvjYGYF+tRBKXtrcolduIkQ/m/sOAVcVeVDUDvh1T91xCnWCdUGCPZg2avZ90mv3g==}+ engines: {node: '>=18'}+ peerDependencies:+ react: ^18 || ^19 || ^19.0.0-rc+ zod: ^3.23.8+ peerDependenciesMeta:+ zod:+ optional: true+'@ai-sdk/[email protected]':resolution: {integrity: sha512-GUj+LBoAlRQF1dL/M49jtufGqtLOMApxTpCmVjoRpIPt/dFALVL9RfqfvxwztyIwbK+IxGzcYjSGRsrWrj+86g==}engines: {node: '>=18'}peerDependencies:zod: ^3.23.8+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.23.8+'@alloc/[email protected]':resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}engines: {node: '>=10'}@@ -9139,6 +9164,13 @@ snapshots:secure-json-parse: 2.7.0zod: 3.24.3+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 1.1.3+ nanoid: 3.3.8+ secure-json-parse: 2.7.0+ zod: 3.24.3+'@ai-sdk/[email protected]':dependencies:json-schema: 0.4.0@@ -9153,6 +9185,16 @@ snapshots:optionalDependencies:zod: 3.24.3+ dependencies:+ '@ai-sdk/provider-utils': 2.2.8([email protected])+ '@ai-sdk/ui-utils': 1.2.11([email protected])+ react: 18.3.1+ swr: 2.2.5([email protected])+ throttleit: 2.1.0+ optionalDependencies:+ zod: 3.24.3+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 1.1.3@@ -9160,6 +9202,13 @@ snapshots:zod: 3.24.3zod-to-json-schema: 3.24.1([email protected])+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 1.1.3+ '@ai-sdk/provider-utils': 2.2.8([email protected])+ zod: 3.24.3+ zod-to-json-schema: 3.24.1([email protected])+'@alloc/[email protected]': {}'@ampproject/[email protected]':diff --git a/frontend/src/components/app-config/constants.ts b/frontend/src/components/app-config/constants.tsindex 66ebcdedc2..9e78f10585 100644--- a/frontend/src/components/app-config/constants.ts+++ b/frontend/src/components/app-config/constants.ts@@ -27,4 +27,26 @@ export const KNOWN_AI_MODELS = ["o1-mini","o1-preview","o3-mini",++ // AWS Bedrock Models+ "bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0",+ "bedrock/anthropic.claude-3-sonnet-20240229",+ "bedrock/anthropic.claude-3-haiku-20240307",+ "bedrock/meta.llama3-8b-instruct-v1:0",+ "bedrock/amazon.titan-text-express-v1",+ "bedrock/us.amazon.nova-pro-v1:0",+ "bedrock/cohere.command-r-plus-v1",+ "bedrock/ai21.j2-ultra-v1",+] as const;++/**+ * AWS regions where the Bedrock service is available+ */+export const AWS_REGIONS = [+ "us-east-1",+ "us-east-2",+ "us-west-2",+ "eu-central-1",+ "ap-northeast-1",+ "ap-southeast-1",] as const;diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 6dd33a670e..0aee2e4941 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -45,7 +45,7 @@ import {} from "lucide-react";import { ExternalLink } from "../ui/links";import { cn } from "@/utils/cn";-import { KNOWN_AI_MODELS } from "./constants";+import { KNOWN_AI_MODELS, AWS_REGIONS } from "./constants";import { Textarea } from "../ui/textarea";import { get } from "lodash-es";import { Tooltip } from "../ui/tooltip";@@ -1187,6 +1187,88 @@ export const UserConfigForm: React.FC = () => {</div>)}/>++ <p className="text-sm font-semibold mt-3">+ AWS Bedrock Configuration+ </p>+ <p className="text-sm text-muted-secondary mb-2">+ To use AWS Bedrock, you need to configure AWS credentials and+ region. See the{" "}+ <ExternalLink href="https://docs.marimo.io/guides/editor_features/ai_completion.html#aws-bedrock">+ documentation+ </ExternalLink>{" "}+ for more details.+ </p>+ <FormField+ control={form.control}+ disabled={isWasmRuntime}+ name="ai.bedrock.region_name"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel>AWS Region</FormLabel>+ <FormControl>+ <NativeSelect+ data-testid="bedrock-region-select"+ onChange={(e) => field.onChange(e.target.value)}+ value={+ typeof field.value === "string"+ ? field.value+ : "us-east-1"+ }+ disabled={field.disabled}+ className="inline-flex mr-2"+ >+ {AWS_REGIONS.map((option) => (+ <option value={option} key={option}>+ {option}+ </option>+ ))}+ </NativeSelect>+ </FormControl>+ <FormMessage />+ <IsOverridden+ userConfig={config}+ name="ai.bedrock.region_name"+ />+ </FormItem>+ <FormDescription>+ The AWS region where Bedrock service is available.+ </FormDescription>+ </div>+ )}+ />++ <FormField+ control={form.control}+ disabled={isWasmRuntime}+ name="ai.bedrock.profile_name"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel>AWS Profile Name (Optional)</FormLabel>+ <FormControl>+ <Input+ data-testid="bedrock-profile-input"+ className="m-0 inline-flex"+ placeholder="default"+ {...field}+ value={field.value || ""}+ />+ </FormControl>+ <FormMessage />+ <IsOverridden+ userConfig={config}+ name="ai.bedrock.profile_name"+ />+ </FormItem>+ <FormDescription>+ The AWS profile name from your ~/.aws/credentials file.+ Leave blank to use your default AWS credentials.+ </FormDescription>+ </div>+ )}+ /></SettingGroup><SettingGroup title="AI Assist">@@ -1259,7 +1341,10 @@ export const UserConfigForm: React.FC = () => {<FormDescription>If the model starts with "claude-", we will use yourAnthropic API key. If the model starts with "gemini-", we- will use your Google AI API key. Otherwise, we will use+ will use your Google AI API key. If the model starts with+ a "bedrock/" prefix followed by a model id (e.g.,+ "bedrock/anthropic.claude-3-sonnet-20240229"), we will use+ your AWS Bedrock configuration. Otherwise, we will useyour OpenAI API key.</FormDescription></div>@@ -1455,7 +1540,10 @@ const SettingGroup = ({const IsOverridden = ({userConfig,name,-}: { userConfig: UserConfig; name: FieldPath<UserConfig> }) => {+}: {+ userConfig: UserConfig;+ name: FieldPath<UserConfig>;+}) => {const currentValue = get(userConfig, name);const overrides = useAtomValue(configOverridesAtom);const overriddenValue = get(overrides as UserConfig, name);diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 0d92354072..316ab29970 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -145,6 +145,14 @@ export const UserConfigSchema = zapi_key: z.string().optional(),}).optional(),+ bedrock: z+ .object({+ region_name: z.string().optional(),+ profile_name: z.string().optional(),+ aws_access_key_id: z.string().optional(),+ aws_secret_access_key: z.string().optional(),+ })+ .optional(),}).passthrough().default({}),diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex ae806c5344..a4047f681f 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -75,7 +75,8 @@ export function isAiEnabled(config: UserConfig) {return (Boolean(config.ai?.open_ai?.api_key) ||Boolean(config.ai?.anthropic?.api_key) ||- Boolean(config.ai?.google?.api_key)+ Boolean(config.ai?.google?.api_key) ||+ Boolean(config.ai?.bedrock?.profile_name));}diff --git a/marimo/_ai/llm/__init__.py b/marimo/_ai/llm/__init__.pyindex 123b6ab311..6f596dc9fa 100644--- a/marimo/_ai/llm/__init__.py+++ b/marimo/_ai/llm/__init__.py@@ -1,4 +1,4 @@# Copyright 2025 Marimo. All rights reserved.-from marimo._ai.llm._impl import anthropic, google, groq, openai+from marimo._ai.llm._impl import anthropic, bedrock, google, groq, openai-__all__ = ["openai", "anthropic", "google", "groq"]+__all__ = ["openai", "anthropic", "google", "groq", "bedrock"]diff --git a/marimo/_ai/llm/_impl.py b/marimo/_ai/llm/_impl.pyindex 886ebc33e2..877cfb14fd 100644--- a/marimo/_ai/llm/_impl.py+++ b/marimo/_ai/llm/_impl.py@@ -411,3 +411,106 @@ class groq(ChatModel):choice = response.choices[0]content = choice.message.contentreturn content or ""+++class bedrock(ChatModel):+ """+ AWS Bedrock ChatModel++ Args:+ model: The model ID to use.+ Format: [<cross-region>.]<provider>.<model> (e.g., "us.anthropic.claude-3-7-sonnet-20250219-v1:0")+ system_message: The system message to use+ region_name: The AWS region to use (e.g., "us-east-1")+ profile_name: The AWS profile to use for credentials (optional)+ credentials: AWS credentials (optional)+ Dict with keys: "aws_access_key_id" and "aws_secret_access_key"+ If not provided, credentials will be retrieved from the environment+ or the AWS configuration files.+ """++ def __init__(+ self,+ model: str,+ *,+ system_message: str = DEFAULT_SYSTEM_MESSAGE,+ region_name: str = "us-east-1",+ profile_name: Optional[str] = None,+ aws_access_key_id: Optional[str] = None,+ aws_secret_access_key: Optional[str] = None,+ ):+ if not model.startswith("bedrock/"):+ model = f"bedrock/{model}"+ self.model = model+ self.system_message = system_message+ self.region_name = region_name+ self.profile_name = profile_name+ self.aws_access_key_id = aws_access_key_id+ self.aws_secret_access_key = aws_secret_access_key++ def _setup_credentials(self) -> None:+ # Use profile name if provided, otherwise use API key+ if self.profile_name:+ os.environ["AWS_PROFILE"] = self.profile_name+ elif self.aws_access_key_id and self.aws_secret_access_key:+ os.environ["AWS_ACCESS_KEY_ID"] = self.aws_access_key_id+ os.environ["AWS_SECRET_ACCESS_KEY"] = self.aws_secret_access_key+ else:+ pass # Use default credential chain++ def __call__(+ self, messages: list[ChatMessage], config: ChatModelConfig+ ) -> object:+ DependencyManager.boto3.require(+ "bedrock chat model requires boto3. `pip install boto3`"+ )+ DependencyManager.litellm.require(+ "bedrock chat model requires litellm. `pip install litellm`"+ )+ from litellm import completion as litellm_completion++ self._setup_credentials()++ try:+ # Make API call+ response = litellm_completion(+ model=self.model,+ messages=convert_to_openai_messages(+ [ChatMessage(role="system", content=self.system_message)]+ + messages+ ),+ max_tokens=config.max_tokens,+ temperature=config.temperature,+ top_p=config.top_p,+ frequency_penalty=config.frequency_penalty,+ presence_penalty=config.presence_penalty,+ stream=False,+ )++ return response.choices[0].message.content++ except Exception as e:+ # Handle common AWS exceptions with helpful messages+ error_msg = str(e)++ if "AccessDenied" in error_msg:+ raise ValueError(+ f"Access denied to AWS Bedrock model {self.model}. "+ "Make sure your credentials have the necessary permissions."+ ) from e+ elif (+ "ValidationException" in error_msg+ and "model id" in error_msg.lower()+ ):+ raise ValueError(+ f"Model {self.model} not found or not enabled for your account. "+ "Make sure you've enabled model access in the AWS Bedrock console."+ ) from e+ elif "ResourceNotFoundException" in error_msg:+ raise ValueError(+ f"Model {self.model} not found in region {self.region_name}. "+ "Check that the model ID is correct and available in this region."+ ) from e+ else:+ # Re-raise original exception if not handled+ raisediff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 734a33213d..f848f544a8 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -230,6 +230,7 @@ class AiConfig(TypedDict, total=False):- `open_ai`: the OpenAI config- `anthropic`: the Anthropic config- `google`: the Google AI config+ - `bedrock`: the Bedrock config"""rules: NotRequired[str]@@ -237,6 +238,7 @@ class AiConfig(TypedDict, total=False):open_ai: OpenAiConfiganthropic: AnthropicConfiggoogle: GoogleAiConfig+ bedrock: BedrockConfig@dataclass@@ -268,7 +270,7 @@ class AnthropicConfig(TypedDict, total=False):**Keys.**- - `api_key`: the Anthropic+ - `api_key`: the Anthropic API key"""api_key: str@@ -286,6 +288,24 @@ class GoogleAiConfig(TypedDict, total=False):api_key: str+@dataclass+class BedrockConfig(TypedDict, total=False):+ """Configuration options for Bedrock.++ **Keys.**++ - `profile_name`: the AWS profile to use+ - `region_name`: the AWS region to use+ - `aws_access_key_id`: the AWS access key ID+ - `aws_secret_access_key`: the AWS secret access key+ """++ profile_name: NotRequired[str]+ region_name: NotRequired[str]+ aws_access_key_id: NotRequired[str]+ aws_secret_access_key: NotRequired[str]++@dataclassclass PythonLanguageServerConfig(TypedDict, total=False):"""diff --git a/marimo/_config/secrets.py b/marimo/_config/secrets.pyindex f508d2d23b..af0a8ae328 100644--- a/marimo/_config/secrets.py+++ b/marimo/_config/secrets.py@@ -32,6 +32,8 @@ def mask_secrets(config: MarimoConfig) -> MarimoConfig:["ai", "open_ai", "api_key"],["ai", "anthropic", "api_key"],["ai", "google", "api_key"],+ ["ai", "bedrock", "aws_access_key_id"],+ ["ai", "bedrock", "aws_secret_access_key"],["runtime", "dotenv"],]diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 3e6fe77750..215405fd88 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -205,6 +205,8 @@ class DependencyManager:)tomlkit = Dependency("tomlkit")loro = Dependency("loro")+ boto3 = Dependency("boto3")+ litellm = Dependency("litellm")# Version requirements to properly support the new superfences introduced in# pymdown#2470diff --git a/marimo/_secrets/load_dotenv.py b/marimo/_secrets/load_dotenv.pyindex 7a215fd423..93593ac5a3 100644--- a/marimo/_secrets/load_dotenv.py+++ b/marimo/_secrets/load_dotenv.py@@ -2,6 +2,7 @@from __future__ import annotationsimport os+from typing import Optionalfrom marimo._dependencies.dependencies import DependencyManager@@ -11,7 +12,7 @@ def load_dotenv_with_fallback(file: str) -> None:implementation if the dotenv library is not installed."""if DependencyManager.dotenv.has():- from dotenv import load_dotenv # type: ignore[import-not-found]+ from dotenv import load_dotenv# By default, load_dotenv does not override existing keys in the# environment.@@ -20,21 +21,21 @@ def load_dotenv_with_fallback(file: str) -> None:load_to_environ(parse_dotenv(file))-def read_dotenv_with_fallback(file: str) -> dict[str, str]:+def read_dotenv_with_fallback(file: str) -> dict[str, Optional[str]]:"""Read a .env file using the dotenv library, falling to our customimplementation if the dotenv library is not installed."""if DependencyManager.dotenv.has():- from dotenv import dotenv_values # type: ignore[import-not-found]+ from dotenv import dotenv_values- return dotenv_values(file) # type: ignore[no-any-return]+ return dotenv_values(file)else:return parse_dotenv(file)-def parse_dotenv(filepath: str) -> dict[str, str]:+def parse_dotenv(filepath: str) -> dict[str, Optional[str]]:"""Parse a .env file into a dictionary of key-value pairs."""- env_dict: dict[str, str] = {}+ env_dict: dict[str, Optional[str]] = {}try:with open(filepath, encoding="utf-8") as f:for line in f:@@ -60,13 +61,15 @@ def parse_dotenv(filepath: str) -> dict[str, str]:return env_dict-def load_to_environ(env_dict: dict[str, str]) -> None:+def load_to_environ(env_dict: dict[str, Optional[str]]) -> None:"""Load a dictionary of key-value pairs into the environment."""for key, value in env_dict.items():if key in os.environ:# By default, load_dotenv does not override existing keys in the# environment, so we should do the same.continue+ if value is None:+ continueos.environ[key] = valuediff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.pyindex aa6f38d4dd..53306f3858 100644--- a/marimo/_server/ai/providers.py+++ b/marimo/_server/ai/providers.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import osfrom abc import ABC, abstractmethodfrom collections.abc import Generator, Iteratorfrom dataclasses import dataclass@@ -40,6 +41,14 @@ if TYPE_CHECKING:from google.generativeai.types import ( # type: ignore[import-not-found]GenerateContentResponse,)++ # Used for Bedrock, unified interface for all models+ from litellm import ( # type: ignore[attr-defined]+ CustomStreamWrapper as LitellmStream,+ )+ from litellm.types.utils import (+ ModelResponseStream as LitellmStreamResponse,+ )from openai import ( # type: ignore[import-not-found]OpenAI,Stream as OpenAiStream,@@ -108,6 +117,19 @@ class AnyProviderConfig:api_key=key,)+ @staticmethod+ def for_bedrock(config: AiConfig) -> AnyProviderConfig:+ if "bedrock" not in config:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Bedrock config not found",+ )+ key = _get_key(config["bedrock"], "Bedrock")+ return AnyProviderConfig(+ base_url=_get_base_url(config["bedrock"], "Bedrock"),+ api_key=key,+ )+@staticmethoddef for_completion(config: CompletionConfig) -> AnyProviderConfig:key = _get_key(config, "AI completion")@@ -118,15 +140,27 @@ class AnyProviderConfig:@staticmethoddef for_model(model: str, config: AiConfig) -> AnyProviderConfig:- if model.startswith("claude"):+ if _model_is_anthropic(model):return AnyProviderConfig.for_anthropic(config)- elif model.startswith("google") or model.startswith("gemini"):+ elif _model_is_google(model):return AnyProviderConfig.for_google(config)+ elif _model_is_bedrock(model):+ return AnyProviderConfig.for_bedrock(config)else:return AnyProviderConfig.for_openai(config)def _get_key(config: Any, name: str) -> str:+ if name == "Bedrock":+ if "profile_name" in config:+ profile_name = config.get("profile_name", "")+ return f"profile:{profile_name}"+ elif (+ "aws_access_key_id" in config and "aws_secret_access_key" in config+ ):+ return f"{config['aws_access_key_id']}:{config['aws_secret_access_key']}"+ else:+ return ""if "api_key" in config:key = config["api_key"]if key:@@ -137,8 +171,13 @@ def _get_key(config: Any, name: str) -> str:)-def _get_base_url(config: Any) -> Optional[str]:- if "base_url" in config:+def _get_base_url(config: Any, name: str = "") -> Optional[str]:+ if name == "Bedrock":+ if "region_name" in config:+ return cast(str, config["region_name"])+ else:+ return None+ elif "base_url" in config:return cast(str, config["base_url"])return None@@ -424,13 +463,88 @@ class GoogleProvider(return None+class BedrockProvider(+ CompletionProvider[+ "LitellmStreamResponse",+ "LitellmStream",+ ]+):+ def setup_credentials(self, config: AnyProviderConfig) -> None:+ # Use profile name if provided, otherwise use API key+ try:+ if config.api_key.startswith("profile:"):+ profile_name = config.api_key.replace("profile:", "")+ os.environ["AWS_PROFILE"] = profile_name+ elif len(config.api_key) > 0:+ # If access_key_id and secret_access_key is provided directly, use it+ aws_access_key_id = config.api_key.split(":")[0]+ aws_secret_access_key = config.api_key.split(":")[1]+ os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id+ os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key+ except Exception as e:+ LOGGER.error(f"{config} Error setting up AWS credentials: {e}")+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Error setting up AWS credentials",+ ) from e++ def stream_completion(+ self,+ messages: list[ChatMessage],+ system_prompt: str,+ max_tokens: int,+ ) -> LitellmStream:+ DependencyManager.litellm.require(why="for AI assistance with Bedrock")+ DependencyManager.boto3.require(why="for AI assistance with Bedrock")+ from litellm import completion as litellm_completion++ self.setup_credentials(self.config)++ return litellm_completion(+ model=self.model,+ messages=cast(+ Any,+ convert_to_openai_messages(+ [ChatMessage(role="system", content=system_prompt)]+ + messages+ ),+ ),+ max_completion_tokens=max_tokens,+ stream=True,+ timeout=15,+ )++ def extract_content(self, response: LitellmStreamResponse) -> str | None:+ if (+ hasattr(response, "choices")+ and response.choices+ and response.choices[0].delta+ ):+ return str(response.choices[0].delta.content)+ return None+++def _model_is_google(model: str) -> bool:+ return model.startswith("google") or model.startswith("gemini")+++def _model_is_anthropic(model: str) -> bool:+ return model.startswith("claude")+++def _model_is_bedrock(model: str) -> bool:+ return model.startswith("bedrock/")++def get_completion_provider(config: AnyProviderConfig, model: str) -> CompletionProvider[Any, Any]:- if model.startswith("claude"):+ if _model_is_anthropic(model):return AnthropicProvider(model, config)- elif model.startswith("google") or model.startswith("gemini"):+ elif _model_is_google(model):return GoogleProvider(model, config)+ elif _model_is_bedrock(model):+ return BedrockProvider(model, config)else:return OpenAIProvider(model, config)diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex 99d6236861..5c868114ee 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -46,6 +46,7 @@ router = APIRouter()def get_ai_config(config: MarimoConfig) -> AiConfig:ai_config = config.get("ai", None)+ LOGGER.debug(f"ai_config: {ai_config}")if ai_config is None:raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,diff --git a/openapi/api.yaml b/openapi/api.yamlindex cd42afeb8c..ddea820d95 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1329,6 +1329,17 @@ components:api_key:type: stringtype: object+ bedrock:+ properties:+ aws_access_key_id:+ type: string+ aws_secret_access_key:+ type: string+ profile_name:+ type: string+ region_name:+ type: string+ type: objectgoogle:properties:api_key:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex b282327ca5..ed69036f71 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -3016,6 +3016,12 @@ export interface components {anthropic?: {api_key?: string;};+ bedrock?: {+ aws_access_key_id?: string;+ aws_secret_access_key?: string;+ profile_name?: string;+ region_name?: string;+ };google?: {api_key?: string;};diff --git a/pyproject.toml b/pyproject.tomlindex d041768c37..e15a95c33e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -199,6 +199,8 @@ dependencies = ["python-lsp-server>=1.12.1","pandas-stubs>=1.5.3.230321","pyiceberg>=0.9.0",+ "litellm>=1.70.0",+ "python-dotenv>=1.0.1","types-Pillow~=10.2.0.20240520","types-Pygments~=2.18.0.20240506","types-psutil~=5.9.5.20240516",@@ -280,6 +282,8 @@ extra-dependencies = ["openai>=1.55.3","anthropic==0.34.1","google-generativeai==0.8.5",+ "boto3>=1.38.19",+ "litellm>=1.70.0",# exporting as ipynb"nbformat >=5.10.4","sympy>=1.13.3",diff --git a/tests/_ai/llm/test_impl.py b/tests/_ai/llm/test_impl.pyindex 4061c2fcfd..2d38b440ef 100644--- a/tests/_ai/llm/test_impl.py+++ b/tests/_ai/llm/test_impl.py@@ -11,6 +11,7 @@ from marimo._ai._types import ChatMessage, ChatModelConfigfrom marimo._ai.llm._impl import (DEFAULT_SYSTEM_MESSAGE,anthropic,+ bedrock,google,groq,openai,@@ -108,6 +109,22 @@ def mock_azure_openai_client():yield mock_client, mock_azure_openai_class+def mock_litellm_completion():+ """Fixture for mocking the OpenAI client."""+ with patch("litellm.completion") as mock_litellm_completion:+ # Setup the response structure+ mock_response = MagicMock()+ mock_choice = MagicMock()+ mock_message = MagicMock()+ mock_message.content = "Test response"+ mock_choice.message = mock_message+ mock_response.choices = [mock_choice]+ mock_litellm_completion.return_value = mock_response++ yield mock_litellm_completion++@pytest.fixturedef test_messages():"""Fixture for test messages."""@@ -892,3 +909,76 @@ class TestAnthropic:model = anthropic("claude-3-opus-20240229")with pytest.raises(ValueError):_ = model._require_api_key+++ not DependencyManager.boto3.has() or not DependencyManager.litellm.has(),+ reason="boto3 or litellm is not installed",+)+class TestBedrock:+ """Test the Bedrock model class"""++ def test_init(self):+ """Test initialization of the bedrock model class"""+ model = bedrock(+ "anthropic.claude-3-sonnet-20240229",+ system_message="Test system message",+ region_name="us-east-1",+ )++ # bedrock automatically prefixes with bedrock/ for litellm usage+ assert model.model == "bedrock/anthropic.claude-3-sonnet-20240229"+ assert model.system_message == "Test system message"+ assert model.region_name == "us-east-1"+ assert model.profile_name is None+ assert model.aws_access_key_id is None+ assert model.aws_secret_access_key is None++ def test_init_with_credentials(self):+ """Test initialization with explicit credentials"""+ model = bedrock(+ "anthropic.claude-3-sonnet-20240229",+ aws_access_key_id="test-key",+ aws_secret_access_key="test-secret",+ )++ assert model.aws_access_key_id == "test-key"+ assert model.aws_secret_access_key == "test-secret"++ def test_init_with_profile(self):+ """Test initialization with AWS profile"""+ model = bedrock(+ "anthropic.claude-3-sonnet-20240229",+ profile_name="test-profile",+ )++ assert model.profile_name == "test-profile"++ def test_call(self, mock_litellm_completion, test_messages, test_config):+ """Test calling the bedrock class with LiteLLM client."""+ model_name = "anthropic.claude-3-sonnet-20240229"++ # Create model with API key to avoid _require_api_key+ model = bedrock(model_name)++ result = model(test_messages, test_config)++ # Verify result+ assert result == "Test response"++ # Verify API call+ mock_litellm_completion.assert_called_once()+ call_args = mock_litellm_completion.call_args[1]+ assert call_args["model"] == f"bedrock/{model_name}"+ assert len(call_args["messages"]) == 2+ assert call_args["messages"][0]["role"] == "system"+ assert call_args["messages"][0]["content"] == DEFAULT_SYSTEM_MESSAGE+ assert call_args["messages"][1]["role"] == "user"+ assert call_args["messages"][1]["content"] == "Test prompt"+ assert call_args["max_tokens"] == 100+ # Use pytest.approx for floating point comparisons+ assert call_args["temperature"] == pytest.approx(0.7)+ assert call_args["top_p"] == pytest.approx(0.9)+ assert call_args["frequency_penalty"] == pytest.approx(0.5)+ assert call_args["presence_penalty"] == pytest.approx(0.5)+ assert call_args["stream"] is Falsediff --git a/tests/_server/ai/test_providers.py b/tests/_server/ai/test_providers.pynew file mode 100644index 0000000000..867921d536--- /dev/null+++ b/tests/_server/ai/test_providers.py@@ -0,0 +1,74 @@+"""Tests for the LLM providers in marimo._server.ai.providers."""++import pytest++from marimo._config.config import AiConfig+from marimo._server.ai.providers import (+ AnthropicProvider,+ AnyProviderConfig,+ BedrockProvider,+ GoogleProvider,+ OpenAIProvider,+ get_completion_provider,+)+++ ("model_name", "provider_name"),+ [+ pytest.param("gpt-4", "openai", id="openai"),+ pytest.param("claude-3-opus-20240229", "anthropic", id="anthropic"),+ pytest.param("gemini-1.5-flash", "google", id="google"),+ pytest.param(+ "bedrock/anthropic.claude-3-sonnet-20240229",+ "bedrock",+ id="bedrock",+ ),+ ],+)+def test_anyprovider_for_model(model_name, provider_name):+ """Test that the correct config is returned for a given model."""+ ai_config = AiConfig(+ open_ai={+ "model": model_name,+ "api_key": "openai-key",+ },+ anthropic={+ "api_key": "anthropic-key",+ },+ google={+ "api_key": "google-key",+ },+ bedrock={+ "profile_name": "aws-profile",+ },+ )+ config = AnyProviderConfig.for_model(model_name, ai_config)++ if provider_name != "bedrock":+ assert config.api_key == f"{provider_name}-key"+ else:+ # bedrock overloads the api_key for profile name+ assert config.api_key == "profile:aws-profile"+++ ("model_name", "provider_type"),+ [+ pytest.param("gpt-4", OpenAIProvider, id="openai"),+ pytest.param(+ "claude-3-opus-20240229", AnthropicProvider, id="anthropic"+ ),+ pytest.param("gemini-1.5-flash", GoogleProvider, id="google"),+ pytest.param(+ "bedrock/anthropic.claude-3-sonnet-20240229",+ BedrockProvider,+ id="bedrock",+ ),+ ],+)+def test_get_completion_provider(model_name, provider_type):+ """Test that the correct provider is returned for a given model."""+ config = AnyProviderConfig(api_key="test-key", base_url="http://test-url")+ provider = get_completion_provider(config, model_name)+ assert isinstance(provider, provider_type)diff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txtindex 33058f6d25..301921e326 100644--- a/tests/snapshots/api.txt+++ b/tests/snapshots/api.txt@@ -11,6 +11,7 @@ aiChatModelConfigllmanthropic+ bedrockgroqopenai