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
feat: add anthropic support (#2147)
Myles Scolnick8560feeb2b33
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.mdindex e788399656..0bd4ef2400 100644--- a/docs/guides/editor_features/ai_completion.md+++ b/docs/guides/editor_features/ai_completion.md@@ -63,6 +63,22 @@ cell. This will open an input to modify the cell using AI.</figure></div>+### Using Anthropic++To use Anthropic with marimo:++1. Sign up for an account at [Anthropic](https://console.anthropic.com/) and grab your [Anthropic Key](https://console.anthropic.com/settings/keys).+2. Add the following to your `~/.marimo.toml`:++```toml+[ai.open_ai]+model = "claude-3-5-sonnet-20240620"+# or any model from https://docs.anthropic.com/en/docs/about-claude/models++[ai.anthropic]+api_key = "sk-..."+```+### Using other AI providersmarimo supports OpenAI's GPT-3.5 API by default. If your provider is compatible with OpenAI's API, you can use it by changing the `base_url` in the configuration.diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex e73f87c326..5c6ece424f 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -636,6 +636,10 @@ export const UserConfigForm: React.FC = () => {/></FormControl><FormMessage />+ <FormDescription>+ If the model starts with "claude-", we will use your Anthropic+ API key. Otherwise, we will use your OpenAI API key.+ </FormDescription></FormItem>)}/>diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 87a2de9ffe..8161d96a66 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -33,7 +33,7 @@ import { aiCompletionCellAtom } from "@/core/ai/state";import { mergeRefs } from "@/utils/mergeRefs";import { useSetLastFocusedCellId } from "@/core/cells/focus";import type { LanguageAdapterType } from "@/core/codemirror/language/types";-import { autoInstantiateAtom } from "@/core/config/config";+import { autoInstantiateAtom, isAiEnabled } from "@/core/config/config";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import { useSplitCellCallback } from "../useSplitCell";@@ -143,11 +143,13 @@ const CellEditorInternal = ({maybeAddMarimoImport(autoInstantiate, createNewCell);});+ const aiEnabled = isAiEnabled(userConfig);+const extensions = useMemo(() => {const extensions = setupCodeMirror({cellId,showPlaceholder,- enableAI: Boolean(userConfig.ai.open_ai?.api_key),+ enableAI: aiEnabled,cellCodeCallbacks: {updateCellCode,afterToggleMarkdown,@@ -208,7 +210,7 @@ const CellEditorInternal = ({cellId,userConfig.keymap,userConfig.completion,- userConfig.ai.open_ai?.api_key,+ aiEnabled,theme,showPlaceholder,createAbove,diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 2f8ef00160..6a94666588 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -102,6 +102,11 @@ export const UserConfigSchema = zmodel: z.string().optional(),}).optional(),+ anthropic: z+ .object({+ api_key: z.string().optional(),+ })+ .optional(),}).default({}),experimental: zdiff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex cd7ee5c2c6..eb9277fef1 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -39,9 +39,15 @@ export function getUserConfig() {}export const aiEnabledAtom = atom<boolean>((get) => {- return Boolean(get(userConfigAtom).ai.open_ai?.api_key);+ return isAiEnabled(get(userConfigAtom));});+export function isAiEnabled(config: UserConfig) {+ return (+ Boolean(config.ai.open_ai?.api_key) || Boolean(config.ai.anthropic?.api_key)+ );+}+/*** Atom for storing the app config.*/diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex f711eeb1a0..c9d9202809 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -174,9 +174,11 @@ class AiConfig(TypedDict):**Keys.**- `open_ai`: the OpenAI config+ - `anthropic`: the Anthropic config"""open_ai: OpenAiConfig+ anthropic: AnthropicConfig@dataclass@@ -186,7 +188,8 @@ class OpenAiConfig(TypedDict):**Keys.**- `api_key`: the OpenAI API key- - `model`: the model to use+ - `model`: the model to use.+ if model starts with `claude-` we use the AnthropicConfig- `base_url`: the base URL for the API"""@@ -195,6 +198,18 @@ class OpenAiConfig(TypedDict):base_url: NotRequired[str]+@dataclass+class AnthropicConfig(TypedDict):+ """Configuration options for Anthropic.++ **Keys.**++ - `api_key`: the Anthropic+ """++ api_key: str++@mddoc@dataclassclass MarimoConfig(TypedDict):@@ -303,7 +318,7 @@ 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"]]+ secrets = [["ai", "open_ai", "api_key"], ["ai", "anthropic", "api_key"]]new_config = _deep_copy(config)for secret in secrets:diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex 3f404b33ff..93f8a4e39b 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -19,7 +19,17 @@ from marimo._server.router import APIRouterfrom marimo._utils.assert_never import assert_neverif TYPE_CHECKING:- from openai import OpenAI, Stream # type: ignore[import-not-found]+ from anthropic import ( # type: ignore[import-not-found]+ Client,+ Stream as AnthropicStream,+ )+ from anthropic.types import ( # type: ignore[import-not-found]+ RawMessageStreamEvent,+ )+ from openai import ( # type: ignore[import-not-found]+ OpenAI,+ Stream as OpenAiStream,+ )from openai.types.chat import ( # type: ignore[import-not-found]ChatCompletionChunk,)@@ -36,7 +46,8 @@ def get_openai_client(config: MarimoConfig) -> "OpenAI":from openai import OpenAI # type: ignore[import-not-found]except ImportError:raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST, detail="OpenAI not installed"+ status_code=HTTPStatus.BAD_REQUEST,+ detail="OpenAI not installed. Run `pip install openai`",) from Noneif "ai" not in config:@@ -68,6 +79,42 @@ def get_openai_client(config: MarimoConfig) -> "OpenAI":return OpenAI(api_key=key, base_url=base_url)+def get_anthropic_client(config: MarimoConfig) -> "Client":+ try:+ from anthropic import Client # type: ignore[import-not-found]+ except ImportError:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Anthropic not installed. Run `pip install anthropic`",+ ) from None++ if "ai" not in config:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Anthropic not configured",+ )+ if "anthropic" not in config["ai"]:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Anthropic not configured",+ )+ if "api_key" not in config["ai"]["anthropic"]:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Anthropic API key not configured",+ )++ key: str = config["ai"]["anthropic"]["api_key"]++ if not key:+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Anthropic API key not configured",+ )++ return Client(api_key=key)++def get_model(config: MarimoConfig) -> str:model: str = (config.get("ai", {}).get("open_ai", {}).get("model", "gpt-4-turbo")@@ -77,15 +124,34 @@ def get_model(config: MarimoConfig) -> str:return model+def get_content(+ response: RawMessageStreamEvent | ChatCompletionChunk,+) -> str | None:+ if hasattr(response, "choices"):+ return response.choices[0].delta.content # type: ignore++ from anthropic.types import (+ RawContentBlockDeltaEvent,+ TextDelta,+ )++ if isinstance(response, RawContentBlockDeltaEvent):+ if isinstance(response.delta, TextDelta):+ return response.delta.text # type: ignore++ return None++def make_stream_response(- response: Stream[ChatCompletionChunk],+ response: OpenAiStream[ChatCompletionChunk]+ | AnthropicStream[RawMessageStreamEvent],) -> Generator[str, None, None]:original_content = ""- buffer: str = ""+ buffer = ""in_code_fence = False- # If it starts or ends with markdown, remove it+for chunk in response:- content = chunk.choices[0].delta.content+ content = get_content(chunk)if not content:continue@@ -158,7 +224,6 @@ async def ai_completion(app_state.require_current_session()config = app_state.config_manager.get_config(hide_secrets=False)body = await parse_request(request, cls=AiCompletionRequest)- client = get_openai_client(config)if body.language == "python":system_prompt = (@@ -193,7 +258,32 @@ async def ai_completion(if body.code.strip():prompt = f"{prompt}\n\nCurrent code:\n{body.code}"- response = client.chat.completions.create(+ model = get_model(config)++ # If the model starts with claude, use anthropic+ if model.startswith("claude"):+ anthropic_client = get_anthropic_client(config)+ response = anthropic_client.messages.create(+ model=model,+ max_tokens=1000,+ messages=[+ {+ "role": "user",+ "content": prompt,+ }+ ],+ system=system_prompt,+ stream=True,+ temperature=0,+ )++ return StreamingResponse(+ content=make_stream_response(response),+ media_type="application/json",+ )++ openai_client = get_openai_client(config)+ response = openai_client.chat.completions.create(model=get_model(config),messages=[{diff --git a/openapi/api.yaml b/openapi/api.yamlindex 6db873f572..a41107258f 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -823,6 +823,9 @@ components:app_title:nullable: truetype: string+ css_file:+ nullable: true+ type: stringlayout_file:nullable: truetype: string@@ -960,6 +963,13 @@ components:properties:ai:properties:+ anthropic:+ properties:+ api_key:+ type: string+ required:+ - api_key+ type: objectopen_ai:properties:api_key:@@ -975,6 +985,7 @@ components:type: objectrequired:- open_ai+ - anthropictype: objectcompletion:properties:@@ -1784,7 +1795,7 @@ components:type: objectinfo:title: marimo API- version: 0.8.2+ version: 0.8.3openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 479ccf6134..8c2bb3b42d 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2020,6 +2020,7 @@ export interface components {KernelReady: {app_config: {app_title?: string | null;+ css_file?: string | null;layout_file?: string | null;/** @enum {string} */width: "normal" | "compact" | "medium" | "full";@@ -2079,6 +2080,9 @@ export interface components {};MarimoConfig: {ai: {+ anthropic: {+ api_key: string;+ };open_ai: {api_key: string;base_url: string;diff --git a/pyproject.toml b/pyproject.tomlindex 1bd4c730cd..f2851359ed 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -140,6 +140,7 @@ testoptional = ["anywidget~=0.9.13","ipython~=8.12.3","openai~=1.41.1",+ "anthropic==0.34.1",# exporting as ipynb"nbformat >=5.10.4",]diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 12d1856faf..4db4d266e1 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -27,16 +27,31 @@ HEADERS = {HAS_DEPS = DependencyManager.openai.has()+# Anthropic+@dataclass+class TextDelta:+ text: str+++# Anthropic+@dataclass+class RawContentBlockDeltaEvent:+ delta: TextDelta+++# OpenAI@dataclassclass Delta:content: str+# OpenAI@dataclassclass Choice:delta: Delta+# OpenAI@dataclassclass FakeChoices:choices: List[Choice]@@ -66,6 +81,30 @@ class TestAiEndpoints:assert response.status_code == 400, response.textassert response.json() == {"detail": "OpenAI API key not configured"}+ @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(@@ -142,6 +181,43 @@ class TestAiEndpoints:"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("anthropic.Client")+ def test_anthropic_completion_with_code(+ client: TestClient, anthropic_mock: Any+ ) -> None:+ user_config_manager = get_user_config_manager(client)++ anthropic_client = MagicMock()+ anthropic_mock.return_value = anthropic_client++ anthropic_client.messages.create.return_value = [+ RawContentBlockDeltaEvent(TextDelta("import pandas as pd"))+ ]++ with anthropic_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": "",+ },+ )+ assert response.status_code == 200, response.text+ # Assert the prompt it was called with+ prompt: str = anthropic_client.messages.create.call_args.kwargs[+ "messages"+ ][0]["content"]+ assert prompt == (+ "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501+ )+@staticmethod@with_session(SESSION_ID)@pytest.mark.skipif(@@ -217,7 +293,9 @@ class TestAiEndpoints:def openai_config(config: UserConfigManager):prev_config = config.get_config()try:- config.save_config({"ai": {"open_ai": {"api_key": "fake-api"}}})+ config.save_config(+ {"ai": {"open_ai": {"api_key": "fake-api", "model": ""}}}+ )yieldfinally:config.save_config(prev_config)@@ -252,6 +330,7 @@ def openai_config_custom_base_url(config: UserConfigManager):"open_ai": {"api_key": "fake-api","base_url": "https://my-openai-instance.com",+ "model": "",}}}@@ -265,7 +344,41 @@ def openai_config_custom_base_url(config: UserConfigManager):def no_openai_config(config: UserConfigManager):prev_config = config.get_config()try:- config.save_config({"ai": {"open_ai": {"api_key": ""}}})+ config.save_config({"ai": {"open_ai": {"api_key": "", "model": ""}}})+ yield+ finally:+ config.save_config(prev_config)+++@contextmanager+def no_anthropic_config(config: UserConfigManager):+ prev_config = config.get_config()+ try:+ config.save_config(+ {+ "ai": {+ "open_ai": {"model": "claude-3.5"},+ "anthropic": {"api_key": ""},+ }+ }+ )+ yield+ finally:+ config.save_config(prev_config)+++@contextmanager+def anthropic_config(config: UserConfigManager):+ prev_config = config.get_config()+ try:+ config.save_config(+ {+ "ai": {+ "open_ai": {"model": "claude-3.5"},+ "anthropic": {"api_key": "fake-key"},+ }+ }+ )yieldfinally:config.save_config(prev_config)