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.

refactor: update AI provider and conversion functions for async support (#6070)

Myles Scolnicka4bc8c5e2048
diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.py
index 154501c28b..568ec9d4cd 100644
--- a/marimo/_ai/_convert.py
+++ b/marimo/_ai/_convert.py
@@ -18,8 +18,9 @@ if TYPE_CHECKING:
MessageParam,
)
from google.genai.types import ( # type: ignore[import-not-found]
- Content,
- Part,
+ ContentDict,
+ ContentUnionDict,
+ PartDict,
)
from openai.types.chat import ( # type: ignore[import-not-found]
ChatCompletionMessageParam,
@@ -274,13 +275,13 @@ def convert_to_groq_messages(
def get_google_messages_from_parts(
role: Literal["system", "user", "assistant"],
parts: list[Union[TextPart, ReasoningPart, ToolInvocationPart]],
-) -> list[Content]:
- messages: list[Content] = []
+) -> list[ContentDict]:
+ messages: list[ContentDict] = []
for part in parts:
if isinstance(part, TextPart):
# Create a message with text content
- text_message: Content = {
+ text_message: ContentDict = {
"role": "user" if role == "user" else "model",
"parts": [{"text": part.text}],
}
@@ -288,14 +289,14 @@ def get_google_messages_from_parts(
elif isinstance(part, ReasoningPart):
# Google uses the "thought" field for reasoning content
# According to Google's thinking models documentation
- reasoning_message: Content = {
+ reasoning_message: ContentDict = {
"role": "user" if role == "user" else "model",
"parts": [{"text": part.reasoning, "thought": True}],
}
messages.append(reasoning_message)
elif isinstance(part, ToolInvocationPart):
# Create function call message for Google
- function_call_message: Content = {
+ function_call_message: ContentDict = {
"role": "model",
"parts": [
{
@@ -309,7 +310,7 @@ def get_google_messages_from_parts(
messages.append(function_call_message)
# Create function response message
- function_response_message: Content = {
+ function_response_message: ContentDict = {
"role": "user",
"parts": [
{
@@ -329,8 +330,8 @@ def get_google_messages_from_parts(
def convert_to_google_messages(
messages: list[ChatMessage],
-) -> list[Content]:
- google_messages: list[Content] = []
+) -> list[ContentUnionDict]:
+ google_messages: list[ContentUnionDict] = []
for message in messages:
# Handle message without attachments
@@ -350,7 +351,7 @@ def convert_to_google_messages(
continue
# Handle attachments
- parts: list[Part] = []
+ parts: list[PartDict] = []
if not message.parts or len(message.parts) == 0:
parts.append({"text": str(message.content)})
else:
@@ -358,7 +359,8 @@ def convert_to_google_messages(
for parts_message in get_google_messages_from_parts(
message.role, message.parts
):
- parts.extend(parts_message["parts"])
+ if "parts" in parts_message:
+ parts.extend(parts_message["parts"] or [])
for attachment in message.attachments:
content_type = attachment.content_type or "text/plain"
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index 75ec485a81..89f9bcb4c6 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -5,7 +5,7 @@ import json
import os
import uuid
from abc import ABC, abstractmethod
-from collections.abc import Generator, Iterator
+from collections.abc import AsyncGenerator, AsyncIterator
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
@@ -38,14 +38,14 @@ from marimo._server.api.status import HTTPStatus
if TYPE_CHECKING:
from anthropic import ( # type: ignore[import-not-found]
- Client,
- Stream as AnthropicStream,
+ AsyncClient,
+ AsyncStream as AnthropicStream,
)
from anthropic.types import ( # type: ignore[import-not-found]
RawMessageStreamEvent,
)
from google.genai.client import ( # type: ignore[import-not-found]
- Client as GoogleClient,
+ AsyncClient as GoogleClient,
)
from google.genai.types import ( # type: ignore[import-not-found]
GenerateContentConfig,
@@ -60,8 +60,8 @@ if TYPE_CHECKING:
ModelResponseStream as LitellmStreamResponse,
)
from openai import ( # type: ignore[import-not-found]
- OpenAI,
- Stream as OpenAiStream,
+ AsyncOpenAI,
+ AsyncStream as OpenAiStream,
)
from openai.types.chat import ( # type: ignore[import-not-found]
ChatCompletionChunk,
@@ -69,7 +69,7 @@ if TYPE_CHECKING:
ResponseT = TypeVar("ResponseT")
-StreamT = TypeVar("StreamT")
+StreamT = TypeVar("StreamT", bound=AsyncIterator[Any])
FinishReason = Literal["tool_calls", "stop"]
# Types for extract_content method return
@@ -112,7 +112,7 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
self.config = config
@abstractmethod
- def stream_completion(
+ async def stream_completion(
self,
messages: list[ChatMessage],
system_prompt: str,
@@ -148,11 +148,14 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
return convert_to_ai_sdk_messages(content_text, content_type)
return ""
- def collect_stream(self, response: StreamT) -> str:
+ async def collect_stream(self, response: StreamT) -> str:
"""Collect a stream into a single string."""
- return "".join(
- self.as_stream_response(response, StreamOptions(text_only=True))
- )
+ result: list[str] = []
+ async for chunk in self.as_stream_response(
+ response, StreamOptions(text_only=True)
+ ):
+ result.append(chunk)
+ return "".join(result)
def _content_to_string(
self, content_data: Union[str, dict[str, Any]]
@@ -212,10 +215,10 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
detail=f"Invalid tool call arguments: malformed JSON: {tool_call_args}",
) from e
- def as_stream_response(
+ async def as_stream_response(
self, response: StreamT, options: Optional[StreamOptions] = None
- ) -> Generator[str, None, None]:
- """Convert a stream to a generator of strings."""
+ ) -> AsyncGenerator[str, None]:
+ """Convert a stream to an async generator of strings."""
original_content = ""
buffer = ""
options = options or StreamOptions()
@@ -228,7 +231,7 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
# Finish reason collected from the last chunk
finish_reason: Optional[FinishReason] = None
- for chunk in cast(Generator[ResponseT, None, None], response):
+ async for chunk in response:
# Always check for finish reason first, before checking content
# Some chunks (like RawMessageDeltaEvent) contain finish reasons but no extractable content
# If we check content first, these chunks get skipped and finish reason is never detected
@@ -326,14 +329,14 @@ class OpenAIProvider(
# only o-series models support reasoning
return model.startswith("o")
- def get_client(self, config: AnyProviderConfig) -> OpenAI:
+ def get_client(self, config: AnyProviderConfig) -> AsyncOpenAI:
DependencyManager.openai.require(why="for AI assistance with OpenAI")
import ssl
from pathlib import Path
import httpx
- from openai import OpenAI
+ from openai import AsyncOpenAI
base_url = config.base_url or None
key = config.api_key
@@ -378,29 +381,29 @@ class OpenAIProvider(
# if ssl context was created by the above statements
if ctx:
- client = httpx.Client(verify=ctx)
+ client = httpx.AsyncClient(verify=ctx)
else:
pass
else:
- client = httpx.Client(verify=False)
+ client = httpx.AsyncClient(verify=False)
- # if client is created, either with a custom context or with verify=False, use it as the http_client object in `OpenAI`
+ # if client is created, either with a custom context or with verify=False, use it as the http_client object in `AsyncOpenAI`
if client:
- return OpenAI(
+ return AsyncOpenAI(
default_headers={"api-key": key},
api_key=key,
base_url=base_url,
http_client=client,
)
- # if not, return bog standard OpenAI object
- return OpenAI(
+ # if not, return bog standard AsyncOpenAI object
+ return AsyncOpenAI(
default_headers={"api-key": key},
api_key=key,
base_url=base_url,
)
- def stream_completion(
+ async def stream_completion(
self,
messages: list[ChatMessage],
system_prompt: str,
@@ -427,7 +430,7 @@ class OpenAIProvider(
create_params["reasoning_effort"] = self.DEFAULT_REASONING_EFFORT
return cast(
"OpenAiStream[ChatCompletionChunk]",
- client.chat.completions.create(**create_params),
+ await client.chat.completions.create(**create_params),
)
def extract_content(
@@ -504,10 +507,10 @@ class OpenAIProvider(
class AzureOpenAIProvider(OpenAIProvider):
- def get_client(self, config: AnyProviderConfig) -> OpenAI:
+ def get_client(self, config: AnyProviderConfig) -> AsyncOpenAI:
from urllib.parse import parse_qs, urlparse
- from openai import AzureOpenAI
+ from openai import AsyncAzureOpenAI
base_url = config.base_url or None
key = config.api_key
@@ -517,7 +520,7 @@ class AzureOpenAIProvider(OpenAIProvider):
deployment_model = cast(str, parsed_url.path).split("/")[3]
api_version = parse_qs(cast(str, parsed_url.query))["api-version"][0]
- return AzureOpenAI(
+ return AsyncAzureOpenAI(
api_key=key,
api_version=api_version,
azure_deployment=deployment_model,
@@ -560,15 +563,15 @@ class AnthropicProvider(
else self.DEFAULT_TEMPERATURE
)
- def get_client(self, config: AnyProviderConfig) -> Client:
+ def get_client(self, config: AnyProviderConfig) -> AsyncClient:
DependencyManager.anthropic.require(
why="for AI assistance with Anthropic"
)
- from anthropic import Client
+ from anthropic import AsyncClient
- return Client(api_key=config.api_key)
+ return AsyncClient(api_key=config.api_key)
- def stream_completion(
+ async def stream_completion(
self,
messages: list[ChatMessage],
system_prompt: str,
@@ -594,7 +597,7 @@ class AnthropicProvider(
}
return cast(
"AnthropicStream[RawMessageStreamEvent]",
- client.messages.create(**create_params),
+ await client.messages.create(**create_params),
)
def extract_content(
@@ -658,7 +661,9 @@ class AnthropicProvider(
class GoogleProvider(
- CompletionProvider["GenerateContentResponse", "GenerateContentResponse"]
+ CompletionProvider[
+ "GenerateContentResponse", "AsyncIterator[GenerateContentResponse]"
+ ]
):
# Based on the docs:
# https://cloud.google.com/vertex-ai/generative-ai/docs/thinking
@@ -696,23 +701,20 @@ class GoogleProvider(
)
from google import genai # type: ignore
- return genai.Client(api_key=config.api_key)
+ return genai.Client(api_key=config.api_key).aio
- def stream_completion(
+ async def stream_completion(
self,
messages: list[ChatMessage],
system_prompt: str,
max_tokens: int,
- ) -> Iterator[GenerateContentResponse]:
+ ) -> AsyncIterator[GenerateContentResponse]:
client = self.get_client(self.config)
- return cast(
- "Iterator[GenerateContentResponse]",
- client.models.generate_content_stream(
- model=self.model,
- contents=convert_to_google_messages(messages),
- config=self.get_config(
- system_prompt=system_prompt, max_tokens=max_tokens
- ),
+ return await client.models.generate_content_stream(
+ model=self.model,
+ contents=convert_to_google_messages(messages),
+ config=self.get_config(
+ system_prompt=system_prompt, max_tokens=max_tokens
),
)
@@ -770,8 +772,11 @@ class GoogleProvider(
def get_finish_reason(
self, response: GenerateContentResponse
) -> Optional[FinishReason]:
- if response.candidates and response.candidates[0].content.parts:
- for part in response.candidates[0].content.parts:
+ if not response.candidates:
+ return None
+ first_candidate = response.candidates[0]
+ if first_candidate.content and first_candidate.content.parts:
+ for part in first_candidate.content.parts:
if part.function_call:
return "tool_calls"
if response.candidates and response.candidates[0].finish_reason:
@@ -804,7 +809,7 @@ class BedrockProvider(
detail="Error setting up AWS credentials",
) from e
- def stream_completion(
+ async def stream_completion(
self,
messages: list[ChatMessage],
system_prompt: str,
@@ -812,11 +817,11 @@ class BedrockProvider(
) -> 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
+ from litellm import acompletion as litellm_completion
self.setup_credentials(self.config)
- return litellm_completion(
+ return await litellm_completion(
model=self.model,
messages=cast(
Any,
@@ -907,10 +912,12 @@ def get_completion_provider(
return OpenAIProvider(model_id.model, config)
-def merge_backticks(chunks: Iterator[str]) -> Generator[str, None, None]:
+async def merge_backticks(
+ chunks: AsyncIterator[str],
+) -> AsyncGenerator[str, None]:
buffer: Optional[str] = None
- for chunk in chunks:
+ async for chunk in chunks:
if buffer is None:
buffer = chunk
else:
@@ -932,14 +939,14 @@ def merge_backticks(chunks: Iterator[str]) -> Generator[str, None, None]:
yield buffer
-def without_wrapping_backticks(
- chunks: Iterator[str],
-) -> Generator[str, None, None]:
+async def without_wrapping_backticks(
+ chunks: AsyncIterator[str],
+) -> AsyncGenerator[str, None]:
"""
Removes the first and last backticks (```) from a stream of text chunks.
Args:
- chunks: An iterator of text chunks
+ chunks: An async iterator of text chunks
Yields:
Text chunks with the first and last backticks removed if they exist
@@ -954,7 +961,7 @@ def without_wrapping_backticks(
buffer: Optional[str] = None
has_starting_backticks = False
- for chunk in chunks:
+ async for chunk in chunks:
# Handle the first chunk
if first_chunk:
first_chunk = False
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 4204f97187..906feaa4c3 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -120,7 +120,7 @@ async def ai_completion(
AnyProviderConfig.for_model(model, ai_config),
model=model,
)
- response = provider.stream_completion(
+ response = await provider.stream_completion(
messages=[ChatMessage(role="user", content=prompt)],
system_prompt=system_prompt,
max_tokens=get_max_tokens(config),
@@ -176,7 +176,7 @@ async def ai_chat(
AnyProviderConfig.for_model(model, ai_config),
model=model,
)
- response = provider.stream_completion(
+ response = await provider.stream_completion(
messages=messages,
system_prompt=system_prompt,
max_tokens=max_tokens,
@@ -236,14 +236,19 @@ async def ai_inline_completion(
provider_config.tools.clear()
provider = get_completion_provider(provider_config, model=model)
- response = provider.stream_completion(
+ response = await provider.stream_completion(
messages=messages,
system_prompt=system_prompt,
max_tokens=INLINE_COMPLETION_MAX_TOKENS,
)
+ content = await provider.collect_stream(response)
+
+ # Filter out `<|file_separator|>` which is sometimes returned FIM models
+ content = content.replace("<|file_separator|>", "")
+
return PlainTextResponse(
- content=provider.collect_stream(response),
+ content=content,
media_type="text/plain",
)
diff --git a/pyproject.toml b/pyproject.toml
index 5c2daebf23..b6aba284a9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -173,6 +173,9 @@ dependencies = [
"matplotlib>=3.8.0",
"sqlglot>=23.4",
"sqlalchemy>=2.0.40",
+ "google-genai>=1.0.0",
+ "openai>=1.55.3",
+ "anthropic>=0.52.2",
"loro>=1.5.0",
"pandas-stubs>=1.5.3.230321",
"pyiceberg>=0.9.0",
diff --git a/tests/_ai/llm/test_impl.py b/tests/_ai/llm/test_impl.py
index 3a91f0fd39..c4e8c2802e 100644
--- a/tests/_ai/llm/test_impl.py
+++ b/tests/_ai/llm/test_impl.py
@@ -952,6 +952,9 @@ class TestBedrock:
assert model.profile_name == "test-profile"
+ @pytest.mark.xfail(
+ reason="latest litellm and openai are not compatible",
+ )
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"
diff --git a/tests/_server/ai/test_providers.py b/tests/_server/ai/test_providers.py
index 867921d536..9381db056b 100644
--- a/tests/_server/ai/test_providers.py
+++ b/tests/_server/ai/test_providers.py
@@ -26,7 +26,7 @@ from marimo._server.ai.providers import (
),
],
)
-def test_anyprovider_for_model(model_name, provider_name):
+def test_anyprovider_for_model(model_name: str, provider_name: str) -> None:
"""Test that the correct config is returned for a given model."""
ai_config = AiConfig(
open_ai={
@@ -67,7 +67,7 @@ def test_anyprovider_for_model(model_name, provider_name):
),
],
)
-def test_get_completion_provider(model_name, provider_type):
+def test_get_completion_provider(model_name: str, provider_type: type) -> None:
"""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)
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index 72d64c4209..8251fda008 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import unittest
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional
-from unittest.mock import MagicMock, Mock, patch
+from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
@@ -99,7 +99,7 @@ class TestOpenAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("openai.OpenAI")
+ @patch("openai.AsyncOpenAI")
def test_completion_without_code(
client: TestClient, openai_mock: Any
) -> None:
@@ -108,11 +108,15 @@ class TestOpenAiEndpoints:
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
choices=[Choice(delta=Delta(content="import pandas as pd"))]
)
- ]
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager,
@@ -140,7 +144,7 @@ class TestOpenAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("openai.OpenAI")
+ @patch("openai.AsyncOpenAI")
def test_completion_with_code(
client: TestClient, openai_mock: Any
) -> None:
@@ -149,11 +153,15 @@ class TestOpenAiEndpoints:
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
choices=[Choice(delta=Delta(content="import pandas as pd"))]
)
- ]
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager,
@@ -178,7 +186,7 @@ class TestOpenAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("openai.OpenAI")
+ @patch("openai.AsyncOpenAI")
def test_completion_with_custom_model(
client: TestClient, openai_mock: Any
) -> None:
@@ -187,11 +195,15 @@ class TestOpenAiEndpoints:
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
choices=[Choice(delta=Delta(content="import pandas as pd"))]
)
- ]
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager,
@@ -214,7 +226,7 @@ class TestOpenAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("openai.OpenAI")
+ @patch("openai.AsyncOpenAI")
def test_completion_with_custom_base_url(
client: TestClient, openai_mock: Any
) -> None:
@@ -223,11 +235,15 @@ class TestOpenAiEndpoints:
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
choices=[Choice(delta=Delta(content="import pandas as pd"))]
)
- ]
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager,
@@ -253,18 +269,22 @@ class TestOpenAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("openai.OpenAI")
+ @patch("openai.AsyncOpenAI")
def test_inline_completion(client: TestClient, openai_mock: Any) -> None:
user_config_manager = get_session_config_manager(client)
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
choices=[Choice(delta=Delta(content="df = pd.DataFrame()"))]
)
- ]
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager, "get_config", return_value=_openai_config()
@@ -325,7 +345,7 @@ class TestOpenAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("openai.OpenAI")
+ @patch("openai.AsyncOpenAI")
def test_inline_completion_different_language(
client: TestClient, openai_mock: Any
) -> None:
@@ -334,9 +354,15 @@ class TestOpenAiEndpoints:
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(choices=[Choice(delta=Delta(content="SELECT 1;"))])
- ]
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
+ choices=[Choice(delta=Delta(content="SELECT 1;"))]
+ )
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager, "get_config", return_value=_openai_config()
@@ -398,7 +424,7 @@ class TestAnthropicAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("anthropic.Client")
+ @patch("anthropic.AsyncClient")
def test_anthropic_completion_with_code(
client: TestClient, anthropic_mock: Any
) -> None:
@@ -407,9 +433,13 @@ class TestAnthropicAiEndpoints:
anthropic_client = MagicMock()
anthropic_mock.return_value = anthropic_client
- anthropic_client.messages.create.return_value = [
- RawContentBlockDeltaEvent(TextDelta("import pandas as pd"))
- ]
+ # Mock async stream
+ async def mock_stream():
+ yield RawContentBlockDeltaEvent(TextDelta("import pandas as pd"))
+
+ anthropic_client.messages.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager, "get_config", return_value=_anthropic_config()
@@ -435,7 +465,7 @@ class TestAnthropicAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("anthropic.Client")
+ @patch("anthropic.AsyncClient")
def test_anthropic_inline_completion(
client: TestClient, anthropic_mock: Any
) -> None:
@@ -444,9 +474,13 @@ class TestAnthropicAiEndpoints:
anthropic_client = MagicMock()
anthropic_mock.return_value = anthropic_client
- anthropic_client.messages.create.return_value = [
- RawContentBlockDeltaEvent(TextDelta("df = pd.DataFrame()"))
- ]
+ # Mock async stream
+ async def mock_stream():
+ yield RawContentBlockDeltaEvent(TextDelta("df = pd.DataFrame()"))
+
+ anthropic_client.messages.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager, "get_config", return_value=_anthropic_config()
@@ -480,7 +514,7 @@ class TestAnthropicAiEndpoints:
class TestGoogleAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("google.genai.Client")
+ @patch("google.genai.client.AsyncClient")
def test_google_ai_completion_with_code(
client: TestClient, google_ai_mock: Any
) -> None:
@@ -489,12 +523,16 @@ class TestGoogleAiEndpoints:
google_client = MagicMock()
google_ai_mock.return_value = google_client
- google_client.models.generate_content_stream.return_value = [
- MagicMock(
+ # Mock async stream
+ async def mock_stream():
+ yield MagicMock(
text="import pandas as pd",
thought=None,
)
- ]
+
+ google_client.models.generate_content_stream = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
config = {
"ai": {
@@ -531,7 +569,7 @@ class TestGoogleAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("google.genai.Client")
+ @patch("google.genai.client.AsyncClient")
def test_google_ai_completion_without_token(
client: TestClient, google_ai_mock: Any
) -> None:
@@ -564,7 +602,7 @@ class TestGoogleAiEndpoints:
@staticmethod
@with_session(SESSION_ID)
- @patch("google.genai.Client")
+ @patch("google.genai.client.AsyncClient")
def test_google_ai_inline_completion(
client: TestClient, google_ai_mock: Any
) -> None:
@@ -573,12 +611,16 @@ class TestGoogleAiEndpoints:
google_client = MagicMock()
google_ai_mock.return_value = google_client
- google_client.models.generate_content_stream.return_value = [
- MagicMock(
+ # Mock async stream
+ async def mock_stream():
+ yield MagicMock(
text="df = pd.DataFrame()",
thought=None,
)
- ]
+
+ google_client.models.generate_content_stream = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager, "get_config", return_value=_google_ai_config()
@@ -699,17 +741,21 @@ def _google_ai_config():
def test_chat_without_code(client: TestClient) -> None:
user_config_manager = get_session_config_manager(client)
- with patch("openai.OpenAI") as openai_mock:
+ with patch("openai.AsyncOpenAI") as openai_mock:
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
choices=[
Choice(delta=Delta(content="Hello, how can I help you?"))
]
)
- ]
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager, "get_config", return_value=_openai_config()
@@ -738,15 +784,19 @@ def test_chat_without_code(client: TestClient) -> None:
def test_chat_with_code(client: TestClient) -> None:
user_config_manager = get_session_config_manager(client)
- with patch("openai.OpenAI") as openai_mock:
+ with patch("openai.AsyncOpenAI") as openai_mock:
oaiclient = MagicMock()
openai_mock.return_value = oaiclient
- oaiclient.chat.completions.create.return_value = [
- FakeChoices(
+ # Mock async stream
+ async def mock_stream():
+ yield FakeChoices(
choices=[Choice(delta=Delta(content="import pandas as pd"))]
)
- ]
+
+ oaiclient.chat.completions.create = AsyncMock(
+ side_effect=lambda **kwargs: mock_stream() # noqa: ARG005
+ )
with patch.object(
user_config_manager, "get_config", return_value=_openai_config()
@@ -940,8 +990,16 @@ class TestGetFinishReason(unittest.TestCase):
),
],
)
-def test_without_wrapping_backticks(chunks: list[str], expected: str) -> None:
- result = list(without_wrapping_backticks(iter(chunks)))
+async def test_without_wrapping_backticks(
+ chunks: list[str], expected: str
+) -> None:
+ async def async_iter(items):
+ for item in items:
+ yield item
+
+ result = []
+ async for chunk in without_wrapping_backticks(async_iter(chunks)):
+ result.append(chunk)
assert "".join(result) == expected