CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat: add provider base types and message stream
xf gonga78c48842810
diff --git a/cubepi/providers/__init__.py b/cubepi/providers/__init__.pyindex e69de29..44854ac 100644--- a/cubepi/providers/__init__.py+++ b/cubepi/providers/__init__.py@@ -0,0 +1,39 @@+from cubepi.providers.base import (+ AssistantMessage,+ Content,+ ImageContent,+ Message,+ MessageStream,+ Model,+ ModelCost,+ Provider,+ StreamEvent,+ TextContent,+ ThinkingContent,+ ThinkingLevel,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ Usage,+ UserMessage,+)++__all__ = [+ "AssistantMessage",+ "Content",+ "ImageContent",+ "Message",+ "MessageStream",+ "Model",+ "ModelCost",+ "Provider",+ "StreamEvent",+ "TextContent",+ "ThinkingContent",+ "ThinkingLevel",+ "ToolCall",+ "ToolDefinition",+ "ToolResultMessage",+ "Usage",+ "UserMessage",+]diff --git a/cubepi/providers/base.py b/cubepi/providers/base.pynew file mode 100644index 0000000..a99cf15--- /dev/null+++ b/cubepi/providers/base.py@@ -0,0 +1,147 @@+from __future__ import annotations++import asyncio+from typing import Any, AsyncIterator, Literal, Protocol, runtime_checkable++from pydantic import BaseModel++ThinkingLevel = Literal["off", "minimal", "low", "medium", "high", "xhigh"]+++class ModelCost(BaseModel):+ input: float = 0+ output: float = 0+ cache_read: float = 0+ cache_write: float = 0+++class Usage(BaseModel):+ input_tokens: int = 0+ output_tokens: int = 0+ cache_read_tokens: int = 0+ cache_write_tokens: int = 0+++class Model(BaseModel):+ id: str+ provider: str+ api: str = ""+ reasoning: bool = False+ context_window: int = 200_000+ max_tokens: int = 8192+ cost: ModelCost | None = None+++class TextContent(BaseModel):+ type: Literal["text"] = "text"+ text: str = ""+++class ImageContent(BaseModel):+ type: Literal["image"] = "image"+ source: str = ""+ media_type: str = ""+++class ThinkingContent(BaseModel):+ type: Literal["thinking"] = "thinking"+ thinking: str = ""+++Content = TextContent | ImageContent+++class ToolCall(BaseModel):+ type: Literal["tool_call"] = "tool_call"+ id: str+ name: str+ arguments: dict[str, Any]+++class UserMessage(BaseModel):+ role: Literal["user"] = "user"+ content: list[Content]+ timestamp: float | None = None+++class AssistantMessage(BaseModel):+ role: Literal["assistant"] = "assistant"+ content: list[Content | ThinkingContent | ToolCall]+ stop_reason: str = "stop"+ error_message: str | None = None+ usage: Usage | None = None+ timestamp: float | None = None+++class ToolResultMessage(BaseModel):+ role: Literal["tool_result"] = "tool_result"+ tool_call_id: str+ tool_name: str+ content: list[Content]+ is_error: bool = False+ timestamp: float | None = None+++Message = UserMessage | AssistantMessage | ToolResultMessage+++class ToolDefinition(BaseModel):+ name: str+ description: str+ parameters: dict[str, Any]+++class StreamEvent(BaseModel):+ type: Literal[+ "start",+ "text_start", "text_delta", "text_end",+ "thinking_start", "thinking_delta", "thinking_end",+ "toolcall_start", "toolcall_delta", "toolcall_end",+ "done", "error",+ ]+ delta: str | None = None+ partial: AssistantMessage | None = None+ error_message: str | None = None+++class MessageStream:+ def __init__(self) -> None:+ self._queue: asyncio.Queue[StreamEvent | None] = asyncio.Queue()+ self._result_future: asyncio.Future[AssistantMessage] = (+ asyncio.get_running_loop().create_future()+ )++ def push(self, event: StreamEvent) -> None:+ self._queue.put_nowait(event)+ if event.type in ("done", "error"):+ self._queue.put_nowait(None)++ def set_result(self, message: AssistantMessage) -> None:+ if not self._result_future.done():+ self._result_future.set_result(message)++ def __aiter__(self) -> AsyncIterator[StreamEvent]:+ return self++ async def __anext__(self) -> StreamEvent:+ item = await self._queue.get()+ if item is None:+ raise StopAsyncIteration+ return item++ async def result(self) -> AssistantMessage:+ return await self._result_future+++@runtime_checkable+class Provider(Protocol):+ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ thinking: ThinkingLevel = "off",+ signal: asyncio.Event | None = None,+ ) -> MessageStream: ...diff --git a/tests/providers/test_base.py b/tests/providers/test_base.pynew file mode 100644index 0000000..078b14a--- /dev/null+++ b/tests/providers/test_base.py@@ -0,0 +1,151 @@+import asyncio+from typing import Any++from cubepi.providers.base import (+ AssistantMessage,+ Content,+ ImageContent,+ MessageStream,+ Model,+ ModelCost,+ StreamEvent,+ TextContent,+ ThinkingContent,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ Usage,+ UserMessage,+)+++class TestMessageTypes:+ def test_text_content_defaults(self):+ tc = TextContent()+ assert tc.type == "text"+ assert tc.text == ""++ def test_text_content_with_value(self):+ tc = TextContent(text="hello")+ assert tc.text == "hello"++ def test_image_content(self):+ ic = ImageContent(source="base64data", media_type="image/png")+ assert ic.type == "image"+ assert ic.source == "base64data"+ assert ic.media_type == "image/png"++ def test_thinking_content(self):+ tc = ThinkingContent(thinking="step by step")+ assert tc.type == "thinking"+ assert tc.thinking == "step by step"++ def test_tool_call(self):+ tc = ToolCall(id="tc-1", name="search", arguments={"query": "hello"})+ assert tc.type == "tool_call"+ assert tc.id == "tc-1"+ assert tc.name == "search"+ assert tc.arguments == {"query": "hello"}++ def test_user_message(self):+ msg = UserMessage(content=[TextContent(text="hi")])+ assert msg.role == "user"+ assert msg.timestamp is None++ def test_assistant_message_defaults(self):+ msg = AssistantMessage(content=[TextContent(text="hello")])+ assert msg.role == "assistant"+ assert msg.stop_reason == "stop"+ assert msg.error_message is None+ assert msg.usage is None++ def test_assistant_message_with_tool_calls(self):+ msg = AssistantMessage(+ content=[+ TextContent(text="Let me search."),+ ToolCall(id="tc-1", name="search", arguments={"q": "test"}),+ ],+ stop_reason="tool_use",+ )+ assert len(msg.content) == 2+ assert msg.content[1].type == "tool_call"++ def test_tool_result_message(self):+ msg = ToolResultMessage(+ tool_call_id="tc-1",+ tool_name="search",+ content=[TextContent(text="result")],+ )+ assert msg.role == "tool_result"+ assert msg.is_error is False++ def test_model_defaults(self):+ m = Model(id="gpt-4o", provider="openai")+ assert m.context_window == 200_000+ assert m.max_tokens == 8192+ assert m.reasoning is False+ assert m.cost is None++ def test_usage(self):+ u = Usage()+ assert u.input_tokens == 0+ assert u.output_tokens == 0++ def test_model_cost(self):+ c = ModelCost(input=3.0, output=15.0)+ assert c.cache_read == 0++ def test_tool_definition(self):+ td = ToolDefinition(+ name="search",+ description="Search the web",+ parameters={"type": "object", "properties": {"q": {"type": "string"}}},+ )+ assert td.name == "search"+++class TestMessageStream:+ async def test_stream_iteration_and_result(self):+ stream = MessageStream()+ msg = AssistantMessage(content=[TextContent(text="hello")])++ async def produce():+ await asyncio.sleep(0)+ stream.push(StreamEvent(type="text_delta", delta="hello"))+ stream.push(StreamEvent(type="done"))+ stream.set_result(msg)++ asyncio.create_task(produce())++ events = []+ async for event in stream:+ events.append(event)++ assert len(events) == 2+ assert events[0].type == "text_delta"+ assert events[1].type == "done"++ result = await stream.result()+ assert result.content[0].text == "hello"++ async def test_stream_error_event(self):+ stream = MessageStream()+ error_msg = AssistantMessage(+ content=[],+ stop_reason="error",+ error_message="API error",+ )++ async def produce():+ await asyncio.sleep(0)+ stream.push(StreamEvent(type="error", error_message="API error"))+ stream.set_result(error_msg)++ asyncio.create_task(produce())++ events = []+ async for event in stream:+ events.append(event)++ result = await stream.result()+ assert result.stop_reason == "error"